Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Example]: Use serde, schemars to make structure output code easy #301

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions examples/structured-outputs/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,5 @@ publish = false
async-openai = {path = "../../async-openai"}
serde_json = "1.0.127"
tokio = { version = "1.39.3", features = ["full"] }
schemars = "0.8.21"
serde = "1.0.130"
101 changes: 65 additions & 36 deletions examples/structured-outputs/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,67 +2,96 @@ use std::error::Error;

use async_openai::{
types::{
ChatCompletionRequestSystemMessage, ChatCompletionRequestUserMessage,
CreateChatCompletionRequestArgs, ResponseFormat, ResponseFormatJsonSchema,
ChatCompletionRequestMessage, ChatCompletionRequestSystemMessage,
ChatCompletionRequestUserMessage, CreateChatCompletionRequestArgs, ResponseFormat,
ResponseFormatJsonSchema,
},
Client,
};
use serde_json::json;
use schemars::{schema_for, JsonSchema};
use serde::{de::DeserializeOwned, Deserialize, Serialize};

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let client = Client::new();
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Step {
pub output: String,
pub explanation: String,
}

let schema = json!({
"type": "object",
"properties": {
"steps": {
"type": "array",
"items": {
"type": "object",
"properties": {
"explanation": { "type": "string" },
"output": { "type": "string" }
},
"required": ["explanation", "output"],
"additionalProperties": false
}
},
"final_answer": { "type": "string" }
},
"required": ["steps", "final_answer"],
"additionalProperties": false
});
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct MathReasoningResponse {
pub final_answer: String,
pub steps: Vec<Step>,
}

pub async fn structured_output<T: serde::Serialize + DeserializeOwned + JsonSchema>(
messages: Vec<ChatCompletionRequestMessage>,
) -> Result<Option<T>, Box<dyn Error>> {
let schema = schema_for!(T);
let schema_value = serde_json::to_value(&schema)?;
let response_format = ResponseFormat::JsonSchema {
json_schema: ResponseFormatJsonSchema {
description: None,
name: "math_reasoning".into(),
schema: Some(schema),
schema: Some(schema_value),
strict: Some(true),
},
};

let request = CreateChatCompletionRequestArgs::default()
.max_tokens(512u32)
.model("gpt-4o-2024-08-06")
.messages([
ChatCompletionRequestSystemMessage::from(
"You are a helpful math tutor. Guide the user through the solution step by step.",
)
.into(),
ChatCompletionRequestUserMessage::from("how can I solve 8x + 7 = -23").into(),
])
.model("gpt-4o-mini")
.messages(messages)
.response_format(response_format)
.build()?;

let client = Client::new();
let response = client.chat().create(request).await?;

for choice in response.choices {
if let Some(content) = choice.message.content {
print!("{content}")
return Ok(Some(serde_json::from_str::<T>(&content)?));
}
}

Ok(None)
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
// Expecting output schema
// let schema = json!({
// "type": "object",
// "properties": {
// "steps": {
// "type": "array",
// "items": {
// "type": "object",
// "properties": {
// "explanation": { "type": "string" },
// "output": { "type": "string" }
// },
// "required": ["explanation", "output"],
// "additionalProperties": false
// }
// },
// "final_answer": { "type": "string" }
// },
// "required": ["steps", "final_answer"],
// "additionalProperties": false
// });
if let Some(response) = structured_output::<MathReasoningResponse>(vec![
ChatCompletionRequestSystemMessage::from(
"You are a helpful math tutor. Guide the user through the solution step by step.",
)
.into(),
ChatCompletionRequestUserMessage::from("how can I solve 8x + 7 = -23").into(),
])
.await?
{
println!("{}", serde_json::to_string(&response).unwrap());
}

Ok(())
}