flynn_openai/types/
chat.rs

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