---
schema_version: "1"
id: c97b14aca7b0a3e0642033d8a242725f8ff9988ae4942f5f7f772d4fd6a539c7
title: Grounding with Apex Merge Fields
collection: admin
version: current
locale: en-us
portal_url: https://docs.salesforce.com/admin/current/en-us/ai/264-0-0/prompt_builder_ground_apex.md
canonical_url: https://help.salesforce.com/s/articleView?id=ai.prompt_builder_ground_apex.htm&release=264.0.0&type=5
source_site: help.salesforce.com
content_type: documentation
content_hash: 3a7a71c48aaf4c0ea78c409bdcbf5d571343082c564cd1d7c31c57678a8b6ed8
description: You can use an Apex merge field in a prompt template to return data from a SOQL query or an external API. Apex is also effective if you want to generate well-formatted JSON or do programmatic data filtering.
products:
  - Agentforce
  - Cross Cloud
release: "264"
---
# Grounding with Apex Merge Fields

You can use an Apex merge field in a prompt template to return data from a SOQL query or an external API. Apex is also effective if you want to generate well-formatted JSON or do programmatic data filtering.

### Required Editions

<table class="slds-table slds-table_bordered slds-max-medium-table_stacked slds-m-bottom_small edition"><colgroup><col></colgroup><tbody><tr class=""><td class="slds-cell-wrap" style="vertical-align:top;">Available in: Lightning Experience</td></tr><tr class=""><td class="slds-cell-wrap" style="vertical-align:top;">Available in: <strong>Enterprise</strong>, <strong>Performance</strong>, and <strong>Unlimited</strong> Editions with the Einstein for Platform, or Einstein or Agentforce for Sales or Service add-on, or Agentforce Foundations</td></tr></tbody></table>

To use Apex in Prompt Builder, you must create an Apex class that contains at least 1 method annotated with `InvocableMethod`. For details, see the [Apex Developer Guide](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_annotation_InvocableMethod.htm).

If desired, the `InvocableMethod` annotation can specify a `CapabilityType` that matches the prompt template type.

Example annotation: `@InvocableMethod(CapabilityType='PromptTemplateType://einstein_gpt__salesEmail')`.

This table lists the `CapabilityType` for each prompt template type.

![Note](https://sf-zdocs-cdn-prod.zoominsoftware.com/tdta-ai-generative_ai-264-0-0-production-enus/f8ef6498-d7b2-44e3-9b34-ffd5a850aae9/images/icon_note.png)

Note

Don’t specify a `CapabilityType` for the prompt template type `einstein_gpt__caseEmailDraft`, used for Service Email Assistant. This prompt template type uses Case as an input API name, so you should use another API name for the input, like CaseObject.

 
| Prompt Template Type | CapabilityType |
| --- | --- |
| Sales Email | `PromptTemplateType://einstein_gpt__salesEmail` |
| Field Generation | `PromptTemplateType://einstein_gpt__fieldCompletion` |
| Record Prioritization | `PromptTemplateType://einstein_gpt__recordPrioritization` |
| Record Summary | `PromptTemplateType://einstein_gpt__recordSummary` |

The Flex capability has been retired, so it should no longer be used in Apex classes. We recommend refactoring any ​​Apex code that uses `CapabilityType=FlexTemplate://*` so that it doesn’t use FlexTemplate. Remove the `CapabilityType` attribute and save, and then verify that your prompt template continues to work as expected with the Apex merge fields.

## Method Input

The method’s input parameter must have a `List<Request>` type. The `Request` class defines an `InvocableVariable` member for each input defined by the prompt template type. All inputs are passed from the prompt template into the invocable method. Only the first element in the list has data.

When present, the `CapabilityType` for a prompt template type acts as an interface for the `Request` input class. Each `CapabilityType` requires that the `Request` class defines specific `InvocableVariable` members. For example, the field generation `CapabilityType` requires that you define a `RelatedEntity` member variable in `Request`. If there are additional objects defined in the prompt template, an associated InvocableVariable member must be defined by using the exact spelling and case sensitivity. In this example, the prompt template defined Account as the object that the template is updating.

```java
public class Request {
                @InvocableVariable
                public Account RelatedEntity;
        }
```

![Note](https://sf-zdocs-cdn-prod.zoominsoftware.com/tdta-ai-generative_ai-264-0-0-production-enus/f8ef6498-d7b2-44e3-9b34-ffd5a850aae9/images/icon_note.png)

Note If you change the inputs for a flow or Apex class that’s used as a resource in a prompt template, the prompt template no longer works and you can’t save new versions of the prompt template. See this [known issue](https://issues.salesforce.com/issue/a028c00000ywyBZ/changing-the-shape-of-flowapex-inputs-while-referenced-in-a-prompt-template-leads-to-runtime-failures-and-inability-to-save-new-versions-of-the-temp).

## Method Output

The method output has a `List<Response>` type containing a single string member named `Prompt` that’s annotated with `InvocableVariable`. For details, see the [Apex Developer Guide](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_annotation_InvocableVariable.htm).

## Example Apex Class

```java
public class ApexPromptTemplateExample1 {

    // At least one method must be annotated with InvocableMethod.
    // No CapabilityType is specified (Flex is retired; for a typed template
    // such as Sales Email or Field Generation, add e.g.
    // @InvocableMethod(CapabilityType='PromptTemplateType://einstein_gpt__salesEmail')).
    @InvocableMethod
    public static List<Response> getPrompt(List<Request> requests) {
        // Only the first element in the list has data.
        Request input = requests[0];

        List<Response> responses = new List<Response>();
        Response output = new Response();
        responses.add(output);

        // Build the prompt string returned to the template.
        output.Prompt = 'generate a summary using the following info:';
        // account_1 matches the API Name of the input in the prompt template.
        output.Prompt += '\nAccount 1: ' + input.account_1.Name;
        output.Prompt += '\nAccount 2: ' + input.account_2.Name;
        output.Prompt += '\nCase Number: ' + input.case_1.CaseNumber;

        return responses;
    }

    // Method Input: List<Request>. Define one InvocableVariable per template input.
    // The type and API Name of every variable must match the template exactly
    // (spelling and case sensitivity).
    public class Request {
        @InvocableVariable(required=true)
        public Account account_1;
        @InvocableVariable(required=true)
        public Account account_2;
        @InvocableVariable(required=true)
        public Case case_1;
    }

    // Method Output: List<Response> with a single String member named Prompt
    // annotated with InvocableVariable.
    public class Response {
        @InvocableVariable
        public String Prompt;
    }
}
```

## Add Apex Resource to a Prompt Template

In the Prompt Template Workspace, add an Apex class to a prompt template by clicking the **Resource** field in the Prompt section and selecting **Apex**.

![Note](https://sf-zdocs-cdn-prod.zoominsoftware.com/tdta-ai-generative_ai-264-0-0-production-enus/f8ef6498-d7b2-44e3-9b34-ffd5a850aae9/images/icon_note.png)

Note If you open the Developer Console before you preview a prompt template that uses Apex, you can see debug statements in the Developer Console. For more information, see [Working with Logs in the Developer Console](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_debugging_system_log_console.htm) and [debug(msg)](https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_methods_system_system.htm#apex_System_System_debug) in the Apex Developer Guide.

To use Apex in Prompt Builder, see:

- [Add Apex Merge Fields to a Sales Email Prompt Template](https://help.salesforce.com/s/articleView?id=ai.prompt_builder_add_apex_sales_email.htm&release=264.0.0&type=5 "Create an example sales email prompt template that uses Apex.")
- [Add Apex Merge Fields to a Field Generation Prompt Template](https://help.salesforce.com/s/articleView?id=ai.prompt_builder_add_apex_field_gen.htm&release=264.0.0&type=5 "Create an example field generation prompt template that uses Apex.")
- [Add Apex Merge Fields to a Flex Prompt Template](https://help.salesforce.com/s/articleView?id=ai.prompt_builder_add_apex_flex.htm&release=264.0.0&type=5 "Create an example Flex prompt template that uses Apex.")