openai-interface 0.7.0

A low-level Rust interface for the OpenAI API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
//! # Chat Completions API Module
//!
//! This module provides components shared by many submodules.

use std::str::FromStr;

use serde::{Deserialize, Serialize};

use crate::errors::OapiError;

pub mod create;
pub mod delete;
pub mod retrieve;
pub mod update;

/// The service tier used for processing the request.
///
/// This enum represents the different service tiers that can be specified when
/// making a request to the API. Each tier corresponds to different performance
/// characteristics and pricing models.
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "lowercase")]
pub enum ServiceTier {
    /// Automatically select the service tier based on project settings.
    Auto,
    /// Use the default service tier with standard pricing and performance.
    Default,
    /// Use the flex service tier for flexible processing requirements.
    Flex,
    /// Use the scale service tier for scalable processing needs.
    Scale,
    /// Use the priority service tier for high-priority requests.
    Priority,
    /// Fast mode. Request-level opt-in for
    /// [Fast mode](https://platform.openai.com/docs/guides/fast-mode); the
    /// response reports the actual tier as `priority`.
    Fast,
}

/// Moderation results for the request input and generated output.
///
/// Present on the response when moderated completions are requested via the
/// `moderation` request parameter.
#[derive(Debug, Deserialize, Clone)]
pub struct ChatModeration {
    /// Moderation for the request input.
    pub input: ModerationSide,
    /// Moderation for the generated output.
    pub output: ModerationSide,
}

/// The moderation outcome for one side (input or output) of the completion:
/// either successful results or an error produced while attempting
/// moderation.
#[derive(Debug, Deserialize, Clone)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ModerationSide {
    /// Successful moderation results. Always `moderation_results`.
    ModerationResults {
        /// The moderation model used to generate the results.
        model: String,
        /// A list of moderation results.
        results: Vec<ModerationSideResult>,
    },
    /// An error produced while attempting moderation. Always `error`.
    Error {
        /// The error code.
        code: String,
        /// The error message.
        message: String,
    },
}

/// A moderation result produced for the response input or generated output.
#[derive(Debug, Deserialize, Clone)]
pub struct ModerationSideResult {
    /// A dictionary of moderation categories to booleans, `true` if the
    /// input is flagged under this category.
    pub categories: std::collections::HashMap<String, bool>,
    /// Which modalities of input are reflected by the score for each
    /// category, e.g. `["text"]` or `["text", "image"]`.
    pub category_applied_input_types: std::collections::HashMap<String, Vec<String>>,
    /// A dictionary of moderation categories to scores.
    pub category_scores: std::collections::HashMap<String, f64>,
    /// A boolean indicating whether the content was flagged by any category.
    pub flagged: bool,
    /// The moderation model that produced this result.
    pub model: String,
    /// The object type, which is always `moderation_result`.
    #[serde(rename = "type")]
    pub type_: ModerationResultType,
}

/// The object type of a moderation result. Always `moderation_result`.
#[derive(Debug, Deserialize, Clone)]
#[serde(rename_all = "snake_case")]
pub enum ModerationResultType {
    ModerationResult,
}

#[derive(Debug, Deserialize)]
pub struct ChatCompletion {
    /// A unique identifier for the chat completion.
    pub id: String,
    /// A list of chat completion choices. Can be more than one
    /// if `n` is greater than 1.
    pub choices: Vec<Choice>,
    /// The Unix timestamp (in seconds) of when the chat completion was created.
    pub created: u64,
    /// The model used for the chat completion.
    pub model: String,
    /// Specifies the processing type used for serving the request.
    ///
    /// - If set to 'auto', then the request will be processed with the service tier
    ///   configured in the Project settings. Unless otherwise configured, the Project
    ///   will use 'default'.
    /// - If set to 'default', then the request will be processed with the standard
    ///   pricing and performance for the selected model.
    /// - If set to '[flex](https://platform.openai.com/docs/guides/flex-processing)' or
    ///   '[priority](https://openai.com/api-priority-processing/)', then the request
    ///   will be processed with the corresponding service tier.
    /// - When not set, the default behavior is 'auto'.
    ///
    /// When the `service_tier` parameter is set, the response body will include the
    /// `service_tier` value based on the processing mode actually used to serve the
    /// request. This response value may be different from the value set in the
    /// parameter.
    pub service_tier: Option<ServiceTier>,
    /// The system fingerprint used for the chat completion.
    /// Can be used in conjunction with the `seed` request parameter to understand when
    /// backend changes have been made that might impact determinism.
    pub system_fingerprint: Option<String>,
    /// The object type, which is always `chat.completion`.
    pub object: ChatCompletionObject,
    /// Usage statistics for the completion request.
    pub usage: Option<CompletionUsage>,
    /// Moderation results for the request input and generated output.
    ///
    /// Present when moderated completions are requested via the `moderation`
    /// request parameter.
    pub moderation: Option<ChatModeration>,
}

/// The object type, which is always `chat.completion`.
#[derive(Debug, Deserialize)]
pub enum ChatCompletionObject {
    /// The object type is always `chat.completion`.
    #[serde(rename = "chat.completion")]
    ChatCompletion,
}

#[derive(Debug, Deserialize)]
pub struct Choice {
    /// The reason the model stopped generating tokens.
    ///
    /// This will be `stop` if the model hit a natural stop point or a provided stop
    /// sequence, `length` if the maximum number of tokens specified in the request was
    /// reached, `content_filter` if content was omitted due to a flag from our content
    /// filters, `tool_calls` if the model called a tool, or `function_call`
    /// (deprecated) if the model called a function.
    pub finish_reason: FinishReason,
    /// The index of the choice in the list of choices.
    pub index: usize,
    /// Log probability information for the choice.
    pub logprobs: Option<ChoiceLogprobs>,
    /// A chat completion message generated by the model.
    pub message: ChatCompletionMessage,
}

#[derive(Debug, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum FinishReason {
    Length,
    Stop,
    ToolCalls,
    FunctionCall,
    ContentFilter,
    /// DeepSeek: the request is interrupted due to insufficient resource
    /// of the inference system.
    #[cfg(feature = "deepseek")]
    InsufficientSystemResource,
}

#[derive(Debug, Deserialize)]
pub struct ChatCompletionMessage {
    /// The role of the author of this message. This shall always
    /// be ResponseRole::Assistant
    pub role: ResponseRole,
    /// If the audio output modality is requested, this object contains data
    /// about the audio response from the model.
    /// [Learn more from OpenAI](https://platform.openai.com/docs/guides/audio).
    pub audio: Option<ChatCompletionAudio>,
    /// The contents of the message.
    pub content: Option<String>,
    /// DeepSeek: for thinking mode only. The reasoning contents of the
    /// assistant message, before the final answer.
    #[cfg(feature = "deepseek")]
    pub reasoning_content: Option<String>,
    /// The tool calls generated by the model, such as function calls.
    /// Tool calls deserialization is not supported yet.
    pub tool_calls: Option<Vec<ChatCompletionMessageToolCall>>,
    /// The refusal message generated by the model.
    pub refusal: Option<String>,
    /// Annotations for the message, when applicable, such as URL citations
    /// when the model uses a web search tool.
    pub annotations: Option<Vec<Annotation>>,
}

/// If the audio output modality is requested, this object contains data about
/// the audio response from the model.
/// [Learn more from OpenAI](https://platform.openai.com/docs/guides/audio).
#[derive(Debug, Deserialize, Clone)]
pub struct ChatCompletionAudio {
    /// Unique identifier for this audio response.
    pub id: String,
    /// Base64 encoded audio bytes generated by the model, in the format
    /// specified in the request.
    pub data: String,
    /// The Unix timestamp (in seconds) for when this audio response will no
    /// longer be accessible on the server for use in multi-turn conversations.
    pub expires_at: u64,
    /// Transcript of the audio generated by the model.
    pub transcript: String,
}

/// An annotation for a chat completion message.
#[derive(Debug, Deserialize, Clone)]
pub struct Annotation {
    /// The type of the annotation. Always `url_citation`.
    #[serde(rename = "type")]
    pub type_: AnnotationType,
    /// The URL citation.
    pub url_citation: UrlCitation,
}

#[derive(Debug, Deserialize, Clone)]
#[serde(rename_all = "snake_case")]
pub enum AnnotationType {
    /// A URL citation when using web search.
    UrlCitation,
}

/// A URL citation when the model uses a web search tool.
#[derive(Debug, Deserialize, Clone)]
pub struct UrlCitation {
    /// The index of the first character of the URL citation in the message.
    pub start_index: usize,
    /// The index of the last character of the URL citation in the message.
    pub end_index: usize,
    /// The title of the web resource.
    pub title: String,
    /// The URL of the web resource.
    pub url: String,
}

#[derive(Debug, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ChatCompletionMessageToolCall {
    /// The type of the tool. Currently, only `function` is supported.
    /// The field { type = "function" } is added automatically.
    Function {
        /// The ID of the tool call.
        id: String,
        /// The function that the model called.
        function: MessageToolCallFunction,
    },
    /// The type of the tool. Always `custom`.
    /// The field { type = "custom" } is added automatically.
    Custom {
        /// The id of the tool call.
        id: String,
        /// The custom tool that the model called.
        custom: MessageToolCallCustom,
    },
}

#[derive(Debug, Deserialize)]
pub struct MessageToolCallCustom {
    /// The input for the custom tool call generated by the model.
    pub input: String,
    /// The name of the custom tool to call.
    pub name: String,
}

#[derive(Debug, Deserialize)]
pub struct MessageToolCallFunction {
    /// 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.
    pub arguments: String,
    /// The name of the function to call.
    pub name: String,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ResponseRole {
    /// The role of the response message is always assistant.
    Assistant,
}

#[derive(Debug, Deserialize)]
pub struct ChoiceLogprobs {
    /// A list of message content tokens with log probability information.
    pub content: Option<Vec<TokenLogProb>>,
    /// DeepSeek: a list of reasoning content tokens with log probability
    /// information. Only present for thinking models.
    #[cfg(feature = "deepseek")]
    pub reasoning_content: Option<Vec<TokenLogProb>>,
    /// A list of message refusal tokens with log probability information.
    pub refusal: Option<Vec<TokenLogProb>>,
}

#[derive(Debug, Deserialize)]
pub struct TokenLogProb {
    /// The token.
    pub token: String,
    /// 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.
    pub logprob: f32,
    /// 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.
    pub bytes: Option<Vec<u8>>,
    /// 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.
    pub top_logprobs: Vec<TopLogprob>,
}

#[derive(Debug, Deserialize)]
pub struct TopLogprob {
    /// The token.
    pub token: String,
    /// 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.
    pub logprob: f32,
    /// 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.
    pub bytes: Option<Vec<u8>>,
}

#[derive(Debug, Deserialize)]
pub struct CompletionUsage {
    /// Number of tokens in the generated completion.
    pub completion_tokens: usize,
    /// Number of tokens in the prompt.
    pub prompt_tokens: usize,

    /// DeepSeek: number of tokens in the prompt that hits the context cache.
    #[cfg(feature = "deepseek")]
    pub prompt_cache_hit_tokens: Option<usize>,
    /// DeepSeek: number of tokens in the prompt that misses the context cache.
    #[cfg(feature = "deepseek")]
    pub prompt_cache_miss_tokens: Option<usize>,

    /// Total number of tokens used in the request (prompt + completion).
    pub total_tokens: usize,
    /// Breakdown of tokens used in a completion.
    pub completion_tokens_details: Option<CompletionTokensDetails>,
    /// Breakdown of tokens used in the prompt.
    pub prompt_tokens_details: Option<PromptTokensDetails>,
}

#[derive(Debug, Deserialize)]
pub struct CompletionTokensDetails {
    /// When using Predicted Outputs, the number of tokens in the prediction that
    /// appeared in the completion.
    pub accepted_prediction_tokens: Option<usize>,
    /// Audio input tokens generated by the model.
    pub audio_tokens: Option<usize>,
    /// Tokens generated by the model for reasoning.
    pub reasoning_tokens: Option<usize>,
    /// When using Predicted Outputs, the number of tokens in the prediction that did
    /// not appear in the completion. However, like reasoning tokens, these tokens are
    /// still counted in the total completion tokens for purposes of billing, output,
    /// and context window limits.
    pub rejected_prediction_tokens: Option<usize>,
}

#[derive(Debug, Deserialize)]
pub struct PromptTokensDetails {
    /// Audio input tokens present in the prompt.
    pub audio_tokens: Option<usize>,
    /// Cached tokens present in the prompt.
    pub cached_tokens: Option<usize>,
}

impl FromStr for ChatCompletion {
    type Err = crate::errors::OapiError;

    fn from_str(content: &str) -> Result<Self, Self::Err> {
        let parse_result: Result<ChatCompletion, _> = serde_json::from_str(content)
            .map_err(|e| OapiError::DeserializationError(e.to_string()));
        parse_result
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn service_tier_parses_official_values() {
        for (raw, is_fast) in [
            (r#""auto""#, false),
            (r#""default""#, false),
            (r#""flex""#, false),
            (r#""scale""#, false),
            (r#""priority""#, false),
            (r#""fast""#, true),
        ] {
            let tier: ServiceTier =
                serde_json::from_str(raw).unwrap_or_else(|e| panic!("failed to parse {raw}: {e}"));
            assert_eq!(matches!(tier, ServiceTier::Fast), is_fast, "raw: {raw}");
        }
    }

    #[test]
    fn no_streaming_example_deepseek() {
        let json = r#"{
          "id": "30f6413a-a827-4cf3-9898-f13a8634b798",
          "object": "chat.completion",
          "created": 1757944111,
          "model": "deepseek-chat",
          "choices": [
            {
              "index": 0,
              "message": {
                "role": "assistant",
                "content": "Hello! How can I help you today? 😊"
              },
              "logprobs": null,
              "finish_reason": "stop"
            }
          ],
          "usage": {
            "prompt_tokens": 10,
            "completion_tokens": 11,
            "total_tokens": 21,
            "prompt_tokens_details": {
              "cached_tokens": 0
            },
            "prompt_cache_hit_tokens": 0,
            "prompt_cache_miss_tokens": 10
          },
          "system_fingerprint": "fp_08f168e49b_prod0820_fp8_kvcache"
        }"#;

        let parsed = ChatCompletion::from_str(json);
        match parsed {
            Ok(_) => {}
            Err(e) => {
                panic!("Failed to deserialize: {}", e);
            }
        }
    }

    #[test]
    fn no_streaming_example_qwen() {
        let json = r#"{
            "choices": [
                {
                    "message": {
                        "role": "assistant",
                        "content": "我是阿里云开发的一款超大规模语言模型,我叫通义千问。"
                    },
                    "finish_reason": "stop",
                    "index": 0,
                    "logprobs": null
                }
            ],
            "object": "chat.completion",
            "usage": {
                "prompt_tokens": 3019,
                "completion_tokens": 104,
                "total_tokens": 3123,
                "prompt_tokens_details": {
                    "cached_tokens": 2048
                }
            },
            "created": 1735120033,
            "system_fingerprint": null,
            "model": "qwen-plus",
            "id": "chatcmpl-6ada9ed2-7f33-9de2-8bb0-78bd4035025a"
        }"#;

        let parsed = ChatCompletion::from_str(json);
        match parsed {
            Ok(_) => {}
            Err(e) => {
                panic!("Failed to deserialize: {}", e);
            }
        }
    }
}