Skip to main content

dynamo_async_openai/types/
chat.rs

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