Expand description
§Chat Completion Module
This module provides functionality for interacting with OpenAI’s Chat Completion API. It includes structures for request configuration, response handling, and a high-level client for making chat completion requests.
§Features
- Simple Chat: Basic text-to-text conversations
- Structured Output: JSON schema-based responses for structured data
- Flexible Configuration: Support for all OpenAI chat completion parameters
- Type Safety: Strongly typed request and response structures
§Examples
§Basic Usage
use openai_tools::chat::ChatCompletion;
use openai_tools::common::Message;
use openai_tools::errors::Result;
let mut chat = ChatCompletion::new();
let messages = vec![
Message::from_string("user".to_string(), "Hello, world!".to_string())
];
chat.model_id("gpt-4o-mini".to_string())
.messages(messages)
.temperature(0.7);
let response = chat.chat().await?;
println!("{}", response.choices[0].message.content);
§Structured Output with JSON Schema
use openai_tools::chat::{ChatCompletion, ChatCompletionResponseFormat};
use openai_tools::structured_output::Schema;
use openai_tools::common::Message;
use openai_tools::errors::Result;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
struct WeatherInfo {
location: String,
temperature: f32,
condition: String,
}
let mut schema = Schema::chat_json_schema("weather".to_string());
schema.add_property("location".to_string(), "string".to_string(), None);
schema.add_property("temperature".to_string(), "number".to_string(), None);
schema.add_property("condition".to_string(), "string".to_string(), None);
let mut chat = ChatCompletion::new();
chat.model_id("gpt-4o-mini".to_string())
.messages(vec![Message::from_string("user".to_string(), "What's the weather in Tokyo?".to_string())])
.response_format(ChatCompletionResponseFormat::new("json_schema".to_string(), schema));
let response = chat.chat().await?;
let weather: WeatherInfo = serde_json::from_str(&response.choices[0].message.content)?;
Structs§
- Chat
Completion - High-level client for OpenAI Chat Completion API.
- Chat
Completion Request Body - Request body structure for OpenAI Chat Completion API.
- Chat
Completion Response - Complete response from the OpenAI Chat Completion API.
- Chat
Completion Response Format - Specifies the format that the model must output for chat completions.
- Chat
Response Message - Choice
- Represents a single choice in the chat completion response.