openai-oxide 0.12.0

Idiomatic Rust client for the OpenAI API — 1:1 parity with the official Python SDK
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
// Chat resource — client.chat().completions().create()

use crate::client::OpenAI;
use crate::error::OpenAIError;
use crate::streaming::SseStream;
use crate::types::chat::{ChatCompletionChunk, ChatCompletionRequest, ChatCompletionResponse};

/// Access chat-related endpoints.
///
/// OpenAI guide: <https://platform.openai.com/docs/guides/chat-completions>
/// API reference: <https://platform.openai.com/docs/api-reference/chat>
pub struct Chat<'a> {
    client: &'a OpenAI,
}

impl<'a> Chat<'a> {
    pub(crate) fn new(client: &'a OpenAI) -> Self {
        Self { client }
    }

    /// Access the completions sub-resource.
    pub fn completions(&self) -> Completions<'_> {
        Completions {
            client: self.client,
        }
    }
}

/// Chat completions endpoint.
pub struct Completions<'a> {
    client: &'a OpenAI,
}

impl<'a> Completions<'a> {
    pub async fn create_stream_raw(
        &self,
        request: &impl serde::Serialize,
    ) -> Result<crate::streaming::SseStream<serde_json::Value>, OpenAIError> {
        let builder = self
            .client
            .request(reqwest::Method::POST, "/chat/completions")
            .header(reqwest::header::ACCEPT, "text/event-stream")
            .header(reqwest::header::CACHE_CONTROL, "no-cache")
            .json(request);

        let response = self.client.send_raw_with_retry(builder).await?;
        let response = OpenAI::check_stream_response(response).await?;
        Ok(crate::streaming::SseStream::new(response))
    }

    /// Create a chat completion with a custom request type, returning raw JSON.
    ///
    /// Use this when you need to send fields not yet in [`ChatCompletionRequest`]
    /// or want to work with the raw API response.
    ///
    /// ```ignore
    /// use serde_json::json;
    ///
    /// let raw = client.chat().completions().create_raw(&json!({
    ///     "model": "gpt-4o",
    ///     "messages": [{"role": "user", "content": "Hi"}],
    ///     "custom_field": true
    /// })).await?;
    /// println!("{}", raw["choices"][0]["message"]["content"]);
    /// ```
    pub async fn create_raw(
        &self,
        request: &impl serde::Serialize,
    ) -> Result<serde_json::Value, crate::error::OpenAIError> {
        self.client.post_json("/chat/completions", request).await
    }

    /// Create a chat completion.
    ///
    /// `POST /chat/completions`
    pub async fn create(
        &self,
        mut request: ChatCompletionRequest,
    ) -> Result<ChatCompletionResponse, OpenAIError> {
        Self::prepare_reasoning_request(&mut request);
        self.client.post("/chat/completions", &request).await
    }

    /// Create a chat completion and parse the response into a typed struct.
    ///
    /// Automatically sets `response_format` to a strict JSON schema derived
    /// from `T` using [`schemars::JsonSchema`]. The response content is
    /// deserialized into `T` and returned in [`ParsedChatCompletion::parsed`].
    ///
    /// ```ignore
    /// #[derive(Deserialize, JsonSchema)]
    /// struct Answer { text: String, confidence: f64 }
    ///
    /// let result = client.chat().completions()
    ///     .parse::<Answer>(request).await?;
    /// println!("{}", result.parsed.unwrap().text);
    /// ```
    ///
    /// Requires the `structured` feature.
    #[cfg(feature = "structured")]
    pub async fn parse<T: serde::de::DeserializeOwned + schemars::JsonSchema>(
        &self,
        mut request: ChatCompletionRequest,
    ) -> Result<crate::parsing::ParsedChatCompletion<T>, OpenAIError> {
        request.response_format = Some(crate::parsing::response_format_from_type::<T>());
        Self::prepare_reasoning_request(&mut request);
        let response: ChatCompletionResponse =
            self.client.post("/chat/completions", &request).await?;
        crate::parsing::parse_completion(response)
    }

    /// Create a streaming chat completion with high-level typed events.
    ///
    /// Returns a [`ChatCompletionStream`](crate::stream_helpers::ChatCompletionStream)
    /// that yields [`ChatStreamEvent`](crate::stream_helpers::ChatStreamEvent) with
    /// automatic text/tool-call accumulation.
    ///
    /// Use `.get_final_completion()` to consume the stream and get the
    /// assembled [`ChatCompletionResponse`].
    pub async fn create_stream_helper(
        &self,
        request: ChatCompletionRequest,
    ) -> Result<crate::stream_helpers::ChatCompletionStream, OpenAIError> {
        let stream = self.create_stream(request).await?;
        Ok(crate::stream_helpers::ChatCompletionStream::new(stream))
    }

    /// Create a streaming chat completion.
    ///
    /// Returns a `Stream<Item = Result<ChatCompletionChunk>>`.
    /// The `stream` field in the request is automatically set to `true`.
    pub async fn create_stream(
        &self,
        mut request: ChatCompletionRequest,
    ) -> Result<SseStream<ChatCompletionChunk>, OpenAIError> {
        Self::prepare_reasoning_request(&mut request);
        request.stream = Some(true);
        let builder = self
            .client
            .request(reqwest::Method::POST, "/chat/completions")
            .header(reqwest::header::ACCEPT, "text/event-stream")
            .header(reqwest::header::CACHE_CONTROL, "no-cache")
            .json(&request);

        let response = self.client.send_raw_with_retry(builder).await?;
        let response = OpenAI::check_stream_response(response).await?;
        Ok(SseStream::new(response))
    }

    /// Automatically aligns parameters for O1/O3 reasoning models to prevent API errors.
    fn prepare_reasoning_request(request: &mut ChatCompletionRequest) {
        if request.model.starts_with("o1") || request.model.starts_with("o3") {
            // Reasoning models crash if temperature or other generation parameters are passed
            if request.temperature.is_some() {
                tracing::warn!(
                    "temperature is not supported for reasoning models. Dropping parameter."
                );
                request.temperature = None;
            }
            if request.top_p.is_some() {
                tracing::warn!("top_p is not supported for reasoning models. Dropping parameter.");
                request.top_p = None;
            }
            if request.presence_penalty.is_some() {
                tracing::warn!(
                    "presence_penalty is not supported for reasoning models. Dropping parameter."
                );
                request.presence_penalty = None;
            }
            if request.frequency_penalty.is_some() {
                tracing::warn!(
                    "frequency_penalty is not supported for reasoning models. Dropping parameter."
                );
                request.frequency_penalty = None;
            }

            // Map max_tokens -> max_completion_tokens
            if request.max_tokens.is_some() && request.max_completion_tokens.is_none() {
                tracing::debug!("Mapping max_tokens to max_completion_tokens for reasoning model");
                request.max_completion_tokens = request.max_tokens;
                request.max_tokens = None;
            }

            // Change system messages to developer messages
            for msg in request.messages.iter_mut() {
                if let crate::types::chat::ChatCompletionMessageParam::System { content, name } =
                    msg
                {
                    tracing::debug!(
                        "Converting system message to developer message for reasoning model"
                    );
                    *msg = crate::types::chat::ChatCompletionMessageParam::Developer {
                        content: content.clone(),
                        name: name.clone(),
                    };
                }
            }
        }
    }

    /// Retrieve a stored chat completion by ID.
    ///
    /// `GET /chat/completions/{completion_id}`
    ///
    /// Requires the completion to have been created with `store: true`.
    pub async fn retrieve(
        &self,
        completion_id: &str,
    ) -> Result<ChatCompletionResponse, OpenAIError> {
        self.client
            .get(&format!("/chat/completions/{completion_id}"))
            .await
    }

    /// List stored chat completions.
    ///
    /// `GET /chat/completions`
    pub async fn list_stored(
        &self,
        params: &[(String, String)],
    ) -> Result<serde_json::Value, OpenAIError> {
        self.client
            .get_with_query("/chat/completions", params)
            .await
    }

    /// Delete a stored chat completion.
    ///
    /// `DELETE /chat/completions/{completion_id}`
    pub async fn delete(&self, completion_id: &str) -> Result<serde_json::Value, OpenAIError> {
        self.client
            .delete(&format!("/chat/completions/{completion_id}"))
            .await
    }

    /// List messages in a stored chat completion.
    ///
    /// `GET /chat/completions/{completion_id}/messages`
    pub async fn list_messages(
        &self,
        completion_id: &str,
        params: &[(String, String)],
    ) -> Result<serde_json::Value, OpenAIError> {
        self.client
            .get_with_query(
                &format!("/chat/completions/{completion_id}/messages"),
                params,
            )
            .await
    }
}

#[cfg(test)]
mod tests {
    use crate::OpenAI;
    use crate::config::ClientConfig;
    use crate::types::chat::{ChatCompletionMessageParam, ChatCompletionRequest, UserContent};

    #[tokio::test]
    async fn test_chat_completions_create() {
        let mut server = mockito::Server::new_async().await;
        let mock = server
            .mock("POST", "/chat/completions")
            .match_header("authorization", "Bearer sk-test")
            .match_header("content-type", "application/json")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                r#"{
                    "id": "chatcmpl-abc123",
                    "object": "chat.completion",
                    "created": 1677858242,
                    "model": "gpt-4o-mini",
                    "choices": [{
                        "index": 0,
                        "message": {
                            "role": "assistant",
                            "content": "Hello! How can I help?"
                        },
                        "logprobs": null,
                        "finish_reason": "stop"
                    }],
                    "usage": {
                        "prompt_tokens": 10,
                        "completion_tokens": 6,
                        "total_tokens": 16
                    }
                }"#,
            )
            .create_async()
            .await;

        let client = OpenAI::with_config(ClientConfig::new("sk-test").base_url(server.url()));

        let request = ChatCompletionRequest::new(
            "gpt-4o-mini",
            vec![ChatCompletionMessageParam::User {
                content: UserContent::Text("Hello".into()),
                name: None,
            }],
        );

        let response = client.chat().completions().create(request).await.unwrap();
        assert_eq!(response.id, "chatcmpl-abc123");
        assert_eq!(
            response.choices[0].finish_reason,
            crate::types::common::FinishReason::Stop
        );
        assert_eq!(
            response.choices[0].message.content.as_deref(),
            Some("Hello! How can I help?")
        );
        mock.assert_async().await;
    }

    #[tokio::test]
    async fn test_chat_completions_create_raw() {
        let mut server = mockito::Server::new_async().await;
        let mock = server
            .mock("POST", "/chat/completions")
            .match_header("authorization", "Bearer sk-test")
            .match_body(mockito::Matcher::Json(serde_json::json!({
                "model": "gpt-4o",
                "messages": [{"role": "user", "content": "Hi"}],
                "custom_field": true
            })))
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"id":"chatcmpl-raw","object":"chat.completion","custom_resp":42}"#)
            .create_async()
            .await;

        let client = OpenAI::with_config(ClientConfig::new("sk-test").base_url(server.url()));

        let raw = client
            .chat()
            .completions()
            .create_raw(&serde_json::json!({
                "model": "gpt-4o",
                "messages": [{"role": "user", "content": "Hi"}],
                "custom_field": true
            }))
            .await
            .unwrap();

        assert_eq!(raw["id"], "chatcmpl-raw");
        assert_eq!(raw["custom_resp"], 42);
        mock.assert_async().await;
    }

    #[tokio::test]
    async fn test_chat_completions_api_error() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("POST", "/chat/completions")
            .with_status(401)
            .with_body(
                r#"{"error":{"message":"Incorrect API key provided","type":"invalid_request_error","param":null,"code":"invalid_api_key"}}"#,
            )
            .create_async()
            .await;

        let client = OpenAI::with_config(
            ClientConfig::new("sk-bad")
                .base_url(server.url())
                .max_retries(0),
        );

        let request = ChatCompletionRequest::new(
            "gpt-4o",
            vec![ChatCompletionMessageParam::User {
                content: UserContent::Text("Hi".into()),
                name: None,
            }],
        );

        let err = client
            .chat()
            .completions()
            .create(request)
            .await
            .unwrap_err();
        match err {
            crate::error::OpenAIError::ApiError {
                status, message, ..
            } => {
                assert_eq!(status, 401);
                assert!(message.contains("API key"));
            }
            other => panic!("expected ApiError, got: {other:?}"),
        }
    }

    #[tokio::test]
    async fn test_chat_stream_retries_on_429() {
        use futures_util::StreamExt;

        let mut server = mockito::Server::new_async().await;

        // First request: 429
        let _mock_429 = server
            .mock("POST", "/chat/completions")
            .with_status(429)
            .with_body(r#"{"error":{"message":"Rate limit","type":"rate_limit","param":null,"code":null}}"#)
            .expect(1)
            .create_async()
            .await;

        // Second request: 200 with SSE
        let _mock_ok = server
            .mock("POST", "/chat/completions")
            .with_status(200)
            .with_header("content-type", "text/event-stream")
            .with_body("data: {\"id\":\"c1\",\"object\":\"chat.completion.chunk\",\"created\":1,\"model\":\"gpt-4o\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"Hi\"},\"finish_reason\":null}]}\n\ndata: [DONE]\n\n")
            .expect(1)
            .create_async()
            .await;

        let client = OpenAI::with_config(
            ClientConfig::new("sk-test")
                .base_url(server.url())
                .max_retries(2),
        );

        let request = ChatCompletionRequest::new(
            "gpt-4o",
            vec![ChatCompletionMessageParam::User {
                content: UserContent::Text("Hi".into()),
                name: None,
            }],
        );

        let stream = client
            .chat()
            .completions()
            .create_stream(request)
            .await
            .unwrap();

        let chunks: Vec<_> = stream
            .collect::<Vec<_>>()
            .await
            .into_iter()
            .filter_map(|r| r.ok())
            .collect();

        assert!(!chunks.is_empty());
        assert_eq!(chunks[0].choices[0].delta.content.as_deref(), Some("Hi"));

        _mock_429.assert_async().await;
        _mock_ok.assert_async().await;
    }
}