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 #[serde(skip_serializing_if = "Option::is_none")]
514 pub schema: Option<serde_json::Value>,
515 /// 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).
516 #[serde(skip_serializing_if = "Option::is_none")]
517 pub strict: Option<bool>,
518}
519
520#[derive(Clone, Serialize, Default, Debug, Deserialize, PartialEq)]
521#[serde(rename_all = "lowercase")]
522pub enum ChatCompletionToolType {
523 #[default]
524 Function,
525}
526
527#[derive(Clone, Serialize, Default, Debug, Builder, Deserialize, PartialEq)]
528#[builder(name = "ChatCompletionToolArgs")]
529#[builder(pattern = "mutable")]
530#[builder(setter(into, strip_option), default)]
531#[builder(derive(Debug))]
532#[builder(build_fn(error = "OpenAIError"))]
533pub struct ChatCompletionTool {
534 #[builder(default = "ChatCompletionToolType::Function")]
535 pub r#type: ChatCompletionToolType,
536 pub function: FunctionObject,
537}
538
539#[derive(Clone, Serialize, Default, Debug, Deserialize, PartialEq)]
540pub struct FunctionName {
541 /// The name of the function to call.
542 pub name: String,
543}
544
545/// Specifies a tool the model should use. Use to force the model to call a specific function.
546#[derive(Clone, Serialize, Default, Debug, Deserialize, PartialEq)]
547pub struct ChatCompletionNamedToolChoice {
548 /// The type of the tool. Currently, only `function` is supported.
549 pub r#type: ChatCompletionToolType,
550
551 pub function: FunctionName,
552}
553
554/// Controls which (if any) tool is called by the model.
555/// `none` means the model will not call any tool and instead generates a message.
556/// `auto` means the model can pick between generating a message or calling one or more tools.
557/// `required` means the model must call one or more tools.
558/// Specifying a particular tool via `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool.
559///
560/// `none` is the default when no tools are present. `auto` is the default if tools are present.
561#[derive(Clone, Serialize, Default, Debug, Deserialize, PartialEq)]
562#[serde(rename_all = "lowercase")]
563pub enum ChatCompletionToolChoiceOption {
564 #[default]
565 None,
566 Auto,
567 Required,
568 #[serde(untagged)]
569 Named(ChatCompletionNamedToolChoice),
570}
571
572#[derive(Clone, Serialize, Debug, Deserialize, PartialEq, Default)]
573#[serde(rename_all = "lowercase")]
574/// The amount of context window space to use for the search.
575pub enum WebSearchContextSize {
576 Low,
577 #[default]
578 Medium,
579 High,
580}
581
582#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
583#[serde(rename_all = "lowercase")]
584pub enum WebSearchUserLocationType {
585 Approximate,
586}
587
588/// Approximate location parameters for the search.
589#[derive(Clone, Serialize, Debug, Default, Deserialize, PartialEq)]
590pub struct WebSearchLocation {
591 /// The two-letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of the user, e.g. `US`.
592 pub country: Option<String>,
593 /// Free text input for the region of the user, e.g. `California`.
594 pub region: Option<String>,
595 /// Free text input for the city of the user, e.g. `San Francisco`.
596 pub city: Option<String>,
597 /// The [IANA timezone](https://timeapi.io/documentation/iana-timezones) of the user, e.g. `America/Los_Angeles`.
598 pub timezone: Option<String>,
599}
600
601#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
602pub struct WebSearchUserLocation {
603 // The type of location approximation. Always `approximate`.
604 pub r#type: WebSearchUserLocationType,
605
606 pub approximate: WebSearchLocation,
607}
608
609/// Options for the web search tool.
610#[derive(Clone, Serialize, Debug, Default, Deserialize, PartialEq)]
611pub struct WebSearchOptions {
612 /// 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.
613 pub search_context_size: Option<WebSearchContextSize>,
614
615 /// Approximate location parameters for the search.
616 pub user_location: Option<WebSearchUserLocation>,
617}
618
619#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
620#[serde(rename_all = "snake_case")]
621pub enum ServiceTier {
622 Auto,
623 Default,
624 Flex,
625 Scale,
626 Priority,
627 OnDemand,
628 Performance,
629}
630
631#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
632#[serde(rename_all = "snake_case")]
633pub enum ServiceTierResponse {
634 Scale,
635 Default,
636 Flex,
637 Priority,
638 OnDemand,
639 Performance,
640}
641
642#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
643#[serde(rename_all = "lowercase")]
644pub enum ReasoningEffort {
645 Minimal,
646 Low,
647 Medium,
648 High,
649}
650
651/// Output types that you would like the model to generate for this request.
652///
653/// Most models are capable of generating text, which is the default: `["text"]`
654///
655/// The `gpt-4o-audio-preview` model can also be used to [generate
656/// audio](https://platform.openai.com/docs/guides/audio). To request that this model generate both text and audio responses, you can use: `["text", "audio"]`
657#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
658#[serde(rename_all = "lowercase")]
659pub enum ChatCompletionModalities {
660 Text,
661 Audio,
662}
663
664/// 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.
665#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
666#[serde(untagged)]
667pub enum PredictionContentContent {
668 /// The content used for a Predicted Output. This is often the text of a file you are regenerating with minor changes.
669 Text(String),
670 /// 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.
671 Array(Vec<ChatCompletionRequestMessageContentPartText>),
672}
673
674/// Static predicted output content, such as the content of a text file that is being regenerated.
675#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
676#[serde(tag = "type", rename_all = "lowercase", content = "content")]
677pub enum PredictionContent {
678 /// The type of the predicted content you want to provide. This type is
679 /// currently always `content`.
680 Content(PredictionContentContent),
681}
682
683#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
684#[serde(rename_all = "lowercase")]
685pub enum ChatCompletionAudioVoice {
686 Alloy,
687 Ash,
688 Ballad,
689 Coral,
690 Echo,
691 Sage,
692 Shimmer,
693 Verse,
694}
695
696#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
697#[serde(rename_all = "lowercase")]
698pub enum ChatCompletionAudioFormat {
699 Wav,
700 Mp3,
701 Flac,
702 Opus,
703 Pcm16,
704}
705
706#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
707pub struct ChatCompletionAudio {
708 /// 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).
709 pub voice: ChatCompletionAudioVoice,
710 /// Specifies the output audio format. Must be one of `wav`, `mp3`, `flac`, `opus`, or `pcm16`.
711 pub format: ChatCompletionAudioFormat,
712}
713
714#[derive(Clone, Serialize, Default, Debug, Builder, Deserialize, PartialEq)]
715#[builder(name = "CreateChatCompletionRequestArgs")]
716#[builder(pattern = "mutable")]
717#[builder(setter(into, strip_option), default)]
718#[builder(derive(Debug))]
719#[builder(build_fn(error = "OpenAIError"))]
720pub struct CreateChatCompletionRequest {
721 /// 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).
722 pub messages: Vec<ChatCompletionRequestMessage>, // min: 1
723
724 /// ID of the model to use.
725 /// 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.
726 pub model: String,
727
728 /// Whether or not to store the output of this chat completion request
729 ///
730 /// for use in our [model distillation](https://platform.openai.com/docs/guides/distillation) or [evals](https://platform.openai.com/docs/guides/evals) products.
731 #[serde(skip_serializing_if = "Option::is_none")]
732 pub store: Option<bool>, // nullable: true, default: false
733
734 /// **o1 models only**
735 ///
736 /// Constrains effort on reasoning for
737 /// [reasoning models](https://platform.openai.com/docs/guides/reasoning).
738 ///
739 /// Currently supported values are `low`, `medium`, and `high`. Reducing
740 ///
741 /// reasoning effort can result in faster responses and fewer tokens
742 /// used on reasoning in a response.
743 #[serde(skip_serializing_if = "Option::is_none")]
744 pub reasoning_effort: Option<ReasoningEffort>,
745
746 /// Developer-defined tags and values used for filtering completions in the [dashboard](https://platform.openai.com/chat-completions).
747 #[serde(skip_serializing_if = "Option::is_none")]
748 pub metadata: Option<serde_json::Value>, // nullable: true
749
750 /// 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.
751 #[serde(skip_serializing_if = "Option::is_none")]
752 pub frequency_penalty: Option<f32>, // min: -2.0, max: 2.0, default: 0
753
754 /// Modify the likelihood of specified tokens appearing in the completion.
755 ///
756 /// Accepts a json object that maps tokens (specified by their token ID in the tokenizer) to an associated bias value from -100 to 100.
757 /// Mathematically, the bias is added to the logits generated by the model prior to sampling.
758 /// The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection;
759 /// values like -100 or 100 should result in a ban or exclusive selection of the relevant token.
760 #[serde(skip_serializing_if = "Option::is_none")]
761 pub logit_bias: Option<HashMap<String, serde_json::Value>>, // default: null
762
763 /// 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`.
764 #[serde(skip_serializing_if = "Option::is_none")]
765 pub logprobs: Option<bool>,
766
767 /// 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.
768 #[serde(skip_serializing_if = "Option::is_none")]
769 pub top_logprobs: Option<u8>,
770
771 /// The maximum number of [tokens](https://platform.openai.com/tokenizer) that can be generated in the chat completion.
772 ///
773 /// This value can be used to control [costs](https://openai.com/api/pricing/) for text generated via API.
774 /// This value is now deprecated in favor of `max_completion_tokens`, and is
775 /// not compatible with [o1 series models](https://platform.openai.com/docs/guides/reasoning).
776 #[deprecated]
777 #[serde(skip_serializing_if = "Option::is_none")]
778 pub max_tokens: Option<u32>,
779
780 /// 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).
781 #[serde(skip_serializing_if = "Option::is_none")]
782 pub max_completion_tokens: Option<u32>,
783
784 /// 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.
785 #[serde(skip_serializing_if = "Option::is_none")]
786 pub n: Option<u8>, // min:1, max: 128, default: 1
787
788 #[serde(skip_serializing_if = "Option::is_none")]
789 pub modalities: Option<Vec<ChatCompletionModalities>>,
790
791 /// 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.
792 #[serde(skip_serializing_if = "Option::is_none")]
793 pub prediction: Option<PredictionContent>,
794
795 /// Parameters for audio output. Required when audio output is requested with `modalities: ["audio"]`. [Learn more](https://platform.openai.com/docs/guides/audio).
796 #[serde(skip_serializing_if = "Option::is_none")]
797 pub audio: Option<ChatCompletionAudio>,
798
799 /// 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.
800 #[serde(skip_serializing_if = "Option::is_none")]
801 pub presence_penalty: Option<f32>, // min: -2.0, max: 2.0, default 0
802
803 /// 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`.
804 ///
805 /// 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).
806 ///
807 /// Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON.
808 ///
809 /// **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.
810 #[serde(skip_serializing_if = "Option::is_none")]
811 pub response_format: Option<ResponseFormat>,
812
813 /// This feature is in Beta.
814 /// If specified, our system will make a best effort to sample deterministically, such that repeated requests
815 /// with the same `seed` and parameters should return the same result.
816 /// Determinism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend.
817 #[serde(skip_serializing_if = "Option::is_none")]
818 pub seed: Option<i64>,
819
820 /// Specifies the latency tier to use for processing the request. This parameter is relevant for customers subscribed to the scale tier service:
821 /// - If set to 'auto', the system will utilize scale tier credits until they are exhausted.
822 /// - If set to 'default', the request will be processed using the default service tier with a lower uptime SLA and no latency guarentee.
823 /// - When not set, the default behavior is 'auto'.
824 ///
825 /// When this parameter is set, the response body will include the `service_tier` utilized.
826 #[serde(skip_serializing_if = "Option::is_none")]
827 pub service_tier: Option<ServiceTier>,
828
829 /// Up to 4 sequences where the API will stop generating further tokens.
830 #[serde(skip_serializing_if = "Option::is_none")]
831 pub stop: Option<Stop>,
832
833 /// If set, partial message deltas will be sent, like in ChatGPT.
834 /// 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)
835 /// 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).
836 #[serde(skip_serializing_if = "Option::is_none")]
837 pub stream: Option<bool>,
838
839 #[serde(skip_serializing_if = "Option::is_none")]
840 pub stream_options: Option<ChatCompletionStreamOptions>,
841
842 /// What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random,
843 /// while lower values like 0.2 will make it more focused and deterministic.
844 ///
845 /// We generally recommend altering this or `top_p` but not both.
846 #[serde(skip_serializing_if = "Option::is_none")]
847 pub temperature: Option<f32>, // min: 0, max: 2, default: 1,
848
849 /// An alternative to sampling with temperature, called nucleus sampling,
850 /// where the model considers the results of the tokens with top_p probability mass.
851 /// So 0.1 means only the tokens comprising the top 10% probability mass are considered.
852 ///
853 /// We generally recommend altering this or `temperature` but not both.
854 #[serde(skip_serializing_if = "Option::is_none")]
855 pub top_p: Option<f32>, // min: 0, max: 1, default: 1
856
857 /// A list of tools the model may call. Currently, only functions are supported as a tool.
858 /// Use this to provide a list of functions the model may generate JSON inputs for. A max of 128 functions are supported.
859 #[serde(skip_serializing_if = "Option::is_none")]
860 pub tools: Option<Vec<ChatCompletionTool>>,
861
862 #[serde(skip_serializing_if = "Option::is_none")]
863 pub tool_choice: Option<ChatCompletionToolChoiceOption>,
864
865 /// Whether to enable [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) during tool use.
866 #[serde(skip_serializing_if = "Option::is_none")]
867 pub parallel_tool_calls: Option<bool>,
868
869 /// 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).
870 #[serde(skip_serializing_if = "Option::is_none")]
871 pub user: Option<String>,
872
873 /// This tool searches the web for relevant results to use in a response.
874 /// Learn more about the [web search tool](https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat).
875 #[serde(skip_serializing_if = "Option::is_none")]
876 pub web_search_options: Option<WebSearchOptions>,
877
878 /// Deprecated in favor of `tool_choice`.
879 ///
880 /// Controls which (if any) function is called by the model.
881 /// `none` means the model will not call a function and instead generates a message.
882 /// `auto` means the model can pick between generating a message or calling a function.
883 /// Specifying a particular function via `{"name": "my_function"}` forces the model to call that function.
884 ///
885 /// `none` is the default when no functions are present. `auto` is the default if functions are present.
886 #[deprecated]
887 #[serde(skip_serializing_if = "Option::is_none")]
888 pub function_call: Option<ChatCompletionFunctionCall>,
889
890 /// Deprecated in favor of `tools`.
891 ///
892 /// A list of functions the model may generate JSON inputs for.
893 #[deprecated]
894 #[serde(skip_serializing_if = "Option::is_none")]
895 pub functions: Option<Vec<ChatCompletionFunctions>>,
896
897 /// The key to use for caching the prompt.
898 #[serde(skip_serializing_if = "Option::is_none")]
899 pub prompt_cache_key: Option<String>,
900}
901
902/// Options for streaming response. Only set this when you set `stream: true`.
903#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq)]
904pub struct ChatCompletionStreamOptions {
905 /// 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.
906 pub include_usage: bool,
907}
908
909#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq)]
910#[serde(rename_all = "snake_case")]
911pub enum FinishReason {
912 #[serde(alias = "eos", alias = "")]
913 Stop,
914 Length,
915 ToolCalls,
916 ContentFilter,
917 FunctionCall,
918}
919
920#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
921pub struct TopLogprobs {
922 /// The token.
923 pub token: String,
924 /// The log probability of this token.
925 pub logprob: f32,
926 /// 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.
927 pub bytes: Option<Vec<u8>>,
928}
929
930#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
931pub struct ChatCompletionTokenLogprob {
932 /// The token.
933 pub token: String,
934 /// 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.
935 pub logprob: f32,
936 /// 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.
937 pub bytes: Option<Vec<u8>>,
938 /// 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.
939 pub top_logprobs: Vec<TopLogprobs>,
940}
941
942#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
943pub struct ChatChoiceLogprobs {
944 /// A list of message content tokens with log probability information.
945 pub content: Option<Vec<ChatCompletionTokenLogprob>>,
946 pub refusal: Option<Vec<ChatCompletionTokenLogprob>>,
947}
948
949#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
950pub struct ChatChoice {
951 /// The index of the choice in the list of choices.
952 pub index: u32,
953 pub message: ChatCompletionResponseMessage,
954 /// The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence,
955 /// `length` if the maximum number of tokens specified in the request was reached,
956 /// `content_filter` if content was omitted due to a flag from our content filters,
957 /// `tool_calls` if the model called a tool, or `function_call` (deprecated) if the model called a function.
958 #[serde(skip_serializing_if = "Option::is_none")]
959 pub finish_reason: Option<FinishReason>,
960 /// Log probability information for the choice.
961 #[serde(skip_serializing_if = "Option::is_none")]
962 pub logprobs: Option<ChatChoiceLogprobs>,
963}
964
965/// Represents a chat completion response returned by model, based on the provided input.
966#[derive(Debug, Deserialize, Clone, PartialEq, Serialize)]
967pub struct CreateChatCompletionResponse {
968 /// A unique identifier for the chat completion.
969 pub id: String,
970 /// A list of chat completion choices. Can be more than one if `n` is greater than 1.
971 pub choices: Vec<ChatChoice>,
972 /// The Unix timestamp (in seconds) of when the chat completion was created.
973 pub created: u32,
974 /// The model used for the chat completion.
975 pub model: String,
976 /// The service tier used for processing the request. This field is only included if the `service_tier` parameter is specified in the request.
977 #[serde(skip_serializing_if = "Option::is_none")]
978 pub service_tier: Option<ServiceTierResponse>,
979 /// This fingerprint represents the backend configuration that the model runs with.
980 ///
981 /// Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism.
982 #[serde(skip_serializing_if = "Option::is_none")]
983 pub system_fingerprint: Option<String>,
984
985 /// The object type, which is always `chat.completion`.
986 pub object: Option<String>,
987 pub usage: Option<CompletionUsage>,
988}
989
990/// Parsed server side events stream until an \[DONE\] is received from server.
991pub type ChatCompletionResponseStream =
992 Pin<Box<dyn Stream<Item = Result<CreateChatCompletionStreamResponse, OpenAIError>> + Send>>;
993
994#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
995pub struct FunctionCallStream {
996 /// The name of the function to call.
997 pub name: Option<String>,
998 /// The arguments to call the function with, as generated by the model in JSON format.
999 /// Note that the model does not always generate valid JSON, and may hallucinate
1000 /// parameters not defined by your function schema. Validate the arguments in your
1001 /// code before calling your function.
1002 pub arguments: Option<String>,
1003}
1004
1005#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
1006pub struct ChatCompletionMessageToolCallChunk {
1007 pub index: u32,
1008 /// The ID of the tool call.
1009 pub id: Option<String>,
1010 /// The type of the tool. Currently, only `function` is supported.
1011 pub r#type: Option<ChatCompletionToolType>,
1012 pub function: Option<FunctionCallStream>,
1013}
1014
1015/// A chat completion delta generated by streamed model responses.
1016#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
1017pub struct ChatCompletionStreamResponseDelta {
1018 /// The contents of the chunk message.
1019 pub content: Option<String>,
1020 /// Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model.
1021 #[deprecated]
1022 pub function_call: Option<FunctionCallStream>,
1023
1024 pub tool_calls: Option<Vec<ChatCompletionMessageToolCallChunk>>,
1025 /// The role of the author of this message.
1026 pub role: Option<Role>,
1027 /// The refusal message generated by the model.
1028 pub refusal: Option<String>,
1029}
1030
1031#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
1032pub struct ChatChoiceStream {
1033 /// The index of the choice in the list of choices.
1034 pub index: u32,
1035 pub delta: ChatCompletionStreamResponseDelta,
1036 /// The reason the model stopped generating tokens. This will be
1037 /// `stop` if the model hit a natural stop point or a provided
1038 /// stop sequence,
1039 ///
1040 /// `length` if the maximum number of tokens specified in the
1041 /// request was reached,
1042 /// `content_filter` if content was omitted due to a flag from our
1043 /// content filters,
1044 /// `tool_calls` if the model called a tool, or `function_call`
1045 /// (deprecated) if the model called a function.
1046 #[serde(skip_serializing_if = "Option::is_none")]
1047 pub finish_reason: Option<FinishReason>,
1048 /// Log probability information for the choice.
1049 #[serde(skip_serializing_if = "Option::is_none")]
1050 pub logprobs: Option<ChatChoiceLogprobs>,
1051}
1052
1053#[derive(Debug, Deserialize, Clone, PartialEq, Serialize)]
1054/// Represents a streamed chunk of a chat completion response returned by model, based on the provided input.
1055pub struct CreateChatCompletionStreamResponse {
1056 /// A unique identifier for the chat completion. Each chunk has the same ID.
1057 pub id: String,
1058 /// 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}`.
1059 pub choices: Vec<ChatChoiceStream>,
1060
1061 /// The Unix timestamp (in seconds) of when the chat completion was created. Each chunk has the same timestamp.
1062 pub created: u32,
1063 /// The model to generate the completion.
1064 pub model: String,
1065 /// The service tier used for processing the request. This field is only included if the `service_tier` parameter is specified in the request.
1066 pub service_tier: Option<ServiceTierResponse>,
1067 /// This fingerprint represents the backend configuration that the model runs with.
1068 /// Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism.
1069 pub system_fingerprint: Option<String>,
1070 /// The object type, which is always `chat.completion.chunk`.
1071 pub object: Option<String>,
1072
1073 /// An optional field that will only be present when you set `stream_options: {"include_usage": true}` in your request.
1074 /// When present, it contains a null value except for the last chunk which contains the token usage statistics for the entire request.
1075 pub usage: Option<CompletionUsage>,
1076}