--- title: Create a custom Apex class to send additional context slug: p8pb4190 canonical_url: https://docs.coveo.com/en/p8pb4190/ collection: coveo-for-agentforce source_format: adoc --- # Create a custom Apex class to send additional context You can create a custom Apex class that you can use in a prompt template to send additional [context](https://docs.coveo.com/en/1345/) to the Coveo Passage Retrieval API. Sending additional [context](https://docs.coveo.com/en/1345/) helps the API tailor responses to the specific user [query](https://docs.coveo.com/en/231/). To send additional [context](https://docs.coveo.com/en/1345/), you must: . [Create a custom Apex class](#create-a-custom-apex-class). . [Create a custom prompt template action](#create-a-custom-prompt-template-action). > **Note** > > For information on how to send case record context, see [Create a custom Apex class to send case record context](https://docs.coveo.com/en/p93f0222/). ## Prerequisites Before you start, make sure you've completed the following tasks: * Fulfilled the [prerequisites](https://docs.coveo.com/en/p5fa9004#prerequisites) to set up and deploy the **Coveo Passage Retrieval API** action. * [Configured the **Coveo Passage Retrieval API** action](https://docs.coveo.com/en/p5fa9004#configure-the-action). ## Create a custom Apex class . Create an Apex class that invokes the Coveo Passage Retrieval API class, `CoveoAgentforce.InvocablePassageRetrievalFlex`, as follows: ```apex global with sharing class CustomPRAPIFlex { @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 retrievePassages(List requests) { List responses = new List(); // Convert the incoming requests to the format expected by the Coveo Passage Retrieval API class List coveoRequests = new List(); for(Request request: requests) { CoveoAgentforce.InvocablePassageRetrievalFlex.Request coveoRequest = new CoveoAgentforce.InvocablePassageRetrievalFlex.Request(); coveoRequest.userInput = request.userInput; <1> coveoRequest.prapiConfig = request.prapiConfig; <2> coveoRequest.additionalContext = '{"company": "Coveo", "user": "John Doe"}'; <3> coveoRequests.add(coveoRequest); } List coveoResponses = CoveoAgentforce.InvocablePassageRetrievalFlex.retrievePassages(coveoRequests); <4> for(CoveoAgentforce.InvocablePassageRetrievalFlex.Response coveoResponse: coveoResponses) { Response response = new Response(); response.Prompt = coveoResponse.Prompt; <5> responses.add(response); } return responses; } global class Request { <6> @InvocableVariable(required=true label='User Query' description='The user input to retrieve passages for') global String userInput; <7> @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; <7> } global class Response { <6> @InvocableVariable(label='Passages response' description='The passages retrieved from Coveo Passage Retrieval API') global String Prompt; <8> } } ``` <1> The `userInput` is the query for which you want to retrieve passages. <2> The `prapiConfig` is the name of the custom metadata type record that contains the configuration options for the Coveo Passage Retrieval API. <3> The `additionalContext` adds custom context to the request, such as information about the user or the current record. The `additionalContext` must be passed as a valid JSON string of key-value pairs. <4> 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. <5> Converts the Coveo responses to the format expected by your custom prompt template class. <6> 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. <7> The `Request` class must include the `String userInput` and `String prapiConfig` attributes to call the Coveo Passage Retrieval API class. <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. . Save your new Apex class. You must now [create a custom prompt template action](#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](#create-a-prompt-template). . [Access your Agentforce AI agent](#access-your-agentforce-ai-agent). . [Create a topic](#create-a-topic). . [Assign the Agentforce action to your topic](#assign-the-agentforce-action-to-your-topic). ### Create a prompt template . From the Salesforce Setup menu, in the Quick Find box, enter **Prompt Builder**, and then select **Prompt Builder**. . In the upper-right corner of the builder, click **New Prompt Template**. . On the **New Prompt Template** page, specify the following information: ![Create a prompt template | Coveo for Agentforce](pass:m[coveo-for-agentforce/prapi-prompt-template-for-additional-context.png]) .. From the **Prompt Template Type** dropdown menu, select **Flex**. .. [[prapi-prompt-template-name]][[ccapi-prompt-template-name]]In the **Prompt Template Name** field, enter a descriptive name for your prompt template (for example, `Custom Answer Questions 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. .. (Optional) In the **Template Description** field, provide a brief description of your prompt template (for example, `Custom Passage Retrieval API flex prompt template to pass additional context`). .. 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](#create-a-custom-apex-class). ... In the **Name** field, enter `userInput` as a descriptive name for the data source containing the user's input. The **API Name** field is automatically filled by Salesforce based on the information you entered in the **Name** field. Don't modify this value. ... From the **Source Type** dropdown menu, select **Free Text**, 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. ... 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. ... From the **Source Type** dropdown menu, select **Free Text**. .. Click **Next** to access the **Prompt Builder**. . [[prompt-template-workspace]]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](https://help.salesforce.com/s/articleView?id=ai.prompt_builder_best_practices.htm&type=5) for guidelines and recommendations. > **Warning** > > You must include your custom Apex class, such as `Apex:CustomPRAPIFlex` in your prompt template instructions. This class invokes the Coveo Passage Retrieval API class to send additional context to the Coveo Passage Retrieval API and to retrieve relevant passages from [items](https://docs.coveo.com/en/210/) [indexed](https://docs.coveo.com/en/204/) in your [Coveo organization](https://docs.coveo.com/en/185/). > > All source references such as `{!$Input:userInput}` and `{!$Apex:}` in the following example are links to [resources](https://help.salesforce.com/s/articleView?id=ai.prompt_builder_get_to_know.htm&type=5). > You must specify them by selecting **Insert Resource** in the **Prompt** section. > Don't paste them in the instructions. **Example** ```text 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:CustomPRAPIFlex.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:CustomPRAPIFlex` 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: ```text Context: You must answer the following question... ### ### 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... ``` . [[prapi-prompt-template]]At the upper-left corner of the Prompt Builder, click **Preview Settings** (![Prompt Builder Preview Settings icon | Coveo for Agentforce](coveo-for-agentforce/prompt-builder-preview-settings-icon-button.png)) to specify your prompt template settings. .. In the **Inputs** section, specify the following information: ... In the **userInput** field, enter a question to test your template, for example: ```text What is Barca Skipper? ``` ... 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](https://docs.coveo.com/en/p5fa9004#create-a-custom-metadata-configuration). .. In the **Output** section: ... Ensure the **Generate Response** option is enabled. ... From the **Response Language** dropdown menu, select **English**. ... Under **On Preview**, ensure the **Expand Resolved Prompt** and **Expand Generated Response** checkboxes are selected. . Click **Save & Preview** to save your prompt template settings and preview the results. For subsequent changes, click **Preview** to see the updated results. . Once you're satisfied with the results, click **Activate** to enable your prompt template. ### Access your Agentforce AI agent . From the Salesforce Setup menu, in the Quick Find box, enter `Agentforce Agents`, and then select **Agentforce Agents**. . 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](https://help.salesforce.com/s/articleView?id=ai.agent_setup_explore_types.htm&type=5) at this time. > Use a different agent type to leverage your Coveo-powered actions. . If your Agentforce AI agent is currently active, click **Deactivate** in the upper-right corner of the Agentforce Builder. > **Tip** > > You must always deactivate your Agentforce AI agent to make changes to it. ### Create a topic . In the Agentforce Builder, select **Topics** from the left tab. . Click the **New** actions menu, and then select **New Topic**. . (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. . Click **Next**. . In the second step of the modal, specify the following information: ![Create a topic page | Coveo for Agentforce](pass:m[coveo-for-agentforce/prapi-create-a-topic.png]) > **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. > See [Best Practices for Topic Instructions](https://help.salesforce.com/s/articleView?id=ai.copilot_topics_instructions.htm&type=5) for guidance on writing effective instructions for your topic. .. 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. .. In the **Classification Description** field, provide a brief topic description (one to three sentences). Enter text similar to the following: **Example** ```text 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. .. In the **Scope** field, enter a job description for your topic. Enter text similar to the following: **Example** ```text 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. ``` .. [[prapi-custom-topic-instructions]]In the **Instruction** field, instruct Agentforce to use your custom prompt template action to retrieve passages as follows: **Example** ```text Always use the "" action and answer with the output of the action only. ``` Where `` is the name of your [custom prompt template](#create-a-prompt-template) action (for example, `Custom Answer Question with Coveo`). ... Click **Add Instructions**, and then enter text similar to the following: ```text If the "" 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. ``` ... Click **Add Instructions**, and then enter text similar to the following: ```text Always use the following as input for the "" action {"prapiConfig": ""} ``` Where `` is the name of your [Coveo Passage Retrieval configuration](https://docs.coveo.com/en/p5fa9004#create-a-custom-metadata-configuration) (for example, `General_Barca_Questions`). .. In the **Example User Input** fields, add examples of questions or requests that users might ask. **Example** ```text What is Barca Skipper? ``` > **Tip** > > This section is only available if you're using the [Agentforce (Default)](https://help.salesforce.com/s/articleView?id=ai.agent_setup_explore_types.htm&type=5) agent. > If you're using a custom agent, you can skip this step. . Click **Next**. . Skip the **Select the actions you want to include in your topic** step. . 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 . In the **Topics** panel, select the topic you created. . In the **Topic Details** panel, select **This Topic's Actions**. ![Topic details panel | Coveo for Agentforce](pass:m[coveo-for-agentforce/prapi-topic-action-highlight.png]) . To add your custom prompt template action to the topic, click the **New** action menu, and then select **Create New Action**. . On the **Create an Agent Action** page, specify the following information: ![Create an agent action modal | Coveo for Agentforce](pass:m[coveo-for-agentforce/prapi-create-agent-action-additional-context.png]) .. From the **Reference Action Type** dropdown menu, select **Prompt Template**. .. From the **Reference Action** field, select the prompt template you created (for example, **Custom Answer Questions With Coveo**). The **Agent Action Label** and **Agent Action API Name** fields are automatically filled by Salesforce. .. Click **Next** and scroll to the **Agent Action Configuration** section. ![Agent action configuration panel | Coveo for Agentforce](pass:m[coveo-for-agentforce/prapi-agent-action-configuration-additional-context.png]) .. In the **Agent Action Instructions** field, enter a description for your custom action. **Example** ```text Retrieve relevant passages from the documentation to answer user questions. ``` .. Clear the **Show loading text for this action** checkbox. .. Under the **Inputs** section: ... Provide instructions for the **userInput** input. **Example** ```text The question from the user. ``` ... Provide instructions for the **prapiConfig** input. **Example** ```text The API name of the configuration to use. ``` .. Under the **Output** section: ... Under **Data Type**, select the **Show in conversation** checkbox. ... From the **Output Rendering** dropdown menu, select **Rich Text**. .. Click **Finish** to create your action. The **This Topic's Actions** tab now displays your custom action. ![PRAPI prompt template action | Coveo for Agentforce](pass:m[coveo-for-agentforce/prapi-assign-custom-context-prompt-template-to-topic.png]) > **Tip** > > If you don't see your custom action in the list, refresh the page. . Click **Activate** in the upper-right corner of the builder to enable your AI agent. . [Test your custom prompt template action](#test-the-action) to confirm it's working as expected. You've successfully set up and deployed your custom Apex class to send additional context. Your Agentforce AI agent can now retrieve relevant passages from the [items](https://docs.coveo.com/en/210/) [indexed](https://docs.coveo.com/en/204/) in your [Coveo organization](https://docs.coveo.com/en/185/) to answer user questions. ## Test the action . Launch the [Agentforce Builder](https://help.salesforce.com/s/articleView?id=ai.agent_builder_explore.htm&type=5). . Enter a question related to your topic in the **Conversation Preview** panel on the right side of the screen. . Review the information displayed on the **Plan Canvas** (center screen) to verify expected behavior. .. Confirm your AI agent selects the correct topic. .. Confirm the generated response matches the passages returned by the **Coveo Passage Retrieval API** action.