Skip to main content

openai_interface/chat/
mod.rs

1//! # Chat Completions API Module
2//!
3//! This module provides components shared by many submodules.
4
5use std::str::FromStr;
6
7use serde::{Deserialize, Serialize};
8
9use crate::errors::OapiError;
10
11pub mod create;
12pub mod delete;
13pub mod retrieve;
14pub mod update;
15
16crate::wire_string_enum! {
17    /// The service tier used for processing the request.
18    ///
19    /// This enum represents the different service tiers that can be specified when
20    /// making a request to the API. Each tier corresponds to different performance
21    /// characteristics and pricing models.
22    pub enum ServiceTier {
23        /// Automatically select the service tier based on project settings.
24        Auto => "auto",
25        /// Use the default service tier with standard pricing and performance.
26        Default => "default",
27        /// Use the flex service tier for flexible processing requirements.
28        Flex => "flex",
29        /// Use the scale service tier for scalable processing needs.
30        Scale => "scale",
31        /// Use the priority service tier for high-priority requests.
32        Priority => "priority",
33        /// Fast mode. Request-level opt-in for
34        /// [Fast mode](https://platform.openai.com/docs/guides/fast-mode); the
35        /// response reports the actual tier as `priority`.
36        Fast => "fast",
37    }
38}
39
40/// Moderation results for the request input and generated output.
41///
42/// Present on the response when moderated completions are requested via the
43/// `moderation` request parameter.
44#[derive(Debug, Deserialize, Serialize, Clone)]
45pub struct ChatModeration {
46    /// Moderation for the request input.
47    pub input: ModerationSide,
48    /// Moderation for the generated output.
49    pub output: ModerationSide,
50}
51
52/// The moderation outcome for one side (input or output) of the completion:
53/// either successful results or an error produced while attempting
54/// moderation.
55#[derive(Debug, Deserialize, Serialize, Clone)]
56#[serde(tag = "type", rename_all = "snake_case")]
57pub enum ModerationSide {
58    /// Successful moderation results. Always `moderation_results`.
59    ModerationResults {
60        /// The moderation model used to generate the results.
61        model: String,
62        /// A list of moderation results.
63        results: Vec<ModerationSideResult>,
64    },
65    /// An error produced while attempting moderation. Always `error`.
66    Error {
67        /// The error code.
68        code: String,
69        /// The error message.
70        message: String,
71    },
72}
73
74/// A moderation result produced for the response input or generated output.
75#[derive(Debug, Deserialize, Serialize, Clone)]
76pub struct ModerationSideResult {
77    /// A dictionary of moderation categories to booleans, `true` if the
78    /// input is flagged under this category.
79    pub categories: std::collections::HashMap<String, bool>,
80    /// Which modalities of input are reflected by the score for each
81    /// category, e.g. `["text"]` or `["text", "image"]`.
82    pub category_applied_input_types: std::collections::HashMap<String, Vec<String>>,
83    /// A dictionary of moderation categories to scores.
84    pub category_scores: std::collections::HashMap<String, f64>,
85    /// A boolean indicating whether the content was flagged by any category.
86    pub flagged: bool,
87    /// The moderation model that produced this result.
88    pub model: String,
89    /// The object type, which is always `moderation_result`.
90    #[serde(rename = "type")]
91    pub type_: ModerationResultType,
92}
93
94crate::wire_string_enum! {
95    /// The object type of a moderation result. Always `moderation_result`.
96    pub enum ModerationResultType {
97        ModerationResult => "moderation_result",
98    }
99}
100
101#[derive(Debug, Deserialize, Serialize, Clone)]
102pub struct ChatCompletion {
103    /// A unique identifier for the chat completion.
104    pub id: String,
105    /// A list of chat completion choices. Can be more than one
106    /// if `n` is greater than 1.
107    pub choices: Vec<Choice>,
108    /// The Unix timestamp (in seconds) of when the chat completion was created.
109    pub created: u64,
110    /// The model used for the chat completion.
111    pub model: String,
112    /// Specifies the processing type used for serving the request.
113    ///
114    /// - If set to 'auto', then the request will be processed with the service tier
115    ///   configured in the Project settings. Unless otherwise configured, the Project
116    ///   will use 'default'.
117    /// - If set to 'default', then the request will be processed with the standard
118    ///   pricing and performance for the selected model.
119    /// - If set to '[flex](https://platform.openai.com/docs/guides/flex-processing)' or
120    ///   '[priority](https://openai.com/api-priority-processing/)', then the request
121    ///   will be processed with the corresponding service tier.
122    /// - When not set, the default behavior is 'auto'.
123    ///
124    /// When the `service_tier` parameter is set, the response body will include the
125    /// `service_tier` value based on the processing mode actually used to serve the
126    /// request. This response value may be different from the value set in the
127    /// parameter.
128    pub service_tier: Option<ServiceTier>,
129    /// The system fingerprint used for the chat completion.
130    /// Can be used in conjunction with the `seed` request parameter to understand when
131    /// backend changes have been made that might impact determinism.
132    pub system_fingerprint: Option<String>,
133    /// The object type, which is always `chat.completion`.
134    ///
135    /// `Some` only when the backend sends a recognized value; some
136    /// non-OpenAI gateways omit or repurpose the field.
137    pub object: Option<ChatCompletionObject>,
138    /// Usage statistics for the completion request.
139    pub usage: Option<CompletionUsage>,
140    /// Moderation results for the request input and generated output.
141    ///
142    /// Present when moderated completions are requested via the `moderation`
143    /// request parameter.
144    pub moderation: Option<ChatModeration>,
145}
146
147crate::wire_string_enum! {
148    /// The object type, which is always `chat.completion`.
149    pub enum ChatCompletionObject {
150        /// The object type is always `chat.completion`.
151        ChatCompletion => "chat.completion",
152    }
153}
154
155#[derive(Debug, Deserialize, Serialize, Clone)]
156pub struct Choice {
157    /// The reason the model stopped generating tokens.
158    ///
159    /// This will be `stop` if the model hit a natural stop point or a provided stop
160    /// sequence, `length` if the maximum number of tokens specified in the request was
161    /// reached, `content_filter` if content was omitted due to a flag from our content
162    /// filters, `tool_calls` if the model called a tool, or `function_call`
163    /// (deprecated) if the model called a function.
164    pub finish_reason: FinishReason,
165    /// The index of the choice in the list of choices.
166    pub index: u32,
167    /// Log probability information for the choice.
168    pub logprobs: Option<ChoiceLogprobs>,
169    /// A chat completion message generated by the model.
170    pub message: ChatCompletionMessage,
171}
172
173crate::wire_string_enum! {
174    /// The reason the model stopped generating tokens.
175    ///
176    /// Values that are not part of the official API (some gateways emit
177    /// their own, e.g. `eos`) are preserved as
178    /// [`FinishReason::Unknown`] instead of failing deserialization.
179    pub enum FinishReason {
180        /// The maximum number of tokens specified in the request was reached.
181        Length => "length",
182        /// The model hit a natural stop point or a provided stop sequence.
183        Stop => "stop",
184        /// The model called a tool.
185        ToolCalls => "tool_calls",
186        /// The model called a function (deprecated).
187        FunctionCall => "function_call",
188        /// Content was omitted due to a flag from our content filters.
189        ContentFilter => "content_filter",
190        /// DeepSeek: the request is interrupted due to insufficient resource
191        /// of the inference system.
192        InsufficientSystemResource => "insufficient_system_resource",
193    }
194}
195
196#[derive(Debug, Deserialize, Serialize, Clone)]
197pub struct ChatCompletionMessage {
198    /// The role of the author of this message. This shall always
199    /// be [`Role::Assistant`]
200    pub role: Role,
201    /// If the audio output modality is requested, this object contains data
202    /// about the audio response from the model.
203    /// [Learn more from OpenAI](https://platform.openai.com/docs/guides/audio).
204    pub audio: Option<ChatCompletionAudio>,
205    /// The contents of the message.
206    pub content: Option<String>,
207    /// For thinking models: the reasoning contents of the assistant
208    /// message, before the final answer.
209    #[cfg(feature = "reasoning")]
210    pub reasoning_content: Option<String>,
211    /// The tool calls generated by the model, such as function calls.
212    /// Tool calls deserialization is not supported yet.
213    pub tool_calls: Option<Vec<ChatCompletionMessageToolCall>>,
214    /// The refusal message generated by the model.
215    pub refusal: Option<String>,
216    /// Annotations for the message, when applicable, such as URL citations
217    /// when the model uses a web search tool.
218    pub annotations: Option<Vec<Annotation>>,
219}
220
221/// If the audio output modality is requested, this object contains data about
222/// the audio response from the model.
223/// [Learn more from OpenAI](https://platform.openai.com/docs/guides/audio).
224#[derive(Debug, Deserialize, Serialize, Clone)]
225pub struct ChatCompletionAudio {
226    /// Unique identifier for this audio response.
227    pub id: String,
228    /// Base64 encoded audio bytes generated by the model, in the format
229    /// specified in the request.
230    pub data: String,
231    /// The Unix timestamp (in seconds) for when this audio response will no
232    /// longer be accessible on the server for use in multi-turn conversations.
233    pub expires_at: u64,
234    /// Transcript of the audio generated by the model.
235    pub transcript: String,
236}
237
238/// An annotation for a chat completion message.
239#[derive(Debug, Deserialize, Serialize, Clone)]
240pub struct Annotation {
241    /// The type of the annotation. Always `url_citation`.
242    #[serde(rename = "type")]
243    pub type_: AnnotationType,
244    /// The URL citation.
245    pub url_citation: UrlCitation,
246}
247
248crate::wire_string_enum! {
249    /// The type of an annotation.
250    pub enum AnnotationType {
251        /// A URL citation when using web search.
252        UrlCitation => "url_citation",
253    }
254}
255
256/// A URL citation when the model uses a web search tool.
257#[derive(Debug, Deserialize, Serialize, Clone)]
258pub struct UrlCitation {
259    /// The index of the first character of the URL citation in the message.
260    pub start_index: usize,
261    /// The index of the last character of the URL citation in the message.
262    pub end_index: usize,
263    /// The title of the web resource.
264    pub title: String,
265    /// The URL of the web resource.
266    pub url: String,
267}
268
269#[derive(Debug, Deserialize, Serialize, Clone)]
270#[serde(tag = "type", rename_all = "snake_case")]
271pub enum ChatCompletionMessageToolCall {
272    /// The type of the tool. Currently, only `function` is supported.
273    /// The field { type = "function" } is added automatically.
274    Function {
275        /// The ID of the tool call.
276        id: String,
277        /// The function that the model called.
278        function: MessageToolCallFunction,
279    },
280    /// The type of the tool. Always `custom`.
281    /// The field { type = "custom" } is added automatically.
282    Custom {
283        /// The id of the tool call.
284        id: String,
285        /// The custom tool that the model called.
286        custom: MessageToolCallCustom,
287    },
288}
289
290#[derive(Debug, Deserialize, Serialize, Clone)]
291pub struct MessageToolCallCustom {
292    /// The input for the custom tool call generated by the model.
293    pub input: String,
294    /// The name of the custom tool to call.
295    pub name: String,
296}
297
298#[derive(Debug, Deserialize, Serialize, Clone)]
299pub struct MessageToolCallFunction {
300    /// The arguments to call the function with, as generated by the model in JSON
301    /// format. Note that the model does not always generate valid JSON, and may
302    /// hallucinate parameters not defined by your function schema. Validate the
303    /// arguments in your code before calling your function.
304    pub arguments: String,
305    /// The name of the function to call.
306    pub name: String,
307}
308
309crate::wire_string_enum! {
310    /// The role of the author of a message, as reported in responses and
311    /// streamed deltas.
312    ///
313    /// Values that are not part of the official API are preserved as
314    /// [`Role::Unknown`] instead of failing deserialization.
315    pub enum Role {
316        /// The author is the model.
317        Assistant => "assistant",
318        /// The author is a developer-defined persona.
319        Developer => "developer",
320        /// The author is the system prompt.
321        System => "system",
322        /// The author is a tool response.
323        Tool => "tool",
324        /// The author is the end user.
325        User => "user",
326    }
327}
328
329/// Legacy alias of [`Role`].
330pub type ResponseRole = Role;
331
332#[derive(Debug, Deserialize, Serialize, Clone)]
333pub struct ChoiceLogprobs {
334    /// A list of message content tokens with log probability information.
335    pub content: Option<Vec<TokenLogProb>>,
336    /// A list of reasoning content tokens with log probability information.
337    /// Only present for thinking models.
338    #[cfg(feature = "reasoning")]
339    pub reasoning_content: Option<Vec<TokenLogProb>>,
340    /// A list of message refusal tokens with log probability information.
341    pub refusal: Option<Vec<TokenLogProb>>,
342}
343
344#[derive(Debug, Deserialize, Serialize, Clone)]
345pub struct TokenLogProb {
346    /// The token.
347    pub token: String,
348    /// The log probability of this token, if it is within the top 20 most likely
349    /// tokens. Otherwise, the value `-9999.0` is used to signify that the token is very
350    /// unlikely.
351    pub logprob: f32,
352    /// A list of integers representing the UTF-8 bytes representation of the token.
353    ///
354    /// Useful in instances where characters are represented by multiple tokens and
355    /// their byte representations must be combined to generate the correct text
356    /// representation. Can be `null` if there is no bytes representation for the token.
357    pub bytes: Option<Vec<u8>>,
358    /// List of the most likely tokens and their log probability, at this token
359    /// position. In rare cases, there may be fewer than the number of requested
360    /// `top_logprobs` returned.
361    pub top_logprobs: Vec<TopLogprob>,
362}
363
364#[derive(Debug, Deserialize, Serialize, Clone)]
365pub struct TopLogprob {
366    /// The token.
367    pub token: String,
368    /// A list of integers representing the UTF-8 bytes representation of the token.
369    ///
370    /// Useful in instances where characters are represented by multiple tokens and
371    /// their byte representations must be combined to generate the correct text
372    /// representation. Can be `null` if there is no bytes representation for the token.
373    pub logprob: f32,
374    /// List of the most likely tokens and their log probability, at this token
375    /// position. In rare cases, there may be fewer than the number of requested
376    /// `top_logprobs` returned.
377    pub bytes: Option<Vec<u8>>,
378}
379
380#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
381pub struct CompletionUsage {
382    /// Number of tokens in the generated completion.
383    pub completion_tokens: u64,
384    /// Number of tokens in the prompt.
385    pub prompt_tokens: u64,
386
387    /// DeepSeek: number of tokens in the prompt that hits the context cache.
388    #[cfg(feature = "deepseek")]
389    pub prompt_cache_hit_tokens: Option<u64>,
390    /// DeepSeek: number of tokens in the prompt that misses the context cache.
391    #[cfg(feature = "deepseek")]
392    pub prompt_cache_miss_tokens: Option<u64>,
393
394    /// Total number of tokens used in the request (prompt + completion).
395    pub total_tokens: u64,
396    /// Breakdown of tokens used in a completion.
397    pub completion_tokens_details: Option<CompletionTokensDetails>,
398    /// Breakdown of tokens used in the prompt.
399    pub prompt_tokens_details: Option<PromptTokensDetails>,
400}
401
402#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
403pub struct CompletionTokensDetails {
404    /// When using Predicted Outputs, the number of tokens in the prediction that
405    /// appeared in the completion.
406    pub accepted_prediction_tokens: Option<u64>,
407    /// Audio input tokens generated by the model.
408    pub audio_tokens: Option<u64>,
409    /// Tokens generated by the model for reasoning.
410    pub reasoning_tokens: Option<u64>,
411    /// When using Predicted Outputs, the number of tokens in the prediction that did
412    /// not appear in the completion. However, like reasoning tokens, these tokens are
413    /// still counted in the total completion tokens for purposes of billing, output,
414    /// and context window limits.
415    pub rejected_prediction_tokens: Option<u64>,
416}
417
418#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
419pub struct PromptTokensDetails {
420    /// Audio input tokens present in the prompt.
421    pub audio_tokens: Option<u64>,
422    /// Cached tokens present in the prompt.
423    pub cached_tokens: Option<u64>,
424}
425
426impl FromStr for ChatCompletion {
427    type Err = crate::errors::OapiError;
428
429    fn from_str(content: &str) -> Result<Self, Self::Err> {
430        let parse_result: Result<ChatCompletion, _> = serde_json::from_str(content)
431            .map_err(|e| OapiError::DeserializationError(e.to_string()));
432        parse_result
433    }
434}
435
436#[cfg(test)]
437mod test {
438    use super::*;
439
440    #[test]
441    fn service_tier_parses_official_values() {
442        for (raw, is_fast) in [
443            (r#""auto""#, false),
444            (r#""default""#, false),
445            (r#""flex""#, false),
446            (r#""scale""#, false),
447            (r#""priority""#, false),
448            (r#""fast""#, true),
449        ] {
450            let tier: ServiceTier =
451                serde_json::from_str(raw).unwrap_or_else(|e| panic!("failed to parse {raw}: {e}"));
452            assert_eq!(matches!(tier, ServiceTier::Fast), is_fast, "raw: {raw}");
453        }
454    }
455
456    #[test]
457    fn no_streaming_example_deepseek() {
458        let json = r#"{
459          "id": "30f6413a-a827-4cf3-9898-f13a8634b798",
460          "object": "chat.completion",
461          "created": 1757944111,
462          "model": "deepseek-chat",
463          "choices": [
464            {
465              "index": 0,
466              "message": {
467                "role": "assistant",
468                "content": "Hello! How can I help you today? 😊"
469              },
470              "logprobs": null,
471              "finish_reason": "stop"
472            }
473          ],
474          "usage": {
475            "prompt_tokens": 10,
476            "completion_tokens": 11,
477            "total_tokens": 21,
478            "prompt_tokens_details": {
479              "cached_tokens": 0
480            },
481            "prompt_cache_hit_tokens": 0,
482            "prompt_cache_miss_tokens": 10
483          },
484          "system_fingerprint": "fp_08f168e49b_prod0820_fp8_kvcache"
485        }"#;
486
487        let parsed = ChatCompletion::from_str(json);
488        match parsed {
489            Ok(_) => {}
490            Err(e) => {
491                panic!("Failed to deserialize: {}", e);
492            }
493        }
494    }
495
496    #[test]
497    fn no_streaming_example_qwen() {
498        let json = r#"{
499            "choices": [
500                {
501                    "message": {
502                        "role": "assistant",
503                        "content": "我是阿里云开发的一款超大规模语言模型,我叫通义千问。"
504                    },
505                    "finish_reason": "stop",
506                    "index": 0,
507                    "logprobs": null
508                }
509            ],
510            "object": "chat.completion",
511            "usage": {
512                "prompt_tokens": 3019,
513                "completion_tokens": 104,
514                "total_tokens": 3123,
515                "prompt_tokens_details": {
516                    "cached_tokens": 2048
517                }
518            },
519            "created": 1735120033,
520            "system_fingerprint": null,
521            "model": "qwen-plus",
522            "id": "chatcmpl-6ada9ed2-7f33-9de2-8bb0-78bd4035025a"
523        }"#;
524
525        let parsed = ChatCompletion::from_str(json);
526        match parsed {
527            Ok(_) => {}
528            Err(e) => {
529                panic!("Failed to deserialize: {}", e);
530            }
531        }
532    }
533}