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