outfox_openai/spec/chat.rs
1use std::{collections::HashMap, pin::Pin};
2
3use derive_builder::Builder;
4use futures::Stream;
5use serde::{Deserialize, Serialize};
6
7use crate::error::OpenAIError;
8use crate::spec::{PartibleTextContent, TextObject};
9
10#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
11#[serde(untagged)]
12pub enum Prompt {
13 String(String),
14 StringArray(Vec<String>),
15 // Minimum value is 0, maximum value is 4_294_967_295 (inclusive).
16 IntegerArray(Vec<u32>),
17 ArrayOfIntegerArray(Vec<Vec<u32>>),
18}
19
20#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
21#[serde(untagged)]
22pub enum Stop {
23 String(String), // nullable: true
24 StringArray(Vec<String>), // minItems: 1; maxItems: 4
25}
26
27#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
28pub struct Logprobs {
29 pub tokens: Vec<String>,
30 pub token_logprobs: Vec<Option<f32>>, // Option is to account for null value in the list
31 pub top_logprobs: Vec<serde_json::Value>,
32 pub text_offset: Vec<u32>,
33}
34
35#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq)]
36#[serde(rename_all = "snake_case")]
37pub enum CompletionFinishReason {
38 Stop,
39 Length,
40 ContentFilter,
41}
42
43#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
44pub struct Choice {
45 pub text: String,
46 pub index: u32,
47 pub logprobs: Option<Logprobs>,
48 pub finish_reason: Option<CompletionFinishReason>,
49}
50
51#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
52pub enum ChatCompletionFunctionCall {
53 /// The model does not call a function, and responds to the end-user.
54 #[serde(rename = "none")]
55 None,
56 /// The model can pick between an end-user or calling a function.
57 #[serde(rename = "auto")]
58 Auto,
59
60 // In spec this is ChatCompletionFunctionCallOption
61 // based on feedback from @m1guelpf in https://github.com/64bit/async-openai/pull/118
62 // it is diverged from the spec
63 /// Forces the model to call the specified function.
64 #[serde(untagged)]
65 Function { name: String },
66}
67
68#[derive(Debug, Serialize, Deserialize, Clone, Copy, Default, PartialEq)]
69#[serde(rename_all = "lowercase")]
70pub enum Role {
71 System,
72 #[default]
73 User,
74 Assistant,
75 Tool,
76 Function,
77}
78
79/// The name and arguments of a function that should be called, as generated by the model.
80#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
81pub struct FunctionCall {
82 /// The name of the function to call.
83 pub name: String,
84 /// The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function.
85 pub arguments: String,
86}
87
88/// Usage statistics for the completion request.
89#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Default)]
90pub struct CompletionUsage {
91 /// Number of tokens in the prompt.
92 pub prompt_tokens: u32,
93 /// Number of tokens in the generated completion.
94 pub completion_tokens: u32,
95 /// Total number of tokens used in the request (prompt + completion).
96 pub total_tokens: u32,
97 /// Breakdown of tokens used in the prompt.
98 pub prompt_tokens_details: Option<PromptTokensDetails>,
99 /// Breakdown of tokens used in a completion.
100 pub completion_tokens_details: Option<CompletionTokensDetails>,
101}
102
103/// Breakdown of tokens used in a completion.
104#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Default)]
105pub struct PromptTokensDetails {
106 /// Audio input tokens present in the prompt.
107 pub audio_tokens: Option<u32>,
108 /// Cached tokens present in the prompt.
109 pub cached_tokens: Option<u32>,
110}
111
112/// Breakdown of tokens used in a completion.
113#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Default)]
114pub struct CompletionTokensDetails {
115 pub accepted_prediction_tokens: Option<u32>,
116 /// Audio input tokens generated by the model.
117 pub audio_tokens: Option<u32>,
118 /// Tokens generated by the model for reasoning.
119 pub reasoning_tokens: Option<u32>,
120 /// When using Predicted Outputs, the number of tokens in the
121 /// prediction that did not appear in the completion. However, like
122 /// reasoning tokens, these tokens are still counted in the total
123 /// completion tokens for purposes of billing, output, and context
124 /// window limits.
125 pub rejected_prediction_tokens: Option<u32>,
126}
127
128#[derive(Debug, Serialize, Deserialize, Default, Clone, Builder, PartialEq)]
129#[builder(name = "ChatCompletionRequestDeveloperMessageBuilder")]
130#[builder(pattern = "mutable")]
131#[builder(setter(into, strip_option), default)]
132#[builder(derive(Debug))]
133#[builder(build_fn(error = "OpenAIError"))]
134pub struct ChatCompletionRequestDeveloperMessage {
135 /// The contents of the developer message.
136 pub content: PartibleTextContent,
137
138 /// An optional name for the participant. Provides the model information to differentiate between participants of the same role.
139 #[serde(skip_serializing_if = "Option::is_none")]
140 pub name: Option<String>,
141}
142impl ChatCompletionRequestDeveloperMessage {
143 pub fn to_texts(&self) -> Vec<String> {
144 self.content.to_texts()
145 }
146}
147
148#[derive(Debug, Serialize, Deserialize, Default, Clone, Builder, PartialEq)]
149#[builder(name = "ChatCompletionRequestSystemMessageBuilder")]
150#[builder(pattern = "mutable")]
151#[builder(setter(into, strip_option), default)]
152#[builder(derive(Debug))]
153#[builder(build_fn(error = "OpenAIError"))]
154pub struct ChatCompletionRequestSystemMessage {
155 /// The contents of the system message.
156 pub content: PartibleTextContent,
157 /// An optional name for the participant. Provides the model information to differentiate between participants of the same role.
158 #[serde(skip_serializing_if = "Option::is_none")]
159 pub name: Option<String>,
160}
161impl ChatCompletionRequestSystemMessage {
162 pub fn to_texts(&self) -> Vec<String> {
163 self.content.to_texts()
164 }
165}
166
167#[derive(Debug, Serialize, Deserialize, Default, Clone, Builder, PartialEq)]
168pub struct ChatCompletionRequestMessageContentPartRefusal {
169 /// The refusal message generated by the model.
170 pub refusal: String,
171}
172
173#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq)]
174#[serde(rename_all = "lowercase")]
175pub enum ImageDetail {
176 #[default]
177 Auto,
178 Low,
179 High,
180}
181
182#[derive(Debug, Serialize, Deserialize, Default, Clone, Builder, PartialEq)]
183#[builder(name = "ImageUrlBuilder")]
184#[builder(pattern = "mutable")]
185#[builder(setter(into, strip_option), default)]
186#[builder(derive(Debug))]
187#[builder(build_fn(error = "OpenAIError"))]
188pub struct ImageUrl {
189 /// Either a URL of the image or the base64 encoded image data.
190 pub url: String,
191 /// Specifies the detail level of the image. Learn more in the [Vision guide](https://platform.openai.com/docs/guides/vision/low-or-high-fidelity-image-understanding).
192 pub detail: Option<ImageDetail>,
193}
194
195#[derive(Debug, Serialize, Deserialize, Default, Clone, Builder, PartialEq)]
196#[builder(name = "ChatCompletionRequestMessageContentPartImageBuilder")]
197#[builder(pattern = "mutable")]
198#[builder(setter(into, strip_option), default)]
199#[builder(derive(Debug))]
200#[builder(build_fn(error = "OpenAIError"))]
201pub struct ChatCompletionRequestMessageContentPartImage {
202 pub image_url: ImageUrl,
203}
204
205#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq)]
206#[serde(rename_all = "lowercase")]
207pub enum InputAudioFormat {
208 Wav,
209 #[default]
210 Mp3,
211}
212
213#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq)]
214pub struct InputAudio {
215 /// Base64 encoded audio data.
216 pub data: String,
217 /// The format of the encoded audio data. Currently supports "wav" and "mp3".
218 pub format: InputAudioFormat,
219}
220
221/// Learn about [audio inputs](https://platform.openai.com/docs/guides/audio).
222#[derive(Debug, Serialize, Deserialize, Default, Clone, Builder, PartialEq)]
223#[builder(name = "ChatCompletionRequestMessageContentPartAudioBuilder")]
224#[builder(pattern = "mutable")]
225#[builder(setter(into, strip_option), default)]
226#[builder(derive(Debug))]
227#[builder(build_fn(error = "OpenAIError"))]
228pub struct ChatCompletionRequestMessageContentPartAudio {
229 pub input_audio: InputAudio,
230}
231
232#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
233#[serde(tag = "type")]
234#[serde(rename_all = "snake_case")]
235pub enum ChatCompletionRequestUserMessageContentPart {
236 Text(TextObject),
237 ImageUrl(ChatCompletionRequestMessageContentPartImage),
238 InputAudio(ChatCompletionRequestMessageContentPartAudio),
239}
240
241#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
242#[serde(tag = "type")]
243#[serde(rename_all = "snake_case")]
244pub enum ChatCompletionRequestAssistantMessageContentPart {
245 Text(TextObject),
246 Refusal(ChatCompletionRequestMessageContentPartRefusal),
247}
248
249#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
250#[serde(tag = "type")]
251#[serde(rename_all = "snake_case")]
252pub enum ChatCompletionRequestToolMessageContentPart {
253 Text(TextObject),
254}
255
256#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
257#[serde(untagged)]
258pub enum ChatCompletionRequestUserMessageContent {
259 /// The text contents of the message.
260 Text(String),
261 /// An array of content parts with a defined type. Supported options differ based on the [model](https://platform.openai.com/docs/models) being used to generate the response. Can contain text, image, or audio inputs.
262 Array(Vec<ChatCompletionRequestUserMessageContentPart>),
263}
264impl ChatCompletionRequestUserMessageContent {
265 pub fn to_texts(&self) -> Vec<String> {
266 match self {
267 ChatCompletionRequestUserMessageContent::Text(text) => vec![text.clone()],
268 ChatCompletionRequestUserMessageContent::Array(parts) => parts
269 .iter()
270 .filter_map(|part| match part {
271 ChatCompletionRequestUserMessageContentPart::Text(text) => {
272 Some(text.text.clone())
273 }
274 _ => None,
275 })
276 .collect(),
277 }
278 }
279}
280
281#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
282#[serde(untagged)]
283pub enum ChatCompletionRequestAssistantMessageContent {
284 /// The text contents of the message.
285 Text(String),
286 /// An array of content parts with a defined type. Can be one or more of type `text`, or exactly one of type `refusal`.
287 Array(Vec<ChatCompletionRequestAssistantMessageContentPart>),
288}
289impl ChatCompletionRequestAssistantMessageContent {
290 pub fn to_texts(&self) -> Vec<String> {
291 match self {
292 ChatCompletionRequestAssistantMessageContent::Text(text) => vec![text.clone()],
293 ChatCompletionRequestAssistantMessageContent::Array(parts) => parts
294 .iter()
295 .filter_map(|part| match part {
296 ChatCompletionRequestAssistantMessageContentPart::Text(text) => {
297 Some(text.text.clone())
298 }
299 _ => None,
300 })
301 .collect(),
302 }
303 }
304}
305
306#[derive(Debug, Serialize, Deserialize, Default, Clone, Builder, PartialEq)]
307#[builder(name = "ChatCompletionRequestUserMessageBuilder")]
308#[builder(pattern = "mutable")]
309#[builder(setter(into, strip_option), default)]
310#[builder(derive(Debug))]
311#[builder(build_fn(error = "OpenAIError"))]
312pub struct ChatCompletionRequestUserMessage {
313 /// The contents of the user message.
314 pub content: ChatCompletionRequestUserMessageContent,
315 /// An optional name for the participant. Provides the model information to differentiate between participants of the same role.
316 #[serde(skip_serializing_if = "Option::is_none")]
317 pub name: Option<String>,
318}
319impl ChatCompletionRequestUserMessage {
320 pub fn to_texts(&self) -> Vec<String> {
321 self.content.to_texts()
322 }
323}
324
325#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq)]
326pub struct ChatCompletionRequestAssistantMessageAudio {
327 /// Unique identifier for a previous audio response from the model.
328 pub id: String,
329}
330
331#[derive(Debug, Serialize, Deserialize, Default, Clone, Builder, PartialEq)]
332#[builder(name = "ChatCompletionRequestAssistantMessageBuilder")]
333#[builder(pattern = "mutable")]
334#[builder(setter(into, strip_option), default)]
335#[builder(derive(Debug))]
336#[builder(build_fn(error = "OpenAIError"))]
337pub struct ChatCompletionRequestAssistantMessage {
338 /// The contents of the assistant message. Required unless `tool_calls` or `function_call` is specified.
339 #[serde(skip_serializing_if = "Option::is_none")]
340 pub content: Option<ChatCompletionRequestAssistantMessageContent>,
341 /// The refusal message by the assistant.
342 #[serde(skip_serializing_if = "Option::is_none")]
343 pub refusal: Option<String>,
344 /// An optional name for the participant. Provides the model information to differentiate between participants of the same role.
345 #[serde(skip_serializing_if = "Option::is_none")]
346 pub name: Option<String>,
347 /// Data about a previous audio response from the model.
348 /// [Learn more](https://platform.openai.com/docs/guides/audio).
349 #[serde(skip_serializing_if = "Option::is_none")]
350 pub audio: Option<ChatCompletionRequestAssistantMessageAudio>,
351 #[serde(skip_serializing_if = "Option::is_none")]
352 pub tool_calls: Option<Vec<ChatCompletionMessageToolCall>>,
353}
354impl ChatCompletionRequestAssistantMessage {
355 pub fn to_texts(&self) -> Vec<String> {
356 self.content
357 .as_ref()
358 .map_or_else(Vec::new, |content| content.to_texts())
359 }
360}
361
362/// Tool message
363#[derive(Debug, Serialize, Deserialize, Default, Clone, Builder, PartialEq)]
364#[builder(name = "ChatCompletionRequestToolMessageBuilder")]
365#[builder(pattern = "mutable")]
366#[builder(setter(into, strip_option), default)]
367#[builder(derive(Debug))]
368#[builder(build_fn(error = "OpenAIError"))]
369pub struct ChatCompletionRequestToolMessage {
370 /// The contents of the tool message.
371 pub content: PartibleTextContent,
372 pub tool_call_id: String,
373}
374impl ChatCompletionRequestToolMessage {
375 pub fn to_texts(&self) -> Vec<String> {
376 self.content.to_texts()
377 }
378}
379
380#[derive(Debug, Serialize, Deserialize, Default, Clone, Builder, PartialEq)]
381#[builder(name = "ChatCompletionRequestFunctionMessageBuilder")]
382#[builder(pattern = "mutable")]
383#[builder(setter(into, strip_option), default)]
384#[builder(derive(Debug))]
385#[builder(build_fn(error = "OpenAIError"))]
386pub struct ChatCompletionRequestFunctionMessage {
387 /// The return value from the function call, to return to the model.
388 pub content: Option<String>,
389 /// The name of the function to call.
390 pub name: String,
391}
392impl ChatCompletionRequestFunctionMessage {
393 pub fn to_texts(&self) -> Vec<String> {
394 self.content
395 .as_ref()
396 .map_or_else(Vec::new, |content| vec![content.clone()])
397 }
398}
399
400#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
401#[serde(tag = "role")]
402#[serde(rename_all = "lowercase")]
403pub enum ChatCompletionRequestMessage {
404 Developer(ChatCompletionRequestDeveloperMessage),
405 System(ChatCompletionRequestSystemMessage),
406 User(ChatCompletionRequestUserMessage),
407 Assistant(ChatCompletionRequestAssistantMessage),
408 Tool(ChatCompletionRequestToolMessage),
409 Function(ChatCompletionRequestFunctionMessage),
410}
411impl ChatCompletionRequestMessage {
412 pub fn to_texts(&self) -> Vec<String> {
413 match self {
414 ChatCompletionRequestMessage::Developer(msg) => msg.to_texts(),
415 ChatCompletionRequestMessage::System(msg) => msg.to_texts(),
416 ChatCompletionRequestMessage::User(msg) => msg.to_texts(),
417 ChatCompletionRequestMessage::Assistant(msg) => msg.to_texts(),
418 ChatCompletionRequestMessage::Tool(msg) => msg.to_texts(),
419 ChatCompletionRequestMessage::Function(msg) => msg.to_texts(),
420 }
421 }
422}
423
424#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
425pub struct ChatCompletionMessageToolCall {
426 /// The ID of the tool call.
427 pub id: String,
428 /// The type of the tool. Currently, only `function` is supported.
429 #[serde(rename = "type")]
430 pub kind: ChatCompletionToolType,
431 /// The function that the model called.
432 pub function: FunctionCall,
433}
434
435#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq)]
436pub struct ChatCompletionResponseMessageAudio {
437 /// Unique identifier for this audio response.
438 pub id: String,
439 /// The Unix timestamp (in seconds) for when this audio response will no longer be accessible on the server for use in multi-turn conversations.
440 pub expires_at: u32,
441 /// Base64 encoded audio bytes generated by the model, in the format specified in the request.
442 pub data: String,
443 /// Transcript of the audio generated by the model.
444 pub transcript: String,
445}
446
447/// A chat completion message generated by the model.
448#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
449pub struct ChatCompletionResponseMessage {
450 /// The contents of the message.
451 pub content: Option<String>,
452 /// The refusal message generated by the model.
453 pub refusal: Option<String>,
454 /// The tool calls generated by the model, such as function calls.
455 pub tool_calls: Option<Vec<ChatCompletionMessageToolCall>>,
456
457 /// The role of the author of this message.
458 pub role: Role,
459
460 /// If the audio output modality is requested, this object contains data about the audio response from the model. [Learn more](https://platform.openai.com/docs/guides/audio).
461 pub audio: Option<ChatCompletionResponseMessageAudio>,
462}
463
464#[derive(Clone, Serialize, Default, Debug, Deserialize, Builder, PartialEq)]
465#[builder(name = "FunctionObjectBuilder")]
466#[builder(pattern = "mutable")]
467#[builder(setter(into, strip_option), default)]
468#[builder(derive(Debug))]
469#[builder(build_fn(error = "OpenAIError"))]
470pub struct FunctionObject {
471 /// The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64.
472 pub name: String,
473 /// A description of what the function does, used by the model to choose when and how to call the function.
474 #[serde(skip_serializing_if = "Option::is_none")]
475 pub description: Option<String>,
476 /// The parameters the functions accepts, described as a JSON Schema object. See the [guide](https://platform.openai.com/docs/guides/text-generation/function-calling) for examples, and the [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for documentation about the format.
477 ///
478 /// Omitting `parameters` defines a function with an empty parameter list.
479 #[serde(skip_serializing_if = "Option::is_none")]
480 pub parameters: Option<serde_json::Value>,
481
482 /// Whether to enable strict schema adherence when generating the function call. If set to true, the model will follow the exact schema defined in the `parameters` field. Only a subset of JSON Schema is supported when `strict` is `true`. Learn more about Structured Outputs in the [function calling guide](https://platform.openai.com/docs/guides/function-calling).
483 #[serde(skip_serializing_if = "Option::is_none")]
484 pub strict: Option<bool>,
485}
486
487#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
488#[serde(tag = "type", rename_all = "snake_case")]
489pub enum ResponseFormat {
490 /// The type of response format being defined: `text`
491 Text,
492 /// The type of response format being defined: `json_object`
493 JsonObject,
494 /// The type of response format being defined: `json_schema`
495 JsonSchema {
496 json_schema: ResponseFormatJsonSchema,
497 },
498}
499
500#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
501pub struct ResponseFormatJsonSchema {
502 /// A description of what the response format is for, used by the model to determine how to respond in the format.
503 #[serde(skip_serializing_if = "Option::is_none")]
504 pub description: Option<String>,
505 /// The name of the response format. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64.
506 pub name: String,
507 /// The schema for the response format, described as a JSON Schema object.
508 #[serde(skip_serializing_if = "Option::is_none")]
509 pub schema: Option<serde_json::Value>,
510 /// Whether to enable strict schema adherence when generating the output. If set to true, the model will always follow the exact schema defined in the `schema` field. Only a subset of JSON Schema is supported when `strict` is `true`. To learn more, read the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs).
511 #[serde(skip_serializing_if = "Option::is_none")]
512 pub strict: Option<bool>,
513}
514
515#[derive(Clone, Serialize, Default, Debug, Deserialize, PartialEq)]
516#[serde(rename_all = "lowercase")]
517pub enum ChatCompletionToolType {
518 #[default]
519 Function,
520}
521
522#[derive(Clone, Serialize, Default, Debug, Builder, Deserialize, PartialEq)]
523#[builder(name = "ChatCompletionToolBuilder")]
524#[builder(pattern = "mutable")]
525#[builder(setter(into, strip_option), default)]
526#[builder(derive(Debug))]
527#[builder(build_fn(error = "OpenAIError"))]
528pub struct ChatCompletionTool {
529 #[builder(default = "ChatCompletionToolType::Function")]
530 #[serde(rename = "type")]
531 pub kind: ChatCompletionToolType,
532 pub function: FunctionObject,
533}
534
535#[derive(Clone, Serialize, Default, Debug, Deserialize, PartialEq)]
536pub struct FunctionName {
537 /// The name of the function to call.
538 pub name: String,
539}
540
541/// Specifies a tool the model should use. Use to force the model to call a specific function.
542#[derive(Clone, Serialize, Default, Debug, Deserialize, PartialEq)]
543pub struct ChatCompletionNamedToolChoice {
544 /// The type of the tool. Currently, only `function` is supported.
545 #[serde(rename = "type")]
546 pub kind: ChatCompletionToolType,
547
548 pub function: FunctionName,
549}
550
551/// Controls which (if any) tool is called by the model.
552/// `none` means the model will not call any tool and instead generates a message.
553/// `auto` means the model can pick between generating a message or calling one or more tools.
554/// `required` means the model must call one or more tools.
555/// Specifying a particular tool via `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool.
556///
557/// `none` is the default when no tools are present. `auto` is the default if tools are present.present.
558#[derive(Clone, Serialize, Default, Debug, Deserialize, PartialEq)]
559#[serde(rename_all = "lowercase")]
560pub enum ChatCompletionToolChoiceOption {
561 #[default]
562 None,
563 Auto,
564 Required,
565 #[serde(untagged)]
566 Named(ChatCompletionNamedToolChoice),
567}
568
569#[derive(Clone, Serialize, Debug, Deserialize, PartialEq, Default)]
570#[serde(rename_all = "lowercase")]
571/// The amount of context window space to use for the search.
572pub enum WebSearchContextSize {
573 Low,
574 #[default]
575 Medium,
576 High,
577}
578
579#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
580#[serde(rename_all = "lowercase")]
581pub enum WebSearchUserLocationType {
582 Approximate,
583}
584
585/// Approximate location parameters for the search.
586#[derive(Clone, Serialize, Debug, Default, Deserialize, PartialEq)]
587pub struct WebSearchLocation {
588 /// The two-letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of the user, e.g. `US`.
589 pub country: Option<String>,
590 /// Free text input for the region of the user, e.g. `California`.
591 pub region: Option<String>,
592 /// Free text input for the city of the user, e.g. `San Francisco`.
593 pub city: Option<String>,
594 /// The [IANA timezone](https://timeapi.io/documentation/iana-timezones) of the user, e.g. `America/Los_Angeles`.
595 pub timezone: Option<String>,
596}
597
598#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
599pub struct WebSearchUserLocation {
600 // The type of location approximation. Always `approximate`.
601 #[serde(rename = "type")]
602 pub kind: WebSearchUserLocationType,
603
604 pub approximate: WebSearchLocation,
605}
606
607/// Options for the web search tool.
608#[derive(Clone, Serialize, Debug, Default, Deserialize, PartialEq)]
609pub struct WebSearchOptions {
610 /// High level guidance for the amount of context window space to use for the search. One of `low`, `medium`, or `high`. `medium` is the default.
611 pub search_context_size: Option<WebSearchContextSize>,
612
613 /// Approximate location parameters for the search.
614 pub user_location: Option<WebSearchUserLocation>,
615}
616
617#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
618#[serde(rename_all = "lowercase")]
619pub enum ServiceTier {
620 Auto,
621 Default,
622 Flex,
623}
624
625#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
626#[serde(rename_all = "lowercase")]
627pub enum ServiceTierResponse {
628 Scale,
629 Default,
630 Flex,
631}
632
633#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
634#[serde(rename_all = "lowercase")]
635pub enum ReasoningEffort {
636 Low,
637 Medium,
638 High,
639}
640
641/// Output types that you would like the model to generate for this request.
642///
643/// Most models are capable of generating text, which is the default: `["text"]`
644///
645/// The `gpt-4o-audio-preview` model can also be used to [generate
646/// audio](https://platform.openai.com/docs/guides/audio). To request that this model generate both text and audio responses, you can use: `["text", "audio"]`
647#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
648#[serde(rename_all = "lowercase")]
649pub enum ChatCompletionModalities {
650 Text,
651 Audio,
652}
653
654/// Static predicted output content, such as the content of a text file that is being regenerated.
655#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
656#[serde(tag = "type", rename_all = "lowercase", content = "content")]
657pub enum PredictionContent {
658 /// The type of the predicted content you want to provide. This type is
659 /// currently always `content`.
660 Content(PartibleTextContent),
661}
662
663#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
664#[serde(rename_all = "lowercase")]
665pub enum ChatCompletionAudioVoice {
666 Alloy,
667 Ash,
668 Ballad,
669 Coral,
670 Echo,
671 Sage,
672 Shimmer,
673 Verse,
674}
675
676#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
677#[serde(rename_all = "lowercase")]
678pub enum ChatCompletionAudioFormat {
679 Wav,
680 Mp3,
681 Flac,
682 Opus,
683 Pcm16,
684}
685
686#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
687pub struct ChatCompletionAudio {
688 /// The voice the model uses to respond. Supported voices are `ash`, `ballad`, `coral`, `sage`, and `verse` (also supported but not recommended are `alloy`, `echo`, and `shimmer`; these voices are less expressive).
689 pub voice: ChatCompletionAudioVoice,
690 /// Specifies the output audio format. Must be one of `wav`, `mp3`, `flac`, `opus`, or `pcm16`.
691 pub format: ChatCompletionAudioFormat,
692}
693
694#[derive(Clone, Serialize, Default, Debug, Builder, Deserialize, PartialEq)]
695#[builder(name = "CreateChatCompletionRequestBuilder")]
696#[builder(pattern = "mutable")]
697#[builder(setter(into, strip_option), default)]
698#[builder(derive(Debug))]
699#[builder(build_fn(error = "OpenAIError"))]
700pub struct CreateChatCompletionRequest {
701 /// 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).
702 pub messages: Vec<ChatCompletionRequestMessage>, // min: 1
703
704 /// ID of the model to use.
705 /// 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.
706 pub model: String,
707
708 /// Whether or not to store the output of this chat completion request
709 ///
710 /// for use in our [model distillation](https://platform.openai.com/docs/guides/distillation) or [evals](https://platform.openai.com/docs/guides/evals) products.
711 #[serde(skip_serializing_if = "Option::is_none")]
712 pub store: Option<bool>, // nullable: true, default: false
713
714 /// **o1 models only**
715 ///
716 /// Constrains effort on reasoning for
717 /// [reasoning models](https://platform.openai.com/docs/guides/reasoning).
718 ///
719 /// Currently supported values are `low`, `medium`, and `high`. Reducing
720 ///
721 /// reasoning effort can result in faster responses and fewer tokens
722 /// used on reasoning in a response.
723 #[serde(skip_serializing_if = "Option::is_none")]
724 pub reasoning_effort: Option<ReasoningEffort>,
725
726 /// Developer-defined tags and values used for filtering completions in the [dashboard](https://platform.openai.com/chat-completions).
727 #[serde(skip_serializing_if = "Option::is_none")]
728 pub metadata: Option<serde_json::Value>, // nullable: true
729
730 /// 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.
731 #[serde(skip_serializing_if = "Option::is_none")]
732 pub frequency_penalty: Option<f32>, // min: -2.0, max: 2.0, default: 0
733
734 /// Modify the likelihood of specified tokens appearing in the completion.
735 ///
736 /// Accepts a json object that maps tokens (specified by their token ID in the tokenizer) to an associated bias value from -100 to 100.
737 /// Mathematically, the bias is added to the logits generated by the model prior to sampling.
738 /// The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection;
739 /// values like -100 or 100 should result in a ban or exclusive selection of the relevant token.
740 #[serde(skip_serializing_if = "Option::is_none")]
741 pub logit_bias: Option<HashMap<String, serde_json::Value>>, // default: null
742
743 /// 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`.
744 #[serde(skip_serializing_if = "Option::is_none")]
745 pub logprobs: Option<bool>,
746
747 /// 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.
748 #[serde(skip_serializing_if = "Option::is_none")]
749 pub top_logprobs: Option<u8>,
750
751 /// 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).
752 #[serde(skip_serializing_if = "Option::is_none")]
753 pub max_completion_tokens: Option<u32>,
754
755 /// 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.
756 #[serde(skip_serializing_if = "Option::is_none")]
757 pub n: Option<u8>, // min:1, max: 128, default: 1
758
759 #[serde(skip_serializing_if = "Option::is_none")]
760 pub modalities: Option<Vec<ChatCompletionModalities>>,
761
762 /// 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.
763 #[serde(skip_serializing_if = "Option::is_none")]
764 pub prediction: Option<PredictionContent>,
765
766 /// Parameters for audio output. Required when audio output is requested with `modalities: ["audio"]`. [Learn more](https://platform.openai.com/docs/guides/audio).
767 #[serde(skip_serializing_if = "Option::is_none")]
768 pub audio: Option<ChatCompletionAudio>,
769
770 /// 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.
771 #[serde(skip_serializing_if = "Option::is_none")]
772 pub presence_penalty: Option<f32>, // min: -2.0, max: 2.0, default 0
773
774 /// An object specifying the format that the model must output. Compatible with [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), [GPT-4o mini](https://platform.openai.com/docs/models/gpt-4o-mini), [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`.
775 ///
776 /// Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured Outputs which guarantees the model will match your supplied JSON schema. Learn more in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs).
777 ///
778 /// Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON.
779 ///
780 /// **Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token limit, resulting in a long-running and seemingly "stuck" request. Also note that the message content may be partially cut off if `finish_reason="length"`, which indicates the generation exceeded `max_tokens` or the conversation exceeded the max context length.
781 #[serde(skip_serializing_if = "Option::is_none")]
782 pub response_format: Option<ResponseFormat>,
783
784 /// This feature is in Beta.
785 /// If specified, our system will make a best effort to sample deterministically, such that repeated requests
786 /// with the same `seed` and parameters should return the same result.
787 /// Determinism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend.
788 #[serde(skip_serializing_if = "Option::is_none")]
789 pub seed: Option<i64>,
790
791 /// Specifies the latency tier to use for processing the request. This parameter is relevant for customers subscribed to the scale tier service:
792 /// - If set to 'auto', the system will utilize scale tier credits until they are exhausted.
793 /// - If set to 'default', the request will be processed using the default service tier with a lower uptime SLA and no latency guarantee.
794 /// - When not set, the default behavior is 'auto'.
795 ///
796 /// When this parameter is set, the response body will include the `service_tier` utilized.
797 #[serde(skip_serializing_if = "Option::is_none")]
798 pub service_tier: Option<ServiceTier>,
799
800 /// Up to 4 sequences where the API will stop generating further tokens.
801 #[serde(skip_serializing_if = "Option::is_none")]
802 pub stop: Option<Stop>,
803
804 /// If set, partial message deltas will be sent, like in ChatGPT.
805 /// 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)
806 /// 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).
807 #[serde(skip_serializing_if = "Option::is_none")]
808 pub stream: Option<bool>,
809
810 #[serde(skip_serializing_if = "Option::is_none")]
811 pub stream_options: Option<ChatCompletionStreamOptions>,
812
813 /// What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random,
814 /// while lower values like 0.2 will make it more focused and deterministic.
815 ///
816 /// We generally recommend altering this or `top_p` but not both.
817 #[serde(skip_serializing_if = "Option::is_none")]
818 pub temperature: Option<f32>, // min: 0, max: 2, default: 1,
819
820 /// An alternative to sampling with temperature, called nucleus sampling,
821 /// where the model considers the results of the tokens with top_p probability mass.
822 /// So 0.1 means only the tokens comprising the top 10% probability mass are considered.
823 ///
824 /// We generally recommend altering this or `temperature` but not both.
825 #[serde(skip_serializing_if = "Option::is_none")]
826 pub top_p: Option<f32>, // min: 0, max: 1, default: 1
827
828 /// A list of tools the model may call. Currently, only functions are supported as a tool.
829 /// Use this to provide a list of functions the model may generate JSON inputs for. A max of 128 functions are supported.
830 #[serde(skip_serializing_if = "Option::is_none")]
831 pub tools: Option<Vec<ChatCompletionTool>>,
832
833 #[serde(skip_serializing_if = "Option::is_none")]
834 pub tool_choice: Option<ChatCompletionToolChoiceOption>,
835
836 /// Whether to enable [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) during tool use.
837 #[serde(skip_serializing_if = "Option::is_none")]
838 pub parallel_tool_calls: Option<bool>,
839
840 /// 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).
841 #[serde(skip_serializing_if = "Option::is_none")]
842 pub user: Option<String>,
843
844 /// This tool searches the web for relevant results to use in a response.
845 /// Learn more about the [web search tool](https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat).
846 #[serde(skip_serializing_if = "Option::is_none")]
847 pub web_search_options: Option<WebSearchOptions>,
848}
849
850/// Options for streaming response. Only set this when you set `stream: true`.
851#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq)]
852pub struct ChatCompletionStreamOptions {
853 /// If set, an additional chunk will be streamed before the `data: [DONE]` message. The `usage` field on this chunk shows the token usage statistics for the entire request, and the `choices` field will always be an empty array. All other chunks will also include a `usage` field, but with a null value.
854 pub include_usage: bool,
855}
856
857#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq)]
858#[serde(rename_all = "snake_case")]
859pub enum FinishReason {
860 Stop,
861 Length,
862 ToolCalls,
863 ContentFilter,
864 FunctionCall,
865}
866
867#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
868pub struct TopLogprobs {
869 /// The token.
870 pub token: String,
871 /// The log probability of this token.
872 pub logprob: f32,
873 /// A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be `null` if there is no bytes representation for the token.
874 pub bytes: Option<Vec<u8>>,
875}
876
877#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
878pub struct ChatCompletionTokenLogprob {
879 /// The token.
880 pub token: String,
881 /// The log probability of this token, if it is within the top 20 most likely tokens. Otherwise, the value `-9999.0` is used to signify that the token is very unlikely.
882 pub logprob: f32,
883 /// A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be `null` if there is no bytes representation for the token.
884 pub bytes: Option<Vec<u8>>,
885 /// List of the most likely tokens and their log probability, at this token position. In rare cases, there may be fewer than the number of requested `top_logprobs` returned.
886 pub top_logprobs: Vec<TopLogprobs>,
887}
888
889#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
890pub struct ChatChoiceLogprobs {
891 /// A list of message content tokens with log probability information.
892 pub content: Option<Vec<ChatCompletionTokenLogprob>>,
893 pub refusal: Option<Vec<ChatCompletionTokenLogprob>>,
894}
895
896#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
897pub struct ChatChoice {
898 /// The index of the choice in the list of choices.
899 pub index: u32,
900 pub message: ChatCompletionResponseMessage,
901 /// The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence,
902 /// `length` if the maximum number of tokens specified in the request was reached,
903 /// `content_filter` if content was omitted due to a flag from our content filters,
904 /// `tool_calls` if the model called a tool, or `function_call` (deprecated) if the model called a function.
905 pub finish_reason: Option<FinishReason>,
906 /// Log probability information for the choice.
907 pub logprobs: Option<ChatChoiceLogprobs>,
908}
909
910/// Represents a chat completion response returned by model, based on the provided input.
911#[derive(Debug, Deserialize, Clone, PartialEq, Serialize)]
912pub struct CreateChatCompletionResponse {
913 /// A unique identifier for the chat completion.
914 pub id: String,
915 /// A list of chat completion choices. Can be more than one if `n` is greater than 1.
916 pub choices: Vec<ChatChoice>,
917 /// The Unix timestamp (in seconds) of when the chat completion was created.
918 pub created: u32,
919 /// The model used for the chat completion.
920 pub model: String,
921 /// The service tier used for processing the request. This field is only included if the `service_tier` parameter is specified in the request.
922 pub service_tier: Option<ServiceTierResponse>,
923 /// This fingerprint represents the backend configuration that the model runs with.
924 ///
925 /// Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism.
926 pub system_fingerprint: Option<String>,
927
928 /// The object type, which is always `chat.completion`.
929 pub object: String,
930 pub usage: Option<CompletionUsage>,
931}
932
933/// Parsed server side events stream until an \[DONE\] is received from server.
934pub type ChatCompletionResponseStream =
935 Pin<Box<dyn Stream<Item = Result<CreateChatCompletionStreamResponse, OpenAIError>> + Send>>;
936
937#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
938pub struct FunctionCallStream {
939 /// The name of the function to call.
940 pub name: Option<String>,
941 /// The arguments to call the function with, as generated by the model in JSON format.
942 /// Note that the model does not always generate valid JSON, and may hallucinate
943 /// parameters not defined by your function schema. Validate the arguments in your
944 /// code before calling your function.
945 pub arguments: Option<String>,
946}
947
948#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
949pub struct ChatCompletionMessageToolCallChunk {
950 pub index: u32,
951 /// The ID of the tool call.
952 pub id: Option<String>,
953 /// The type of the tool. Currently, only `function` is supported.
954 #[serde(rename = "type")]
955 pub kind: Option<ChatCompletionToolType>,
956 pub function: Option<FunctionCallStream>,
957}
958
959/// A chat completion delta generated by streamed model responses.
960#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
961pub struct ChatCompletionStreamResponseDelta {
962 /// The contents of the chunk message.
963 pub content: Option<String>,
964
965 pub tool_calls: Option<Vec<ChatCompletionMessageToolCallChunk>>,
966 /// The role of the author of this message.
967 pub role: Option<Role>,
968 /// The refusal message generated by the model.
969 pub refusal: Option<String>,
970}
971
972#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
973pub struct ChatChoiceStream {
974 /// The index of the choice in the list of choices.
975 pub index: u32,
976 pub delta: ChatCompletionStreamResponseDelta,
977 /// The reason the model stopped generating tokens. This will be
978 /// `stop` if the model hit a natural stop point or a provided
979 /// stop sequence,
980 ///
981 /// `length` if the maximum number of tokens specified in the
982 /// request was reached,
983 /// `content_filter` if content was omitted due to a flag from our
984 /// content filters,
985 /// `tool_calls` if the model called a tool, or `function_call`
986 /// (deprecated) if the model called a function.
987 pub finish_reason: Option<FinishReason>,
988 /// Log probability information for the choice.
989 pub logprobs: Option<ChatChoiceLogprobs>,
990}
991
992#[derive(Debug, Deserialize, Clone, PartialEq, Serialize)]
993/// Represents a streamed chunk of a chat completion response returned by model, based on the provided input.
994pub struct CreateChatCompletionStreamResponse {
995 /// A unique identifier for the chat completion. Each chunk has the same ID.
996 pub id: String,
997 /// A list of chat completion choices. Can contain more than one elements if `n` is greater than 1. Can also be empty for the last chunk if you set `stream_options: {"include_usage": true}`.
998 pub choices: Vec<ChatChoiceStream>,
999
1000 /// The Unix timestamp (in seconds) of when the chat completion was created. Each chunk has the same timestamp.
1001 pub created: u32,
1002 /// The model to generate the completion.
1003 pub model: String,
1004 /// The service tier used for processing the request. This field is only included if the `service_tier` parameter is specified in the request.
1005 pub service_tier: Option<ServiceTierResponse>,
1006 /// This fingerprint represents the backend configuration that the model runs with.
1007 /// Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism.
1008 pub system_fingerprint: Option<String>,
1009 /// The object type, which is always `chat.completion.chunk`.
1010 pub object: String,
1011
1012 /// An optional field that will only be present when you set `stream_options: {"include_usage": true}` in your request.
1013 /// When present, it contains a null value except for the last chunk which contains the token usage statistics for the entire request.
1014 pub usage: Option<CompletionUsage>,
1015}