Sub topic 10
Writing a custom Apex action
Standard actions cover common tasks. When your agent needs logic that Salesforce does not ship, you can write an Apex invocable method and add it as a custom action. This chapter assumes you can read basic Apex, know how SOQL queries work, and have an agent with at least one topic from the earlier chapters.
How an Apex action fits in
An agent does not run Apex directly. The agent reads the topic instructions, decides an action is needed, and fills in the action's inputs from the conversation. Salesforce then calls your method, and the agent turns the returned values into a reply.
The Apex class
An invocable method must be static, and it must be the only @InvocableMethod in its class. It takes a List and returns a List. Inputs and outputs are wrapped in inner classes whose fields carry @InvocableVariable.
public with sharing class GetOpenCaseCountAction {
public class Request {
@InvocableVariable(label='Account Id' required=true)
public Id accountId;
}
public class Response {
@InvocableVariable(label='Open Case Count')
public Integer openCaseCount;
}
@InvocableMethod(label='Get Open Case Count' description='Returns the number of open cases for an account')
public static List<Response> getOpenCaseCount(List<Request> requests) {
Set<Id> accountIds = new Set<Id>();
for (Request r : requests) {
accountIds.add(r.accountId);
}
Map<Id, Integer> counts = new Map<Id, Integer>();
for (AggregateResult ar : [
SELECT AccountId acct, COUNT(Id) total
FROM Case
WHERE IsClosed = false AND AccountId IN :accountIds
GROUP BY AccountId
]) {
counts.put((Id) ar.get('acct'), (Integer) ar.get('total'));
}
List<Response> responses = new List<Response>();
for (Request r : requests) {
Response res = new Response();
res.openCaseCount = counts.containsKey(r.accountId) ? counts.get(r.accountId) : 0;
responses.add(res);
}
return responses;
}
}Points worth noting:
- The method is bulkified. It runs one query for all requests, not one per request.
- It returns one
ResponseperRequest, in the same order. Salesforce matches results to inputs by position. with sharingmakes the query respect the running user's record access.- The
labelanddescriptionvalues are what the agent sees. A clear description helps it choose the action correctly.
Deploying the class
If you work in a local project, use the Salesforce CLI. The first command opens a browser to log in and saves the org under an alias. The second deploys everything under force-app.
sf org login web --alias agentforce-dev
sf project deploy start --source-dir force-app --target-org agentforce-devYou can also paste the class into the Developer Console. The CLI is better once you have more than one file.
Adding the action to the agent
- Open your agent in Agentforce Builder.
- Select the topic that should use the action.
- Add a new action and choose Apex as the reference type.
- Pick Get Open Case Count from the list.
- Give the action a name and a plain description of when to use it.
- Check the input and output labels, then save.
The class appears in the list only if it is deployed and contains an @InvocableMethod. The action must also be added to the topic, since an agent can only use actions attached to the active topic.
Telling the topic when to call it
Instructions connect the action to the conversation. Name the action exactly as it appears in the builder.
Topic: Case Status Questions
Description: Answer questions about the status of a customer's support cases.
Instructions:
1. Ask for the account if the user has not named one.
2. Use the Get Open Case Count action to look up the number of open cases.
3. Report the number in one sentence. Do not guess when the action returns no result.
4. If the user asks about anything other than case status, say you cannot help with that.Common errors
| Symptom | Likely cause |
|---|---|
| Class missing from the action list | Not deployed, or no `@InvocableMethod` |
| Deployment fails on the class | More than one invocable method, or a non-static method |
| Agent never calls the action | Action not added to the topic, or the instructions do not mention it |
| Count is always 0 | The agent user cannot see the cases under `with sharing` |
| Agent asks for an ID repeatedly | The input is `required=true` and the agent cannot resolve an account ID from the conversation |
Exercise
Why does the method return a response for every request, even when an account has no open cases?
Show answer
Salesforce matches returned items to inputs by position. The aggregate query returns no row for an account with no open cases, so the code fills in 0 for that request. This keeps the response list the same length and order as the request list.