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.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

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.

Beginner Roles and the conversation

Who is speaking

RoleWritten byCarries
System or developerThe application builderPurpose, rules, tone, limits
UserThe person, or your program on their behalfRequests and supplied material
AssistantThe modelReplies and tool requests
Tool resultYour program, after running a toolWhat 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.

InstructionsStable for the task
User turn
Assistant turnMay ask for a tool
Tool result
Assistant turnAnswer or next request
In stateless use, your application sends the whole history each time. Some services can store it for you.

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.

Do not mix trust levels

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.

TechniqueWhat it doesWatch for
Trim large tool resultsKeeps the useful part of a long outputCutting away the evidence needed later
Summarize older turnsReplaces detail with a shorter accountSummaries that lose numbers or constraints
Keep facts in task stateStores identifiers and decisions outside the chatState and conversation disagreeing
Start a fresh contextBegins a sub-task with only what it needsMissing 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.

Intermediate Structured output and tool calls

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.

ApproachValid JSONMatches your schema
Instruction onlyNot guaranteedNot guaranteed
JSON mode, where offeredIntendedNot guaranteed
Structured outputsYes, for completed repliesYes, 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 enum for fixed choices.
  • Set additionalProperties to false and mark fields required; for optional data, allow null.
  • 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.

You sendMessages and tool descriptions
Model asksTool name, arguments, call id
You check and runValidate, authorize, execute
You replyResult tied to the call id
Model continues

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 wantUse
The final answer as dataStructured output
The model to read or change somethingTool call
Arguments that match a schema exactlyA provider's strict tool mode, plus your validation
To act, then report in a fixed formatBoth, 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.

VagueClearer
search(q): searchessearch_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: numberamount_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.

Expert Reliability, security and portability

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.

CheckExample
ExistenceLook up the identifier
OwnershipDoes this user own the record?
ConsistencyDo line items add up to the total?
GroundingDoes the quoted text appear in the source?
Range and policyIs 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

ErrorResponse
Request rejected as invalidFix the code; do not retry unchanged
Rate limit or overloadWait with increasing delays; cap attempts
Reply cut off by lengthRaise the limit or split the task
RefusalShow it or hand over; do not hammer the model
Schema or rule failureRetry once or twice with the specific problem
Tool failureReturn 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

Next steps