Put the Workflow in Code When the Agent Keeps Improvising
An agent that "uses tools" will sometimes call them in a sensible order and sometimes skip the one that checks a balance, a permission, or a duplicate. If that check is optional in the prompt, it is optional in production. The model is doing what you asked: deciding. The workflow did not want a decision there.
Put the order in code when every successful run must do the same steps. Let the model fill the gaps that are actually language: classify the email, extract the fields, draft the reply, choose among documented options.
A split that holds up
| In code | In the model |
|---|---|
| Authenticate, authorize, and scope to the tenant | Read unstructured text and pull out ids the code will verify |
| "Search, then get, then act" as three calls the program makes | Decide whether the user's paragraph is a refund request or a question |
| Idempotency, retries, timeouts | Phrase the question back when a required field is missing |
| The commit, the payment, the send | Rank a short list the code already filtered |
The code calls the model at the points of judgment and ignores any tool plan the model invents for the steps that are not negotiable. You can still expose tools. The outer function does not ask the model whether to check the duplicate. It checks, then asks the model what to tell the user.
This feels less magical. It is how you get a log that says the check happened. An improvised trace that happened to include the check on Tuesday does not tell you it will happen on Wednesday.
A refund that must not double-pay
Take a support inbox that can request a refund. The language is messy. The money movement is not.
async function handleRefundEmail(input: { tenantId: string; emailText: string }) {
const extracted = await model.extract({
text: input.emailText,
schema: { orderId: "string?", amount: "number?", reason: "string?" },
});
const orderId = extracted.orderId;
if (!orderId) {
return model.draft({ intent: "ask-for-order-id" });
}
const order = await orders.get(input.tenantId, orderId); // code, not a tool the model may skip
if (!order) {
return model.draft({ intent: "order-not-found", orderId });
}
const duplicate = await refunds.findOpen(input.tenantId, orderId);
if (duplicate) {
return model.draft({ intent: "already-refunded", refundId: duplicate.id });
}
const refund = await refunds.create({
tenantId: input.tenantId,
orderId,
amount: order.paidAmount, // not the number the model guessed
idempotencyKey: `refund:${input.tenantId}:${orderId}`,
});
return model.draft({ intent: "refund-created", refundId: refund.id });
}
The model never sees a create_refund tool. It cannot skip the duplicate check because that check is not a tool. It can still write a fluent apology. The amount comes from the order, not from the email, because invoices get forwarded with the wrong total.
If you instead give the model search_orders, get_order, create_refund, and a system prompt that says "always check for duplicates," you will get a week of clean traces and then a double refund when the model jumps to create_refund with an id it invented. Idempotency keys on the write still matter. They are the last line, not a substitute for hiding the write.
Where improvisation is the feature
A support assistant that must handle questions you have not scripted should choose tools. Constrain the choice with the descriptions in MCP tool descriptions that route the model, and keep the write tools behind a confirmation the code enforces. "The model said it confirmed" is not a confirmation. A function that returns only after the user or a policy approves is a confirmation.
Read-only tools can be looser. Write tools should be few, named after the side effect (issue_refund, not update_records), and unreachable until the code has passed the gates.
Evaluation follows the split
For the code path, assert the calls: duplicate check before create, no send when the check fails, amount taken from the order. These are unit tests. They do not need a model.
For the model path, score the classification and the draft against examples: refund versus question, missing order id, already refunded. Mixing both into one "did the agent do well" grade hides a skipped check behind a fluent email.
If you cannot name the steps that must always happen, you do not have a workflow yet. You have a chat. Ship the chat if that is the product. The moment a missed step costs a double refund or a leaked row, lift that step out of the prompt and into a function the model cannot skip.
What I watch in traces
- A write tool called without the preceding get
- An id that does not appear in any previous tool result (the model invented it)
- A confirmation tool that returned
truewith no user turn in between - A retry that created a second row because the first call's result was ignored
Those are not prompt bugs. They are control-flow bugs. Fix them in code.
Keep reading
Approval Sits Between tool_use and tool_result
Human approval is not a new chat message. It is a delay before the matching tool_result. A user turn in that gap is a 400, a lost denial, or a tool that ran anyway.
Screenshots Fill Every Later Turn: Downscale, Then Drop the Pixels
A screenshot is not a log line. It is input on every later request. Downscale on ingest, extract the text, and drop the pixels after the model has read them.
Tool Results Fill Every Later Turn: Truncate Before You Append
A tool_result is not a log line. It is input on every later request. Cap rows at the tool, keep pairing, and compact only completed turns.
Claude Thinking Blocks: Echo the Signature or the Tool Loop Breaks
Pass thinking and redacted_thinking back unchanged. Effort steers depth; max_tokens caps spend.
Streaming LLM Output: SSE Events, Partial Tool JSON, and Abort
Tokens arrive before the JSON is valid. Handle SSE events, concatenate partial_json, and abort the request.
Indirect Prompt Injection: Tool Output Is Not Instructions
A retrieved document, an email, or a tool result can tell the model to take an action. Delimiters do not stop it. The tool allowlist after untrusted text does.
Newsletter
New posts, straight to your inbox
One email when a new post goes up. Double opt-in, unsubscribe anytime. Not a daily digest.
Comments
- No comments yet. Be the first.