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