Sub topic 13
Building custom actions with Flow and Apex
Standard actions cover common tasks. When an agent needs to do something specific to your business, such as look up an order in your own data model, you build a custom action. This chapter assumes you know how topics, instructions, and actions fit together, how the agent user and running user differ, and that you can read basic Flow or Apex.
When a custom action is the right tool
A custom action wraps logic you already control so the agent can call it. The agent never runs your code directly. It picks the action, fills in the inputs, and reads the outputs. Your logic is what touches data.
Build a custom action when:
- No standard action does the job.
- The task needs a fixed, repeatable sequence (query, validate, update) that you don't want the model to improvise.
- You need to call an external system or apply a business rule.
Choose between the two main options like this:
| Question | Flow | Apex invocable method |
|---|---|---|
| Who builds it? | Admins and low-code developers | Developers |
| Best for | Record lookups, updates, approvals, simple branching | Complex logic, bulk processing, callouts with custom handling |
| Testing | Flow debug, agent testing | Apex unit tests, plus agent testing |
| Deployment | Metadata, no code coverage requirement | Needs test coverage to deploy to production |
Start with Flow when it can express the logic. Move to Apex when the logic outgrows it.
How the agent sees an action
The agent sees three things: the action's name and description, its inputs, and its outputs. The reasoning engine reads this metadata to decide whether the action fits the user's request and what values to pass. Good names and descriptions are part of the design, not decoration.
Building an action with Flow
Use an autolaunched flow, which runs without a screen. The steps:
- Create an autolaunched flow with no trigger.
- Add input variables. For each one, select Available for input. Use a clear API name such as
orderNumber. - Build the logic. For example, a Get Records element on Order filtered by the input, then a decision for the not-found case.
- Add output variables, each marked Available for output. Assign values to them in every path through the flow.
- Write a description for the flow and for each variable. The agent reads these.
- Save and activate the flow.
- In Agent Builder, open the topic, add an action, choose Flow as the reference type, and select your flow.
Always assign every output on every path. If the not-found path leaves status empty, the agent has nothing to report and may fill the gap with a guess.
After you add the action, you can edit its instructions inside the topic, adjust the input and output descriptions, and mark an input as one the agent must collect from the user.
Building an action with Apex
An Apex action is a static method marked @InvocableMethod. Its parameter and return type are lists, because the platform can pass several requests at once. Inputs and outputs live in small wrapper classes whose fields carry @InvocableVariable.
public with sharing class GetOrderStatusAction {
public class Request {
@InvocableVariable(label='Order Number' required=true)
public String orderNumber;
}
public class Response {
@InvocableVariable(label='Order Status')
public String status;
}
@InvocableMethod(
label='Get Order Status'
description='Returns the status of an order for a given order number'
)
public static List<Response> getStatus(List<Request> requests) {
Set<String> orderNumbers = new Set<String>();
for (Request r : requests) {
orderNumbers.add(r.orderNumber);
}
Map<String, String> statusByNumber = new Map<String, String>();
for (Order o : [
SELECT OrderNumber, Status
FROM Order
WHERE OrderNumber IN :orderNumbers
WITH USER_MODE
]) {
statusByNumber.put(o.OrderNumber, o.Status);
}
List<Response> results = new List<Response>();
for (Request r : requests) {
Response res = new Response();
res.status = statusByNumber.containsKey(r.orderNumber)
? statusByNumber.get(r.orderNumber)
: 'Order not found';
results.add(res);
}
return results;
}
}Three design choices in this class matter:
- One query for the whole batch. The method collects every order number, queries once, and maps the results. Querying inside the loop would hit governor limits when requests are batched.
- One response per request, in order. The platform matches outputs to inputs by position. Return a result for every request, including failures.
- A readable not-found value. The method returns
'Order not found'instead of throwing. The topic instructions can then tell the agent exactly what to do with that string.
Test the method
Apex classes need unit tests before they can deploy to production. Test the found and not-found paths.
@IsTest
private class GetOrderStatusActionTest {
private static GetOrderStatusAction.Request buildRequest(String orderNumber) {
GetOrderStatusAction.Request r = new GetOrderStatusAction.Request();
r.orderNumber = orderNumber;
return r;
}
@IsTest
static void returnsStatusForExistingOrder() {
Account acct = new Account(Name = 'Test Account');
insert acct;
Order ord = new Order(
AccountId = acct.Id,
EffectiveDate = Date.today(),
Status = 'Draft'
);
insert ord;
Order saved = [SELECT OrderNumber FROM Order WHERE Id = :ord.Id];
List<GetOrderStatusAction.Response> results =
GetOrderStatusAction.getStatus(
new List<GetOrderStatusAction.Request>{ buildRequest(saved.OrderNumber) }
);
System.assertEquals(1, results.size());
System.assertEquals('Draft', results[0].status);
}
@IsTest
static void returnsNotFoundForUnknownOrder() {
List<GetOrderStatusAction.Response> results =
GetOrderStatusAction.getStatus(
new List<GetOrderStatusAction.Request>{ buildRequest('00000000') }
);
System.assertEquals('Order not found', results[0].status);
}
}Connecting the action to a topic
An action does nothing until a topic includes it and the instructions say when to use it. The topic below pairs a short classification description with instructions that name the action and set limits.
Topic: Order Status
Classification description: Customer asks where an order is or what state it is in.
Scope: Look up the status of a single order using the Get Order Status action.
Instructions:
- Ask for the order number if the customer has not given one.
- Call the Get Order Status action with that order number.
- Report only the status returned by the action.
- If the action returns 'Order not found', ask the customer to check the number once, then offer to connect them with a human agent.
- Do not discuss refunds or cancellations in this topic.The instructions refer to the action by the name the agent sees, and they tell the agent how to react to the not-found output. That link is why the Apex method returns a plain string instead of an exception.
The same action works in an employee agent. The topic structure is identical, but the instructions assume an internal user.
Topic: My Open Cases
Classification description: An employee asks about support cases assigned to them or their team.
Scope: Summarize cases the employee already has permission to view.
Instructions:
- Use the Get Open Cases action to retrieve cases for the current user.
- Present each case with its number, subject, and status.
- If the employee asks about data they cannot access, say that you cannot show it and suggest contacting their administrator.Access: whose permissions does the action use?
A custom action runs in the context of whoever the agent acts as. A service agent typically runs as its agent user. An employee agent runs as the employee who is chatting. This changes what the same action returns.
- For a service agent, grant the agent user a permission set that includes access to the Apex class or flow, plus the object and field permissions the action needs. Keep it to the minimum.
- For an employee agent, the employee needs access to the class or flow, and their own record access limits the results.
- For Flow, check the flow's run setting. A flow set to run in system context bypasses the caller's permissions, so treat it as a privileged action.
If an action works for you in testing but fails for the agent, compare the agent user's permission set against what the action touches.
Common errors
- The agent never calls the action. The description is vague, or the topic instructions don't mention it. Rewrite both in plain terms.
- The agent passes the wrong value. The input label is ambiguous. Rename it, for example "Order Number" rather than "Value", and add a description.
- The action returns blank output. A Flow path left an output unassigned, or an Apex response list is shorter than the request list.
- Access-denied or empty results. The agent user or employee lacks class, flow, object, or field access.
- Governor limit errors. A query or DML statement sits inside a loop.
Exercise
An Apex action returns data correctly when you run it as an administrator, but the service agent says "Order not found" for orders that exist. Name two likely causes and how you would confirm each.
Show answer
First, the agent user may lack object or field access on Order. Because the query uses WITH USER_MODE, it silently returns no rows. Confirm by checking the agent user's permission sets for Order read access and the fields queried. Second, the agent user may lack record access through sharing, since the class uses with sharing and the orders may be owned by users the agent user cannot see. Confirm by checking the Order sharing settings and the agent user's role. A third possibility is that the agent passed a malformed order number, which you can confirm in agent testing by reviewing the input value.
Exercise
Why does the Apex invocable method take a List of requests and return a List of responses, and what rule must the returned list follow?
Show answer
The platform can pass several requests to the method in one call, so the method must be bulk-safe. It should query once for the whole batch. The returned list must contain one response for every request, in the same order, because outputs are matched to inputs by position.