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