Sub topic 3
Grounding with Apex
Assume you know Salesforce objects, relationships, Flow Builder, Apex syntax, and the basics of prompts. An Apex resource is an invocable Apex method that returns text for a prompt template. Use it when grounding needs complex queries, formatting, or logic that is difficult to express in merge fields or Flow.
This method accepts cases and returns their open tasks as prompt text:
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 task : tasks) {
lines.add('- ' + task.Subject
+ ' (due ' + String.valueOf(task.ActivityDate) + ')');
}
Response response = new Response();
response.Prompt = lines.isEmpty()
? 'No open tasks.'
: String.join(lines, '\n');
results.add(response);
}
return results;
}
}The invocable method must support a list of requests because Salesforce can call it in bulk. WITH USER_MODE makes the query respect the running user's object and field permissions.
Choosing between merge fields, Flow, and Apex
- Use merge fields for a few fields from the input record or related records.
- Use Flow when the template needs filters, loops, or several declarative queries.
- Use Apex when you need advanced queries, custom formatting, or logic that Flow cannot express easily.
Prefer the simplest resource that meets the requirement. Simpler resources are easier to maintain and review.
Previewing and testing the resolved prompt
Preview the template with representative records. Inspect the resolved prompt, not only the generated answer. Check that fields contain the expected values, related records are present, empty values are handled clearly, and Apex or Flow output appears in the intended location.
Test records should include normal data, missing values, no matching records, and users with different permissions.
Permissions, data quality, and size limits
Grounding does not repair incomplete CRM data. A blank description or stale task can produce a misleading answer. Limit returned records and format text predictably so the prompt remains within platform and model limits. Review object, field, and record access for every resource. Avoid inserting sensitive fields unless the template has a clear business need.
Exercise
Which resource should you choose for a template that needs the current record's Subject and Status only?
Show answer
Use merge fields because the values are direct fields and require no additional logic.