Validate structured model output and tool requests
Parse model output into schemas, handle invalid output and refusals, and run only allowlisted tools in a bounded loop.
By Invicly Tech, , in FastAPI with Python for AI Backends. About 13 minutes to read.
In short
When the service needs structured data from a model, such as an answer with citations or a request to run a tool, it parses the output into Pydantic models instead of trusting raw text. A discriminated union tells the parser which shape to expect, invalid output gets one repair attempt or a clean error, and refusals are handled as normal results. Tools come from a server-side allowlist, are read-only, check permissions with the real user's identity and run inside a loop with a hard turn limit.
Think of it like this: The model is a new assistant who fills in forms: you check every form against the template, and you only hand over the keys to rooms on an approved list, for rooms the customer may enter.
Explained simply
A language model returns text. Sometimes we want that text in a fixed shape, for example an answer plus the list of documents it cites, so our code can show citations as links. We ask the model for JSON in that shape, but we cannot assume it will follow the instructions every time.
So we check the output, just as we check a request from a stranger. Pydantic compares the JSON with a model class and either gives us a clean Python object or a clear list of what is wrong. Missing fields, wrong types or extra rubbish all fail the check instead of slipping into the rest of the app.
Sometimes the model will refuse, for example because the question asks for something it should not do. That is a normal answer, not a crash. We give refusals their own shape so the app can show a polite message.
Models can also ask us to run a tool, such as searching the tenant's documents. The model only asks; our server decides. We run only tools on a fixed list, only tools that read data, only with the real user's permissions, and only a few times per question.
Press Play on a diagram to walk through it one step at a time.
- 1Ask the model
Messages plus allowed tool schemas
- 2Validate the output
Answer, tool call or refusal
- 3Check the tool
Allowlisted, args valid, user permitted
- 4Run it read-only
Scoped to the caller's tenant
- 5Add the result and count the turn
Stop at the limit
- Back to step 1
- User to API loop: Which contracts renew in March?1Which contracts renew in March?
- API loop to Model: Messages plus allowed tools (turn 1)2Messages plus allowed tools (turn 1)
- Model to API loop: tool_call search_documents(query)3tool_call search_documents(query)
- API loop to Tool: Run with server tenant and scopes4Run with server tenant and scopes
- Tool to API loop: 3 matching chunks53 matching chunks
- API loop to Model: Tool result (turn 2)6Tool result (turn 2)
- Model to API loop: answer with citations7answer with citations
- API loop to User: Validated answer and sources8Validated answer and sources
In depth
Discriminated unions for model replies
Define one Pydantic model per kind of reply, each with a type field that is a Literal, such as answer, tool_call or refusal. Combine them in a union with Field(discriminator="type"). Pydantic reads the type field first and validates against that one model only, which is faster and gives precise errors such as citations missing in the answer model, instead of a confusing list of failures for every member.
Use TypeAdapter for a bare union: Reply.validate_json(raw) parses and validates in one step. Add constraints that express your rules: citations must have at least one item, each citation ID must look like a chunk ID, and text has a maximum length. After validation, check things a schema cannot know, such as whether every cited chunk was actually in the context you sent; drop or flag citations that were not.
- Literal type field on every variant
- Field(discriminator="type") on the union
- TypeAdapter(...).validate_json(raw)
- Constraints for length and required citations
- Cross-check citations against the context you sent
Handling invalid output and refusals
When validation fails, catch ValidationError. Make at most one repair attempt: send the model its previous output and a short summary of the errors, and ask for corrected JSON. If that fails too, stop. Return a clear error such as 502 with code model_output_invalid, and log the error locations and a hash or truncated, redacted copy of the output, not the full text.
Some providers offer a structured output or JSON schema mode that constrains generation to your schema. Use it when available, but still validate: constraints can be partial, outputs can be cut off at the token limit, and business rules sit outside the schema. A refusal variant, or a provider's own refusal signal, should map to a polite user-facing message and a metric, not to an exception. If refusals rise sharply after a prompt change, that is a regression to investigate.
- 1Raw text from the model
- 2validate_json
Discriminated union
- 3Invalid: one repair attempt
Send the errors back once
- 4Still invalid: 502
model_output_invalid, safe log
- 5Valid: answer, tool call or refusal
Then business checks
An allowlist of read-only tools
Keep a registry in code: a dict from tool name to an entry holding a Pydantic model for the arguments, a description sent to the model and the async function that runs it. Only names in that dict can run. The model sees the descriptions and argument schemas, so it can ask; it never sees or chooses anything else.
In this module every tool is read-only: search_documents, get_document_metadata, list_recent_jobs. Tools that change data, send email or spend money need a separate flow with human confirmation, covered in the security module. Validate the arguments with the tool's model before running it, with tight limits such as top_k between 1 and 10 and a maximum query length, and put a timeout on each tool run.
Permissions on the server, not in the prompt
A prompt that says only search the user's own documents is not a security control. Text in a retrieved document can tell the model to ignore that rule, which is called prompt injection. The defence is to make the rule impossible to break in code.
Tool functions take a context object built from the verified request: the user ID, tenant ID and scopes. The model supplies only the business arguments, such as the search query. Tool argument models must not even have a tenant_id field. Inside the tool, queries use the tenant-scoped repository from the persistence module, and the tool checks the user's scope before running. If the model asks for a tool the user is not allowed to use, return a short tool error message to the model and record it.
- Tool name to request
- Search text
- Optional filters such as date range
- Always validated and bounded
- User ID and tenant ID
- Scopes and roles
- Database session and repository
- Timeouts and limits
A bounded turn loop
The loop alternates between model and tools: send messages, validate the reply, run a tool if one was requested, append the tool result as a tool message, and ask again. It ends when the model returns an answer or a refusal. Set hard limits: a maximum number of turns, such as 4, an overall deadline from the resilience topic, and a cap on total tokens per question.
When a limit is reached, end with a clear outcome, such as an answer saying the question could not be completed, instead of an endless spin. Detect repeats too: if the model calls the same tool with the same arguments twice, return the cached result or stop. Log each turn with the tool name, argument summary, duration and result size so you can debug odd behaviour later.
Learn it in 5 short steps
About 40m each. Track them with a timer in your plan.
- 1Use discriminated Pydantic unions~40m
- 2Handle invalid output and refusals~40m
- 3Allowlist read-only tools~40m
- 4Check permissions on the server~40m
- 5Bound the tool-call loop~40m
Key points
- Parse model output with a Pydantic discriminated union, so every reply is exactly one known type.
- Treat invalid output as an expected event: retry once with the validation error, then fail cleanly.
- A refusal is a valid result; show it to the user rather than treating it as a crash.
- Only run tools from a server-side allowlist, validate their arguments and take tenant and user from the request, never from the model.
- Cap the loop by turns and time so a confused model cannot call tools forever.
Key terms
Tap a card to flip it. 0/6 known
Examples
class Answer(BaseModel):
type: Literal["answer"]
text: str
citations: list[str] = Field(min_length=1)
class ToolCall(BaseModel):
type: Literal["tool_call"]
name: str
arguments: dict
class Refusal(BaseModel):
type: Literal["refusal"]
reason: str
Reply = TypeAdapter(Annotated[Union[Answer, ToolCall, Refusal], Field(discriminator="type")])Imports come from typing and pydantic. Reply.validate_json(raw) returns an Answer, ToolCall or Refusal, or raises ValidationError; the type field picks the model.
Validate a reply and repair it once
Step 1: call the gateway and validate the text against the Reply union. Step 2: on ValidationError, send one follow-up message containing the error list and ask for corrected JSON only. Step 3: validate again; on a second failure raise an error the route maps to 502. Test it by making the fake provider return invalid JSON first and valid JSON second, then invalid both times; the first test should pass with two calls and the second should get 502.
async def get_reply(gw, req: GenerateRequest):
res = await gw.generate(req)
try:
return Reply.validate_json(res.text)
except ValidationError as e:
fix = req.model_copy(update={"messages": [*req.messages,
{"role": "assistant", "content": res.text},
{"role": "user", "content": f"Invalid JSON: {e.errors(include_input=False)}. Reply with corrected JSON only."}]})
res = await gw.generate(fix)
try:
return Reply.validate_json(res.text)
except ValidationError:
raise ModelOutputInvalid()A tool registry with server-side context
Step 1: describe each tool's arguments with a Pydantic model that has no tenant or user fields. Step 2: register tools in a dict. Step 3: when the model asks for a tool, look it up, validate the arguments and call it with a ToolContext built from the verified request. Unknown tools and invalid arguments return an error message to the model instead of running anything. Test it with a model reply that requests a tool named delete_document and check that nothing runs.
class SearchArgs(BaseModel):
query: str = Field(min_length=2, max_length=200)
top_k: int = Field(default=5, ge=1, le=10)
async def search_documents(ctx: ToolContext, args: SearchArgs) -> list[dict]:
return await ctx.repo.search(args.query, args.top_k) # repo is tenant-scoped
TOOLS = {"search_documents": (SearchArgs, search_documents)}
async def run_tool(ctx: ToolContext, call: ToolCall) -> dict:
if call.name not in TOOLS:
return {"error": f"Tool {call.name} is not available"}
model, fn = TOOLS[call.name]
args = model.model_validate(call.arguments) # ValidationError -> tool error
return {"result": await fn(ctx, args)}Quick reference
- Union[A, B, C] with Field(discriminator="type") and a Literal type on each
- TypeAdapter(...).validate_json(raw) parses and validates in one step
- One repair attempt, then fail with a stable error code
- Refusal is a valid reply type; show it politely and count it
- Tools: server-side allowlist, read-only, arguments validated with Pydantic
- Tenant and user come from the request context, never from tool arguments
- Cap turns (for example 4), time and tokens per question
Common mistakes
- Calling json.loads and reading keys by hand, so a missing field becomes a KeyError deep in the code.
- Letting the model choose the tenant_id or user_id argument of a tool.
- A while True tool loop with no turn limit or deadline.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Define Answer, ToolCall and Refusal models and a Reply TypeAdapter, then validate the string {"type": "refusal", "reason": "out of scope"}.
- Exercise 2medium
After validating an Answer, remove any citation that was not among the chunk IDs sent to the model, and mark the answer as low confidence if none remain.
- Exercise 3hard
Write the bounded loop: up to 4 turns, run allowlisted tools via run_tool, stop on answer or refusal, and return a clear outcome when the limit is hit.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- If the provider has a JSON schema mode, do I still need Pydantic validation?
- Yes. Schema modes reduce errors but do not check your business rules, and output can still be cut off by token limits. Validation is cheap and catches what slips through.
- What is the difference between a refusal and an error?
- A refusal is the model deliberately declining, a valid outcome you show to the user. An error is something going wrong, such as invalid output or a timeout, which you log and report with an error code.
- Can tools ever write data?
- In this module, no. Later, write tools can be allowed behind a confirmation step where a human approves the exact change, plus server-side permission checks.
- How many turns should I allow?
- Start small, such as 3 or 4, and measure how many turns real questions need. Raise it only with evidence, and keep the overall deadline and token cap in place.