1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
//! # Chat Module
//!
//! This module provides functionality for interacting with the OpenAI Chat Completions API.
//! It includes tools for building requests, sending them to OpenAI's chat completion endpoint,
//! and processing the responses.
//!
//! ## Key Features
//!
//! - Chat completion request building and sending
//! - Structured output support with JSON schema
//! - Response parsing and processing
//! - Support for various OpenAI models and parameters
//!
//! ## Usage Examples
//!
//! ### Basic Chat Completion
//!
//! ```rust,no_run
//! use openai_tools::chat::request::ChatCompletion;
//! use openai_tools::common::message::Message;
//! use openai_tools::common::role::Role;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let mut chat = ChatCompletion::new();
//! let messages = vec![Message::from_string(Role::User, "Hello!")];
//!
//! let response = chat
//! .model_id("gpt-4o-mini")
//! .messages(messages)
//! .temperature(1.0)
//! .chat()
//! .await?;
//!
//! println!("{}", response.choices[0].message.content.as_ref().unwrap().text.as_ref().unwrap());
//! Ok(())
//! }
//! ```
//!
//! ### Using JSON Schema for Structured Output
//!
//! ```rust,no_run
//! use openai_tools::chat::request::ChatCompletion;
//! use openai_tools::common::message::Message;
//! use openai_tools::common::role::Role;
//! use openai_tools::common::structured_output::Schema;
//! use serde::{Deserialize, Serialize};
//!
//! #[derive(Debug, Serialize, Deserialize)]
//! struct WeatherInfo {
//! location: String,
//! date: String,
//! weather: String,
//! temperature: String,
//! }
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let mut chat = ChatCompletion::new();
//! let messages = vec![Message::from_string(
//! Role::User,
//! "What's the weather like tomorrow in Tokyo?"
//! )];
//!
//! // Create JSON schema for structured output
//! let mut json_schema = Schema::chat_json_schema("weather");
//! json_schema.add_property("location", "string", "The location for weather check");
//! json_schema.add_property("date", "string", "The date for weather forecast");
//! json_schema.add_property("weather", "string", "Weather condition description");
//! json_schema.add_property("temperature", "string", "Temperature information");
//!
//! let response = chat
//! .model_id("gpt-4o-mini")
//! .messages(messages)
//! .temperature(0.7)
//! .json_schema(json_schema)
//! .chat()
//! .await?;
//!
//! // Parse structured response
//! let weather: WeatherInfo = serde_json::from_str(
//! response.choices[0].message.content.as_ref().unwrap().text.as_ref().unwrap()
//! )?;
//! println!("Weather in {}: {} on {}, Temperature: {}",
//! weather.location, weather.weather, weather.date, weather.temperature);
//! Ok(())
//! }
//! ```
//!
//! ### Using Function Calling with Tools
//!
//! ```rust,no_run
//! use openai_tools::chat::request::ChatCompletion;
//! use openai_tools::common::message::Message;
//! use openai_tools::common::role::Role;
//! use openai_tools::common::tool::Tool;
//! use openai_tools::common::parameters::ParameterProperty;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let mut chat = ChatCompletion::new();
//! let messages = vec![Message::from_string(
//! Role::User,
//! "Please calculate 25 + 17 using the calculator tool"
//! )];
//!
//! // Define a calculator function tool
//! let calculator_tool = Tool::function(
//! "calculator",
//! "A calculator that can perform basic arithmetic operations",
//! vec![
//! ("operation", ParameterProperty::from_string("The operation to perform (add, subtract, multiply, divide)")),
//! ("a", ParameterProperty::from_number("The first number")),
//! ("b", ParameterProperty::from_number("The second number")),
//! ],
//! false, // strict mode
//! );
//!
//! let response = chat
//! .model_id("gpt-4o-mini")
//! .messages(messages)
//! .temperature(0.1)
//! .tools(vec![calculator_tool])
//! .chat()
//! .await?;
//!
//! // Handle function calls in the response
//! if let Some(tool_calls) = &response.choices[0].message.tool_calls {
//! // Add the assistant's message with tool calls to conversation history
//! chat.add_message(response.choices[0].message.clone());
//!
//! for tool_call in tool_calls {
//! println!("Function called: {}", tool_call.function.name);
//! if let Ok(args) = tool_call.function.arguments_as_map() {
//! println!("Arguments: {:?}", args);
//! }
//!
//! // Execute the function (in this example, we simulate the calculation)
//! let result = "42"; // This would be the actual calculation result
//!
//! // Add the tool call response to continue the conversation
//! chat.add_message(Message::from_tool_call_response(result, &tool_call.id));
//! }
//!
//! // Get the final response after tool execution
//! let final_response = chat.chat().await?;
//! if let Some(content) = &final_response.choices[0].message.content {
//! if let Some(text) = &content.text {
//! println!("Final answer: {}", text);
//! }
//! }
//! } else if let Some(content) = &response.choices[0].message.content {
//! if let Some(text) = &content.text {
//! println!("{}", text);
//! }
//! }
//! Ok(())
//! }
//! ```