Sub topic 11
Tool calls and structured output across providers
This chapter assumes you have read the earlier chapters on neutral types, the provider interface, and adapters. It also assumes you have used tool calling (function calling) with at least one hosted chat API.
Why tool calls are harder than text
A plain chat completion maps cleanly onto the neutral types: messages go in, text comes out. Tool calls break that symmetry. The model returns a request to run a function, your code runs it, and you send the result back in a follow-up message.
Providers agree on the idea but not on the wire format.
| Aspect | Common variation |
|---|---|
| Tool definition | JSON Schema under a `parameters` key, or under `input_schema` |
| Tool call in response | A separate `tool_calls` field, or a content block mixed with text |
| Arguments | A JSON string you must parse, or an already parsed object |
| Tool result | A message with role `tool`, or a user message holding a result block |
| Call identifier | Present on every call, or missing on some APIs |
Your application should see none of this. The neutral types need to carry tools, and each adapter converts them.
Extending the neutral types
Add tool definitions to the request. Add tool calls to the response. Add a result type for the next turn. Keep arguments as a parsed dictionary so no caller handles raw JSON strings.
from dataclasses import dataclass, field
from typing import Any
@dataclass
class ToolSpec:
name: str
description: str
parameters: dict[str, Any] # JSON Schema object
@dataclass
class ToolCall:
id: str
name: str
arguments: dict[str, Any]
@dataclass
class ToolResult:
call_id: str
content: str
@dataclass
class ToolChatResponse:
text: str
model: str
tool_calls: list[ToolCall] = field(default_factory=list)An empty tool_calls list means the model answered in text. A non-empty list means the caller must run the tools and send the results back.
Translating in the adapter
The adapter owns the format differences. The example below converts a neutral ToolSpec into two common shapes and parses arguments from a response.
import json
def spec_to_chat_style(spec: ToolSpec) -> dict:
return {
"type": "function",
"function": {
"name": spec.name,
"description": spec.description,
"parameters": spec.parameters,
},
}
def spec_to_block_style(spec: ToolSpec) -> dict:
return {
"name": spec.name,
"description": spec.description,
"input_schema": spec.parameters,
}
def parse_arguments(raw: str | dict) -> dict:
if isinstance(raw, dict):
return raw
try:
return json.loads(raw)
except json.JSONDecodeError as exc:
raise ValueError(f"Model returned invalid tool arguments: {raw!r}") from exc
spec = ToolSpec("get_weather", "Get current weather", {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
})
assert spec_to_chat_style(spec)["function"]["parameters"] == spec.parameters
assert spec_to_block_style(spec)["input_schema"] == spec.parameters
assert parse_arguments('{"city": "Oslo"}') == {"city": "Oslo"}Model output can contain malformed JSON, so parsing needs an explicit failure path. Decide whether that failure is a retryable ProviderError or a validation error your loop handles by asking the model to try again.
Structured output
Structured output means getting JSON that matches a schema. Providers offer it in different ways: a native JSON schema mode, a forced tool call whose arguments are the output, or only a prompt instruction.
Expose one neutral operation, such as a response_schema field on the request. Each adapter picks the strongest mechanism it has. Whatever the mechanism, validate the result in your own code. A provider that guarantees the schema and one that merely asks for it should look the same to callers.
def validate_required(data: dict, schema: dict) -> dict:
missing = [k for k in schema.get("required", []) if k not in data]
if missing:
raise ValueError(f"Missing required fields: {missing}")
return data
schema = {"type": "object", "required": ["title", "year"]}
assert validate_required({"title": "Dune", "year": 1965}, schema)For production use a full JSON Schema validator. This check only shows where validation belongs.
Common errors
- Passing provider-shaped history back. If you store raw provider messages, switching providers mid-conversation fails. Store neutral messages and let each adapter convert them.
- Dropping call IDs. Results must reference the call they answer. Generate an ID in the adapter when the provider supplies none.
- Assuming one call per turn. Models can return several calls. Always loop over the list.
- Trusting arguments. Validate them before running a tool that has side effects.
Exercise
A provider returns tool arguments as a JSON string, and another returns them as a parsed object. Where should this difference be handled, and what type should the application see?
Show answer
Handle it in each adapter, or in a shared helper such as parse_arguments the adapters call. The application should always see a parsed dictionary in ToolCall.arguments, and should never need to know which form the provider used.
Exercise
Why should conversation history be stored as neutral messages rather than as the provider's raw response objects?
Show answer
Raw objects use one provider's format. If you switch or fall back to another provider mid-conversation, that provider cannot read them. Neutral messages can be converted by whichever adapter handles the next request.