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