Sub topic 14
Combining flows with Apex, subflows, and prompt templates
This chapter covers three ways to extend a flow-based agent action when a single autolaunched flow is not enough. It assumes you can build an autolaunched flow with input and output variables, register it in Agent Builder, and read a fault path. It also assumes you know basic Apex syntax. If those are new, review the earlier chapters first.
Why composition matters
A flow registered as an action should do one job and return a result the agent can explain. Real jobs often need more than Flow does well on its own:
- Apex handles logic that is awkward or slow in Flow, such as complex calculations, callouts with custom parsing, or bulk-safe processing.
- Subflows let you reuse a tested piece of flow logic in several actions without copying it.
- Prompt templates let the flow call a large language model (LLM) to generate or summarize text, such as a customer-friendly explanation built from record data.
The agent still sees only one action. It reads the top-level flow's name, description, inputs, and outputs. Everything you compose underneath is hidden from the agent. This is useful, but it means the top-level flow's descriptions must cover the combined behavior.
Calling Apex from a flow
Flow can call Apex through an invocable method. This is a static method marked with @InvocableMethod. The flow's Action element then lists it by its label. Rules to remember:
- Only one
@InvocableMethodis allowed per class. - The method takes a
Listand returns aList, because Flow can call it with several records at once. The returned list must have the same size and order as the input list. - To pass several values, wrap them in an inner class whose fields are marked
@InvocableVariable. - The
labelanddescriptionon both the method and the variables show up in Flow Builder. Write them as you would write flow variable descriptions.
The class below raises a case's priority to High. It returns a success flag and a message for each request instead of throwing, so the flow can report a problem to the agent.
public with sharing class CaseEscalationHelper {
public class Request {
@InvocableVariable(
label='Case Id'
description='The Id of the case to escalate.'
required=true
)
public Id caseId;
}
public class Result {
@InvocableVariable(
label='Success'
description='True if the case was escalated.'
)
public Boolean success;
@InvocableVariable(
label='Message'
description='A short message describing the outcome.'
)
public String message;
}
@InvocableMethod(
label='Escalate Case'
description='Sets the priority of each given case to High.'
)
public static List<Result> escalate(List<Request> requests) {
Set<Id> ids = new Set<Id>();
for (Request r : requests) {
if (r.caseId != null) {
ids.add(r.caseId);
}
}
Map<Id, Case> cases = new Map<Id, Case>(
[SELECT Id, Priority FROM Case WHERE Id IN :ids WITH USER_MODE]
);
List<Case> toUpdate = new List<Case>();
for (Case c : cases.values()) {
c.Priority = 'High';
toUpdate.add(c);
}
Map<Id, String> errors = new Map<Id, String>();
List<Database.SaveResult> saves =
Database.update(toUpdate, false, AccessLevel.USER_MODE);
for (Integer i = 0; i < saves.size(); i++) {
if (!saves[i].isSuccess()) {
errors.put(toUpdate[i].Id, saves[i].getErrors()[0].getMessage());
}
}
List<Result> results = new List<Result>();
for (Request r : requests) {
Result res = new Result();
if (r.caseId == null || !cases.containsKey(r.caseId)) {
res.success = false;
res.message = 'No accessible case was found for that Id.';
} else if (errors.containsKey(r.caseId)) {
res.success = false;
res.message = errors.get(r.caseId);
} else {
res.success = true;
res.message = 'The case priority is now High.';
}
results.add(res);
}
return results;
}
}In the flow, add an Action element, choose Escalate Case, map the case Id into caseId, and store the returned success and message values in flow variables. Then branch on success with a Decision element and copy message into the flow's output variable. The agent gets a plain sentence either way.
Choosing between Flow-only and Apex
| Situation | Better choice |
|---|---|
| Look up a record, check a field, update it | Flow only |
| Branching on a few field values | Flow only |
| Heavy loops, string parsing, or math across many records | Apex |
| HTTP callout needing custom authentication or response parsing | Apex (or an external service action if one fits) |
| Logic that admins need to maintain | Flow, with Apex only for the hard part |
| Logic a developer needs unit tests for | Apex |
Apex also has direct registration as an agent action, with no flow in between. Wrapping it in a flow is still useful when you want a Decision element, a fault path, or a prompt template step around the Apex call.
Common Apex errors
- Returning a list of the wrong size. Flow expects one result per request. A mismatch causes a runtime error, so always build one result per input.
- Unhandled exceptions. An uncaught exception ends the flow interview. The agent then receives a generic failure and cannot tell the user what went wrong. Catch expected errors and return them as data.
- Queries or DML inside a loop over
requests. Flow can batch calls, so a per-request query will hit governor limits. Collect Ids first, query once, as the example does. - Missing descriptions. Variables without labels or descriptions are hard to map in Flow Builder.
Reusing logic with subflows
A subflow is an autolaunched flow that another flow calls with the Subflow element. Use one when two or more actions need the same steps, for example finding a contact by email, or checking whether a case is open.
Design rules:
- Mark the subflow's variables as available for input or output, just as you do for an action. The parent flow can only see variables with those settings.
- Keep the subflow free of agent-facing wording. Its descriptions are for builders, not for the LLM.
- Give the subflow its own fault path, and return a status variable the parent can check. A subflow that fails with an unhandled fault stops the whole interview.
- Activate the subflow before activating the parent. A parent that references an inactive or missing subflow cannot be activated.
A parent flow can reference a specific version of the subflow or the active one. Referencing the active version means a change to the subflow changes every action that uses it. That helps with a shared fix, and it is a risk if you edit a subflow without retesting the actions that call it.
| Concern | Subflow | Copied elements |
|---|---|---|
| Fixing a bug once | One change | Change in each flow |
| Testing | Test the subflow, then each parent | Test each flow |
| Risk of unexpected side effects | Higher, shared by all callers | Lower, isolated |
| Debugging | Interview log shows nested steps | All steps in one flow |
Generating text with prompt templates
A prompt template is a reusable instruction for an LLM, created in Prompt Builder. It can include merge fields, so the prompt is filled in with record data at run time. Flow Builder lists prompt templates as actions you can add to a flow. The template's inputs become the action's inputs, and the generated text comes back as an output you can store in a variable.
Typical uses inside an agent action:
- Summarize a case's history into two sentences for the customer.
- Draft a short reply that includes order details.
- Turn raw fields into a plain-language explanation.
A pattern that works well:
- The flow looks up the record with Get Records.
- The flow passes the record, or fields from it, into the prompt template action.
- The flow copies the generated text into an output variable such as
summaryText. - The agent reads
summaryTextand replies, usually as written.
You might wonder why the agent does not write the summary itself. The answer is control. A prompt template lets you fix tone, length, and what the model may use as grounding data, and you can test it separately in Prompt Builder. The agent's own reply is shaped by its topic instructions, which are broader.
Gotchas with prompt templates
- Generated output is not deterministic. Do not use it as input to a Decision element that controls updates. Branch on record fields, not on generated text.
- Grounding depends on what you pass in. If the template receives an empty record, the model will produce something generic. Check for a failed Get Records before calling the template.
- Access rules still apply. The template sees only what the running user's context lets it see. Review the earlier chapter on run context before adding templates that reference sensitive fields.
- Extra latency and cost. Each template call adds a model request. Do not call one in a loop.
- Licensing and availability. Prompt Builder requires the right Einstein or Agentforce licenses, and a template may not be available in every org. Check your org's setup before designing around it.
Keeping the composed action understandable
Composition changes how you test and describe the action:
- Describe the top-level flow's inputs and outputs for the agent, not the internal pieces. The agent should never need to know that an Apex class exists.
- Make every branch, including those inside subflows and Apex, end in a value for the output variables. A branch that leaves an output empty gives the agent nothing to say.
- Test each part alone first: the Apex class with unit tests, the subflow with a debug run, the prompt template in Prompt Builder. Then test the top-level flow, then the agent preview.
- Deploy dependencies together. The Apex class, subflows, prompt template, and top-level flow must all exist in the target org, and subflows must be active before the parent.
Exercise
A flow action calls an Apex invocable method that takes a List<Request> with 3 items. The method returns a list with 2 results. What happens, and how do you prevent it?
Show answer
Flow expects one result per input, in the same order, so the mismatch causes a runtime error and the interview fails. Prevent it by building exactly one Result for every Request in a final loop over the input list, including requests that fail or have a null Id, and by returning failure information as data in the Result.
Exercise
Your "Get Case Status" action and your "Update Case Contact" action both need to find a contact by email. What is the better design, and what risk comes with it?
Show answer
Put the contact lookup in a shared autolaunched subflow with input and output variables, and call it from both parent flows. The risk is that editing the subflow changes the behavior of both actions, so you must retest every parent flow after a change.
Exercise
A prompt template returns a summary in a flow. A teammate wants a Decision element that updates the case if the summary contains the word "urgent". Why is this a poor design, and what should you do instead?
Show answer
Generated text can vary between runs, so branching on it makes updates unpredictable. Branch on a record field such as Priority or Status instead, and use the prompt template only to produce text for the agent to show to the user.