LLM structured outputs
The llm feature (it enables openapi) adds vld::llm:
llm_schemarewrites vld's JSON Schema into what a provider accepts, and checks the provider's limits before you send the request;parse_llmfinds the JSON in a model reply and validates it;VldError::llm_feedback()turns the issues into short lines for a retry prompt.
vld = { version = "0.8", features = ["llm", "derive"] }
Schema per provider
use vld::llm::{LlmSchema, LlmSchemaExt, Provider};
#[derive(Debug, vld::Validate)]
struct Forecast {
#[vld(vld::string().min(2))]
city: String,
#[vld(vld::number().int().min(1).max(14))]
days: i64,
#[vld(vld::enumeration(&["metric", "imperial"]).optional())]
units: Option<String>,
}
let openai = Forecast::llm_schema(Provider::OpenAiStrict)?; // a schema!/derive type
let inline = vld::object().field("q", vld::string()).llm_schema(Provider::Gemini)?; // a schema value
let raw = vld::llm::llm_schema(&serde_json::json!({"type": "object"}), Provider::Generic)?; // any JSON Schema
Every provider gets the same base rewrite:
- nested named types (
vld::nested!(T), derive fields) go into$defs;$ref: #/components/schemas/Xbecomes#/$defs/X, and a reference to the root type becomes#(recursion); - the OpenAPI-only
discriminatoris removed; {"anyOf": [X, {"type": "null"}]}becomesXwith"type": [t, "null"](andnulladded toenum).
Then per provider:
OpenAI (OpenAiStrict) | Anthropic | Gemini | Generic | |
|---|---|---|---|---|
| root | must be an object | must be an object | any | any |
required | every property; optional ones become nullable | kept | kept | kept |
additionalProperties | false on every object; a map (record) is an error | false on every object; a map is an error | kept | kept |
oneOf / const | → anyOf / one-value enum | → anyOf / one-value enum | → anyOf / one-value enum | kept |
allOf | error | kept | error | kept |
not, if/then/else, dependent*, patternProperties | error | error | error | kept |
prefixItems (tuples) | error | error | kept | kept |
pattern | kept | kept unless it has lookaround / backreferences | → description | kept |
format | date-time, time, date, duration, email, hostname, ipv4, ipv6, uuid | the same plus uri | date-time, date, time | all |
minimum / maximum | kept | → description | kept | kept |
exclusiveMinimum / exclusiveMaximum / multipleOf | kept | → description | → description | kept |
minLength / maxLength | → description | → description | → description | kept |
minItems / maxItems | kept | minItems 0 or 1 kept, the rest → description | kept | kept |
other keywords (default, uniqueItems, vld's x-*) | → description | → description | → description | kept |
| recursion | allowed | error | allowed | allowed |
empty schema (vld::lazy, any()) | error | kept | error | kept |
| limits checked | 5000 properties, depth 10, 1000 enum values, 120 000 characters of names and enum values | 24 optional and 16 union-typed parameters | — | — |
A keyword moved to the description is appended as text, so the model still sees the rule (vld still enforces it when parsing the reply):
{ "type": "string", "description": "max length 80; min length 2" }
A schema the provider would reject returns LlmSchemaError (RootNotObject, Unsupported { path, keyword }, Untyped { path }, Recursive { name }, TooMany { what, count, max }, UnresolvedRef) instead of a 400 from the API.
Request bodies
OpenAI (Responses API, structured outputs):
let body = serde_json::json!({
"model": "gpt-5",
"input": "Weather in Oslo for 3 days",
"text": { "format": {
"type": "json_schema", "name": "forecast", "strict": true,
"schema": Forecast::llm_schema(Provider::OpenAiStrict)?,
}},
});
Anthropic (strict tool use):
let body = serde_json::json!({
"model": "claude-sonnet-4-5",
"max_tokens": 1024,
"tools": [{
"name": "forecast", "description": "Get a forecast", "strict": true,
"input_schema": Forecast::llm_schema(Provider::Anthropic)?,
}],
"messages": [{ "role": "user", "content": "Weather in Oslo for 3 days" }],
});
Gemini:
let body = serde_json::json!({
"contents": [{ "parts": [{ "text": "Weather in Oslo for 3 days" }] }],
"generationConfig": {
"responseMimeType": "application/json",
"responseJsonSchema": Forecast::llm_schema(Provider::Gemini)?,
},
});
Parsing the reply
parse_llm::<T>(text) takes the first JSON object or array in a fenced block (```json), otherwise the first balanced {…} / […] in the text that parses, so prose before and after is ignored. parse_llm_with(&schema, text) does the same with a schema value; extract_json(text) only extracts.
use vld::llm::{parse_llm, LlmParseError};
match parse_llm::<Forecast>(reply) {
Ok(f) => println!("{f:?}"),
Err(LlmParseError::NoJson) => { /* the model answered in prose */ }
Err(LlmParseError::Invalid(e)) => println!("{}", e.llm_feedback()),
}
Feedback and the retry loop
llm_feedback() writes one line per issue, path: expected <rule>, got <value>:
city: expected string length >= 2, got "O"
days: expected number <= 14, got 30
units: expected one of metric, imperial, got "kelvin"
llm_feedback_with(&LlmFeedbackOptions { .. }) sets:
max_issues(default 10): later issues becomeand N more;retry_prompt: wraps the lines inYour previous output was invalid: … Return corrected JSON only.;schema: the schema you sent; an unknown key then gets; allowed keys: a, b.
llm_feedback_json() gives the same as [{"path", "expected", "received", "hint"}] for tool results. A .redact()ed field shows [redacted], never the value.
use vld::llm::{parse_llm, LlmFeedbackOptions, LlmSchema, Provider};
let schema = Forecast::llm_schema(Provider::OpenAiStrict)?;
let options = LlmFeedbackOptions { retry_prompt: true, schema: Some(schema.clone()), ..Default::default() };
let mut messages = vec![user("Weather in Oslo for 3 days")];
let forecast = loop {
let reply = call_model(&messages, &schema).await?; // your client
match parse_llm::<Forecast>(&reply) {
Ok(f) => break f,
Err(e) => {
messages.push(assistant(&reply));
messages.push(user(&e.llm_feedback_with(&options)));
}
}
};
For MCP and rig tools, the same feedback is returned automatically: see rmcp and rig.