Sub topic 8
Grounding with Apex
This chapter assumes you have read the chapters on merge fields and Flow grounding. It also assumes you can read and write basic Apex: classes, SOQL, collections, and annotations. You should know how a prompt template receives its input record.
When Apex is the right resource
Merge fields read stored values. A Flow resource can query records and branch on conditions. Some grounding needs more than that:
- Aggregating, sorting, or filtering across many records in ways that are awkward to build in Flow.
- Calling shared Apex logic that already exists, such as a scoring or formatting utility.
- Building a text block with precise formatting, such as a numbered list, a truncated list, or a localized date.
- Reaching data through a callout or an integration service that your team already wraps in Apex.
An Apex resource is an invocable method that receives the template's input record and returns text. Prompt Builder inserts that text into the prompt wherever you place the resource.
How the pieces connect
The method must follow a fixed contract. Prompt Builder only offers Apex classes that meet it.
- The class has one method annotated with
@InvocableMethod. - The method takes a
Listof a request class and returns aListof a response class. - The request class has an
@InvocableVariablenamedRelatedEntity. It holds the record that anchors the template, such as aCase. - The response class has an
@InvocableVariablenamedPromptof typeString. That string is the text inserted into the prompt. - The
capabilityTypeattribute names the template type that may use the method.
A first working example
This is the class from the chapter plan. It reads open tasks for each case and returns a bulleted text block.
public with sharing class CaseOpenTaskGrounding {
public class Request {
@InvocableVariable(required=true)
public Case RelatedEntity;
}
public class Response {
@InvocableVariable
public String Prompt;
}
@InvocableMethod(
label='Get open tasks for case'
capabilityType='PromptTemplateType://einstein_gpt__fieldCompletion'
)
public static List<Response> getOpenTasks(List<Request> requests) {
List<Response> results = new List<Response>();
for (Request req : requests) {
List<Task> tasks = [
SELECT Subject, ActivityDate
FROM Task
WHERE WhatId = :req.RelatedEntity.Id AND IsClosed = false
WITH USER_MODE
LIMIT 10
];
List<String> lines = new List<String>();
for (Task t : tasks) {
lines.add('- ' + t.Subject + ' (due ' + String.valueOf(t.ActivityDate) + ')');
}
Response res = new Response();
res.Prompt = lines.isEmpty() ? 'No open tasks.' : String.join(lines, '\n');
results.add(res);
}
return results;
}
}Several details matter here.
with sharingandWITH USER_MODE. The class respects record sharing. The query also enforces object and field permissions of the running user. If the user cannot read a task, that task never reaches the prompt. This is the behavior you want for grounding.capabilityType. The valuePromptTemplateType://einstein_gpt__fieldCompletionmakes the method available to field generation templates. Other template types use their own identifiers, so match the value to the template type you build. If the method does not appear in the resource picker, check this attribute first.- The returned text. The method returns exactly the string you build. Prompt Builder does not add labels or formatting, so the empty case and the layout are your job.
Referencing the resource in a template
After the class is saved, open the template in Prompt Builder and insert the Apex resource through the resource picker. The inserted reference uses the $Apex prefix and the class name, in the same style as the Flow reference. Let the picker write it for you instead of typing it by hand.
You are a support assistant. Write a two-sentence status note for an agent taking over.
Case subject: {!$Input:Case.Subject}
Status: {!$Input:Case.Status}
Open tasks:
{!$Apex:CaseOpenTaskGrounding.Prompt}
Base the note only on the information above. If the task list says there are no open tasks, say so.Keep the instruction about the empty case in the template, and keep the empty-case text in Apex. Both together mean the model sees a clear statement instead of a blank gap.
Fixing the bulk problem
The first example runs a query inside a loop. Prompt Builder normally calls the method with a single request. Other callers, such as a Flow that invokes the same method for a list of records, can pass many. A query per request can hit the governor limit on SOQL queries, which fails the whole transaction.
The bulk-safe version collects all case IDs, runs one query, and groups the results.
public with sharing class CaseOpenTaskGrounding {
private static final Integer MAX_TASKS_PER_CASE = 10;
public class Request {
@InvocableVariable(required=true)
public Case RelatedEntity;
}
public class Response {
@InvocableVariable
public String Prompt;
}
@InvocableMethod(
label='Get open tasks for case'
capabilityType='PromptTemplateType://einstein_gpt__fieldCompletion'
)
public static List<Response> getOpenTasks(List<Request> requests) {
Set<Id> caseIds = new Set<Id>();
for (Request req : requests) {
caseIds.add(req.RelatedEntity.Id);
}
Map<Id, List<String>> linesByCase = new Map<Id, List<String>>();
for (Task t : [
SELECT Subject, ActivityDate, WhatId
FROM Task
WHERE WhatId IN :caseIds AND IsClosed = false
WITH USER_MODE
ORDER BY ActivityDate ASC NULLS LAST
LIMIT 2000
]) {
List<String> lines = linesByCase.get(t.WhatId);
if (lines == null) {
lines = new List<String>();
linesByCase.put(t.WhatId, lines);
}
if (lines.size() < MAX_TASKS_PER_CASE) {
String due = t.ActivityDate == null
? 'no due date'
: 'due ' + String.valueOf(t.ActivityDate);
lines.add('- ' + t.Subject + ' (' + due + ')');
}
}
List<Response> results = new List<Response>();
for (Request req : requests) {
List<String> lines = linesByCase.get(req.RelatedEntity.Id);
Response res = new Response();
res.Prompt = (lines == null || lines.isEmpty())
? 'No open tasks.'
: String.join(lines, '\n');
results.add(res);
}
return results;
}
}Three changes are worth noting:
- One query serves every request. The per-case cap moves into the loop, because
LIMITin SOQL applies to the whole result set. ORDER BY ActivityDate ASC NULLS LASTputs the most urgent tasks first, so the cap drops the least urgent ones.- A task with no due date prints
no due dateinstead ofdue null. Anullleaking into a prompt gives the model a confusing token to interpret.
The response list must be in the same order as the request list, and it must have the same length. The final loop guarantees both.
Handling errors and slow work
Apex runs inside the user's request, and the user may be waiting for the template to resolve. Keep these rules in mind.
- Fail soft where you can. If an optional lookup finds nothing, return a plain sentence. Reserve exceptions for conditions that really mean the prompt cannot be built.
- Avoid callouts you do not need. An external service adds latency and a new failure mode. If the data can be copied into Salesforce on a schedule, grounding from the copy is faster and more predictable.
- Respect governor limits. Query counts, rows, and CPU time all apply to the invocation. Use
LIMITand filters so a record with thousands of related rows does not stall the prompt. - Keep output short. The returned text becomes part of the prompt. Long output takes space from the instructions and from the model's reply, and it raises cost. Return the few rows that matter, not every row.
Testing the class
Write an Apex test before you wire the class into a template. It pins the contract, covers the empty case, and runs the user-mode query.
@IsTest
private class CaseOpenTaskGroundingTest {
@IsTest
static void returnsOpenTasksAsBullets() {
Case c = new Case(Subject = 'Printer down');
insert c;
insert new Task(
Subject = 'Call customer',
WhatId = c.Id,
ActivityDate = Date.today().addDays(2)
);
CaseOpenTaskGrounding.Request req = new CaseOpenTaskGrounding.Request();
req.RelatedEntity = c;
List<CaseOpenTaskGrounding.Response> res =
CaseOpenTaskGrounding.getOpenTasks(
new List<CaseOpenTaskGrounding.Request>{ req });
System.assertEquals(1, res.size());
System.assert(res[0].Prompt.contains('Call customer'));
}
@IsTest
static void returnsFallbackWhenNoTasks() {
Case c = new Case(Subject = 'No tasks here');
insert c;
CaseOpenTaskGrounding.Request req = new CaseOpenTaskGrounding.Request();
req.RelatedEntity = c;
List<CaseOpenTaskGrounding.Response> res =
CaseOpenTaskGrounding.getOpenTasks(
new List<CaseOpenTaskGrounding.Request>{ req });
System.assertEquals('No open tasks.', res[0].Prompt);
}
}An Apex test confirms the text the method returns. It does not confirm what the prompt looks like once the text is inserted. For that, use the template preview, covered in a later chapter.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| The class is missing from the resource picker | The `capabilityType` does not match the template type, or the request and response classes lack the expected variables | Match the type string, and confirm `RelatedEntity` and `Prompt` exist and are annotated |
| Preview shows empty text where the resource should be | The method returned an empty string, or the user cannot read the queried records | Return an explicit fallback sentence, and preview as a user with realistic permissions |
| `Too many SOQL queries` | A query inside the request loop | Collect IDs first and run one query |
| The prompt says `due null` | `String.valueOf` on a null date | Test for `null` and write a readable phrase |
| The model repeats raw formatting or odd tokens | Output includes IDs, API names, or markup | Return only the human-readable values the model needs |
| Different users see different grounding | `with sharing` and `WITH USER_MODE` enforce each user's access | This is expected. Test with the profiles that will use the template |
Design checklist
- Return plain text, one idea per line, with a short label if the text mixes several kinds of data.
- Cap the number of rows and the length of long text fields.
- Always return a sentence for the empty case, and tell the model in the template how to treat it.
- Keep the class small. If it needs a lot of logic, move that logic to a service class and call it from the invocable method.
- Write a test for the empty case, the normal case, and a case with more rows than your cap.
Exercise
Your invocable method runs SELECT ... FROM Task WHERE WhatId = :req.RelatedEntity.Id inside a for loop over requests. It works in preview, but a Flow that calls it for 250 cases fails with a governor limit error. What is wrong, and how do you fix it? Also name one way to keep the returned text from showing due null.
Show answer
The query runs once per request, so 250 requests use 250 queries and exceed the SOQL query limit. Collect all case IDs into a Set, run one query with WHERE WhatId IN :caseIds, group the tasks by WhatId in a Map, then build one Response per Request in the original order. Because LIMIT applies to the whole query, cap the rows per case in the loop. To avoid due null, check ActivityDate == null and write a readable phrase such as "no due date" instead of calling String.valueOf on a null.
Exercise
A teammate says the Apex class compiles and its tests pass, but it does not appear when they search for resources in Prompt Builder. Give two things to check.
Show answer
First, check that the capabilityType on the @InvocableMethod matches the type of the template, for example PromptTemplateType://einstein_gpt__fieldCompletion for a field generation template. Second, check that the request class has an @InvocableVariable named RelatedEntity and the response class has one named Prompt, and that the method takes and returns lists of those classes.