Sub topic 11
Structured output and tool calling on local models
This chapter assumes you can already send a chat completion to your local server and read choices[0].message. It covers two features that vary between servers and models: getting JSON back reliably, and letting the model request a function call.
Why these features need care
A hosted API enforces structure on the server side. A local server may only pass your request to the model, which then predicts text. Whether you get valid JSON or a well-formed tool call depends on three things: the server version, the model, and the request fields you use. Test each feature against your own setup before relying on it.
Asking for JSON
The response_format parameter asks the server to constrain output to JSON. The loosest form is json_object. Even then, the prompt should say you want JSON and describe the shape.
import json
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="local")
response = client.chat.completions.create(
model="llama3.2",
messages=[
{
"role": "system",
"content": 'Reply only with JSON shaped like {"city": string, "country": string}.',
},
{"role": "user", "content": "Where is the Eiffel Tower?"},
],
response_format={"type": "json_object"},
temperature=0,
)
data = json.loads(response.choices[0].message.content)
print(data["city"], data["country"])JSON mode guarantees syntax, not your schema. The keys can be missing or misnamed, so check them before use. Some servers also accept {"type": "json_schema", ...}, which constrains output to a schema. Others ignore the field or return a 400 error.
Tool calling
With tool calling, you describe functions in the tools list. The model does not run anything. It replies with a tool_calls entry naming a function and its arguments, your code runs the function, and you send the result back.
import json
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="local")
def get_temperature(city: str) -> str:
return json.dumps({"city": city, "celsius": 18})
tools = [{
"type": "function",
"function": {
"name": "get_temperature",
"description": "Get the current temperature for a city.",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}]
messages = [{"role": "user", "content": "How warm is it in Lisbon?"}]
first = client.chat.completions.create(
model="llama3.2", messages=messages, tools=tools
)
reply = first.choices[0].message
if reply.tool_calls:
messages.append(reply)
for call in reply.tool_calls:
args = json.loads(call.function.arguments)
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": get_temperature(**args),
})
final = client.chat.completions.create(
model="llama3.2", messages=messages, tools=tools
)
print(final.choices[0].message.content)
else:
print(reply.content)Two details matter here. function.arguments is a JSON string, so parse it yourself. The result goes back in a message with role tool, linked by tool_call_id.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| 400 error mentioning tools | The model or server does not support tools | Choose a model that advertises tool support, or update the server |
| `tool_calls` is empty and the answer is plain text | The model chose not to call, or ignores tools | Make the description clearer, or handle the fallback branch |
| `json.loads` raises an error | Output was cut off by `max_tokens`, or JSON mode was ignored | Raise `max_tokens`, check `finish_reason`, and retry |
| Wrong or missing argument names | Small models drift from the schema | Validate arguments and return an error message to the model |
Exercise
A request with response_format={"type": "json_object"} returns text that parses as JSON, but your code fails with a KeyError. What happened, and what should you do?
Show answer
JSON mode guarantees valid JSON syntax, not your schema. The model returned different or missing keys. Describe the exact shape in the system prompt, use json_schema if your server supports it, and validate the keys after parsing, retrying or reporting an error when they are wrong.
Exercise
After the model returns a tool call, what message must you append before asking for the final answer, and which fields does it need?
Show answer
Append the assistant message that contains the tool call, then a message with role tool. The tool message needs tool_call_id matching the call's id, and content holding the function result as a string.