Create a custom Apex class to send case record context

You can create a custom Apex class that you can use in a prompt template to send case record context to the Coveo Passage Retrieval API. Sending case record context helps the API tailor responses to the specific user query.

To send case record context, you must:

Note

For information on how to send additional context, see Create a custom Apex class to send additional context.

Prerequisites

Before you start, make sure you’ve completed the following tasks:

Create a custom Apex class

  1. Create an Apex class that invokes the Coveo Passage Retrieval API class, CoveoAgentforce.InvocablePassageRetrievalFlex, as follows:

    global with sharing class PassageRetrievalWithRecordContext {
    
        @InvocableMethod(label='Coveo Passage Retrieval API in a Prompt Template'
        description='Retrieve Passages from Coveo PRAPI to use in a Prompt Template')
        global static List<Response> retrievePassages(List<Request> requests) {
            List<Response> responses = new List<Response>();
    
            // Convert the incoming requests to the format expected by the Coveo Passage Retrieval API class.
            List<CoveoAgentforce.InvocablePassageRetrievalFlex.Request> coveoRequests = new List<CoveoAgentforce.InvocablePassageRetrievalFlex.Request>();
            for(Request request: requests) {
                Case myExampleCaseRecord = request.caseRecord; 1
    
                CoveoAgentforce.InvocablePassageRetrievalFlex.Request coveoRequest = new CoveoAgentforce.InvocablePassageRetrievalFlex.Request();
                coveoRequest.userInput = myExampleCaseRecord.Subject; 2
                coveoRequest.prapiConfig = request.prapiConfig; 3
                coveoRequest.additionalContext = JSON.serialize(new Map<String,String>{'Case_Description' => myExampleCaseRecord.Description}); 4
                coveoRequests.add(coveoRequest);
            }
    
            List<CoveoAgentforce.InvocablePassageRetrievalFlex.Response> coveoResponses = CoveoAgentforce.InvocablePassageRetrievalFlex.retrievePassages(coveoRequests); 5
            for(CoveoAgentforce.InvocablePassageRetrievalFlex.Response coveoResponse: coveoResponses) {
                Response response = new Response();
                response.Prompt = coveoResponse.Prompt; 6
                responses.add(response);
            }
            return responses;
        }
    
        global class Request { 7
            @InvocableVariable(required=true label='Case record' description='The case to retrieve passages for')
            global Case caseRecord;
            @InvocableVariable(required=true label='User Query' description='The user input to retrieve passages for')
            global String userInput;
            @InvocableVariable(required=true label='Name of the Passage Retrieval configuration'
            description='The Name of the custom metadata type record to apply a Passage Retrieval configuration,
            can either be the ID "m00000000000001" or the Developer Name "My_PRAPI_Config" or the fully qualified name "MyNamespace__My_PRAPI_Config"')
            global String prapiConfig;
        }
    
        global class Response { 7
            @InvocableVariable(label='Passages response' description='The passages retrieved from Coveo Passage Retrieval API')
            global String Prompt; 8
        }
    }
    1 Puts the caseRecord in a variable of type Case.
    2 Sets the userInput to the subject of the case record so it can be used as the query to retrieve the most relevant passages.
    3 The prapiConfig is the name of the custom metadata type record that contains the configuration options for the Coveo Passage Retrieval API.
    4 The additionalContext adds case record context to the request. You can specify any field from the case record as context (for example, Case_Description or a custom field such as Boat__c). The additionalContext must be passed as a valid JSON string of key-value pairs.
    5 Calls the Coveo Passage Retrieval API with the requests to retrieve passages. The response will already be formatted as a list of Response objects that each contain a Prompt attribute. This is the expected format for the prompt template, a single string that contains the passages and the citations for each passage.
    6 Converts the Coveo responses to the format expected by your custom prompt template class.
    7 The Request and Response classes define the input and output of the InvocableMethod. You can change these classes to better suit your needs, but they must be global and they must include the InvocableVariable annotation.
    8 The Response class must include the String Prompt attribute, which is the expected format for the prompt template. If this attribute isn’t specified, your class won’t be visible in the Prompt Builder.
  2. Save your new Apex class.

You must now create a custom prompt template action to deploy your new Apex class and retrieve passages from the Coveo Passage Retrieval API.

Create a custom prompt template action

To deploy your custom Apex class using a custom prompt template action, you must:

Create a prompt template

  1. From the Salesforce Setup menu, in the Quick Find box, enter Prompt Builder, and then select Prompt Builder.

  2. In the upper-right corner of the builder, click New Prompt Template.

  3. On the New Prompt Template page, specify the following information:

    Create a prompt template | Coveo for Agentforce
    1. From the Prompt Template Type dropdown menu, select Flex.

    2. In the Prompt Template Name field, enter a descriptive name for your prompt template (for example, Solve Cases With Coveo).

      The API Name field is automatically filled by Salesforce based on the information you entered in the Prompt Template Name field. Don’t modify this value.

    3. (Optional) In the Template Description field, provide a brief description of your prompt template (for example, Custom Passage Retrieval API prompt template to pass case record context).

    4. Under Inputs, click Add, and then specify the following data sources:

      Important

      Input names are case-sensitive. Ensure that the names you provide match those you specified in the Request class of your custom Apex class.

      1. In the Name field, enter caseRecord as a descriptive name for the data source containing the case record.

        The API Name field is automatically filled by Salesforce based on the information you entered in the Name field. Don’t modify this value.

      2. From the Source Type dropdown menu, select Object as the source type.

      3. In the Object field, select the Case object, and then click Add.

        Tip

        Keep the Require when template runs checkbox selected for all data sources. This ensures that the prompt template action only runs when all required data sources are provided.

      4. In the next Name field, enter userInput as a descriptive name for the data source containing the case subject.

        The API Name field is automatically filled by Salesforce based on the information you entered in the Name field. Don’t modify this value.

      5. From the Source Type dropdown menu, select Free Text, and then click Add.

      6. In the next Name field, enter prapiConfig as a descriptive name for the data source containing the Coveo Passage Retrieval API configuration.

        The API Name field is automatically filled by Salesforce based on the information you entered in the Name field. Don’t modify this value.

      7. From the Source Type dropdown menu, select Free Text.

    5. Click Next to access the Prompt Builder.

  4. In the Prompt section, enter your prompt template instructions and specify related resources.

    Important

    Writing prompt template instructions is an iterative process. The information in this section isn’t exhaustive and only provides an example. Adjust the information to fit your specific use case. See Best Practices for Building Prompt Templates for guidelines and recommendations.

    Warning

    You must include your custom Apex class, such as Apex:PassageRetrievalWithRecordContext in your prompt template instructions. This class invokes the Coveo Passage Retrieval API class to send record context to the Coveo Passage Retrieval API and to retrieve relevant passages from items indexed in your Coveo organization.

    All source references such as {!$Input:userInput} and {!$Apex:<CLASS_NAME>} in the following example are links to resources, which must be specified by selecting Insert Resources in the Prompt section. They must not be pasted in the instructions.

    Example
    Context:
    You're a service agent and knowledge expert supporting agents in answering customer questions accurately and efficiently.
    Your role is to synthesize clear, factual answers based only on the retrieved document passages and cite all referenced materials.
    Agents rely on your answer to assist users, but they validate and finalize the response.
    A user just asked this question
    
    ###
    {!$Input:userInput}
    ###
    
    Use the following passages in order to answer the user question:
    {!$Apex:PassageRetrievalWithRecordContext.Prompt} 1
    
    To structure your response
    Use only the provided passages to generate the answer.
    Do not invent or infer beyond what's present.
    Write in concise, declarative English, using the active voice.
    Include all used citations at the end as a numbered list.
    1 The Apex:PassageRetrievalWithRecordContext is a placeholder for the Coveo Passage Retrieval API response. It contains the passages and citations returned by the API. When a user asks a question, the Agentforce AI agent essentially receives input similar to the following:
    Context:
    You must answer the following question...
    
    ###
    <QUESTION_ENTERED_BY_USER>
    ###
    
    Use the following passages to answer the question:
    {
      "passages": ["lorem ipsum", "dolor sit amet", "consectetur adipiscing elit"],
      "citations": ["https://www.lipsum.com/", "https://www.google.com", "https://www.coveo.com"]
    }
    
    To structure your response
    Use only the provided passages to generate the answer...
  5. At the upper-left corner of the Prompt Builder, click Preview Settings (Prompt Builder Preview Settings icon | Coveo for Agentforce) to specify your prompt template settings.

    1. In the Inputs section, specify the following information:

      1. In the caseRecord field, enter or select a case record to test your template.

      2. In the userInput field, enter a prompt to test your template, for example:

        Solve this case.
      3. In the prapiConfig field, enter the name of the PR API configuration. This name must match the one you specified in your custom metadata configuration.

    2. In the Output section:

      1. Ensure the Generate Response option is enabled.

      2. From the Response Language dropdown menu, select English.

      3. Under On Preview, ensure the Expand Resolved Prompt and Expand Generated Response checkboxes are selected.

  6. Click Save & Preview to save your prompt template settings and preview the results. For subsequent changes, click Preview to see the updated results.

  7. Once you’re satisfied with the results, click Activate to enable your prompt template.

Access your Agentforce AI agent

  1. From the Salesforce Setup menu, in the Quick Find box, enter Agentforce Agents, and then select Agentforce Agents.

  2. On the page that opens, find your Agentforce AI agent, such as Einstein Copilot or Agentforce (Default), click down to access the Actions menu, and then select Open in Builder.

    Important

    You can’t use Coveo-powered Agentforce actions in a Service Agent at this time. Use a different agent type to leverage your Coveo-powered actions.

  3. If your Agentforce AI agent is currently active, click Deactivate in the upper-right corner of the Agentforce Builder.

    Tip
    Tip

    You must always deactivate your Agentforce AI agent to make changes to it.

Create a topic

  1. In the Agentforce Builder, select Topics from the left tab.

  2. Click the New actions menu, and then select New Topic.

  3. (Optional) In the Create a Topic modal, specify the job you want this topic to perform.

    Tip

    You can skip this step and specify the job you want this topic to perform in the second step of the modal.

  4. Click Next.

  5. In the second step of the modal, specify the following information:

    Create a topic page | Coveo for Agentforce
    Important
    Important

    Creating a topic is an iterative process. The information in this section isn’t exhaustive and is only meant to provide you with an example. You must adjust the information to fit your specific use case.

    1. In the Name field, enter a descriptive name for your topic (for example, Barca Product Support).

      By default, the API Name field is automatically filled by Salesforce based on the information you entered in the Name field.

    2. In the Classification Description field, provide a brief topic description (one to three sentences). Enter text similar to the following:

      Example
      When a user asks a question about Barca, a company that sells boats and related products, these questions can be to provide an answer to a support type of question or be general questions about boats and related products.

      The description should be clear and concise, providing enough context for the topic’s purpose. Agentforce uses this information to determine which topic to use when answering questions.

    3. In the Scope field, enter a job description for your topic. Enter text similar to the following:

      Example
      Your job is to answer the questions the user asks providing useful information about products or helping the user resolve an issue.
      You will create a medium to short answer to the questions asked.
      Ensure responses are well-structured and formatted correctly to provide clarity and usefulness to the user.
    4. In the Instruction field, instruct Agentforce to use your custom prompt template action to retrieve passages as follows:

      Example
      Always use the "<CUSTOM_PRAPI_PROMPT_TEMPLATE>" action and answer with the output of the action only.

      Where <CUSTOM_PRAPI_PROMPT_TEMPLATE> is the name of your custom prompt template action (for example, Solve Cases with Coveo).

      1. Click Add Instructions, and then enter text similar to the following:

        If the "<CUSTOM_PRAPI_PROMPT_TEMPLATE>" action does not provide you with passages, do not attempt to answer the question and simply say that you couldn't find any relevant document to answer the question.
      2. Click Add Instructions, and then enter text similar to the following:

        You should always use the following for the Input to the "<CUSTOM_PRAPI_PROMPT_TEMPLATE>" action {"prapiConfig": "<YOUR_PRAPI_CONFIG_NAME>"}

        Where <YOUR_PRAPI_CONFIG_NAME> is the name of your Coveo Passage Retrieval configuration (for example, General_Barca_Questions).

    5. In the Example User Input fields, add examples of questions or requests that users might ask.

      Example
      Solve this case.
      Tip

      This section is only available if you’re using the Agentforce (Default) agent. If you’re using a custom agent, you can skip this step.

  6. Click Next.

  7. Skip the Select the actions you want to include in your topic step.

  8. Click Finish to create your topic.

    Tip

    If a Topic Overlap Detected warning appears, review your topics to ensure they’re distinct. Make any necessary adjustments to avoid overlap.

Assign the Agentforce action to your topic

  1. On the Topics panel, select the topic you created.

  2. On the Topic Details panel, select This Topic’s Actions.

    Topic details panel | Coveo for Agentforce
  3. To add your custom prompt template action to the topic, click the New action menu, and then select Create New Action.

  4. On the Create an Agent Action page, specify the following information:

    Create an agent action modal | Coveo for Agentforce
    1. From the Reference Action Type dropdown menu, select Prompt Template.

    2. From the Reference Action field, select the prompt template you created (for example, Solve Cases With Coveo).

      The Agent Action Label and Agent Action API Name fields are automatically filled by Salesforce.

    3. Click Next and scroll to the Agent Action Configuration section.

      Agent action configuration panel | Coveo for Agentforce
    4. In the Agent Action Instructions field, enter a description for your custom action.

      Example
      Retrieve relevant passages from the documentation to answer user questions.
    5. Clear the Show loading text for this action checkbox.

    6. Under the Inputs section:

      1. Provide instructions for the userInput input.

        Example
        The question from the user.
      2. Provide instructions for the caseRecord input.

        Example
        The case record for which to retrieve passages.
      3. Provide instructions for the prapiConfig input.

        Example
        The API name of the configuration to use.
    7. Under the Output section:

      1. Under Data Type, select the Show in conversation checkbox.

      2. From the Output Rendering dropdown menu, select Rich Text.

    8. Click Finish to create your action. The This Topic’s Actions tab now displays your custom action.

      PRAPI prompt template action | Coveo for Agentforce
      Tip

      If you don’t see your custom action in the list, refresh the page.

  5. Click Activate in the upper-right corner of the builder to enable your AI agent.

  6. Test your custom prompt template action to confirm it’s working as expected.

You’ve successfully set up and deployed your custom Apex class to send case record context. Your Agentforce AI agent is now able to retrieve relevant passages from the items indexed in your Coveo organization to answer user questions.

Test the action

  1. Open a case record in the Lightning Service Console.

  2. Click Agentforce icon button in the upper-right corner of the Lightning Service Console to open the Agentforce chat window.

  3. In the Agentforce chat window, enter a request such as Solve this case.

  4. Review the response provided by your Agentforce AI agent. Make sure that the response is relevant to the case subject and description, and that it includes citations to the sources used to generate the response.