Message Roles, Structured Output and Function Calling
A model reads a list of messages and writes the next one. Get that list and its replies right.
Model APIs take a list of messages with roles that say who is speaking and how much weight the text carries. Structured output asks for a reply that matches a JSON Schema. Tool calling lets the model request a function, which your code runs and answers. A schema fixes the shape of a reply, not its truth, so validate values and check permissions yourself.
What you will learn: message roles across providers, instruction priority, JSON Schema outputs, the tool-calling exchange, validation, retries and safety.
Prerequisites: How LLMs Power Agents: Transformers, Tokens and Sampling and basic JSON. Python for the code.
Who is speaking
| Role | Written by | Carries |
|---|---|---|
| System or developer | The application builder | Purpose, rules, tone, limits |
| User | The person, or your program on their behalf | Requests and supplied material |
| Assistant | The model | Replies and tool requests |
| Tool result | Your program, after running a tool | What happened |
Providers differ in names and shapes. OpenAI's current guidance uses a developer role for application instructions, which earlier versions called system, and its APIs represent tool results as their own message or item type. Anthropic's Messages API takes instructions in a top-level system field and returns tool results as blocks inside a user turn. Some current Claude models also accept a system message later in the conversation, within placement rules. Read the documentation for the API and model you call.
Priority is guidance, not a wall
Models are trained to give application instructions more weight than user requests; OpenAI documents that developer or system instructions take precedence over user instructions. This is valuable behavior and not an access control. A determined or confusing input can still lead a model astray. Text from web pages, files and tool results should be treated as information and never as instructions, and your code must enforce what truly may not happen. See Prompt Injection Attacks and Defenses.
Never paste user input or retrieved text into the system or developer message. Doing so gives untrusted text the authority of your own instructions. Pass it as user content or a tool result, clearly delimited.
Write instructions that can be followed
- State the job, the audience and what a finished result looks like.
- Explain when to use each tool and when to ask a question.
- Say what to do when information is missing.
- Give an example or two of difficult cases.
- Keep stable material first; many providers can cache a repeated prefix.
Agent System Prompts and Instruction Hierarchy goes into detail.
Why the whole history matters
In a stateless exchange the model knows only what is in the request. If you drop an earlier tool result to save space, the model no longer knows it. If you keep everything, requests grow with each turn, cost rises and old details compete with new ones. Applications therefore manage the list deliberately.
| Technique | What it does | Watch for |
|---|---|---|
| Trim large tool results | Keeps the useful part of a long output | Cutting away the evidence needed later |
| Summarize older turns | Replaces detail with a shorter account | Summaries that lose numbers or constraints |
| Keep facts in task state | Stores identifiers and decisions outside the chat | State and conversation disagreeing |
| Start a fresh context | Begins a sub-task with only what it needs | Missing background |
Never remove a tool request while keeping its result, or the reverse; APIs expect the pairs to stay together. Context Assembly, Retrieval, Compression and Caching treats this subject fully.
Structured outputs and JSON Schema
Programs need predictable data. Asking politely for JSON often works and sometimes returns extra text or missing fields. Structured output features constrain generation to a supplied JSON Schema.
| Approach | Valid JSON | Matches your schema |
|---|---|---|
| Instruction only | Not guaranteed | Not guaranteed |
| JSON mode, where offered | Intended | Not guaranteed |
| Structured outputs | Yes, for completed replies | Yes, within the supported schema subset |
OpenAI recommends structured outputs over JSON mode, and only the former ensures schema adherence. In the Responses API the format is set with text.format; in Chat Completions with response_format. In Claude's API the schema goes in output_config.format with type set to json_schema; an older output_format parameter still works during a transition period.
# Claude API shape (set MODEL to a model that supports structured outputs)
response = client.messages.create(
model=MODEL,
max_tokens=1024,
system="You triage support messages.",
messages=[{"role": "user", "content": text}],
output_config={"format": {"type": "json_schema", "schema": SCHEMA}},
)
if response.stop_reason != "end_turn":
handle_incomplete(response) # refusal, length limit and so on
Check why the reply ended. A refusal or a length limit can leave output that does not match the schema. Providers support only part of JSON Schema, so check their lists of supported keywords before relying on one.
Design the schema for the reader
- Use clear field names and descriptions; the model reads them.
- Use
enumfor fixed choices. - Set
additionalPropertiestofalseand mark fields required; for optional data, allownull. - Give an honest way out, such as a value for "unknown" or "not found", so the model is not forced to invent.
- Keep it shallow. Deeply nested structures are harder to fill and to validate.
Validate and retry
Even with provider support, validate in your code, particularly across different providers and for rules a schema cannot express. This offline example uses a scripted model that fails twice before succeeding.
"""Validate a model's structured reply and retry with the error. Offline."""
import json
SCHEMA = {
"type": "object",
"additionalProperties": False,
"required": ["category", "priority", "order_id"],
"properties": {
"category": {"type": "string", "enum": ["billing", "delivery", "other"]},
"priority": {"type": "integer", "minimum": 1, "maximum": 3},
"order_id": {"type": ["string", "null"]},
},
}
TYPES = {"object": dict, "string": str, "integer": int, "null": type(None)}
def problems(value, schema, path="reply"):
"""A teaching subset of JSON Schema. Use a real library in production."""
allowed = schema.get("type")
allowed = [allowed] if isinstance(allowed, str) else allowed
if type(value) not in [TYPES[name] for name in allowed]:
return [f"{path} must be {' or '.join(allowed)}"]
found = []
if "enum" in schema and value not in schema["enum"]:
found.append(f"{path} must be one of {schema['enum']}")
if "minimum" in schema and value < schema["minimum"]:
found.append(f"{path} must be at least {schema['minimum']}")
if "maximum" in schema and value > schema["maximum"]:
found.append(f"{path} must be at most {schema['maximum']}")
if isinstance(value, dict):
for key in schema.get("required", []):
if key not in value:
found.append(f"{path}.{key} is missing")
for key, item in value.items():
if key in schema["properties"]:
found += problems(item, schema["properties"][key], f"{path}.{key}")
elif schema.get("additionalProperties") is False:
found.append(f"{path}.{key} is not allowed")
return found
def business_rules(reply, known_orders):
"""Checks a schema cannot express."""
if reply["order_id"] and reply["order_id"] not in known_orders:
return [f"order {reply['order_id']} does not exist"]
return []
def ask(model, question, known_orders, attempts=3):
messages = [{"role": "user", "content": question}]
for attempt in range(1, attempts + 1):
text = model(messages)
try:
reply = json.loads(text)
errors = problems(reply, SCHEMA) or business_rules(reply, known_orders)
except json.JSONDecodeError as error:
errors = [f"not valid JSON: {error.msg}"]
print(f"attempt {attempt}: {errors or 'accepted'}")
if not errors:
return reply
messages.append({"role": "assistant", "content": text})
messages.append({"role": "user",
"content": "Fix these problems: " + "; ".join(errors)})
return None # the caller must handle this case
if __name__ == "__main__":
scripted = iter([
'Sure! {"category": "delivery"}',
'{"category": "shipping", "priority": 5, "order_id": "A-17"}',
'{"category": "delivery", "priority": 2, "order_id": "A-17"}',
])
result = ask(lambda messages: next(scripted),
"Order A-17 has not arrived.", known_orders={"A-17"})
print("result:", result)
Output:
attempt 1: ['not valid JSON: Expecting value']
attempt 2: ["reply.category must be one of ['billing', 'delivery', 'other']", 'reply.priority must be at most 3']
attempt 3: accepted
result: {'category': 'delivery', 'priority': 2, 'order_id': 'A-17'}
The retry count is limited and the function can return nothing, so the caller must have a plan for that. Note the order of checks: parse, then shape, then facts such as whether the order exists.
Function calling, turn by turn
You describe tools with a name, a description and a parameter schema. The model may reply with a request to call one. The model runs nothing.
This runs the exchange with a scripted model, in the block shape used by Claude's Messages API.
"""Follow one tool call through the message list. The model is scripted."""
def lookup_order(order_id):
return {"order_id": order_id, "status": "in transit", "eta_days": 2}
TOOLS = {"lookup_order": lookup_order}
def scripted_model(messages):
last = messages[-1]
if isinstance(last["content"], str): # a question from the user
return [{"type": "tool_use", "id": "call_1", "name": "lookup_order",
"input": {"order_id": "A-17"}}]
result = last["content"][0]["content"] # the tool result
return [{"type": "text", "text": f"Your order is {result}."}]
def run(question):
messages = [{"role": "user", "content": question}]
while True:
reply = scripted_model(messages)
messages.append({"role": "assistant", "content": reply})
calls = [block for block in reply if block["type"] == "tool_use"]
if not calls:
return messages
results = []
for call in calls: # your code runs the tool
output = TOOLS[call["name"]](**call["input"])
results.append({"type": "tool_result", "tool_use_id": call["id"],
"content": f"{output['status']}, "
f"{output['eta_days']} days away"})
messages.append({"role": "user", "content": results})
if __name__ == "__main__":
for number, message in enumerate(run("Where is order A-17?"), start=1):
content = message["content"]
if isinstance(content, str):
print(f"{number}. {message['role']:<9} text: {content}")
continue
for block in content:
detail = block.get("text") or block.get("content") or (
f"{block.get('name')}({block.get('input')})")
print(f"{number}. {message['role']:<9} {block['type']}: {detail}")
Output:
1. user text: Where is order A-17?
2. assistant tool_use: lookup_order({'order_id': 'A-17'})
3. user tool_result: in transit, 2 days away
4. assistant text: Your order is in transit, 2 days away.
Three details prevent most errors. Add the assistant's reply to the history before the results. Return one result for every call, matched by identifier, including for failures, flagged as errors. And loop until no calls remain, with a step limit that this teaching example omits. See Agent Tools, Function Calling and Tool Registries.
Structured output or tool call?
| You want | Use |
|---|---|
| The final answer as data | Structured output |
| The model to read or change something | Tool call |
| Arguments that match a schema exactly | A provider's strict tool mode, plus your validation |
| To act, then report in a fixed format | Both, where the provider allows the combination |
Claude's documentation, for instance, describes strict tool use with strict set to true alongside its JSON output format.
Tool descriptions are part of the prompt
The model chooses tools from their names, descriptions and parameter schemas, so write them for a reader who has never seen your system. Say what the tool does, when to use it, when not to, what the units and formats are and what comes back. Two tools with overlapping descriptions invite wrong choices.
| Vague | Clearer |
|---|---|
search(q): searches | search_policies(query): find passages in current company policies. Not for customer records. Returns up to five passages with titles. |
update(data) | set_ticket_priority(ticket_id, priority): priority is 1 (urgent) to 3. Changes one ticket. |
amount: number | amount_cents: whole number of cents, greater than zero |
Narrow tools are easier to authorize and test than a general one that accepts free-form commands. Return results that help the next decision: what happened, key identifiers and, on failure, whether trying again could help. Avoid returning secrets or more personal data than the task requires, because whatever a tool returns enters the context and may appear in a reply or a log.
Test the message layer
- A reply with no tool call, one call and several calls.
- An unknown tool name and a missing argument.
- A tool that raises an error or times out.
- A reply cut off part way through.
- Input that tries to imitate a system message or a tool result.
- A very long history near the model's limit.
All of these can be produced by a scripted model, as in the examples above, so they run quickly and cost nothing.
Correct shape, wrong content
A reply can satisfy every constraint and still be false: a real-looking order number that does not exist, a priority chosen carelessly, a date in the wrong year. Treat each field as a claim.
| Check | Example |
|---|---|
| Existence | Look up the identifier |
| Ownership | Does this user own the record? |
| Consistency | Do line items add up to the total? |
| Grounding | Does the quoted text appear in the source? |
| Range and policy | Is the amount within the limit? |
Constrained generation can also push a model to fill a required field it knows nothing about. Nullable fields and explicit "unknown" values reduce that pressure. Test with inputs that lack the information and confirm that the output says so.
Security rules for messages and tools
- Identity comes from your session, never from a model-supplied argument.
- Every tool call is validated and authorized at the moment of execution.
- Output placed in a web page, query or shell is escaped or parameterized like any untrusted input.
- Secrets are not placed in messages; tools hold credentials themselves.
- Logs of messages are protected, redacted and retained for a stated period.
Handle errors by kind
| Error | Response |
|---|---|
| Request rejected as invalid | Fix the code; do not retry unchanged |
| Rate limit or overload | Wait with increasing delays; cap attempts |
| Reply cut off by length | Raise the limit or split the task |
| Refusal | Show it or hand over; do not hammer the model |
| Schema or rule failure | Retry once or twice with the specific problem |
| Tool failure | Return a clear error result so the model can adapt |
Stay portable
Keep an internal representation of messages, tool calls and results, and translate at the edge for each provider. Do not assume that parallel tool calls, reasoning content, caching or strictness behave alike. Where a provider returns extra blocks that must be sent back, keep them intact. Run the same test set against every adapter. Model Routing, Fallbacks and Gateways discusses switching models, and What Is MCP? Hosts, Clients, Servers and Capabilities standardizes how tools are offered to applications.
Frequently asked questions
Is "function calling" different from "tool calling"?
The terms are largely used for the same mechanism. "Tool" can also include provider-hosted tools such as search that run on the provider's side.
Does a schema cost tokens?
Schemas and tool descriptions are part of what the model processes, so large ones add cost and latency. Check your usage figures and send only relevant tools.
Can the model call tools in parallel?
Many APIs allow several calls in one reply. Run them in parallel only when they are independent and safe, and return every result.
Should I ask for explanations inside the JSON?
A short rationale field can help review. Do not treat it as proof of why the model answered as it did.
References and further reading
- Claude documentation: Structured outputs
- Claude documentation: Mid-conversation system messages
- OpenAI documentation: Structured model outputs
- Understanding JSON Schema
Next steps
Designing Tool Schemas and Contracts
Describe tools so models use them well.
Agent System Prompts and Instruction Hierarchy
Write the instructions at the top of the list.
Reliable Tool Execution and Error Recovery
Make the running of calls dependable.