async_openai_alt/types/
chat.rs

1use std::{collections::HashMap, pin::Pin};
2
3use derive_builder::Builder;
4use futures::Stream;
5use serde::{Deserialize, Deserializer, 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 50256 (inclusive).
15    IntegerArray(Vec<u16>),
16    ArrayOfIntegerArray(Vec<Vec<u16>>),
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    pub logprobs: Option<Logprobs>,
47    pub finish_reason: Option<CompletionFinishReason>,
48}
49
50#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
51pub enum ChatCompletionFunctionCall {
52    /// The model does not call a function, and responds to the end-user.
53    #[serde(rename = "none")]
54    None,
55    /// The model can pick between an end-user or calling a function.
56    #[serde(rename = "auto")]
57    Auto,
58
59    // In spec this is ChatCompletionFunctionCallOption
60    // based on feedback from @m1guelpf in https://github.com/64bit/async-openai/pull/118
61    // it is diverged from the spec
62    /// Forces the model to call the specified function.
63    #[serde(untagged)]
64    Function { name: String },
65}
66
67#[derive(Debug, Serialize, Deserialize, Clone, Copy, Default, PartialEq)]
68#[serde(rename_all = "lowercase")]
69pub enum Role {
70    System,
71    #[default]
72    User,
73    Assistant,
74    Tool,
75    Function,
76}
77
78/// The name and arguments of a function that should be called, as generated by the model.
79#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
80pub struct FunctionCall {
81    /// The name of the function to call.
82    pub name: String,
83    /// 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.
84    pub arguments: String,
85}
86
87/// Usage statistics for the completion request.
88#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
89pub struct CompletionUsage {
90    /// Number of tokens in the prompt.
91    pub prompt_tokens: u32,
92    /// Number of tokens in the generated completion.
93    pub completion_tokens: u32,
94    /// Total number of tokens used in the request (prompt + completion).
95    pub total_tokens: u32,
96    /// Breakdown of tokens used in the prompt.
97    pub prompt_tokens_details: Option<PromptTokensDetails>,
98    /// Breakdown of tokens used in a completion.
99    pub completion_tokens_details: Option<CompletionTokensDetails>,
100}
101
102/// Breakdown of tokens used in a completion.
103#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
104pub struct PromptTokensDetails {
105    /// Audio input tokens present in the prompt.
106    pub audio_tokens: Option<u32>,
107    /// Cached tokens present in the prompt.
108    pub cached_tokens: Option<u32>,
109}
110
111/// Breakdown of tokens used in a completion.
112#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
113pub struct CompletionTokensDetails {
114    pub accepted_prediction_tokens: Option<u32>,
115    /// Audio input tokens generated by the model.
116    pub audio_tokens: Option<u32>,
117    /// Tokens generated by the model for reasoning.
118    pub reasoning_tokens: Option<u32>,
119    ///  When using Predicted Outputs, the number of tokens in the
120    /// prediction that did not appear in the completion. However, like
121    /// reasoning tokens, these tokens are still counted in the total
122    /// completion tokens for purposes of billing, output, and context
123    /// window limits.
124    pub rejected_prediction_tokens: Option<u32>,
125}
126
127#[derive(Debug, Serialize, Deserialize, Default, Clone, Builder, PartialEq)]
128#[builder(name = "ChatCompletionRequestSystemMessageArgs")]
129#[builder(pattern = "mutable")]
130#[builder(setter(into, strip_option), default)]
131#[builder(derive(Debug))]
132#[builder(build_fn(error = "OpenAIError"))]
133pub struct ChatCompletionRequestSystemMessage {
134    /// The contents of the system message.
135    pub content: ChatCompletionRequestSystemMessageContent,
136    /// An optional name for the participant. Provides the model information to differentiate between participants of the same role.
137    #[serde(skip_serializing_if = "Option::is_none")]
138    pub name: Option<String>,
139}
140
141#[derive(Debug, Serialize, Deserialize, Default, Clone, Builder, PartialEq)]
142#[builder(name = "ChatCompletionRequestMessageContentPartTextArgs")]
143#[builder(pattern = "mutable")]
144#[builder(setter(into, strip_option), default)]
145#[builder(derive(Debug))]
146#[builder(build_fn(error = "OpenAIError"))]
147pub struct ChatCompletionRequestMessageContentPartText {
148    pub text: String,
149}
150
151#[derive(Debug, Serialize, Deserialize, Default, Clone, Builder, PartialEq)]
152pub struct ChatCompletionRequestMessageContentPartRefusal {
153    /// The refusal message generated by the model.
154    pub refusal: String,
155}
156
157#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq)]
158#[serde(rename_all = "lowercase")]
159pub enum ImageDetail {
160    #[default]
161    Auto,
162    Low,
163    High,
164}
165
166#[derive(Debug, Serialize, Deserialize, Default, Clone, Builder, PartialEq)]
167#[builder(name = "ImageUrlArgs")]
168#[builder(pattern = "mutable")]
169#[builder(setter(into, strip_option), default)]
170#[builder(derive(Debug))]
171#[builder(build_fn(error = "OpenAIError"))]
172pub struct ImageUrl {
173    /// Either a URL of the image or the base64 encoded image data.
174    pub url: String,
175    /// 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).
176    pub detail: Option<ImageDetail>,
177}
178
179#[derive(Debug, Serialize, Deserialize, Default, Clone, Builder, PartialEq)]
180#[builder(name = "ChatCompletionRequestMessageContentPartImageArgs")]
181#[builder(pattern = "mutable")]
182#[builder(setter(into, strip_option), default)]
183#[builder(derive(Debug))]
184#[builder(build_fn(error = "OpenAIError"))]
185pub struct ChatCompletionRequestMessageContentPartImage {
186    pub image_url: ImageUrl,
187}
188
189#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
190#[serde(tag = "type")]
191#[serde(rename_all = "snake_case")]
192pub enum ChatCompletionRequestUserMessageContentPart {
193    Text(ChatCompletionRequestMessageContentPartText),
194    ImageUrl(ChatCompletionRequestMessageContentPartImage),
195}
196
197#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
198#[serde(tag = "type")]
199#[serde(rename_all = "snake_case")]
200pub enum ChatCompletionRequestSystemMessageContentPart {
201    Text(ChatCompletionRequestMessageContentPartText),
202}
203
204#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
205#[serde(tag = "type")]
206#[serde(rename_all = "snake_case")]
207pub enum ChatCompletionRequestAssistantMessageContentPart {
208    Text(ChatCompletionRequestMessageContentPartText),
209    Refusal(ChatCompletionRequestMessageContentPartRefusal),
210}
211
212#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
213#[serde(tag = "type")]
214#[serde(rename_all = "snake_case")]
215pub enum ChatCompletionRequestToolMessageContentPart {
216    Text(ChatCompletionRequestMessageContentPartText),
217}
218
219#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
220#[serde(untagged)]
221pub enum ChatCompletionRequestSystemMessageContent {
222    /// The text contents of the system message.
223    Text(String),
224    /// An array of content parts with a defined type. For system messages, only type `text` is supported.
225    Array(Vec<ChatCompletionRequestSystemMessageContentPart>),
226}
227
228#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
229#[serde(untagged)]
230pub enum ChatCompletionRequestUserMessageContent {
231    /// The text contents of the message.
232    Text(String),
233    /// An array of content parts with a defined type, each can be of type `text` or `image_url` when passing in images. You can pass multiple images by adding multiple `image_url` content parts. Image input is only supported when using the `gpt-4o` model.
234    Array(Vec<ChatCompletionRequestUserMessageContentPart>),
235}
236
237#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
238#[serde(untagged)]
239pub enum ChatCompletionRequestAssistantMessageContent {
240    /// The text contents of the message.
241    Text(String),
242    /// An array of content parts with a defined type. Can be one or more of type `text`, or exactly one of type `refusal`.
243    Array(Vec<ChatCompletionRequestAssistantMessageContentPart>),
244}
245
246#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
247#[serde(untagged)]
248pub enum ChatCompletionRequestToolMessageContent {
249    /// The text contents of the tool message.
250    Text(String),
251    /// An array of content parts with a defined type. For tool messages, only type `text` is supported.
252    Array(Vec<ChatCompletionRequestToolMessageContentPart>),
253}
254
255#[derive(Debug, Serialize, Deserialize, Default, Clone, Builder, PartialEq)]
256#[builder(name = "ChatCompletionRequestUserMessageArgs")]
257#[builder(pattern = "mutable")]
258#[builder(setter(into, strip_option), default)]
259#[builder(derive(Debug))]
260#[builder(build_fn(error = "OpenAIError"))]
261pub struct ChatCompletionRequestUserMessage {
262    /// The contents of the user message.
263    pub content: ChatCompletionRequestUserMessageContent,
264    /// An optional name for the participant. Provides the model information to differentiate between participants of the same role.
265    #[serde(skip_serializing_if = "Option::is_none")]
266    pub name: Option<String>,
267}
268
269#[derive(Debug, Serialize, Deserialize, Default, Clone, Builder, PartialEq)]
270#[builder(name = "ChatCompletionRequestAssistantMessageArgs")]
271#[builder(pattern = "mutable")]
272#[builder(setter(into, strip_option), default)]
273#[builder(derive(Debug))]
274#[builder(build_fn(error = "OpenAIError"))]
275pub struct ChatCompletionRequestAssistantMessage {
276    /// The contents of the assistant message. Required unless `tool_calls` or `function_call` is specified.
277    #[serde(skip_serializing_if = "Option::is_none")]
278    pub content: Option<ChatCompletionRequestAssistantMessageContent>,
279    /// The refusal message by the assistant.
280    #[serde(skip_serializing_if = "Option::is_none")]
281    pub refusal: Option<String>,
282    /// An optional name for the participant. Provides the model information to differentiate between participants of the same role.
283    #[serde(skip_serializing_if = "Option::is_none")]
284    pub name: Option<String>,
285    #[serde(skip_serializing_if = "Option::is_none")]
286    pub tool_calls: Option<Vec<ChatCompletionMessageToolCall>>,
287    /// Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model.
288    #[deprecated]
289    #[serde(skip_serializing_if = "Option::is_none")]
290    pub function_call: Option<FunctionCall>,
291}
292
293/// Tool message
294#[derive(Debug, Serialize, Deserialize, Default, Clone, Builder, PartialEq)]
295#[builder(name = "ChatCompletionRequestToolMessageArgs")]
296#[builder(pattern = "mutable")]
297#[builder(setter(into, strip_option), default)]
298#[builder(derive(Debug))]
299#[builder(build_fn(error = "OpenAIError"))]
300pub struct ChatCompletionRequestToolMessage {
301    /// The contents of the tool message.
302    pub content: ChatCompletionRequestToolMessageContent,
303    pub tool_call_id: String,
304}
305
306#[derive(Debug, Serialize, Deserialize, Default, Clone, Builder, PartialEq)]
307#[builder(name = "ChatCompletionRequestFunctionMessageArgs")]
308#[builder(pattern = "mutable")]
309#[builder(setter(into, strip_option), default)]
310#[builder(derive(Debug))]
311#[builder(build_fn(error = "OpenAIError"))]
312pub struct ChatCompletionRequestFunctionMessage {
313    /// The return value from the function call, to return to the model.
314    pub content: Option<String>,
315    /// The name of the function to call.
316    pub name: String,
317}
318
319#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
320#[serde(tag = "role")]
321#[serde(rename_all = "lowercase")]
322pub enum ChatCompletionRequestMessage {
323    System(ChatCompletionRequestSystemMessage),
324    User(ChatCompletionRequestUserMessage),
325    Assistant(ChatCompletionRequestAssistantMessage),
326    Tool(ChatCompletionRequestToolMessage),
327    Function(ChatCompletionRequestFunctionMessage),
328}
329
330#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
331pub struct ChatCompletionMessageToolCall {
332    /// The ID of the tool call.
333    pub id: String,
334    /// The type of the tool. Currently, only `function` is supported.
335    pub r#type: ChatCompletionToolType,
336    /// The function that the model called.
337    pub function: FunctionCall,
338}
339
340/// A chat completion message generated by the model.
341#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
342pub struct ChatCompletionResponseMessage {
343    /// The contents of the message.
344    pub content: Option<String>,
345    /// The refusal message generated by the model.
346    pub refusal: Option<String>,
347    /// The tool calls generated by the model, such as function calls.
348    pub tool_calls: Option<Vec<ChatCompletionMessageToolCall>>,
349
350    /// The role of the author of this message.
351    pub role: Role,
352
353    /// Deprecated and replaced by `tool_calls`.
354    /// The name and arguments of a function that should be called, as generated by the model.
355    #[deprecated]
356    pub function_call: Option<FunctionCall>,
357}
358
359#[derive(Clone, Serialize, Default, Debug, Deserialize, Builder, PartialEq)]
360#[builder(name = "ChatCompletionFunctionsArgs")]
361#[builder(pattern = "mutable")]
362#[builder(setter(into, strip_option), default)]
363#[builder(derive(Debug))]
364#[builder(build_fn(error = "OpenAIError"))]
365#[deprecated]
366pub struct ChatCompletionFunctions {
367    /// 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.
368    pub name: String,
369    /// A description of what the function does, used by the model to choose when and how to call the function.
370    #[serde(skip_serializing_if = "Option::is_none")]
371    pub description: Option<String>,
372    /// 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.
373    ///
374    /// Omitting `parameters` defines a function with an empty parameter list.
375    pub parameters: serde_json::Value,
376}
377
378#[derive(Clone, Serialize, Default, Debug, Deserialize, Builder, PartialEq)]
379#[builder(name = "FunctionObjectArgs")]
380#[builder(pattern = "mutable")]
381#[builder(setter(into, strip_option), default)]
382#[builder(derive(Debug))]
383#[builder(build_fn(error = "OpenAIError"))]
384pub struct FunctionObject {
385    /// 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.
386    pub name: String,
387    /// A description of what the function does, used by the model to choose when and how to call the function.
388    #[serde(skip_serializing_if = "Option::is_none")]
389    pub description: Option<String>,
390    /// 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.
391    ///
392    /// Omitting `parameters` defines a function with an empty parameter list.
393    #[serde(skip_serializing_if = "Option::is_none")]
394    pub parameters: Option<serde_json::Value>,
395
396    /// 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).
397    #[serde(skip_serializing_if = "Option::is_none")]
398    pub strict: Option<bool>,
399}
400
401#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
402#[serde(tag = "type", rename_all = "snake_case")]
403pub enum ResponseFormat {
404    /// The type of response format being defined: `text`
405    Text,
406    /// The type of response format being defined: `json_object`
407    JsonObject,
408    /// The type of response format being defined: `json_schema`
409    JsonSchema {
410        json_schema: ResponseFormatJsonSchema,
411    },
412}
413
414#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
415pub struct ResponseFormatJsonSchema {
416    /// A description of what the response format is for, used by the model to determine how to respond in the format.
417    #[serde(skip_serializing_if = "Option::is_none")]
418    pub description: Option<String>,
419    /// The name of the response format. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length
420    pub name: String,
421    /// The schema for the response format, described as a JSON Schema object.
422    #[serde(skip_serializing_if = "Option::is_none")]
423    pub schema: Option<serde_json::Value>,
424    /// 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).
425    #[serde(skip_serializing_if = "Option::is_none")]
426    pub strict: Option<bool>,
427}
428
429#[derive(Clone, Serialize, Default, Debug, Deserialize, PartialEq)]
430#[serde(rename_all = "lowercase")]
431pub enum ChatCompletionToolType {
432    #[default]
433    Function,
434}
435
436#[derive(Clone, Serialize, Default, Debug, Builder, Deserialize, PartialEq)]
437#[builder(name = "ChatCompletionToolArgs")]
438#[builder(pattern = "mutable")]
439#[builder(setter(into, strip_option), default)]
440#[builder(derive(Debug))]
441#[builder(build_fn(error = "OpenAIError"))]
442pub struct ChatCompletionTool {
443    #[builder(default = "ChatCompletionToolType::Function")]
444    pub r#type: ChatCompletionToolType,
445    pub function: FunctionObject,
446}
447
448#[derive(Clone, Serialize, Default, Debug, Deserialize, PartialEq)]
449pub struct FunctionName {
450    /// The name of the function to call.
451    pub name: String,
452}
453
454/// Specifies a tool the model should use. Use to force the model to call a specific function.
455#[derive(Clone, Serialize, Default, Debug, Deserialize, PartialEq)]
456pub struct ChatCompletionNamedToolChoice {
457    /// The type of the tool. Currently, only `function` is supported.
458    pub r#type: ChatCompletionToolType,
459
460    pub function: FunctionName,
461}
462
463/// Controls which (if any) tool is called by the model.
464/// `none` means the model will not call any tool and instead generates a message.
465/// `auto` means the model can pick between generating a message or calling one or more tools.
466/// `required` means the model must call one or more tools.
467/// Specifying a particular tool via `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool.
468///
469/// `none` is the default when no tools are present. `auto` is the default if tools are present.present.
470#[derive(Clone, Serialize, Default, Debug, Deserialize, PartialEq)]
471#[serde(rename_all = "lowercase")]
472pub enum ChatCompletionToolChoiceOption {
473    #[default]
474    None,
475    Auto,
476    Required,
477    #[serde(untagged)]
478    Named(ChatCompletionNamedToolChoice),
479}
480
481#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
482#[serde(rename_all = "lowercase")]
483pub enum ServiceTier {
484    Auto,
485    Default,
486}
487
488#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
489#[serde(rename_all = "lowercase")]
490pub enum ServiceTierResponse {
491    Scale,
492    Default,
493}
494
495#[derive(Clone, Serialize, Default, Debug, Builder, Deserialize, PartialEq)]
496#[builder(name = "CreateChatCompletionRequestArgs")]
497#[builder(pattern = "mutable")]
498#[builder(setter(into, strip_option), default)]
499#[builder(derive(Debug))]
500#[builder(build_fn(error = "OpenAIError"))]
501pub struct CreateChatCompletionRequest {
502    /// A list of messages comprising the conversation so far. [Example Python code](https://cookbook.openai.com/examples/how_to_format_inputs_to_chatgpt_models).
503    pub messages: Vec<ChatCompletionRequestMessage>, // min: 1
504
505    /// ID of the model to use.
506    /// 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.
507    pub model: String,
508
509    /// 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.
510    ///
511    /// [See more information about frequency and presence penalties.](https://platform.openai.com/docs/api-reference/parameter-details)
512    #[serde(skip_serializing_if = "Option::is_none")]
513    pub frequency_penalty: Option<f32>, // min: -2.0, max: 2.0, default: 0
514
515    /// Modify the likelihood of specified tokens appearing in the completion.
516    ///
517    /// Accepts a json object that maps tokens (specified by their token ID in the tokenizer) to an associated bias value from -100 to 100.
518    /// Mathematically, the bias is added to the logits generated by the model prior to sampling.
519    /// The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection;
520    /// values like -100 or 100 should result in a ban or exclusive selection of the relevant token.
521    #[serde(skip_serializing_if = "Option::is_none")]
522    pub logit_bias: Option<HashMap<String, serde_json::Value>>, // default: null
523
524    /// 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`.
525    #[serde(skip_serializing_if = "Option::is_none")]
526    pub logprobs: Option<bool>,
527
528    /// 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.
529    #[serde(skip_serializing_if = "Option::is_none")]
530    pub top_logprobs: Option<u8>,
531
532    /// The maximum number of [tokens](https://platform.openai.com/tokenizer) that can be generated in the chat completion.
533    ///
534    /// The total length of input tokens and generated tokens is limited by the model's context length. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens.
535    #[serde(skip_serializing_if = "Option::is_none")]
536    pub max_tokens: Option<u32>,
537
538    /// 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.
539    #[serde(skip_serializing_if = "Option::is_none")]
540    pub n: Option<u8>, // min:1, max: 128, default: 1
541
542    /// 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.
543    ///
544    /// [See more information about frequency and presence penalties.](https://platform.openai.com/docs/api-reference/parameter-details)
545    #[serde(skip_serializing_if = "Option::is_none")]
546    pub presence_penalty: Option<f32>, // min: -2.0, max: 2.0, default 0
547
548    /// 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`.
549    ///
550    /// 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).
551    ///
552    /// Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON.
553    ///
554    /// **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.
555    #[serde(skip_serializing_if = "Option::is_none")]
556    pub response_format: Option<ResponseFormat>,
557
558    ///  This feature is in Beta.
559    /// If specified, our system will make a best effort to sample deterministically, such that repeated requests
560    /// with the same `seed` and parameters should return the same result.
561    /// Determinism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend.
562    #[serde(skip_serializing_if = "Option::is_none")]
563    pub seed: Option<i64>,
564
565    /// Specifies the latency tier to use for processing the request. This parameter is relevant for customers subscribed to the scale tier service:
566    /// - If set to 'auto', the system will utilize scale tier credits until they are exhausted.
567    /// - If set to 'default', the request will be processed using the default service tier with a lower uptime SLA and no latency guarentee.
568    /// - When not set, the default behavior is 'auto'.
569    ///
570    /// When this parameter is set, the response body will include the `service_tier` utilized.
571    #[serde(skip_serializing_if = "Option::is_none")]
572    pub service_tier: Option<ServiceTier>,
573
574    /// Up to 4 sequences where the API will stop generating further tokens.
575    #[serde(skip_serializing_if = "Option::is_none")]
576    pub stop: Option<Stop>,
577
578    /// If set, partial message deltas will be sent, like in ChatGPT.
579    /// 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)
580    /// 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).
581    #[serde(skip_serializing_if = "Option::is_none")]
582    pub stream: Option<bool>,
583
584    #[serde(skip_serializing_if = "Option::is_none")]
585    pub stream_options: Option<ChatCompletionStreamOptions>,
586
587    /// What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random,
588    /// while lower values like 0.2 will make it more focused and deterministic.
589    ///
590    /// We generally recommend altering this or `top_p` but not both.
591    #[serde(skip_serializing_if = "Option::is_none")]
592    pub temperature: Option<f32>, // min: 0, max: 2, default: 1,
593
594    /// An alternative to sampling with temperature, called nucleus sampling,
595    /// where the model considers the results of the tokens with top_p probability mass.
596    /// So 0.1 means only the tokens comprising the top 10% probability mass are considered.
597    ///
598    ///  We generally recommend altering this or `temperature` but not both.
599    #[serde(skip_serializing_if = "Option::is_none")]
600    pub top_p: Option<f32>, // min: 0, max: 1, default: 1
601
602    /// A list of tools the model may call. Currently, only functions are supported as a tool.
603    /// Use this to provide a list of functions the model may generate JSON inputs for. A max of 128 functions are supported.
604    #[serde(skip_serializing_if = "Option::is_none")]
605    pub tools: Option<Vec<ChatCompletionTool>>,
606
607    #[serde(skip_serializing_if = "Option::is_none")]
608    pub tool_choice: Option<ChatCompletionToolChoiceOption>,
609
610    /// Whether to enable [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) during tool use.
611    #[serde(skip_serializing_if = "Option::is_none")]
612    pub parallel_tool_calls: Option<bool>,
613
614    /// 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).
615    #[serde(skip_serializing_if = "Option::is_none")]
616    pub user: Option<String>,
617
618    /// Deprecated in favor of `tool_choice`.
619    ///
620    /// Controls which (if any) function is called by the model.
621    /// `none` means the model will not call a function and instead generates a message.
622    /// `auto` means the model can pick between generating a message or calling a function.
623    /// Specifying a particular function via `{"name": "my_function"}` forces the model to call that function.
624    ///
625    /// `none` is the default when no functions are present. `auto` is the default if functions are present.
626    #[deprecated]
627    #[serde(skip_serializing_if = "Option::is_none")]
628    pub function_call: Option<ChatCompletionFunctionCall>,
629
630    /// Deprecated in favor of `tools`.
631    ///
632    /// A list of functions the model may generate JSON inputs for.
633    #[deprecated]
634    #[serde(skip_serializing_if = "Option::is_none")]
635    pub functions: Option<Vec<ChatCompletionFunctions>>,
636}
637
638/// Options for streaming response. Only set this when you set `stream: true`.
639#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq)]
640pub struct ChatCompletionStreamOptions {
641    /// 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.
642    pub include_usage: bool,
643}
644
645#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq)]
646#[serde(rename_all = "snake_case")]
647pub enum FinishReason {
648    Stop,
649    Length,
650    ToolCalls,
651    ContentFilter,
652    FunctionCall,
653}
654
655#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
656pub struct TopLogprobs {
657    /// The token.
658    pub token: String,
659    /// The log probability of this token.
660    pub logprob: f32,
661    /// 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.
662    pub bytes: Option<Vec<u8>>,
663}
664
665#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
666pub struct ChatCompletionTokenLogprob {
667    /// The token.
668    pub token: String,
669    /// 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.
670    pub logprob: f32,
671    /// 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.
672    pub bytes: Option<Vec<u8>>,
673    ///  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.
674    pub top_logprobs: Vec<TopLogprobs>,
675}
676
677#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
678pub struct ChatChoiceLogprobs {
679    /// A list of message content tokens with log probability information.
680    pub content: Option<Vec<ChatCompletionTokenLogprob>>,
681    pub refusal: Option<Vec<ChatCompletionTokenLogprob>>,
682}
683
684#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
685pub struct ChatChoice {
686    /// The index of the choice in the list of choices.
687    pub index: u32,
688    pub message: ChatCompletionResponseMessage,
689    /// The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence,
690    /// `length` if the maximum number of tokens specified in the request was reached,
691    /// `content_filter` if content was omitted due to a flag from our content filters,
692    /// `tool_calls` if the model called a tool, or `function_call` (deprecated) if the model called a function.
693    pub finish_reason: Option<FinishReason>,
694    /// Log probability information for the choice.
695    pub logprobs: Option<ChatChoiceLogprobs>,
696}
697
698/// Represents a chat completion response returned by model, based on the provided input.
699#[derive(Debug, Deserialize, Clone, PartialEq, Serialize)]
700pub struct CreateChatCompletionResponse {
701    /// A unique identifier for the chat completion.
702    pub id: String,
703    /// A list of chat completion choices. Can be more than one if `n` is greater than 1.
704    pub choices: Vec<ChatChoice>,
705    /// The Unix timestamp (in seconds) of when the chat completion was created.
706    pub created: u32,
707    /// The model used for the chat completion.
708    pub model: String,
709    /// The service tier used for processing the request. This field is only included if the `service_tier` parameter is specified in the request.
710    pub service_tier: Option<ServiceTierResponse>,
711    /// This fingerprint represents the backend configuration that the model runs with.
712    ///
713    /// Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism.
714    pub system_fingerprint: Option<String>,
715
716    /// The object type, which is always `chat.completion`.
717    pub object: String,
718    pub usage: Option<CompletionUsage>,
719}
720
721/// Parsed server side events stream until an \[DONE\] is received from server.
722pub type ChatCompletionResponseStream =
723    Pin<Box<dyn Stream<Item = Result<CreateChatCompletionStreamResponse, OpenAIError>> + Send>>;
724
725#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
726pub struct FunctionCallStream {
727    /// The name of the function to call.
728    pub name: Option<String>,
729    /// The arguments to call the function with, as generated by the model in JSON format.
730    /// Note that the model does not always generate valid JSON, and may hallucinate
731    /// parameters not defined by your function schema. Validate the arguments in your
732    /// code before calling your function.
733    pub arguments: Option<String>,
734}
735
736#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
737pub struct ChatCompletionMessageToolCallChunk {
738    pub index: i32,
739    /// The ID of the tool call.
740    pub id: Option<String>,
741    /// The type of the tool. Currently, only `function` is supported.
742    pub r#type: Option<ChatCompletionToolType>,
743    pub function: Option<FunctionCallStream>,
744}
745
746/// A chat completion delta generated by streamed model responses.
747#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
748pub struct ChatCompletionStreamResponseDelta {
749    /// The contents of the chunk message.
750    pub content: Option<String>,
751    /// The name and arguments of a function that should be called, as generated by the model.
752    #[deprecated]
753    pub function_call: Option<FunctionCallStream>,
754
755    pub tool_calls: Option<Vec<ChatCompletionMessageToolCallChunk>>,
756    /// The role of the author of this message.
757    pub role: Option<Role>,
758    /// The refusal message generated by the model.
759    pub refusal: Option<String>,
760}
761
762#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
763pub struct ChatChoiceStream {
764    /// The index of the choice in the list of choices.
765    pub index: u32,
766    pub delta: ChatCompletionStreamResponseDelta,
767    #[serde(default, deserialize_with = "deserialize_finish_reason")]
768    pub finish_reason: Option<FinishReason>,
769    /// Log probability information for the choice.
770    pub logprobs: Option<ChatChoiceLogprobs>,
771}
772
773fn deserialize_finish_reason<'de, D>(deserializer: D) -> Result<Option<FinishReason>, D::Error>
774where
775    D: Deserializer<'de>,
776{
777    let s = match String::deserialize(deserializer) {
778        Ok(s) => s,
779        Err(_) => return Ok(None),
780    };
781
782    match s.as_str() {
783        "stop" => Ok(Some(FinishReason::Stop)),
784        "length" => Ok(Some(FinishReason::Length)),
785        "tool_calls" => Ok(Some(FinishReason::ToolCalls)),
786        "content_filter" => Ok(Some(FinishReason::ContentFilter)),
787        "function_call" => Ok(Some(FinishReason::FunctionCall)),
788
789        // treat any other value as None
790        _ => Ok(None),
791    }
792}
793
794#[derive(Debug, Deserialize, Clone, PartialEq, Serialize)]
795/// Represents a streamed chunk of a chat completion response returned by model, based on the provided input.
796pub struct CreateChatCompletionStreamResponse {
797    /// A unique identifier for the chat completion. Each chunk has the same ID.
798    pub id: String,
799    /// 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}`.
800    pub choices: Vec<ChatChoiceStream>,
801
802    /// The Unix timestamp (in seconds) of when the chat completion was created. Each chunk has the same timestamp.
803    pub created: u32,
804    /// The model to generate the completion.
805    pub model: String,
806    /// The service tier used for processing the request. This field is only included if the `service_tier` parameter is specified in the request.
807    pub service_tier: Option<ServiceTierResponse>,
808    /// This fingerprint represents the backend configuration that the model runs with.
809    /// Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism.
810    pub system_fingerprint: Option<String>,
811    /// The object type, which is always `chat.completion.chunk`.
812    pub object: String,
813
814    /// An optional field that will only be present when you set `stream_options: {"include_usage": true}` in your request.
815    /// When present, it contains a null value except for the last chunk which contains the token usage statistics for the entire request.
816    pub usage: Option<CompletionUsage>,
817}