OpenAPI

LLM structured outputs

Send a vld schema to OpenAI, Anthropic or Gemini as a structured-output or tool schema, parse the reply, and feed validation errors back to the model.

The llm feature (it enables openapi) adds vld::llm:

  • llm_schema rewrites vld's JSON Schema into what a provider accepts, and checks the provider's limits before you send the request;
  • parse_llm finds the JSON in a model reply and validates it;
  • VldError::llm_feedback() turns the issues into short lines for a retry prompt.
Cargo.toml
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/X becomes #/$defs/X, and a reference to the root type becomes # (recursion);
  • the OpenAPI-only discriminator is removed;
  • {"anyOf": [X, {"type": "null"}]} becomes X with "type": [t, "null"] (and null added to enum).

Then per provider:

OpenAI (OpenAiStrict)AnthropicGeminiGeneric
rootmust be an objectmust be an objectanyany
requiredevery property; optional ones become nullablekeptkeptkept
additionalPropertiesfalse on every object; a map (record) is an errorfalse on every object; a map is an errorkeptkept
oneOf / const→ anyOf / one-value enum→ anyOf / one-value enum→ anyOf / one-value enumkept
allOferrorkepterrorkept
not, if/then/else, dependent*, patternPropertieserrorerrorerrorkept
prefixItems (tuples)errorerrorkeptkept
patternkeptkept unless it has lookaround / backreferences→ descriptionkept
formatdate-time, time, date, duration, email, hostname, ipv4, ipv6, uuidthe same plus uridate-time, date, timeall
minimum / maximumkept→ descriptionkeptkept
exclusiveMinimum / exclusiveMaximum / multipleOfkept→ description→ descriptionkept
minLength / maxLength→ description→ description→ descriptionkept
minItems / maxItemskeptminItems 0 or 1 kept, the rest → descriptionkeptkept
other keywords (default, uniqueItems, vld's x-*)→ description→ description→ descriptionkept
recursionallowederrorallowedallowed
empty schema (vld::lazy, any())errorkepterrorkept
limits checked5000 properties, depth 10, 1000 enum values, 120 000 characters of names and enum values24 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 become and N more;
  • retry_prompt: wraps the lines in Your 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.