Instructions and a Result Your Code Can Use
An agent loop can run tools until the model stops asking for them, but the program cannot rely on it yet. Two things are missing. The model needs to know what it is working toward and when it has arrived. And the program needs an answer it can read, check and save, not a paragraph of free text. This lesson covers how to write the instructions of an agent, the ways a run can end, and how to make it end on a result that is validated before anything is written.
Instructions for a model that acts over many steps
An agent's instructions are its system prompt, the first message of the transcript. In a single chat call the system prompt mostly shapes one reply. In an agent it has a harder job: the model reads it again at every step of the loop, after each tool result, and has to decide from it what to do next. So the instructions are less a description of a personality and more a short brief for someone who will work alone for a while.
A useful brief answers four questions:
- The goal. What the run is for, in one or two sentences: resolve one customer message about an order.
- The rules. What must always or never happen: never promise a refund the order does not qualify for, never invent an order number.
- How the tools are meant to be used. Not what each tool does (its own description says that), but how they fit together: read the order before deciding, look up the policy before quoting it.
- What counts as done. The exact moment the run ends and what the model hands over then. Without it, a model may stop after the first tool result, or keep looking long after it has enough.
Giving each part its own heading makes the brief easy for the model to scan and easy for you to edit. A short example for a support agent:
# Goal
You handle one customer message about an order. Decide what
should happen and write the reply the customer will receive.
# Rules
- Use only facts from the tools. Never guess an order number,
a date or an amount.
- Offer a refund only when the help pages say the order qualifies.
# How to use the tools
- Start with get_order for the order the message names.
- Use search_help to find the policy that applies, then
read_help_page to read it before you rely on it.
# When you are done
When you know the resolution, call submit_resolution once.
A plain text reply is not saved and does not end the task.The right level of detail sits between two failures. Instructions that hardcode every branch ("if the parcel is late by more than three days and the customer is angry, then...") are brittle: the first case nobody wrote down breaks them. Instructions that are vague ("be helpful and solve the problem") give the model nothing concrete to decide by, and they assume it shares knowledge it does not have, such as which actions your shop allows. Anthropic's guide to context engineering calls this finding the right altitude, and recommends a minimal set of instructions that still fully outlines the expected behaviour (minimal does not mean short).
A practical way to get there is to start small, run the agent on real tasks, and add an instruction only for a failure you actually saw. When the model needs to learn a pattern, a few typical examples teach it better than a long list of edge cases.
True or false?
The more edge cases a system prompt lists, the more reliably an agent behaves.
False. A long list of special cases makes the prompt brittle and still misses the case nobody thought of. A few typical examples and clear rules generalise better.
In an agent, the system prompt is read again at every step of the loop, because it stays at the start of the transcript that is sent with every call.
True. Every call sends the whole transcript, system prompt included, so the instructions guide each decision of the run, not only the first one.
Three ways a run can end
The loop calls the model, runs the tools it asks for and calls it again. The run is over when the model hands over its answer, and there are three shapes that answer can take.
A plain text reply. The model answers without asking for a tool, and the reply has finish_reason "stop". This is the simplest ending and it suits a chat, where a person reads the answer. It suits a program badly: the text has no fixed shape, so the code cannot reliably read the decision out of it. And "stop" only means the model stopped writing at a natural point, not that the task was finished.
A final reply in structured output. The request asks for a reply that follows a JSON schema (in Chat Completions, through response_format with type json_schema), and the program validates it against a Pydantic model. The answer now has a shape, but it is a second kind of reply for the loop to handle: the same run has to allow tool calls on some steps and a schema-shaped text reply on the last, and the program has to tell which one it got.
A call to a final-answer tool. The program offers one more tool, for example submit_resolution, whose parameters are the fields of the result. The model ends the run by calling it, and the arguments of that call are the result.
| The run ends on | The program receives | What the loop needs |
|---|---|---|
| a plain text reply | free text, no fixed shape | nothing new, but the decision is hard to read from it |
| a structured reply | JSON in the reply text, checked against a schema | a second kind of reply to recognise and validate |
| a final-answer tool call | JSON arguments, checked against a schema | one more tool name in the code it already has |
The third way fits an agent best because the loop already knows how to handle a tool call: read the name, parse the arguments, run something, send back a tool message. The final-answer tool goes through exactly that path. Its schema is sent like any other tool's, its arguments are validated like any other tool's, and if they are wrong the model hears about it the way it hears about any failed call. The only new rule is what happens when that one tool succeeds: the run ends.
OpenAI's own advice points the same way: use function calling when the model connects to your system, and a structured response format when you want to shape what the model says to the user.
True or false?
A reply whose finish_reason is "stop" means the agent has finished its task.
False. "stop" only says the model stopped generating at a natural point. Whether the task is done is decided by the program, for example by a final result that passed validation.
With a final-answer tool, the loop needs no separate code path for reading a structured final reply.
True. The result arrives as tool-call arguments, which the loop already parses and validates for every other tool.
The final-answer tool
The final-answer tool starts with the shape of the result, written as a Pydantic model. Each field is something the program will use afterwards: which action to take, for which order, and the reply to send.
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field
class Resolution(BaseModel):
model_config = ConfigDict(extra="forbid")
action: Literal["refund", "replace", "reply_only"]
order_id: str = Field(description="The order the message is about")
reply: str = Field(description="The message the customer will receive")
SUBMIT_RESOLUTION = {
"type": "function",
"function": {
"name": "submit_resolution",
"description": (
"Hand over the final resolution and end the task. "
"Call it once, after you have read the order and the policy."
),
"parameters": Resolution.model_json_schema(),
},
}Three details carry the design. Literal names the allowed actions, so any other word fails validation. By default, Pydantic ignores fields the class does not define, so a field the model invents would pass and the model would never learn it was wrong; extra="forbid" turns such a field into an error. And the tool's parameters come from Resolution.model_json_schema(), so the schema the model sees and the schema the code checks are the same definition and cannot drift apart.
The tool goes into the list of tools next to the others. In the loop, a call to it takes the same path as any call, up to one branch: if its arguments validate, the program keeps the result and the run ends.
- Call the model
- A tool call
- Run the tool any other tool
- Validate the arguments submit_resolution
- Save the result, end the run
- Send back the error
- Call the model to A tool call
- A tool call to Run the tool: other name
- A tool call to Validate the arguments: final-answer tool
- Run the tool to Call the model: result
- Validate the arguments to Send back the error: invalid
- Send back the error to Call the model: error
- Validate the arguments to Save the result, end the run: valid
Two behaviours of the API matter here.
First, when tools are present, tool_choice defaults to "auto", which lets the model choose: it may call the tool, or it may still answer in plain text. That is why the instructions say what counts as done and that a plain reply is not saved. It is also why the program should treat a plain reply as "not finished yet" rather than as the answer.
Second, parallel_tool_calls defaults to true, so one reply can hold several tool calls, and the final-answer call can arrive next to other calls. The program needs a rule for that case. One option is to reject the final call with a message to submit only after the other results have been read.
Some providers can also force tool arguments to follow the schema exactly (OpenAI calls this strict mode). It helps where it is available, but support differs between providers, and a schema cannot express every rule. Validation in your own code is the check that always applies.
Rejecting a result the model can fix
The arguments of a tool call are a JSON string written by the model. It may be invalid JSON, miss a field, use an action that does not exist or add a field nobody asked for. Throwing the run away at that point wastes every step that came before. The model has everything it needs to fix the mistake, if the program tells it what the mistake was.
So a final result that fails validation is answered like any failed tool call: with a tool message, sent back under the tool_call_id of that call, that names each problem and says what to do. The run continues, and on its next step the model calls the tool again with corrected arguments.
from pydantic import ValidationError
def check_resolution(arguments: str) -> tuple[Resolution | None, str]:
try:
result = Resolution.model_validate_json(arguments)
except ValidationError as err:
problems = "; ".join(
f"{'.'.join(str(p) for p in e['loc']) or 'arguments'}: {e['msg']}"
for e in err.errors()
)
return None, (
f"Result rejected. {problems}. "
"Fix these fields and call submit_resolution again."
)
if not order_exists(result.order_id):
return None, (
f"Result rejected. order_id: no order {result.order_id!r}. "
"Use the order id that get_order returned."
)
return result, "Result accepted."model_validate_json raises a ValidationError, and its errors() method lists each problem with its field path (loc) and a readable message (msg). Joined into one line, they make a precise correction note: a wrong action comes back as action: Input should be 'refund', 'replace' or 'reply_only', a missing field as reply: Field required.
Passing the schema is not the end of the checking. A well-formed order_id can still name an order that does not exist, and a schema cannot know that. Rules like this one are checked in code after validation and rejected the same way, with a message that points to the fix (in the code, order_exists stands for a lookup in your own data).
- Model
- Program
- Model to Program: submit_resolution, action "refund_all"
- Program to Model: rejected: action should be refund, replace or reply_only
- Model to Program: submit_resolution, action "refund"
- Program to Model: accepted, result saved
A model can also keep getting it wrong. Limiting how often that may happen belongs to the stop conditions of the loop; the rejection itself only has to make each new attempt better informed than the last.
True or false?
By default, a Pydantic model ignores fields it does not define, so an invented field passes validation unnoticed.
True. The default is extra="ignore". Setting extra="forbid" turns an unknown field into an error the model can be told about.
If the provider enforces the tool schema, the program no longer needs to validate the final result.
False. A schema only checks shape. Rules such as "the order must exist" still need code, and not every provider enforces schemas at all.
Tools that read and tools that write
Most tools of a support agent only read: they look up an order or open a help page. If the model calls one with poor arguments, the worst outcome is a wasted step and an error it can recover from. A tool that writes is different. Issuing a refund, changing an order or saving a resolution leaves a change behind, and a mistake there is not undone by the next step of the loop.
| Kind | Examples | If the call is wrong |
|---|---|---|
| reads | look up an order, search the help pages | a wasted step, an error to recover from |
| writes | issue a refund, save a resolution | a change that stays after the run |
The line to draw is about who acts. A tool call is a request: the model never touches a file or an order itself; it only writes a name and some arguments into its reply. The program decides whether to carry the request out. For a write, it checks everything it can before it acts: the arguments validate, the order exists, the action is one the order allows, the amount is not more than was paid. Only then does the code perform the write, and if a check fails, it writes nothing and answers with an error the model can act on.
- Model asks refund order
- Code checks schema, order, policy
- Code writes order updated
- Model asks to Code checks: tool call
- Code checks to Code writes: all checks pass
The final-answer tool fits this pattern well: the model only proposes a resolution, and the program saves it once it has passed every check. Two more habits keep writes safe. Give a run only the tools its task needs, so a task that only answers questions gets no write tools at all. And shape the arguments so mistakes are hard to make: a Literal list of actions instead of free text, an order id instead of a description of the order. Adding a person who approves a write before it happens is a further safeguard, outside the scope of this lesson.
True or false?
When the model calls a write tool, the change has already happened by the time the program reads the reply.
False. The reply only contains a request. Nothing changes until the program runs the function, so it can check the request first and refuse it.
An agent whose task only answers questions should not be given tools that write.
True. A tool the run does not need can only add risk. Without it, a wrong decision cannot leave a change behind.