Sub topic 5
Grounding with related lists, Flow and Apex
This chapter assumes you can build a basic prompt template in Prompt Builder and insert merge fields from the record input, as covered in the previous chapter. It also assumes you know Apex basics (classes, SOQL, annotations) and have seen the Flow Builder canvas.
Why grounding matters
Grounding means putting real, current data into the prompt, so the model writes from facts instead of from its training data. A template that only inserts Case.Subject and Case.Description gives the model a thin view of the case. The model fills the gaps with plausible text, which is where wrong summaries come from.
Three sources extend the data beyond fields on the input record:
- Related lists pull child records, such as case comments or open tasks, directly from the record's relationships.
- Flow resources run an autolaunched flow and insert its text output.
- Apex resources run an invocable Apex method and insert its text output.
All three are resolved before the model is called. The agent never sees them as separate steps. When the template runs, Salesforce builds the full prompt text, applies the Trust Layer (covered in the next chapter), and sends the result to the model.
Choosing a grounding source
| Source | Best for | Cost of building | Main risk |
|---|---|---|---|
| Related list | Child records you can pick as they are | Lowest, no code | Too much text, or the wrong fields |
| Flow | Lookups, filtering, and light formatting an admin can maintain | Medium | Flow errors surface as an empty or failed prompt |
| Apex | Complex queries, aggregation, callouts, or custom formatting | Highest | Sharing and field access mistakes |
Start with the simplest source that works. Move to Flow when you need to filter or combine records, and to Apex when Flow gets awkward.
Related lists
A related list resource inserts child records of the input record. In the Prompt Builder editor, you open the resource picker, choose the record input, and pick a related list such as case comments. You then choose which fields to include for each child record.
Two choices decide whether the result is useful:
- Which fields. Include only fields the model needs. Each extra field adds tokens and noise. Internal IDs and system timestamps rarely help.
- How much data. A case with 200 comments can overflow the prompt or bury the useful part. Use the filtering and limit options the picker offers, where available in your release, to keep recent or relevant records only.
A related list renders as text inside the prompt, so label it clearly. Insert the merge field with the picker rather than typing it, so the syntax matches your org.
You are a service assistant. Prepare a hand-off note for the case below.
Case number: {!$Input:Case.CaseNumber}
Subject: {!$Input:Case.Subject}
Status: {!$Input:Case.Status}
Recent case comments (newest information is most important):
[related list for case comments, inserted with the resource picker]
Rules:
- Use at most five sentences.
- Base the note only on the data above. If the comments are empty, say that no comments exist.
- Do not promise refunds or dates.The bracketed line stands in for the merge field the picker generates. Note the rule about empty comments. Without it, a case with no comments invites the model to invent history.
Flow resources
A Flow resource runs an autolaunched flow and inserts its result. Use it when the data needs logic that a plain related list cannot express, such as "the three most recent open tasks owned by this case's owner" or "the entitlement status for this account."
Build the flow like this:
- Create an autolaunched flow, not a screen flow.
- Add an input variable for the record. Mark it Available for input. Its data type and object must match the template input.
- Use Get Records, Decision and Assignment elements to collect and shape the data.
- Build the result into a single text variable, usually with a text template element, and mark it Available for output.
- Save and activate the flow. A draft or inactive flow does not appear in the picker.
In the template, you add the flow through the resource picker and map the template's record input to the flow's input variable. The picker generates the merge field that inserts the flow's text output.
The flow returns text, so format it for the model. A short labeled list works better than raw field values:
Open tasks:
- Call customer back (due 2026-12-03)
- Send replacement part (due 2026-12-05)If the flow finds nothing, return an explicit line such as Open tasks: none. An empty string leaves the model with a heading and no data, and it may fill the gap.
Apex resources
An Apex resource calls an invocable method. Choose it when you need aggregation, multi-object queries, a callout, or formatting that is easier to write in code.
The method must be @InvocableMethod. It takes a list of request objects and returns a list of response objects, one for each request. The response carries the text the template inserts. This example builds a compact escalation summary for a case:
public with sharing class CaseEscalationContext {
public class Request {
@InvocableVariable(required=true label='Case ID')
public Id caseId;
}
public class Response {
@InvocableVariable(label='Prompt')
public String Prompt;
}
@InvocableMethod(label='Get Case Escalation Context'
description='Returns open task and comment counts for a case')
public static List<Response> getContext(List<Request> requests) {
Set<Id> caseIds = new Set<Id>();
for (Request r : requests) {
caseIds.add(r.caseId);
}
Map<Id, Integer> openTasks = new Map<Id, Integer>();
for (AggregateResult ar : [
SELECT WhatId caseId, COUNT(Id) total
FROM Task
WHERE WhatId IN :caseIds AND IsClosed = false
WITH USER_MODE
GROUP BY WhatId
]) {
openTasks.put((Id) ar.get('caseId'), (Integer) ar.get('total'));
}
Map<Id, Integer> comments = new Map<Id, Integer>();
for (AggregateResult ar : [
SELECT ParentId caseId, COUNT(Id) total
FROM CaseComment
WHERE ParentId IN :caseIds
WITH USER_MODE
GROUP BY ParentId
]) {
comments.put((Id) ar.get('caseId'), (Integer) ar.get('total'));
}
List<Response> responses = new List<Response>();
for (Request r : requests) {
Response resp = new Response();
resp.Prompt = 'Open tasks: '
+ (openTasks.containsKey(r.caseId) ? openTasks.get(r.caseId) : 0)
+ '\nCase comments: '
+ (comments.containsKey(r.caseId) ? comments.get(r.caseId) : 0);
responses.add(resp);
}
return responses;
}
}Points to check in this code:
- The method is bulkified. It runs two queries for the whole request list, not two per request.
with sharingandWITH USER_MODEmake the queries respect the running user's record access and field permissions. This matters because the generated text can reach people who should not see everything.- Every request gets exactly one response, in the same order, including cases with no data. A missing response breaks the mapping.
- The response variable is named
Prompt. Confirm in the resource picker that your org lists the class and shows this output. If the class does not appear, check that it is deployed and that the method is invocable.
Grounding when the agent calls the template
When an agent calls the template as an action, grounding happens inside that action. The agent supplies the input, such as a case ID. The template then resolves the related lists, Flow and Apex on its own. This has practical consequences:
- The model does not see the grounding logic. The agent's topic instructions cannot change which comments are fetched. Change the template for that.
- Access follows the running user. Check that the agent's running user can read the objects and fields the grounding uses. A missing field permission produces a thinner prompt, not always an obvious error.
- Each call costs time. Flow and Apex run on every invocation. A slow query makes the agent slow.
Common errors
- The flow or Apex class is missing from the picker. The flow is inactive or not autolaunched, or the Apex method is not invocable or not deployed.
- The prompt is too long. An unfiltered related list on a busy record. Limit the records and fields.
- The output has the wrong data for the record. The resource input is mapped to the wrong template input, or the Apex code queries without filtering on the supplied IDs.
- The summary invents details. The grounding returned empty text and the template had no "unknown" rule.
- Users see data they should not. The Apex runs in system mode. Use
with sharingandWITH USER_MODE. - Behavior changes after a flow edit. The template calls the active flow version, so a flow change affects the template immediately. Test the template again after any change to its resources.
Check your understanding
Exercise
A "Summarize Case" template uses a related list for case comments. The agent summarizes a brand-new case that has no comments, and the summary describes a customer complaint about delivery delays that is not in the case. Name the likely cause and two changes that reduce the risk.
Show answer
The related list returned nothing, and the template gave the model no instruction for that situation, so it filled the gap with invented content. Fixes: add a rule such as "If no comments exist, say that no comments exist and do not describe history", and make the grounding explicit by labeling the section so an empty section is clear. A Flow or Apex resource can also return an explicit "none" line instead of an empty string. Then test the template in preview against a case with no comments.
Exercise
You need the number of open tasks for the case plus the status of the related entitlement, formatted as two labeled lines. Which grounding source would you choose first, and when would you move to the other?
Show answer
Start with a Flow resource. Get Records and a text template can collect both values and format them without code, and an admin can maintain it. Move to Apex if the logic needs aggregation across many objects, a callout, or performance and bulk handling that the flow cannot provide cleanly.