dynamo_async_openai/types/
chat.rs

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