Skip to main content

lc_providers/openai/chat/
structured.rs

1// lc-providers/src/openai/chat/structured.rs
2//! Structured output support for the OpenAI chat provider.
3
4use schemars::JsonSchema;
5use serde::de::DeserializeOwned;
6use std::marker::PhantomData;
7
8use crate::openai::OpenAIConfig;
9use lc_core::tools::StructuredOutput;
10use lc_schema::Message;
11
12use super::{OpenAIChat, OpenAIError};
13
14/// Method for structured output calls
15pub struct StructuredOutputMethod<T: DeserializeOwned + JsonSchema> {
16    pub(crate) config: OpenAIConfig,
17    pub(crate) client: reqwest::Client,
18    pub(crate) _phantom: PhantomData<T>,
19}
20
21impl<T: DeserializeOwned + JsonSchema> StructuredOutputMethod<T> {
22    /// Invokes the chat API and parses the response into the structured type `T`.
23    pub async fn invoke(&self, messages: Vec<Message>) -> Result<T, OpenAIError> {
24        let chat = OpenAIChat {
25            config: self.config.clone(),
26            client: self.client.clone(),
27        };
28
29        let result = chat.chat_internal(messages).await?;
30        let structured = StructuredOutput::<T>::new(result);
31        structured
32            .parse()
33            .map_err(|e| OpenAIError::Parse(e.to_string()))
34    }
35}