---
schema_version: "1"
id: f4c151e737aed4554e7b2fbe5eb1ca5750d0f2927f9e114c429c058980c88b89
title: Add Apex Merge Fields to a Field Generation Prompt Template
collection: admin
version: current
locale: en-us
portal_url: https://docs.salesforce.com/admin/current/en-us/ai/264-0-0/prompt_builder_add_apex_field_gen.md
canonical_url: https://help.salesforce.com/s/articleView?id=ai.prompt_builder_add_apex_field_gen.htm&release=264.0.0&type=5
source_site: help.salesforce.com
content_type: documentation
content_hash: d1f4843bb2753b51745ba52d330ff829bb0ec4577f0f525d11f5e22563938f62
description: Create an example field generation prompt template that uses Apex.
products:
  - Agentforce
  - Cross Cloud
release: "264"
---
# Add Apex Merge Fields to a Field Generation Prompt Template

Create an example field generation prompt template that uses Apex.

### 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>

<table class="slds-table slds-table_bordered slds-max-medium-table_stacked slds-m-bottom_small permission">
        <colgroup>
          <col style="width:50%">
          <col style="width:50%">
        </colgroup>
        <thead class="slds-text-title_caps ">
          <tr class="">
            <th scope="colgroup" class="slds-cell-wrap" colspan="2" style="text-align:center;vertical-align:top;" id="d95404e63">User Permissions Needed</th>
          </tr>
        </thead>
        <tbody>
          <tr class="">
            <td data-label="User Permissions Needed" class="slds-cell-wrap" style="vertical-align:top;" headers="d95404e63 ">To create and manage prompt templates in Prompt Builder:</td>

            <td class="slds-cell-wrap" style="vertical-align:top;" headers="d95404e63 ">
              <p>Prompt Template Manager permission set</p>
              <ul>
                <li>Manage Prompt Templates</li>

                <li>Execute Prompt Templates</li>

              </ul>
              <p>OR</p>
              <p style="margin-bottom:0;">Customize Application permission set</p>
            </td>

          </tr>
        </tbody>
      </table>

Say you want to provide up-to-the-minute summaries of customer cases for a given customer to your company’s sales team before they make customer calls. We used the same use case in the flow section.

This time, you want to create a field generation prompt template that integrates an Apex class that obtains case data for an LLM to summarize.

Here’s the Apex class that we access as a resource in a prompt template.

```java
public class OpenCasesPrompt {
    @InvocableMethod(label='Open Cases'
        description='Find Cases for an Account'
        CapabilityType='PromptTemplateType://einstein_gpt__fieldCompletion')
    public static List<Response> getCasesPrompt(List<Request> requests) {
        // Validate the expected number of requests as an input
        if (requests.size() != 1)
          throw new ListException('The requests list must contain one entry only');
        Account a = requests[0].RelatedEntity;
        ID searchAcctId = a.Id;
        List<Case> cases =
            [SELECT Id, Subject, Description
             FROM Case
             WHERE AccountId = :searchAcctId AND Status != 'Closed'
             WITH USER_MODE];
        string responseData = null;
        if(cases.isEmpty()) {
            responseData = 'There are no open cases.';
        } else {
            for(Case c : cases) {  
                responseData =
                   (responseData != null) ? responseData + '\n' : '';           
                responseData += String.format('Case details: {0}, {1}.',
                    new List<Object>{c.Subject, c.Description});
            }
        }
       
        List<Response> responses = new List<Response>();
        Response res = new Response();
        res.Prompt = responseData;
        responses.add(res);
        return responses;
    }
    
    public class Request {
        @InvocableVariable(required=true)
        public Account RelatedEntity;
    }
    
    public class Response {
        @InvocableVariable
        public String Prompt;
    }
}
```

The requirements for the Apex class are explained in [Grounding with Apex Merge Fields](https://help.salesforce.com/s/articleView?id=ai.prompt_builder_ground_apex.htm&release=264.0.0&type=5 "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.").

Test coverage is important so let's add a [test class](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing.htm). The test class simulates data sent from Prompt Builder. Two test cases are provided: one for when events are found, and one for when there are no events.

```java
@IsTest
public class OpenCasesPrompt_Test {

    @IsTest
    public static void findMatchingCasesForAccount() {        
        Account a = new Account(Name='Test Account');
        insert a;
        Case c1 = new Case(Subject='Test Case', Description='Important Case', 
            Status='New', AccountId=a.id);
        Case c2 = new Case(Subject='Test Case 2',
            Description='Case Description', Status='In-progress', 
            AccountId=a.id);
        Case c3 = new Case(Subject='Test Case Closed',
            Description='Closed Case', Status='Closed', AccountId=a.id);
        insert new List<Case>{c1, c2, c3};


        List<OpenCasesPrompt.Request> requestsInput
            = new List<OpenCasesPrompt.Request>();
        OpenCasesPrompt.Request request = new OpenCasesPrompt.Request();
        request.RelatedEntity = a;
        requestsInput.add(request);
        
        Test.startTest();
        List<OpenCasesPrompt.Response> responses = 
            OpenCasesPrompt.getCasesPrompt(requestsInput);
        Test.stopTest();
       
        Assert.areEqual(1, responses.size());
        OpenCasesPrompt.Response response = responses[0];

        Assert.areEqual('Case details: Test Case, Important Case.\n' +
                        'Case details: Test Case 2, Case Description.', 
                        response.Prompt);
    }

    @IsTest
    public static void noCasesForAccountResponse() {
        List<OpenCasesPrompt.Request> requestsInput
            = new List<OpenCasesPrompt.Request>();
        OpenCasesPrompt.Request request = new OpenCasesPrompt.Request();
        request.RelatedEntity = new Account();
        requestsInput.add(request);
        
        List<OpenCasesPrompt.Response> responses = 
            OpenCasesPrompt.getCasesPrompt(requestsInput);
        Assert.areEqual(1, responses.size());
       
        OpenCasesPrompt.Response response = responses[0];
        Assert.areEqual('There are no open cases.', response.Prompt);
    }
}
```

Now that the Apex class is ready, let’s call it from Prompt Builder. Before we can do that, we must create a custom field called Open Case Summary on the Account object. The custom field should have a data type of Text Area (Long). See [Create Custom Fields](https://help.salesforce.com/s/articleView?id=platform.adding_fields.htm&type=5&language=en_US). Log out and log in again so that you can see the new custom field in Prompt Builder.

In Prompt Builder, create a new prompt template.

1. For Prompt Template Type, select **Field Generation**.
2. For the Prompt Template Name, enter Apex: Summarize Open Cases.
3. For the Object, select **Account**.
4. For the Object Field, select **Open Case Summary**.
5. Leave the Description field blank.
6. Click **Create**, and you’re redirected to the Prompt Template Workspace.
7. In the [Example Prompt Template Library](https://help.salesforce.com/s/articleView?id=ai.prompt_builder_example_library.htm&release=264.0.0&type=5 "This library of example prompt templates gives you a starting point for creating your own custom prompt templates."), find the field generation prompt template: Summarize open cases for an account. Copy and paste this template into the Prompt Template Workspace.
8. Before you can run this template in Prompt Builder, in the Prompt section, click **Insert Resource**. The search field appears the first time you click this option.
    1. Delete the `<account.Id__Merge_Field>` placeholder.
    2. Click the **Resource** search bar, and select **Account** | **Account ID** .
    3. Delete the <Get\_Open\_Cases\_For\_Account\_\_Prompt\_\_Flow> placeholder.
    4. Click the **Resource** search bar, and select **Apex**.
    5. To add the OpenCasesPrompt Apex class to your template, select **Open Cases**. Open Cases is the label attribute that you set in the @InvocableMethod annotation in the OpenCasesPrompt Apex class.