Skip to main content

parse_structured

Function parse_structured 

Source
pub fn parse_structured<T: DeserializeOwned>(
    response: &ModelResponse,
    schema: &CompiledSchema,
) -> Result<T, StructuredOutputError>
Expand description

Turns a model response into T, or rejects it whole.

ยงErrors

Returns the first StructuredOutputError of the extraction, validation and deserialization gates. There is no partial success.

use serde::Deserialize;
use serde_json::json;
use turnframe_provider::prelude::*;
use turnframe_provider::structured::parse_structured;

#[derive(Debug, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
struct Plan {
    acts: Vec<String>,
}

let schema = CompiledSchema::compile(&json!({
    "type": "object",
    "properties": {"acts": {"type": "array", "items": {"type": "string"}}},
    "required": ["acts"],
    "additionalProperties": false
}))?;

let response = ModelResponse::new(RequestId::nil(), "openai", "gpt-4o")
    .with_text(r#"{"acts": ["set_travel_date"]}"#);
let plan: Plan = parse_structured(&response, &schema)?;
assert_eq!(plan.acts, vec!["set_travel_date".to_owned()]);