Sub topic 11
Structured output and tool calling on local models
Applications usually need data they can parse, not prose. This chapter covers two ways to get that from a local model: constraining the reply to JSON, and letting the model ask your code to run functions (tool calling). Both use the same OpenAI-compatible endpoint as earlier chapters. Support varies a lot between servers and models, so most of the work is checking what yours can do.
You should already have:
- a client configured with a local
base_urland placeholder key, - a working
chat.completions.createcall with system and user messages, - a model that is downloaded and listed by the server.
Three levels of structure
You can ask for structured output at three levels, from weakest to strongest guarantee.
| Level | How you ask | What is guaranteed |
|---|---|---|
| Prompt only | Describe the format in the system message | Nothing. The model may add prose or break the syntax. |
| JSON mode | `response_format={"type": "json_object"}` | Syntactically valid JSON, on servers that enforce it. The keys are not guaranteed. |
| JSON schema | `response_format={"type": "json_schema", ...}` | Output matches your schema, on servers that constrain decoding to it. |
Servers that enforce JSON mode or a schema usually restrict which tokens the model may pick at each step (grammar-constrained decoding). That is why the guarantee can be strong even with a small model. Servers that ignore the field silently fall back to the prompt-only level, so you still need to validate.
JSON mode
JSON mode needs the prompt to say that you want JSON and what shape you want. Many servers also work better when the word "JSON" appears in the messages.
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 a JSON object with the keys "
"city (string) and population_millions (number)."
),
},
{"role": "user", "content": "What is the largest city in Japan?"},
],
response_format={"type": "json_object"},
temperature=0,
)
data = json.loads(response.choices[0].message.content)
print(data["city"], data["population_millions"])Even with JSON mode on, the keys can differ from what you asked for, so the code above can raise KeyError. A model that hits max_tokens mid-object also produces truncated JSON. Check response.choices[0].finish_reason: the value "length" means the output was cut off.
JSON schema
A schema lets you state the exact keys and types. Servers that support it build a grammar from the schema, so the reply cannot leave it.
import json
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="local")
schema = {
"type": "object",
"properties": {
"city": {"type": "string"},
"population_millions": {"type": "number"},
},
"required": ["city", "population_millions"],
"additionalProperties": False,
}
response = client.chat.completions.create(
model="llama3.2",
messages=[
{"role": "user", "content": "Give the largest city in Japan and its population."}
],
response_format={
"type": "json_schema",
"json_schema": {"name": "city_info", "strict": True, "schema": schema},
},
temperature=0,
)
choice = response.choices[0]
if choice.finish_reason == "length":
raise RuntimeError("Output was truncated; raise max_tokens.")
data = json.loads(choice.message.content)
print(data)Some servers accept json_schema only in newer versions. Others expose the same idea under a different field, such as a guided_json extra parameter on vLLM or a grammar field on llama-server's native API. If a server rejects the field with a 400 error, read its documentation and fall back to JSON mode plus validation.
Validate and retry
Treat model output as untrusted input, even when the server enforces a schema. A small validator and a bounded retry loop keep one bad reply from crashing your program.
import json
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="local")
REQUIRED = {"city": str, "population_millions": (int, float)}
def validate(data):
if not isinstance(data, dict):
raise ValueError("Top level is not an object")
for key, types in REQUIRED.items():
if key not in data:
raise ValueError(f"Missing key: {key}")
if not isinstance(data[key], types):
raise ValueError(f"Wrong type for key: {key}")
return data
def ask(question, attempts=3):
messages = [
{
"role": "system",
"content": "Reply only with JSON with keys city (string) and population_millions (number).",
},
{"role": "user", "content": question},
]
for _ in range(attempts):
response = client.chat.completions.create(
model="llama3.2",
messages=messages,
response_format={"type": "json_object"},
temperature=0.2,
)
text = response.choices[0].message.content
try:
return validate(json.loads(text))
except ValueError as err: # json.JSONDecodeError is a ValueError
messages.append({"role": "assistant", "content": text})
messages.append(
{"role": "user", "content": f"That was invalid: {err}. Reply again with valid JSON only."}
)
raise RuntimeError("No valid JSON after several attempts")
print(ask("What is the largest city in Japan?"))Feeding the error back to the model gives it something concrete to correct. Keep the attempt count small, because every retry costs a full generation on your own hardware.
Tool calling
Tool calling lets the model request that your program run a function. The model never runs anything itself. It returns a structured request, you run the function, and you send the result back.
The loop has two requests:
- You send the messages plus a
toolslist describing each function. The model replies withtool_callsinstead of text. - You run the functions, append the results as
toolmessages, and send everything again. The model then writes the final answer.
A complete example
import json
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="local")
def get_weather(city: str) -> dict:
# Stand-in for a real lookup.
return {"city": city, "temp_c": 18, "conditions": "cloudy"}
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather for a city.",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name, e.g. Oslo"}
},
"required": ["city"],
},
},
}
]
available = {"get_weather": get_weather}
messages = [{"role": "user", "content": "What is the weather in Oslo?"}]
first = client.chat.completions.create(
model="llama3.2", messages=messages, tools=tools
)
msg = first.choices[0].message
if not msg.tool_calls:
print(msg.content) # The model chose to answer directly.
else:
messages.append(
{
"role": "assistant",
"content": msg.content or "",
"tool_calls": [
{
"id": tc.id,
"type": "function",
"function": {
"name": tc.function.name,
"arguments": tc.function.arguments,
},
}
for tc in msg.tool_calls
],
}
)
for tc in msg.tool_calls:
fn = available.get(tc.function.name)
try:
args = json.loads(tc.function.arguments)
result = fn(**args) if fn else {"error": f"Unknown tool {tc.function.name}"}
except (json.JSONDecodeError, TypeError) as err:
result = {"error": f"Bad arguments: {err}"}
messages.append(
{"role": "tool", "tool_call_id": tc.id, "content": json.dumps(result)}
)
final = client.chat.completions.create(
model="llama3.2", messages=messages, tools=tools
)
print(final.choices[0].message.content)Points to notice:
tool_calls[i].function.argumentsis a JSON string, not a dictionary. Parse it yourself, and expect that it can be malformed.- Each
toolmessage carries thetool_call_idof the call it answers. Some local servers generate those IDs, and some models need them echoed exactly. - The model may call a function that does not exist, pass wrong argument names, or call several tools at once. The example looks the name up in a dictionary and returns an error object as the result. Models often recover when they see the error.
- The final request still includes
tools. Some servers require this when the history contains tool calls.
Making it reliable with local models
Small local models are noticeably worse at tool calling than large hosted ones. These habits help:
- Write clear function names and one-sentence descriptions. The model decides what to call from this text alone.
- Offer few tools. Two or three works much better than twenty.
- Use a low temperature, such as 0 to 0.2, for tool and JSON requests.
- Cap the loop. Allow a fixed number of tool rounds, such as 5, so a confused model cannot loop forever.
- Use
tool_choiceonly after testing it. Values like"auto"are widely accepted, but forcing a specific function is not supported everywhere.
Probe before you rely on a feature
Support depends on the server, its version, and the specific model. A model whose template has no tool support may produce a 400 error mentioning tools, or it may print the call as plain text in content. Test each feature with a tiny request when your program starts.
import openai
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="local")
probe_tool = [
{
"type": "function",
"function": {
"name": "ping",
"description": "Call this tool to confirm tools work.",
"parameters": {"type": "object", "properties": {}},
},
}
]
def supports_tools(model):
try:
r = client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": "Call the ping tool."}],
tools=probe_tool,
temperature=0,
max_tokens=100,
)
except openai.BadRequestError:
return False
return bool(r.choices[0].message.tool_calls)
print("tools:", supports_tools("llama3.2"))A False result means either that the server rejected the request or that the model answered in text. Both mean you should not depend on tool calling with that setup.
Common failures
| Symptom | Likely cause | Fix |
|---|---|---|
| 400 error that mentions `tools` | The model or server does not support tools | Choose a tool-capable model, or parse JSON from plain text |
| JSON wrapped in prose or Markdown fences | `response_format` was ignored | Strip the fences and validate, or upgrade the server |
| `JSONDecodeError` on the output | Truncated by `max_tokens`, or no enforcement | Check `finish_reason`, raise the limit, retry |
| `tool_calls` is `None` but `content` shows a call | The model wrote the call as text | Try a different model, or add instructions and parse the text |
| Wrong or missing argument names | Weak model, vague descriptions | Simplify the schema, improve descriptions, return an error and retry |
| Streaming tool calls arrive in pieces | The arguments string is split across chunks | Concatenate `arguments` fragments per call index before parsing |
Exercise
Your tool-calling code works with one model, but with another model on the same server message.tool_calls is always None and content contains text like {"name": "get_weather", ...}. Name two reasonable responses, and explain why you should still validate arguments when the call does arrive in tool_calls.
Show answer
The second model most likely does not support native tool calling, so it imitates the call in plain text. You can switch to a tool-capable model, or parse the JSON from content yourself and run the same dispatch code. Arguments still need validation because they are generated text. They arrive as a JSON string that can be malformed, can contain wrong names or types, and can name a tool that does not exist. Parse them in a try block, check them against the function's expectations, and return an error result to the model rather than crashing or running unchecked input.
Exercise
A JSON-mode request returns {"city": "Tokyo", "population_mil and then stops. Which field do you check, what value do you expect, and what do you change?
Show answer
Check response.choices[0].finish_reason. It should be "length", which means generation hit the token cap. Raise max_tokens (or remove the cap), or ask for a shorter object, then retry.