Sub topic 10
When a Rule Needs a Flow or Apex Action Instead of an Instruction
This chapter assumes you can write a topic's classification description, scope, and instructions, and that you know actions are what a topic calls to read or change data. You should also be able to open Agentforce Builder and run a test conversation. Basic familiarity with Flow Builder or Apex is helpful, but you can follow the logic without it.
Instructions guide, logic enforces
Topic instructions are text that a large language model (LLM) reads and weighs when it decides what to say and which action to call. The model usually follows them. "Usually" is the problem. An LLM is probabilistic. It can misread a number, skip a step in a long conversation, or lean toward a customer's request even when your instruction says otherwise.
A Flow or an Apex action runs the same way every time. It takes inputs, applies your rule, and returns outputs. The model cannot reinterpret an if statement.
Use this working rule: instructions shape conversation, and logic enforces business rules. If a wrong answer would cost money, break a policy, expose data, or corrupt a record, don't depend on wording alone.
Sorting a rule: instruction, agent-level, or logic
Ask these questions about each rule you want to write.
| Question | If yes | Where it belongs |
|---|---|---|
| Is it about tone, phrasing, order of questions, or when to hand off? | Judgment is acceptable here | Topic instruction |
| Does it apply to every topic (brand voice, language, escalation default)? | One place avoids drift | Agent-level instructions |
| Does it involve arithmetic, dates, thresholds, or comparing values? | LLMs can miscalculate | Flow or Apex action |
| Does it decide eligibility, approval, or pricing? | Must be identical every time | Flow or Apex action |
| Does it write, update, or delete records? | Needs validation and permissions | Flow or Apex action |
| Does it depend on who the user is or what they may see? | Security must not rely on wording | Action running with sharing and permission checks |
The categories overlap. Often the best design uses two layers: logic decides, and an instruction tells the agent how to use the decision.
A rule that fails as an instruction
Suppose a Returns topic contains this instruction:
If the order was delivered more than 30 days ago, or the refund is over $100, do not approve the refund. Tell the customer you will transfer them to a human agent.This looks specific and testable, and it fails in realistic ways:
- The model must compute "more than 30 days ago" from a delivery date and today's date. It may get this wrong, especially near the boundary or across a month end.
- "Over $100" depends on the model reading a currency value correctly. A value like
100.00or$100.01is easy to mishandle. - Two conditions joined by "or" invite partial application. The model may check one and forget the other.
- A customer can pressure the agent ("It was only a few days late, please just approve it"), and the agent may bend.
- Nothing stops the agent from calling a refund action anyway, because the instruction is advice, not a gate.
Run the same conversation ten times and you may get different results on the edge cases. That inconsistency is the sign that the rule belongs in code.
Moving the rule into an Apex action
An Apex invocable method is a static method that Flow and Agentforce can call. The method below takes a delivery date and an amount, applies both conditions, and returns a yes or no with a reason. It runs the same way for every request.
public with sharing class CheckRefundEligibility {
private static final Integer RETURN_WINDOW_DAYS = 30;
private static final Decimal AUTO_REFUND_LIMIT = 100;
public class Request {
@InvocableVariable(label='Delivered Date' required=true)
public Date deliveredDate;
@InvocableVariable(label='Refund Amount' required=true)
public Decimal refundAmount;
}
public class Result {
@InvocableVariable(label='Eligible')
public Boolean eligible;
@InvocableVariable(label='Reason')
public String reason;
}
@InvocableMethod(
label='Check Refund Eligibility'
description='Checks whether an order can be refunded automatically, based on delivery date and refund amount.'
)
public static List<Result> check(List<Request> requests) {
List<Result> results = new List<Result>();
for (Request req : requests) {
Result res = new Result();
if (req.deliveredDate == null || req.refundAmount == null) {
res.eligible = false;
res.reason = 'Missing delivery date or refund amount.';
} else if (req.deliveredDate.daysBetween(Date.today()) > RETURN_WINDOW_DAYS) {
res.eligible = false;
res.reason = 'The order was delivered more than ' + RETURN_WINDOW_DAYS + ' days ago.';
} else if (req.refundAmount > AUTO_REFUND_LIMIT) {
res.eligible = false;
res.reason = 'The refund amount is above the automatic limit and needs human review.';
} else {
res.eligible = true;
res.reason = 'Within the return window and under the automatic limit.';
}
results.add(res);
}
return results;
}
}Several details matter for agent use:
- The method accepts and returns lists. Invocable methods run in bulk, so you must process every element.
with sharingmakes the method respect the running user's record access. Use it unless you have a reason not to.- The
labelanddescriptionare what the agent and the Builder show. A clear description helps the agent pick the action at the right time. - The limits are constants in one place. Changing the window means changing one line, not rewording several instructions.
- The
reasonoutput gives the agent a precise explanation it can relay without inventing one.
When to choose Flow instead
A Flow action covers the same ground for rules an admin can maintain without code. A Decision element handles the branches, and Get Records or Update Records handle data. Use these criteria:
| Choose Flow when | Choose Apex when |
|---|---|
| The logic is a few branches and field lookups | The logic has loops, complex calculations, or many edge cases |
| Admins will maintain it | Developers own it and it needs unit tests |
| Standard elements cover the data work | You need to call an external system or use libraries |
| You want fast iteration in a visual tool | You need fine control over bulk behavior and error handling |
Both work as agent actions. The choice depends on who maintains the rule and how complicated it is, not on whether the rule is important.
Rewriting the instruction around the action
After you move the decision into an action, the instruction becomes shorter. It no longer contains the rule. It says when to run the action and what to do with the result. The action name below is hypothetical. Use the exact name of the action assigned to your topic.
1. Ask the customer for their order number if they have not provided one.
2. Look up the order with the Get Order Status action to get its delivered date and the refund amount.
3. Run the Check Refund Eligibility action with the delivered date and refund amount.
4. If the result says eligible, tell the customer the refund can proceed and confirm the amount before continuing.
5. If the result says not eligible, tell the customer the reason from the result in one sentence. Offer to transfer them to a human agent. Do not offer a refund anyway.
6. If the order has no delivered date, say you cannot check eligibility and offer the transfer.Notice what changed:
- Each step names observable behavior.
- The policy numbers (30 days, $100) no longer appear in the text. The action owns them, so the text cannot drift out of sync with the rule.
- Step 5 tells the agent to use the action's reason and not make one up.
- Step 6 covers the missing-data case, which the Apex code also handles.
Making the action the only path
An instruction that says "only refund if eligible" is still a suggestion. If the refund action itself is callable in the same topic, a model that ignores the instruction can still issue the refund. For rules where a mistake is expensive, add enforcement in the action that does the work:
- Let the refund action re-check eligibility itself, or take the eligibility check as part of its own logic, instead of trusting the agent to have called the check first.
- Validate inputs on the server side. Do not assume the values the agent passes are correct.
- Run with the user's permissions where possible, so the action cannot do more than the user could.
Think of the instruction as the guide and the action as the lock.
Failure modes to watch for
- Rules duplicated in text and code. If the instruction says 30 days and the code says 45, the agent will tell customers one thing and the action will do another. Keep numbers in the action only.
- Vague action output. An action that returns
falsewith no reason leaves the agent to guess why. Return a short reason string or a status code you describe in the instruction. - Vague action description. If the description does not say what the action checks, the agent may not call it, or may call it at the wrong time.
- Unhandled nulls. The agent may call an action before it has all inputs. Handle missing values and return a clear message.
- Conversation-dependent logic. Don't put "remember what the customer said earlier" rules into code when they belong in instructions. Actions see only the inputs they are given.
- Over-moving to code. Not every rule needs an action. Tone, phrasing, and ordering of questions are fine as instructions, and code adds maintenance cost for no benefit.
Testing a rule that moved to logic
Test the action and the conversation separately.
- Test the action alone with boundary values: delivered exactly 30 days ago, 31 days ago, a refund of exactly 100 and of 100.01, and null inputs. A Flow debug run or an Apex unit test works for this.
- In the Builder preview, run realistic conversations and confirm the agent calls the action and relays the result.
- Add pressure utterances such as "Just approve it, I'm a loyal customer." The agent should still follow the action's answer.
- Check that the agent's wording of the reason matches the action's output.
If the agent calls the action but misstates the result, revise the instruction. If the action returns the wrong result, fix the logic. Keeping those two problems apart is a main benefit of this design.
Exercise
A topic instruction says "Apply a 10% discount to orders over $500 and a 15% discount to orders over $1,000." In testing, the agent sometimes gives 10% on a $1,200 order. Where should you fix this, and what should the revised instruction say?
Show answer
Move the discount rule into a Flow or Apex action that takes the order total and returns the discount percentage, because the rule is a threshold calculation that must give the same answer every time. Rewording the instruction would only make errors less likely, not impossible. The revised instruction should say when to call the action, for example "Run the Calculate Discount action with the order total, then tell the customer the discount percentage it returns," and should not contain the dollar thresholds or percentages. The action should also handle a missing or zero total. Test it at 500, 500.01, 1000, and 1000.01.
Exercise
Name two reasons the numbers in a policy (like a 30-day window) should live in the action and not in the instruction text.
Show answer
First, the model can misread or miscalculate against numbers in text, while code compares them exactly. Second, keeping the numbers in two places lets them drift apart when one is edited, so the agent can state a policy that the action does not enforce. A single copy in the action is also easier to change and test.