Sub topic 12
Calling the same template from Flow and Apex
This chapter assumes you have built a prompt template in Prompt Builder and can activate a version of it. It also assumes you know basic Flow Builder (record-triggered and screen flows) and basic Apex syntax. The template here is the case summary template from earlier chapters, with its API name Summarize_Case.
Why reuse a template outside the agent
An agent action is one way to run a prompt template. The template itself is a separate, named metadata record. Anything that can reference it by API name can run it. That gives you three practical benefits:
- One source of wording. If legal changes the rule "Do not promise refunds or dates", you edit one template version. The agent, the flow and the Apex class all pick it up.
- One place to test. You already tested the template in Prompt Builder. Callers only need to prove they pass the right input.
- Non-conversational use. Some jobs have no conversation. For example, you may want to write a summary into a field when a case closes. A flow or a trigger is a better fit than an agent for that.
The agent is a caller that decides when to run the template based on a conversation. Flow and Apex are callers that decide based on data changes, button clicks or schedules.
What stays the same for every caller
Regardless of the caller, these things apply:
- The input contract. The template declares inputs, such as
Input:Casein the template body{!$Input:Case.CaseNumber}. Each caller must supply a value for each input, and the value must match the declared type. For a record input, the caller passes the record or its ID. - The active version. Calls by API name run the active version. Draft versions and inactive versions are not used. If nobody activated a version, the call fails.
- The Trust Layer. Masking, prompt defense and audit settings apply to every call, because they sit between the template and the model.
- Grounding. Merge fields, related lists, Flow resources and Apex resources inside the template resolve the same way. They run with the context of the calling user, so field-level and object permissions can change what data the template sees.
Two things differ between callers: how you pass inputs, and what you do with the output.
Calling the template from Flow
In Flow Builder, a prompt template appears as an action. The exact menu labels change between releases, so look for it this way:
- Add an Action element to the flow.
- Search for or browse the prompt template category and pick Summarize Case (the label of the template).
- In the action's input section, set each template input. For the
Caseinput, map the record variable, for example{!$Record}in a record-triggered flow, or aGet Recordsresult. - Store the output in a variable. The action returns the generated text as its output, which you can map to a text variable and then use in later elements.
A typical use is a record-triggered flow on Case that fires after status changes to Closed:
- Entry condition:
StatusequalsClosed, and the run is optimized for actions and related records. - Action: Summarize Case, with
Caseset to{!$Record}. - Update Records: write the output into a long text field such as
Closing_Summary__con the case.
Some points need care:
- Record-triggered flows and callouts. Generating text takes a model call, so run it in an asynchronous path of the flow (the "Run Asynchronously" path) rather than in the same transaction as the save. This keeps the save fast, and a slow model response does not block users.
- Fault paths. Add a fault connector on the action. Model calls can fail, for example when the template has no active version or the user lacks permission. Decide what the flow does then: log the error, set a flag field, or skip.
- Saving output. The output is text, so check it fits the target field length. A five-sentence summary is short, but a missing "at most five sentences" rule could produce more than you expect.
- Screen flows. Here you can show the output in a display text component and let the user edit it before saving. This is a good pattern when a human must review generated text.
Calling the template from Apex
Apex uses the ConnectApi.EinsteinLlm class. Three steps are involved: build the input object, call generateMessagesForPromptTemplate with the template's API name, and read the generations.
The version below wraps the call in a small service class so triggers, controllers and tests all share one entry point.
public with sharing class CaseSummaryService {
public class SummaryException extends Exception {}
public static String summarize(Id caseId) {
ConnectApi.EinsteinPromptTemplateGenerationsInput input =
new ConnectApi.EinsteinPromptTemplateGenerationsInput();
input.isPreview = false;
input.additionalConfig = new ConnectApi.EinsteinLlmAdditionalConfigInput();
input.additionalConfig.applicationName = 'PromptBuilderPreview';
ConnectApi.WrappedValue caseValue = new ConnectApi.WrappedValue();
caseValue.value = new Map<String, String>{ 'id' => caseId };
input.inputParams = new Map<String, ConnectApi.WrappedValue>{
'Input:Case' => caseValue
};
ConnectApi.EinsteinPromptTemplateGenerationsRepresentation result =
ConnectApi.EinsteinLlm.generateMessagesForPromptTemplate(
'Summarize_Case', input);
if (result == null || result.generations == null || result.generations.isEmpty()) {
throw new SummaryException('No generation returned for case ' + caseId);
}
return result.generations[0].text;
}
}Read the important lines:
'Summarize_Case'is the API name of the template, not its label. If you rename the label, nothing breaks. If you change the API name, the Apex call fails.'Input:Case'is the key for the template input. It is the same name as the$Input:Casepart of the merge fields{!$Input:Case.CaseNumber}. The key must match exactly.- The value is a map with an
identry. The template loads the record itself, so the Apex code does not need to query the fields. That also means the template's merge fields respect the running user's access. isPreview = falsemeans the call generates text. Withtrue, the call returns the resolved prompt without sending it to the model, which is useful when you want to inspect what a call would send.result.generations[0].textis the first generated answer. The null and empty checks give you a clear error instead of aNullPointerExceptionlater.
Using the service
A small example from an Apex action or anonymous Apex:
Case c = [SELECT Id FROM Case WHERE Status = 'Closed' LIMIT 1];
String summary = CaseSummaryService.summarize(c.Id);
System.debug(summary);Where to be careful in Apex
- Do not call it per record in a loop or a synchronous trigger. Each call is a model round trip. For many records, use a Queueable or Batch Apex class and keep batch sizes small. Check the current limits for your org before sizing batches.
- Testing. Unit tests cannot rely on a live model. Keep the
ConnectApicall inside one method, as the service does above, so you can replace or isolate it in tests. Test the logic around it, such as what you do when the text is empty. - Permissions. The running user needs access to the template and the data it grounds on. If an Apex class runs as a system user, the template may see more data than an agent user would. Use
with sharingand decide on purpose whose access applies.
Choosing between agent, Flow and Apex
| Situation | Best caller | Reason |
|---|---|---|
| A user asks for a summary in a conversation | Agent action | The topic instructions decide when to run it |
| Write a summary to a field when a case closes | Record-triggered Flow | No conversation, declarative, easy for admins to maintain |
| A user clicks a button and reviews the text | Screen Flow | A person can edit the output before it is saved |
| Bulk processing, custom retry logic or integration code | Apex (Queueable or Batch) | Full control over batching and error handling |
Changing the template safely when many callers use it
Reuse brings a risk: one edit changes several behaviors. Follow these habits:
- Treat inputs as a public contract. Adding an optional input is usually safe. Renaming or removing an input breaks every caller that passes it.
- Create a new version, test it, then activate it. Activation switches all callers at the same moment, so test with the Flow and Apex inputs as well as the agent's.
- Keep output shape stable. A flow that stores text in a 255-character field and an agent that quotes the text have different tolerance for length changes. If callers need different output shapes, make a second template instead of one that tries to do both.
- Name callers in your documentation. Keep a list of which agents, flows and classes use each template, so you know what to retest.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Apex throws an error naming the template | Wrong API name, or no active version | Check the API name in Prompt Builder and activate a version |
| Output says fields are unknown or empty | Input key mismatch, or the user cannot read the fields | Match `Input:Case` to the template and check field access |
| Flow save feels slow | Model call runs in the save transaction | Move the action to the asynchronous path |
| Text is cut off in the saved field | Output longer than the field | Tighten the rules in the template or use a long text field |
| Agent and flow give different tone | Callers use different versions or different inputs | Compare the inputs sent and the active version |
Exercise
A record-triggered flow on Case calls the Summarize Case template when Status changes to Closed. Users complain that closing a case takes several seconds. What should you change, and what should you add so a failed model call does not lose the case update?
Show answer
Move the prompt template action to the flow's asynchronous path so the model call runs after the save instead of inside it. Add a fault connector on the action that records the failure, for example by setting a flag field or creating a log record. The case update itself is then already saved, and a failed summary does not roll it back.
Exercise
Your Apex call to generateMessagesForPromptTemplate fails after an admin renames the template's label from "Summarize Case" to "Case Summary". Is the label change the cause? Name two things you would check.
Show answer
Probably not. Apex uses the API name (Summarize_Case), not the label, so a label change alone does not break the call. Check that the API name did not change and that the template still has an active version. Also check that the input key Input:Case still matches the template's declared input.