Sub topic 9
Choosing Between Merge Fields, Flow, and Apex
By now you have seen three ways to put CRM data into a prompt template in Prompt Builder. Merge fields insert field values from the input record and its parents. A Flow resource runs an autolaunched flow and inserts its text output. An Apex resource calls an invocable method and inserts the string it returns. This chapter gives you a way to pick among them for a given grounding need, and shows what goes wrong when you pick badly.
Prerequisites assumed
- You can read a prompt template that uses merge fields such as
{!$Input:Case.Subject}. - You know how to build a simple autolaunched flow with Get Records and Assignment elements.
- You can read Apex, including SOQL,
with sharing, and annotations. - You know that the template's input record anchors everything else in the template.
The core idea: use the simplest tool that works
All three options end the same way. At run time, Prompt Builder replaces each placeholder with text, and the model receives one resolved prompt. The options differ in cost to build, cost to maintain, and how much logic they can express.
Choose in this order:
- If the data is a field on the input record, or on a record reachable by lookup from it, use a merge field.
- If the data needs a query, filtering, a loop, or a calculation that an admin should be able to maintain, use Flow.
- If the logic is too complex for Flow, or needs code-level control, use Apex.
Each step up adds build effort, testing effort, and a new component that someone has to own. Move up only when the step below cannot do the job.
| Need | Merge field | Flow | Apex |
|---|---|---|---|
| Field on the input record | Best fit | Overkill | Overkill |
| Field on a parent record (Account, Contact) | Best fit | Overkill | Overkill |
| List of child records (open tasks, recent orders) | Not possible | Good fit | Good fit |
| Filtering or sorting a list before display | Not possible | Good fit | Good fit |
| Simple calculation or text formatting | Not possible | Good fit | Good fit |
| Complex aggregation, ranking, or multi-step logic | Not possible | Gets awkward | Good fit |
| Callouts to external systems | Not possible | Possible, with care | Possible, with care |
| Maintained by admins without code | Yes | Yes | No |
| Needs deployment and test coverage | No | Flow activation only | Apex tests required |
When merge fields are enough
A merge field is a direct read of a value. There is no query to write and no logic to debug. The first example from this tutorial uses only merge fields:
You are a support assistant. Summarize the case below in two sentences for an agent taking over.
Case subject: {!$Input:Case.Subject}
Status: {!$Input:Case.Status}
Priority: {!$Input:Case.Priority}
Description: {!$Input:Case.Description}
If a value above is empty, say it is not provided. Do not guess.Relationship fields extend that reach to parents without extra components:
Customer account: {!$Input:Case.Account.Name}
Account industry: {!$Input:Case.Account.Industry}
Contact: {!$Input:Case.Contact.Name}Merge fields can follow lookups upward from the input record. They cannot walk downward to a list of children, and they cannot filter. If you catch yourself wishing for "the latest three orders", you have reached the limit of merge fields.
Strengths of merge fields:
- They are visible in the template text, so a reviewer sees exactly what the model receives.
- They have nothing to deploy beyond the template itself.
- They are the easiest to preview and to explain to an auditor.
Weaknesses:
- Values are inserted as they are stored. A date field or a picklist API value may read badly in a sentence.
- An empty field produces empty text, so your instructions must tell the model what to do about it, as the first example does.
- Long text fields such as Description can be large and noisy.
When to move to Flow
Use a Flow resource when the data comes from a query or needs light logic. The template line is short:
Recent order history:
{!$Flow:Get_Recent_Orders.Prompt}The flow does the work. A typical Get_Recent_Orders flow receives the input record, uses Get Records to find the most recent orders for the account, loops over them to build one text line per order, and returns the whole block in a text output variable named Prompt. The template inserts that text where the placeholder sits.
Choose Flow when:
- The data lives in child or unrelated records, such as orders, tasks, or cases.
- You need to filter, for example "only open", "only the last 90 days", or "only the top five".
- You want to format values, such as turning a date into a readable string or a number into a currency phrase.
- The people who will maintain the logic are admins who already work in Flow Builder.
Flow gives you a middle path. The logic is visible on the canvas, versioned, and changeable without a deployment pipeline. The cost is that complex logic in Flow gets hard to read. A flow with several nested loops and many variables is a sign that the problem may belong in Apex.
A flow resource also needs a contract with the template. The flow must be an autolaunched flow, it must accept the input record through a variable the template can supply, and it must return the text through the output variable that the template references. If the names or types do not line up, the resource fails to resolve or resolves to nothing.
When to move to Apex
Use an Apex resource when the logic is beyond what Flow handles cleanly, or when you need code-level control. The example from this tutorial queries open tasks for a case:
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;
}
}Note that this particular job could be done in Flow. Open tasks for a record, capped at ten, is a standard Get Records plus loop. The example shows the Apex contract, not a case where Apex is required. In a real project you would likely build this one in Flow.
Apex earns its place when you need things like these:
- Aggregation or ranking that would take many flow elements, such as scoring orders by recency and value and showing the top three.
- Queries whose shape depends on runtime data in ways Get Records cannot express.
- Shared logic that other Apex code already uses, so the prompt and the rest of the system agree.
- Unit tests that pin down behavior, including edge cases such as an empty result.
- Processing many records efficiently in one call, since an invocable method receives a list of requests.
The costs are real. Apex needs developers, test coverage, and a deployment process. It is also the place where security mistakes are easiest. The example uses with sharing and WITH USER_MODE so the query respects the running user's record access and field-level security. Leave those out and the template can show data the user could not see anywhere else in Salesforce.
A decision path
The diagram turns the order of preference into questions you can ask about a grounding need.
The last question in the diagram matters. Your first choice does not have to be final. A flow that started simple can outgrow itself, and the template does not care. The template line changes from {!$Flow:...} to the Apex form, and the rest of the prompt stays the same.
Worked scenarios
Scenario 1: Summarize a case
The agent needs the subject, status, priority, and description. All four are fields on the input case. Use merge fields. Adding a flow here would add a component to maintain and no new data.
Scenario 2: Draft an email to the account contact
You need the contact's name, the account name, and the account industry. These are one hop away through lookups. Use relationship merge fields such as {!$Input:Case.Contact.Name}. Still no flow needed.
Scenario 3: Mention the customer's last five orders
Orders are child records, and you want a capped, sorted list. Merge fields cannot do this. Build a flow that queries orders, sorts by date, limits to five, and builds a text block. Use {!$Flow:Get_Recent_Orders.Prompt}.
Scenario 4: Rank accounts' open opportunities by weighted risk
The calculation combines stage, amount, age, and a custom scoring rule that other code already implements in Apex. Reimplementing it in Flow would duplicate logic and invite drift. Call the existing logic from an invocable Apex method and use the Apex resource.
Scenario 5: A mix
A real template often uses all three. Merge fields supply the case basics, a flow supplies order history, and an Apex method supplies a computed risk summary. Each resource fills its own placeholder, and the placeholders can sit in the same template. Mix them freely, but keep each one doing the simplest job it can.
Common errors when choosing
- Reaching for Apex first. Developers often do this because it feels most flexible. It also has the highest maintenance cost, and admins cannot adjust it.
- Using a flow for a plain field. A flow whose only job is to return
Case.Subjectadds an indirection and a failure point for nothing. - Dumping a raw list. A resource that returns every related record produces a huge prompt. Cap the count and select only the fields the model needs.
- Returning unlabeled text. A block of lines with no heading or context is hard for the model to interpret. Put a label in the template, as in
Recent order history:above, and keep line formats consistent. - Skipping the empty case. If a query returns nothing, return a clear phrase such as
No open tasks., as the Apex example does. An empty string leaves a label with no content, and the model may fill the gap with an invention. - Ignoring running-user security. A Flow running in system context or Apex without
with sharingcan expose data the user cannot normally see. Decide on purpose which context each resource runs in. - Mismatched contracts. The input variable type, the output variable name, and the template reference all have to agree. Most "my resource returns nothing" problems are a name or type that does not match.
Checking your choice in preview
Whichever resource you choose, confirm it in the template preview. Select a real record, resolve the prompt, and read the final text. Check three things:
- Each placeholder was replaced with the content you expected.
- The size is reasonable, with no long lists or large text fields that crowd out your instructions.
- The empty and edge cases read well, which you can test by previewing against a record that has no orders or no tasks.
Preview shows you the cost of your choice directly. A merge field shows up as a short value. A flow or Apex resource shows up as a block, and you can judge whether that block is worth its tokens and its upkeep.
Summary of trade-offs
| Factor | Merge field | Flow | Apex |
|---|---|---|---|
| Build effort | Lowest | Moderate | Highest |
| Who maintains it | Anyone who edits the template | Admins | Developers |
| Expressive power | Fields and parent lookups only | Queries, loops, formatting | Full code |
| Testing | Preview | Preview and flow debug | Preview and Apex tests |
| Main risk | Raw, unformatted values | Complexity creep | Security and deployment overhead |
Exercise
A template for a sales assistant needs (a) the opportunity name and stage from the input record, (b) the owning account's industry, and (c) the three most recent closed-won opportunities for the same account, sorted by close date. Which resource would you use for each part, and why?
Show answer
Use merge fields for (a) and (b). Name and stage are fields on the input opportunity, and industry is reachable through the relationship, for example {!$Input:Opportunity.Account.Industry}. For (c), use a Flow resource. The data is a filtered, sorted, capped list of other records, which merge fields cannot produce, but the logic (Get Records with a filter, sort, and limit, then a loop to build text) fits comfortably in Flow. Move to Apex only if the ranking logic becomes too complex for the flow.
Exercise
A flow referenced from a template previews as an empty line under the heading "Open tasks:". The flow works when debugged on its own and finds tasks. Name two likely causes and one change that makes the template more robust.
Show answer
Likely causes include a mismatch between the flow's output variable name and the name used in the template reference (the template expects Prompt), and an input variable whose name or type does not match what the template passes in, so the query runs against the wrong or a missing record. A third possibility is that the running user lacks access to the task records. To make the template robust, have the flow return a clear phrase such as "No open tasks." when nothing is found, and add an instruction in the template for what to say when a section is empty.
Exercise
Your team has a complex Apex scoring class used by several features. A product owner asks for the same score in a prompt template. Should you rebuild the logic in Flow? Explain.
Show answer
No. Rebuilding the logic in Flow would duplicate it and risk the two versions drifting apart. Wrap the existing logic in an invocable Apex method that returns the score as text in a Prompt output, keep with sharing and user-mode access, and reference it as an Apex resource in the template. The shared code stays in one place and has one set of tests.