Skip to main content

Structured output

Structured output asks the model for JSON in a shape you declare and hands the answer back as a Rust value, so the rest of your program never parses free text. It is a feature of one request, so this guide uses Client directly. An Agent does not expose response_format yet, which means a typed answer from the model's final turn comes from a Client call, and tool arguments are typed another way, covered at the end.

Choosing a response format​

ResponseFormat has three variants, and a request that sets none leaves the choice to the provider.

pub enum ResponseFormat {
Text,
JsonObject,
JsonSchema { name: String, schema: Value, strict: bool },
}

JsonObject asks for any valid JSON object and says nothing about its shape. JsonSchema constrains the answer to a schema you supply, with a name that labels it on the wire. With strict: true the provider enforces the schema where it can, instead of treating it as a hint. See Requests for how the field sits in a request.

A typed answer​

Client::generate_as sends the request and deserializes the answer into your type.

use freyja::{Client, EndpointPreset, GenerateRequest, Message, ResponseFormat, Role, strict_schema};
use serde::Deserialize;
use serde_json::json;

#[derive(Deserialize)]
struct Recommendation {
name: String,
purpose: String,
}

let client = Client::from_env(EndpointPreset::OpenAi)?;

let request = GenerateRequest::new()
.message(Message::text(Role::User, "Recommend one Rust crate for parsing JSON."))
.response_format(ResponseFormat::JsonSchema {
name: "recommendation".into(),
schema: strict_schema(json!({
"type": "object",
"properties": {
"name": {"type": "string"},
"purpose": {"type": "string"}
},
"required": ["name", "purpose"]
})),
strict: true,
});

let recommendation: Recommendation = client.generate_as(&request).await?;
println!("{}: {}", recommendation.name, recommendation.purpose);

This example calls a real model, so it needs OPENAI_API_KEY and the network. The manual route still works, generate then output_text() then serde_json::from_str, and suits code that needs the raw text as much as the value.

Making a schema acceptable​

OpenAI's strict mode takes a subset of JSON Schema and rejects a schema written to spec, for example one with no additionalProperties: false. strict_schema rewrites a schema into that subset. It adds additionalProperties: false to every object, moves every property into required while making the optional ones nullable, renames oneOf to anyOf, and removes a few keywords that only narrow a value. It is idempotent, so a schema already in the subset passes through unchanged. The full list of what it changes and what it leaves alone is in Requests.

Schemas from schemars​

Freyja does not derive a schema from your type, so the schema and the struct can drift apart. The schemars crate closes that gap. Add it to your own Cargo.toml, derive JsonSchema next to Deserialize, and pass its output through strict_schema:

use schemars::JsonSchema;

#[derive(Deserialize, JsonSchema)]
struct Person {
name: String,
age: Option<u32>,
}

let schema = strict_schema(serde_json::to_value(schemars::schema_for!(Person))?);

let request = GenerateRequest::new()
.message(Message::text(Role::User, "Extract the name and age: Ada is 36."))
.response_format(ResponseFormat::JsonSchema {
name: "person".into(),
schema,
strict: true,
});

let person: Person = client.generate_as(&request).await?;

The Option field becomes optional in the generated schema, and strict_schema turns that into a required field that may be null, which Option<u32> accepts. The generated schema also carries $schema and title keys. They are not among the keywords strict_schema touches, and whether an endpoint accepts them is the endpoint's answer to give.

When the answer does not fit​

A schema constrains the model and does not guarantee the result. When the call succeeds and the text does not deserialize into your type, generate_as returns Error::OutputMismatch. It keeps the model's text, the deserializer's message and the endpoint name, and it sets truncated when the response was cut short:

use freyja::Error;

match client.generate_as::<Person>(&request).await {
Ok(person) => println!("{}", person.name),
Err(Error::OutputMismatch { message, text, truncated, .. }) => {
if truncated {
eprintln!("cut short, raise max_tokens");
}
eprintln!("did not match: {message}\nthe model said: {text}");
}
Err(error) => eprintln!("{} failed: {error}", error.endpoint()),
}

A cut-off JSON object is the usual cause, and the fix is a larger max_tokens on the request rather than a different schema. A mismatch is not retryable, because nothing about repeating the same request changes the shape. Everything generate can raise comes through generate_as too. See Errors.

Provider support​

ProviderJsonObjectJsonSchema
OpenAIyesyes, sent as text.format
OpenAI Chat Completionsyesyes, as response_format
Geminiyesyes, the schema is response_format
Anthropicrefused with UnsupportedCapabilityyes, name and strict are dropped

Anthropic has no schema-less JSON mode, so JsonObject is refused before the network instead of being downgraded to free text. A request that must run on every provider uses JsonSchema. Whether an unrecognized endpoint honours strict is its own matter, see Custom providers.

Typed arguments versus typed output​

Two features both produce a Rust value, and they answer different questions. Typed output is the shape of the model's final answer, set on a request with response_format. Typed tool arguments are the shape of what the model passes to a function, and the #[tool] macro builds that schema from the function's parameter types, which need Deserialize and schemars::JsonSchema. Use typed arguments when the model should act, and typed output when the model's answer is the product. An agent run that must end in a structured answer can hand its final text to your own parser, or make a last Client call with a response_format. See Tool calling for the macro.

See also​