async_llm/request/chat.rs
1use std::{collections::HashMap, pin::Pin};
2
3use futures::Stream;
4use serde::{Deserialize, Serialize};
5
6use crate::{
7 error::Error,
8 types::{
9 AssistantContent, ChatAudio, ChatFunction, ChatFunctionCall, ChatResponseFormat, ChatTool,
10 ChatToolChoice, Content, Modalities, PredictionContent, ReasoningEffort, ServiceTier, Stop,
11 StreamOptions,
12 },
13 ChatResponse, ChatResponseStream, Client, Printable,
14};
15
16use super::{ChatMessage, Requestable};
17
18/// https://platform.openai.com/docs/api-reference/chat/create
19#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
20pub struct ChatRequest {
21 /// A list of messages comprising the conversation so far. Depending on the [model](https://platform.openai.com/docs/models) you use, different message types (modalities) are supported, like [text](https://platform.openai.com/docs/guides/text-generation), [images](https://platform.openai.com/docs/guides/vision), and [audio](https://platform.openai.com/docs/guides/audio).
22 pub messages: Vec<ChatMessage>,
23
24 /// ID of the model to use. See the [model endpoint compatibility](https://platform.openai.com/docs/models#model-endpoint-compatibility) table for details on which models work with the Chat API.
25 pub model: String,
26
27 /// Whether or not to store the output of this chat completion request for use in our [model distillation](https://platform.openai.com/docs/guides/distillation) or [evals](https://platform.openai.com/docs/guides/evals) products.
28 #[serde(skip_serializing_if = "Option::is_none")]
29 pub store: Option<bool>,
30
31 /// Constrains effort on reasoning for [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently supported values are low, medium, and high. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response.
32 #[serde(skip_serializing_if = "Option::is_none")]
33 pub reasoning_effort: Option<ReasoningEffort>,
34
35 /// Developer-defined tags and values used for filtering completions in the dashboard.
36 #[serde(skip_serializing_if = "Option::is_none")]
37 pub metadata: Option<serde_json::Value>,
38
39 /// Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim.
40 #[serde(skip_serializing_if = "Option::is_none")]
41 pub frequency_penalty: Option<f32>, // min: -2.0, max: 2.0, default: 0
42
43 /// Modify the likelihood of specified tokens appearing in the completion.
44 ///
45 /// Accepts a JSON object that maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100. You can use this tokenizer tool to convert text to token IDs. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token.
46 ///
47 /// As an example, you can pass {"50256": -100} to prevent the <|endoftext|> token from being generated.
48 #[serde(skip_serializing_if = "Option::is_none")]
49 pub logit_bias: Option<HashMap<String, serde_json::Value>>, // default: null
50
51 /// Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned in the `content` of `message`.
52 #[serde(skip_serializing_if = "Option::is_none")]
53 pub logprobs: Option<bool>,
54
55 /// An integer between 0 and 20 specifying the number of most likely tokens to return at each token position, each with an associated log probability. logprobs must be set to true if this parameter is used.
56 #[serde(skip_serializing_if = "Option::is_none")]
57 pub top_logprobs: Option<u8>,
58
59 /// The maximum number of [tokens](https://platform.openai.com/tokenizer) that can be generated in the chat completion. This value can be used to control [costs](https://openai.com/api/pricing/) for text generated via API.
60 ///
61 /// This value is now deprecated in favor of `max_completion_tokens`, and is not compatible with [o1 series models](https://platform.openai.com/docs/guides/reasoning).
62 #[deprecated]
63 #[serde(skip_serializing_if = "Option::is_none")]
64 pub max_tokens: Option<u32>,
65
66 /// An upper bound for the number of tokens that can be generated for a completion, including visible output tokens and [reasoning tokens](https://platform.openai.com/docs/guides/reasoning).
67 #[serde(skip_serializing_if = "Option::is_none")]
68 pub max_completion_tokens: Option<u32>,
69
70 /// How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the choices. Keep n as 1 to minimize costs.
71 #[serde(skip_serializing_if = "Option::is_none")]
72 pub n: Option<u8>, // min:1, max: 128, default: 1
73
74 /// Output types that you would like the model to generate for this request. Most models are capable of generating text, which is the default:
75 /// ["text"]
76 /// The gpt-4o-audio-preview model can also be used to generate audio. To request that this model generate both text and audio responses, you can use:
77 /// ["text", "audio"]
78 #[serde(skip_serializing_if = "Option::is_none")]
79 pub modalities: Option<Vec<Modalities>>,
80
81 /// Configuration for a [Predicted Output](https://platform.openai.com/docs/guides/predicted-outputs), which can greatly improve response times when large parts of the model response are known ahead of time. This is most common when you are regenerating a file with only minor changes to most of the content.
82 #[serde(skip_serializing_if = "Option::is_none")]
83 pub prediction: Option<PredictionContent>,
84
85 /// Parameters for audio output. Required when audio output is requested with modalities: ["audio"]. [Learn more](https://platform.openai.com/docs/guides/audio).
86 #[serde(skip_serializing_if = "Option::is_none")]
87 pub audio: Option<ChatAudio>,
88
89 /// Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics.
90 ///
91 /// [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details)
92 #[serde(skip_serializing_if = "Option::is_none")]
93 pub presence_penalty: Option<f32>, // min: -2.0, max: 2.0, default 0
94
95 #[serde(skip_serializing_if = "Option::is_none")]
96 pub response_format: Option<ChatResponseFormat>,
97
98 /// This feature is in Beta.
99 /// If specified, our system will make a best effort to sample deterministically, such that repeated requests
100 /// with the same `seed` and parameters should return the same result.
101 /// Determinism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend.
102 #[serde(skip_serializing_if = "Option::is_none")]
103 pub seed: Option<i64>,
104
105 /// Specifies the latency tier to use for processing the request. This parameter is relevant for customers subscribed to the scale tier service:
106 /// - If set to 'auto', the system will utilize scale tier credits until they are exhausted.
107 /// - If set to 'default', the request will be processed using the default service tier with a lower uptime SLA and no latency guarentee.
108 /// - When not set, the default behavior is 'auto'.
109 ///
110 /// When this parameter is set, the response body will include the `service_tier` utilized.
111 #[serde(skip_serializing_if = "Option::is_none")]
112 pub service_tier: Option<ServiceTier>,
113
114 /// Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence.
115 #[serde(skip_serializing_if = "Option::is_none")]
116 pub stop: Option<Stop>,
117
118 /// If set, partial message deltas will be sent, like in ChatGPT. Tokens will be sent as data-only [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) as they become available, with the stream terminated by a data: [DONE] message. Example [Python code](https://cookbook.openai.com/examples/how_to_stream_completions).
119 #[serde(skip_serializing_if = "Option::is_none")]
120 pub stream: Option<bool>,
121
122 /// Options for streaming response. Only set this when you set stream: true.
123 #[serde(skip_serializing_if = "Option::is_none")]
124 pub stream_options: Option<StreamOptions>,
125
126 /// What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.
127 ///
128 /// We generally recommend altering this or top_p but not both.
129 #[serde(skip_serializing_if = "Option::is_none")]
130 pub temperature: Option<f32>, // min: 0, max: 2, default: 1,
131
132 /// An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.
133 ///
134 /// We generally recommend altering this or temperature but not both.
135 #[serde(skip_serializing_if = "Option::is_none")]
136 pub top_p: Option<f32>, // min: 0, max: 1, default: 1
137
138 /// A list of tools the model may call. Currently, only functions are supported as a tool. Use this to provide a list of functions the model may generate JSON inputs for. A max of 128 functions are supported.
139 #[serde(skip_serializing_if = "Option::is_none")]
140 pub tools: Option<Vec<ChatTool>>,
141
142 /// Controls which (if any) tool is called by the model.
143 /// - `none` means the model will not call any tool and instead generates a message.
144 /// - `auto` means the model can pick between generating a message or calling one or more tools.
145 /// - `required` means the model must call one or more tools.
146 /// - Specifying a particular tool via {"type": "function", "function": {"name": "my_function"}} forces the model to call that tool.
147 /// `none` is the default when no tools are present. `auto` is the default if tools are present.
148 #[serde(skip_serializing_if = "Option::is_none")]
149 pub tool_choice: Option<ChatToolChoice>,
150
151 /// Whether to enable [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) during tool use.
152 #[serde(skip_serializing_if = "Option::is_none")]
153 pub parallel_tool_calls: Option<bool>,
154
155 /// A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).
156 #[serde(skip_serializing_if = "Option::is_none")]
157 pub user: Option<String>,
158
159 /// Deprecated in favor of `tool_choice`.
160 ///
161 /// Controls which (if any) function is called by the model.
162 /// - `none` means the model will not call a function and instead generates a message.
163 /// - `auto` means the model can pick between generating a message or calling a function.
164 /// - Specifying a particular function via `{"name": "my_function"}` forces the model to call that function.
165 ///
166 /// `none` is the default when no functions are present. `auto` is the default if functions are present.
167 #[deprecated]
168 #[serde(skip_serializing_if = "Option::is_none")]
169 pub function_call: Option<ChatFunctionCall>,
170
171 /// Deprecated in favor of `tools`.
172 ///
173 /// A list of functions the model may generate JSON inputs for.
174 #[deprecated]
175 #[serde(skip_serializing_if = "Option::is_none")]
176 pub functions: Option<Vec<ChatFunction>>,
177}
178
179impl ChatRequest {
180 pub fn new(model: impl Into<String>, messages: Vec<ChatMessage>) -> Self {
181 Self {
182 messages,
183 model: model.into(),
184 ..Default::default()
185 }
186 }
187
188 pub fn from_system(message: impl Into<Content>) -> Self {
189 Self {
190 messages: vec![ChatMessage::system(message.into())],
191 ..Default::default()
192 }
193 }
194
195 pub fn from_model(model: impl Into<String>) -> Self {
196 Self::new(model, vec![])
197 }
198
199 pub fn iter_messages(&self) -> impl Iterator<Item = &ChatMessage> {
200 self.messages.iter()
201 }
202
203 pub async fn send(self) -> Result<ChatResponse, Error> {
204 Client::new().chat().create(self).await
205 }
206 pub async fn send_stream(
207 self,
208 ) -> Result<Pin<Box<dyn Stream<Item = Result<ChatResponseStream, Error>> + Send>>, Error> {
209 Client::new().chat().create_stream(self).await
210 }
211}
212
213/// Chainable setters
214impl ChatRequest {
215 pub fn append_system(mut self, message: impl Into<Content>) -> Self {
216 self.messages.push(ChatMessage::system(message));
217 self
218 }
219
220 pub fn append_user(mut self, message: impl Into<String>) -> Self {
221 self.messages.push(ChatMessage::user(message));
222 self
223 }
224
225 pub fn append_developer(mut self, message: impl Into<Content>) -> Self {
226 self.messages.push(ChatMessage::developer(message));
227 self
228 }
229
230 pub fn append_assistant(mut self, message: impl Into<AssistantContent>) -> Self {
231 self.messages.push(ChatMessage::assistant(message));
232 self
233 }
234
235 pub fn append_tool(
236 mut self,
237 message: impl Into<Content>,
238 tool_call_id: impl Into<String>,
239 ) -> Self {
240 self.messages.push(ChatMessage::tool(message, tool_call_id));
241 self
242 }
243
244 pub fn with_tool_choice(mut self, tool_choice: ChatToolChoice) -> Self {
245 self.tool_choice = Some(tool_choice);
246 self
247 }
248
249 pub fn with_model(mut self, model: impl Into<String>) -> Self {
250 self.model = model.into();
251 self
252 }
253
254 pub fn with_stream(mut self) -> Self {
255 self.stream = Some(true);
256 self
257 }
258
259 pub fn with_tools(mut self, tools: Vec<impl Into<ChatTool>>) -> Self {
260 self.tools = Some(tools.into_iter().map(Into::into).collect::<Vec<ChatTool>>());
261 self
262 }
263
264 pub fn with_response_format(mut self, response_format: impl Into<ChatResponseFormat>) -> Self {
265 self.response_format = Some(response_format.into());
266 self
267 }
268}
269
270impl ChatRequest {
271 pub fn to_string_pretty(&self) -> Result<String, Error> {
272 Ok(serde_json::to_string_pretty(&self)?)
273 }
274}
275
276impl Requestable for ChatRequest {
277 fn stream(&self) -> bool {
278 self.stream.unwrap_or(false)
279 }
280}
281
282impl Printable for ChatRequest {
283 fn to_string_pretty(&self) -> Result<String, Error> {
284 Ok(serde_json::to_string_pretty(self)?)
285 }
286}
287
288#[cfg(test)]
289mod tests {
290
291 use super::*;
292
293 #[test]
294 fn chat_request_works() {
295 let request = ChatRequest::new(
296 "gpt-4o-mini",
297 vec![
298 ChatMessage::system("You are a helpful assistant"),
299 ChatMessage::user("Who are you?"),
300 ],
301 )
302 .append_user("1 + 1 =");
303
304 assert!(request.to_string_pretty().is_ok());
305 }
306}