Sub topic 11
Tool calls and structured output across providers
Plain chat completion is the easy case for an abstraction. Tool calls and structured output are harder, because the providers differ in wire format and in how the conversation history is shaped. This chapter extends the neutral types so that application code never sees those differences.
This chapter assumes you have read the earlier chapters on neutral types, the ChatProvider protocol, adapters, and error normalization. You should also have used tool calling (also called function calling) with at least one hosted API.
What you will build
- Neutral types for tool definitions, tool calls, and tool results.
- Translation functions for two wire formats, shown as pure functions over dictionaries so you can test them without an SDK.
- A structured-output strategy that works whether or not a provider supports it natively.
- A provider-neutral tool loop.
How tool calling differs between providers
In tool calling, you describe functions to the model as JSON Schema. The model may reply with a request to call one of them. Your code runs the function and sends the result back. Every provider supports this idea, but the shapes differ.
| Aspect | OpenAI-style chat API | Anthropic-style messages API |
|---|---|---|
| Tool definition | `{"type": "function", "function": {name, description, parameters}}` | `{name, description, input_schema}` |
| Model's tool request | `tool_calls` list on the assistant message | `tool_use` blocks inside the content list |
| Arguments | A JSON **string** you must parse | An already-parsed object |
| Tool result | A message with role `tool` and a `tool_call_id` | A `user` message holding a `tool_result` block with `tool_use_id` |
| Message content | Usually a string | A list of typed blocks |
Check each provider's current documentation before you write an adapter. Field names and options change between API versions.
Extending the neutral types
The earlier Message carried only text. A tool conversation needs two more kinds of content: an assistant message that requests calls, and a message that returns a result. The neutral types hold both.
from dataclasses import dataclass, field
from typing import Any
@dataclass
class ToolSpec:
name: str
description: str
parameters: dict[str, Any] # JSON Schema for the arguments
@dataclass
class ToolCall:
id: str
name: str
arguments: dict[str, Any] # always a parsed dict, never a string
@dataclass
class ToolResult:
call_id: str
content: str
is_error: bool = False
@dataclass
class Message:
role: str # "system", "user", "assistant" or "tool"
content: str = ""
tool_calls: list[ToolCall] = field(default_factory=list)
tool_result: ToolResult | None = None
@dataclass
class ChatRequest:
model: str
messages: list[Message]
max_tokens: int = 512
temperature: float | None = None
tools: list[ToolSpec] = field(default_factory=list)
@dataclass
class ChatResponse:
text: str
model: str
input_tokens: int | None = None
output_tokens: int | None = None
tool_calls: list[ToolCall] = field(default_factory=list)Two design decisions matter here.
- Arguments are parsed once, at the boundary. Application code should never call
json.loadson model output. A provider that returns a string and one that returns an object both become adict. - The call ID is kept. Providers use the ID to pair a result with its request. The neutral
ToolCall.idis whatever the provider issued, and your code echoes it back inToolResult.call_id.
Writing the translators
Each adapter needs four translations: tool definitions out, tool calls in, and messages out for the assistant and result roles. Keeping them as pure functions over dictionaries makes them cheap to test.
The ProviderError class repeats the one from the error-normalization chapter so this block runs on its own.
import json
class ProviderError(Exception):
def __init__(self, message: str, retryable: bool):
super().__init__(message)
self.retryable = retryable
# ---------- OpenAI-style ----------
def to_openai_tools(tools: list[ToolSpec]) -> list[dict]:
return [
{
"type": "function",
"function": {
"name": t.name,
"description": t.description,
"parameters": t.parameters,
},
}
for t in tools
]
def from_openai_message(msg: dict) -> tuple[str, list[ToolCall]]:
calls = []
for c in msg.get("tool_calls") or []:
raw = c["function"]["arguments"]
try:
args = json.loads(raw)
except json.JSONDecodeError:
# Models sometimes emit broken JSON. Another attempt may succeed.
raise ProviderError(f"Malformed tool arguments: {raw!r}", retryable=True)
calls.append(ToolCall(id=c["id"], name=c["function"]["name"], arguments=args))
return msg.get("content") or "", calls
def message_to_openai(m: Message) -> dict:
if m.role == "tool" and m.tool_result:
return {
"role": "tool",
"tool_call_id": m.tool_result.call_id,
"content": m.tool_result.content,
}
out: dict = {"role": m.role, "content": m.content}
if m.tool_calls:
out["tool_calls"] = [
{
"id": c.id,
"type": "function",
"function": {"name": c.name, "arguments": json.dumps(c.arguments)},
}
for c in m.tool_calls
]
return out
# ---------- Anthropic-style ----------
def to_anthropic_tools(tools: list[ToolSpec]) -> list[dict]:
return [
{"name": t.name, "description": t.description, "input_schema": t.parameters}
for t in tools
]
def from_anthropic_content(blocks: list[dict]) -> tuple[str, list[ToolCall]]:
text = "".join(b["text"] for b in blocks if b["type"] == "text")
calls = [
ToolCall(id=b["id"], name=b["name"], arguments=b["input"])
for b in blocks
if b["type"] == "tool_use"
]
return text, calls
def message_to_anthropic(m: Message) -> dict:
if m.role == "tool" and m.tool_result:
r = m.tool_result
return {
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": r.call_id,
"content": r.content,
"is_error": r.is_error,
}
],
}
if m.tool_calls:
blocks: list[dict] = []
if m.content:
blocks.append({"type": "text", "text": m.content})
blocks += [
{"type": "tool_use", "id": c.id, "name": c.name, "input": c.arguments}
for c in m.tool_calls
]
return {"role": "assistant", "content": blocks}
return {"role": m.role, "content": m.content}
# ---------- Checks ----------
openai_msg = {
"content": None,
"tool_calls": [
{
"id": "call_1",
"type": "function",
"function": {"name": "get_weather", "arguments": "{\"city\": \"Oslo\"}"},
}
],
}
text, calls = from_openai_message(openai_msg)
assert text == "" and calls[0].arguments == {"city": "Oslo"}
anthropic_blocks = [
{"type": "text", "text": "Checking."},
{"type": "tool_use", "id": "toolu_1", "name": "get_weather", "input": {"city": "Oslo"}},
]
text, calls2 = from_anthropic_content(anthropic_blocks)
assert text == "Checking." and calls2[0].arguments == {"city": "Oslo"}
result = Message("tool", tool_result=ToolResult(call_id="toolu_1", content="4 C"))
assert message_to_openai(result)["tool_call_id"] == "toolu_1"
assert message_to_anthropic(result)["content"][0]["type"] == "tool_result"Notice that message_to_anthropic turns a neutral tool message into a user message. Neutral code does not know that. The adapter converts the whole history on every call, so the application keeps one history list in neutral form and any provider can read it.
A provider-neutral tool loop
With the neutral types in place, the loop that runs tools contains no provider names. The function below works with any object that has a complete method, including the fake provider from the testing chapter.
from typing import Callable
def run_with_tools(
provider,
request: ChatRequest,
handlers: dict[str, Callable[..., str]],
max_turns: int = 5,
) -> ChatResponse:
for _ in range(max_turns):
response = provider.complete(request)
if not response.tool_calls:
return response
request.messages.append(
Message("assistant", response.text, tool_calls=response.tool_calls)
)
for call in response.tool_calls:
handler = handlers.get(call.name)
if handler is None:
result = ToolResult(call.id, f"Unknown tool: {call.name}", is_error=True)
else:
try:
result = ToolResult(call.id, handler(**call.arguments))
except Exception as exc: # report to the model, do not crash
result = ToolResult(call.id, str(exc), is_error=True)
request.messages.append(Message("tool", tool_result=result))
raise RuntimeError("Tool loop did not finish within max_turns")Three details here are easy to miss.
- Every call gets a result. Providers reject a history in which a requested call has no matching result. This includes calls to unknown tools, which is why the loop answers them with an error result.
- The turn cap is mandatory. A model can request tools forever. The cap turns that into an error you can see.
- Errors go back to the model. A failed handler returns
is_error=Truecontent so the model can correct its arguments. Your code does not crash.
Models can also request several calls in one turn. The neutral tool_calls list handles that without any change.
Structured output
Structured output means getting JSON that matches a schema, for example to extract fields from text. Providers offer three different mechanisms.
- Native schema mode. The request carries a schema, and the provider constrains decoding to match it. Some OpenAI-style APIs offer this through a
response_formatoption. - Forced tool use. You define a single tool whose parameters are your schema and require the model to call it. The tool arguments are your structured result. This works on APIs without native schema mode.
- Prompting only. You ask for JSON in the prompt and parse the reply. This works anywhere but gives no guarantee.
The neutral interface should state the need and let each adapter pick the mechanism. A forced tool is the most portable fallback, because the arguments arrive already parsed.
def extract_structured(
provider,
request: ChatRequest,
schema_name: str,
schema: dict[str, Any],
) -> dict[str, Any]:
"""Ask for output matching `schema`. Works with any adapter that supports tools."""
spec = ToolSpec(
name=schema_name,
description="Return the final answer in this format.",
parameters=schema,
)
request.tools = [spec]
response = provider.complete(request)
for call in response.tool_calls:
if call.name == schema_name:
return call.arguments
raise ProviderError("Model did not return structured output", retryable=True)This function assumes the adapter forces the tool call. A real adapter would add the provider's tool-choice option when the request includes exactly one tool. Add a neutral tool_choice field to ChatRequest when you need that control, and map it in each adapter.
Edge cases to plan for
- Schema subsets. Providers accept different parts of JSON Schema. A schema that works on one may be rejected by another. Keep schemas flat, with simple types and few optional features, if you intend to switch.
- Switching mid-conversation. Tool call IDs from one provider appear in the history sent to the next. Because adapters translate the whole history, this usually works. Test it, because some providers check ID formats.
- Text alongside tool calls. Some providers return explanatory text with a call and some return none. Never assume
textis empty whentool_callsis present. - Tool name rules. Providers restrict the characters and length of tool names. Use lowercase letters, digits, and underscores to stay safe.
- Parallel calls. Providers differ in how readily they emit several calls in one turn. Your loop handles both, but ordering of results may matter to your tools.
- Streaming. Tool arguments often arrive as partial JSON fragments. An adapter must buffer fragments per call and parse only when the call is complete.
When the abstraction leaks
The neutral types hide the wire format. They do not hide model behavior. Two models given the same tool descriptions will choose tools, fill arguments, and handle ambiguity differently. A fallback that succeeds technically can still produce different results. Run your tool-using flows against every provider you intend to fall back to, and keep a small set of recorded test cases for each.
Exercise
Your application stores conversation history in neutral form. A request starts on an OpenAI-style provider, which returns a tool call. The application runs the tool and appends a Message("tool", tool_result=...). Fallback then moves the next request to an Anthropic-style provider. What must the Anthropic adapter do with that history, and why is it safe for the application to store the history in neutral form?
Show answer
The adapter must translate every message on each call. The assistant message with tool_calls becomes an assistant message with tool_use blocks, with the arguments kept as a dict. The neutral tool message becomes a user message holding a tool_result block whose tool_use_id equals the neutral call_id. Storing neutral history is safe because no provider format is baked into it. Each adapter converts from the neutral form to its own wire format, so the history works with whichever provider handles the next request.
Exercise
Why does run_with_tools append an error ToolResult for an unknown tool name, rather than skipping the call?
Show answer
The provider requires every tool call it issued to have a matching result in the next request. Skipping the call would produce an invalid history and a request error. An error result keeps the history valid and tells the model the tool does not exist, so it can try something else.