Sub topic 8
Grounding with Apex
This chapter assumes you know basic Apex syntax, how a Flow resource feeds a prompt template, and how template inputs work. You will write an invocable Apex method that returns grounding text, then see how a template calls it.
When Apex fits
Merge fields read values that already exist on the input record or its parents. A Flow resource adds queries and branching. Apex is the option for cases that Flow handles poorly, such as:
- Queries with logic that is awkward to model in Flow, like sorting, limits, or string formatting across many rows.
- Reusable code that several templates share.
- Calls to existing Apex services in your org.
An Apex resource is an invocable method. Prompt Builder calls it with the input record, and the method returns text that the template inserts.
The shape of a grounding method
Prompt Builder finds your method through the @InvocableMethod annotation. The annotation's capabilityType attribute ties the method to a template type. The method has a fixed shape:
- It is
public staticand takes aListof a request class. - The request class has an
@InvocableVariablefield that receives the input record. For a field completion template on Case, this field is namedRelatedEntity. - It returns a
Listof a response class with aPromptstring field. The text inPromptis what lands in the template. - It must return one response per request, in the same order.
Worked example: open tasks for a case
The class below takes a case, queries its open tasks, and returns one line per task.
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;
}
}Three choices in this code matter:
with sharingandWITH USER_MODEmake the query respect the running user's record access, field-level security, and object permissions. Without them, the prompt could expose data the user cannot see.LIMIT 10keeps the grounding text small, which protects the prompt's size budget.- The fallback
'No open tasks.'gives the model an explicit statement instead of an empty string, so it does not invent tasks.
The query sits inside the loop over requests. That is simple, but it runs one query per request. If a caller can pass many records at once, collect the IDs first and query once. Prompt Builder usually sends one record, so this is a refinement rather than a bug.
Using the method in a template
In Prompt Builder, add the Apex class as a resource in the template. The resource then appears in the template's resource picker, and you insert it at the point where the data belongs. Write the instructions around it as you would for any other grounding data:
Summarize the case below for an agent taking over.
Case subject: {!$Input:Case.Subject}
Open tasks:
{!$Apex:CaseOpenTaskGrounding.Prompt}
If the task list says there are no open tasks, say so. Do not guess.The exact merge field syntax comes from the resource picker. Insert it from the picker instead of typing it, so the name matches what Prompt Builder generates for your class.
How the pieces connect
Common errors
| Symptom | Likely cause |
|---|---|
| The Apex resource does not appear in Prompt Builder | The method is missing `@InvocableMethod`, or its `capabilityType` does not match the template type. |
| Deployment or save fails on the class | The request or response class is not `public`, or its variables lack `@InvocableVariable`. |
| The resolved prompt shows an empty section | `Prompt` was left null, or the query returned nothing and no fallback was set. |
| Users see a query error or missing data | `WITH USER_MODE` blocked fields or objects the user cannot access. Check their permission sets. |
| Output is cut off or the prompt is rejected | The returned text is too large. Lower the `LIMIT` or select fewer fields. |
Test it
Write a unit test that creates a Case with open and closed tasks, calls getOpenTasks, and asserts on the Prompt string. Then use the template preview, covered in a later chapter, to check how the text looks in the full prompt.
Exercise
Why does the example return 'No open tasks.' when the query finds nothing, instead of returning an empty string?
Show answer
An empty string leaves a blank section in the prompt, and the model may fill the gap with invented tasks. An explicit statement tells the model the data is absent, so it can report that accurately.
Exercise
A teammate changes the query to run in system mode so it never fails on field access. What is the risk?
Show answer
The method would return data the running user is not allowed to see, and that data would appear in the generated text. User mode keeps the grounding within the user's own permissions.