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