openai-oxide 0.11.2

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
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
// Structured Outputs — parse chat completions into typed Rust structs.
//
// Mirrors Python SDK's `client.chat.completions.parse(response_format=Model)`.
//
// Requires the `structured` feature (enables `schemars` dependency).

use schemars::JsonSchema;
use serde::de::DeserializeOwned;

use crate::error::OpenAIError;
use crate::types::chat::{
    ChatCompletionChoice, ChatCompletionMessage, ChatCompletionResponse,
    JsonSchema as ApiJsonSchema, ResponseFormat,
};
use crate::types::common::FinishReason;

/// A chat completion with the first choice's content parsed into `T`.
///
/// Wraps the raw [`ChatCompletionResponse`] and adds a `parsed` field.
///
/// ```ignore
/// use schemars::JsonSchema;
/// use serde::Deserialize;
///
/// #[derive(Deserialize, JsonSchema)]
/// struct MathResponse {
///     steps: Vec<Step>,
///     final_answer: String,
/// }
///
/// #[derive(Deserialize, JsonSchema)]
/// struct Step {
///     explanation: String,
///     output: String,
/// }
///
/// let result = client.chat().completions()
///     .parse::<MathResponse>(request)
///     .await?;
///
/// println!("{}", result.parsed.unwrap().final_answer);
/// ```
#[derive(Debug, Clone)]
pub struct ParsedChatCompletion<T> {
    /// The raw API response.
    pub response: ChatCompletionResponse,
    /// The deserialized content from the first choice, or `None` if the
    /// model refused or the content was empty.
    pub parsed: Option<T>,
}

impl<T> std::ops::Deref for ParsedChatCompletion<T> {
    type Target = ChatCompletionResponse;
    fn deref(&self) -> &Self::Target {
        &self.response
    }
}

/// Generate the `response_format` parameter for structured output from a Rust type.
///
/// Applies OpenAI's strict schema rules:
/// - `additionalProperties: false` on all objects
/// - All properties marked as `required`
pub fn response_format_from_type<T: JsonSchema>() -> ResponseFormat {
    let schema = schemars::schema_for!(T);
    let mut value = serde_json::to_value(schema).unwrap_or_default();
    ensure_strict(&mut value);

    ResponseFormat::JsonSchema {
        json_schema: ApiJsonSchema {
            name: std::any::type_name::<T>()
                .rsplit("::")
                .next()
                .unwrap_or("Response")
                .to_string(),
            description: None,
            schema: Some(value),
            strict: Some(true),
        },
    }
}

/// Generate a function tool definition from a Rust type.
///
/// ```ignore
/// use openai_oxide::parsing::tool_from_type;
///
/// #[derive(Deserialize, JsonSchema)]
/// /// Get current weather for a location.
/// struct GetWeather {
///     location: String,
///     unit: Option<String>,
/// }
///
/// let tool = tool_from_type::<GetWeather>("get_weather", "Get current weather");
/// ```
pub fn tool_from_type<T: JsonSchema>(
    name: impl Into<String>,
    description: impl Into<String>,
) -> crate::types::chat::Tool {
    let schema = schemars::schema_for!(T);
    let mut value = serde_json::to_value(schema).unwrap_or_default();
    ensure_strict(&mut value);

    crate::types::chat::Tool::function(name, description, value)
}

/// Generate a strict Responses API function tool from a Rust type.
///
/// Like [`tool_from_type`] but returns [`ResponseTool`] for the Responses API.
///
/// ```ignore
/// use openai_oxide::parsing::response_tool_from_type;
///
/// #[derive(Deserialize, JsonSchema)]
/// struct SearchArgs { query: String, limit: Option<u32> }
///
/// let tool = response_tool_from_type::<SearchArgs>("search", "Search items");
/// ```
pub fn response_tool_from_type<T: JsonSchema>(
    name: impl Into<String>,
    description: impl Into<String>,
) -> crate::types::responses::ResponseTool {
    let schema = schemars::schema_for!(T);
    let mut value = serde_json::to_value(schema).unwrap_or_default();
    ensure_strict(&mut value);

    crate::types::responses::ResponseTool::Function {
        name: name.into(),
        description: Some(description.into()),
        parameters: Some(value),
        strict: Some(true),
    }
}

/// Parse a chat completion response, extracting the content from the first choice.
///
/// Returns an error if:
/// - `finish_reason` is `length` (response was truncated)
/// - `finish_reason` is `content_filter`
/// - Content is present but fails to deserialize
pub fn parse_completion<T: DeserializeOwned>(
    response: ChatCompletionResponse,
) -> Result<ParsedChatCompletion<T>, OpenAIError> {
    let choice = response.choices.first();

    if let Some(choice) = choice {
        check_finish_reason(choice)?;

        let parsed = parse_message_content::<T>(&choice.message)?;

        Ok(ParsedChatCompletion { response, parsed })
    } else {
        Ok(ParsedChatCompletion {
            response,
            parsed: None,
        })
    }
}

/// Check finish_reason for errors.
fn check_finish_reason(choice: &ChatCompletionChoice) -> Result<(), OpenAIError> {
    match choice.finish_reason {
        FinishReason::Length => Err(OpenAIError::InvalidArgument(
            "response was truncated (finish_reason=length) — increase max_completion_tokens".into(),
        )),
        FinishReason::ContentFilter => Err(OpenAIError::InvalidArgument(
            "response was filtered (finish_reason=content_filter)".into(),
        )),
        _ => Ok(()),
    }
}

/// Parse the message content into T, returning None if refusal or empty.
fn parse_message_content<T: DeserializeOwned>(
    message: &ChatCompletionMessage,
) -> Result<Option<T>, OpenAIError> {
    // Don't parse if the model refused
    if message.refusal.is_some() {
        return Ok(None);
    }

    match &message.content {
        Some(content) if !content.is_empty() => {
            let parsed: T = serde_json::from_str(content)?;
            Ok(Some(parsed))
        }
        _ => Ok(None),
    }
}

// ── Responses API structured output ──

/// A Response with its text output parsed into `T`.
#[derive(Debug, Clone)]
pub struct ParsedResponse<T> {
    /// The raw API response.
    pub response: crate::types::responses::Response,
    /// The deserialized text output, or `None` if empty/failed.
    pub parsed: Option<T>,
}

impl<T> std::ops::Deref for ParsedResponse<T> {
    type Target = crate::types::responses::Response;
    fn deref(&self) -> &Self::Target {
        &self.response
    }
}

/// Generate the `text.format` parameter for Responses API structured output.
pub fn text_format_from_type<T: JsonSchema>() -> crate::types::responses::ResponseTextFormat {
    let schema = schemars::schema_for!(T);
    let mut value = serde_json::to_value(schema).unwrap_or_default();
    ensure_strict(&mut value);

    crate::types::responses::ResponseTextFormat::JsonSchema {
        name: std::any::type_name::<T>()
            .rsplit("::")
            .next()
            .unwrap_or("Response")
            .to_string(),
        description: None,
        schema: Some(value),
        strict: Some(true),
    }
}

/// Parse a Responses API response, extracting `output_text()` into `T`.
pub fn parse_response<T: DeserializeOwned>(
    response: crate::types::responses::Response,
) -> Result<ParsedResponse<T>, OpenAIError> {
    if response.status.as_deref() == Some("failed") {
        let msg = response
            .error
            .as_ref()
            .map(|e| e.message.clone())
            .unwrap_or_else(|| "response failed".into());
        return Err(OpenAIError::InvalidArgument(msg));
    }

    let text = response.output_text();
    let parsed = if text.is_empty() {
        None
    } else {
        Some(serde_json::from_str::<T>(&text)?)
    };

    Ok(ParsedResponse { response, parsed })
}

/// Make a JSON Schema compatible with OpenAI strict mode.
///
/// Mirrors the Python SDK's `_ensure_strict_json_schema()` from `openai/lib/_pydantic.py`.
///
/// OpenAI `strict: true` requires:
/// 1. `additionalProperties: false` on every object
/// 2. All properties listed in `required`
/// 3. Optional fields use `anyOf: [{type}, {type: null}]` (not `nullable: true`)
/// 4. `allOf` with 1 item → inline; multi-item → recurse
/// 5. `oneOf` → `anyOf`
/// 6. Recurse into `properties`, `items`, `anyOf`, `allOf`, `$defs`, `definitions`
///
/// See: <https://developers.openai.com/api/docs/guides/structured-outputs>
pub fn ensure_strict(value: &mut serde_json::Value) {
    if let serde_json::Value::Object(map) = value {
        // Recurse into $defs / definitions first (like Python SDK)
        for key in ["$defs", "definitions"] {
            if let Some(defs) = map.get_mut(key).and_then(|v| v.as_object_mut()) {
                for def in defs.values_mut() {
                    ensure_strict(def);
                }
            }
        }

        let is_object = map.get("type").and_then(|t| t.as_str()) == Some("object");

        if is_object {
            map.entry("additionalProperties")
                .or_insert(serde_json::Value::Bool(false));

            // Convert nullable properties: "nullable":true + "type":"T"
            // → {"anyOf": [{"type":"T"}, {"type":"null"}]}
            // schemars 0.8 uses "nullable" keyword; OpenAI requires anyOf pattern.
            if let Some(props) = map.get_mut("properties").and_then(|v| v.as_object_mut()) {
                for (_key, prop) in props.iter_mut() {
                    if let Some(prop_obj) = prop.as_object_mut() {
                        if prop_obj.remove("nullable").and_then(|v| v.as_bool()) == Some(true) {
                            if let Some(type_val) = prop_obj.remove("type") {
                                let desc = prop_obj.remove("description");
                                let mut wrapper = serde_json::Map::new();
                                wrapper.insert(
                                    "anyOf".into(),
                                    serde_json::json!([{"type": type_val}, {"type": "null"}]),
                                );
                                if let Some(d) = desc {
                                    wrapper.insert("description".into(), d);
                                }
                                *prop = serde_json::Value::Object(wrapper);
                            }
                        }
                    }
                }
            }

            // All properties must be required
            if let Some(props) = map.get("properties").and_then(|p| p.as_object()) {
                let keys: Vec<String> = props.keys().cloned().collect();
                map.insert("required".to_string(), serde_json::json!(keys));
            }

            // Recurse into each property
            if let Some(props) = map.get_mut("properties").and_then(|v| v.as_object_mut()) {
                for prop in props.values_mut() {
                    ensure_strict(prop);
                }
            }
        }

        // Recurse into array items
        if let Some(items) = map.get_mut("items") {
            ensure_strict(items);
        }

        // Remove null defaults (not meaningful in strict mode)
        if map.get("default") == Some(&serde_json::Value::Null) {
            map.remove("default");
        }

        // oneOf → anyOf (OpenAI strict doesn't support oneOf)
        if let Some(one_of) = map.remove("oneOf") {
            map.insert("anyOf".into(), one_of);
        }

        // anyOf: recurse into variants
        if let Some(any_of) = map.get_mut("anyOf").and_then(|v| v.as_array_mut()) {
            for variant in any_of.iter_mut() {
                ensure_strict(variant);
            }
        }

        // allOf: inline single-item, recurse multi-item (matches Python SDK)
        if let Some(all_of) = map.remove("allOf") {
            if let Some(arr) = all_of.as_array() {
                if arr.len() == 1 {
                    // Inline single allOf entry
                    if let Some(inner) = arr[0].as_object() {
                        for (k, v) in inner {
                            map.entry(k.clone()).or_insert(v.clone());
                        }
                    }
                    // Re-run strict on this node (inlined content may need processing)
                    ensure_strict(value);
                    return;
                } else {
                    // Multi allOf: keep and recurse
                    let mut all_of = all_of;
                    if let Some(arr) = all_of.as_array_mut() {
                        for entry in arr.iter_mut() {
                            ensure_strict(entry);
                        }
                    }
                    map.insert("allOf".into(), all_of);
                }
            }
        }

        // Remove top-level $schema (not needed in tool schemas)
        map.remove("$schema");
    } else if let serde_json::Value::Array(arr) = value {
        for v in arr {
            ensure_strict(v);
        }
    }
}

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

    #[derive(Debug, Deserialize, JsonSchema, PartialEq)]
    struct MathStep {
        explanation: String,
        output: String,
    }

    #[derive(Debug, Deserialize, JsonSchema, PartialEq)]
    struct MathResponse {
        steps: Vec<MathStep>,
        final_answer: String,
    }

    #[test]
    fn test_response_format_generation() {
        let fmt = response_format_from_type::<MathResponse>();
        match fmt {
            ResponseFormat::JsonSchema { json_schema } => {
                assert_eq!(json_schema.name, "MathResponse");
                assert_eq!(json_schema.strict, Some(true));
                let schema = json_schema.schema.unwrap();
                assert_eq!(schema["type"], "object");
                assert_eq!(schema["additionalProperties"], false);
                // Check required fields
                let required = schema["required"].as_array().unwrap();
                assert!(required.contains(&serde_json::json!("steps")));
                assert!(required.contains(&serde_json::json!("final_answer")));
            }
            _ => panic!("expected JsonSchema variant"),
        }
    }

    #[test]
    fn test_parse_completion_success() {
        let response = ChatCompletionResponse {
            id: "test".into(),
            choices: vec![ChatCompletionChoice {
                finish_reason: FinishReason::Stop,
                index: 0,
                message: ChatCompletionMessage {
                    role: crate::types::common::Role::Assistant,
                    content: Some(
                        r#"{"steps":[{"explanation":"add","output":"4"}],"final_answer":"4"}"#
                            .into(),
                    ),
                    refusal: None,
                    tool_calls: None,
                    annotations: None,
                },
                logprobs: None,
            }],
            created: 0,
            model: "gpt-4o".into(),
            object: "chat.completion".into(),
            service_tier: None,
            system_fingerprint: None,
            usage: None,
        };

        let parsed: ParsedChatCompletion<MathResponse> = parse_completion(response).unwrap();
        let math = parsed.parsed.unwrap();
        assert_eq!(math.final_answer, "4");
        assert_eq!(math.steps.len(), 1);
        assert_eq!(math.steps[0].explanation, "add");
    }

    #[test]
    fn test_parse_completion_length_error() {
        let response = ChatCompletionResponse {
            id: "test".into(),
            choices: vec![ChatCompletionChoice {
                finish_reason: FinishReason::Length,
                index: 0,
                message: ChatCompletionMessage {
                    role: crate::types::common::Role::Assistant,
                    content: Some("partial".into()),
                    refusal: None,
                    tool_calls: None,
                    annotations: None,
                },
                logprobs: None,
            }],
            created: 0,
            model: "gpt-4o".into(),
            object: "chat.completion".into(),
            service_tier: None,
            system_fingerprint: None,
            usage: None,
        };

        let result = parse_completion::<MathResponse>(response);
        assert!(result.is_err());
        assert!(format!("{}", result.unwrap_err()).contains("truncated"));
    }

    #[test]
    fn test_parse_completion_refusal() {
        let response = ChatCompletionResponse {
            id: "test".into(),
            choices: vec![ChatCompletionChoice {
                finish_reason: FinishReason::Stop,
                index: 0,
                message: ChatCompletionMessage {
                    role: crate::types::common::Role::Assistant,
                    content: None,
                    refusal: Some("I can't help with that".into()),
                    tool_calls: None,
                    annotations: None,
                },
                logprobs: None,
            }],
            created: 0,
            model: "gpt-4o".into(),
            object: "chat.completion".into(),
            service_tier: None,
            system_fingerprint: None,
            usage: None,
        };

        let parsed: ParsedChatCompletion<MathResponse> = parse_completion(response).unwrap();
        assert!(parsed.parsed.is_none());
        assert!(parsed.response.choices[0].message.refusal.is_some());
    }

    #[test]
    fn test_tool_from_type() {
        #[derive(JsonSchema)]
        struct GetWeather {
            location: String,
        }

        let tool = tool_from_type::<GetWeather>("get_weather", "Get weather");
        assert_eq!(tool.function.name, "get_weather");
        assert_eq!(tool.function.strict, Some(true));
        let params = tool.function.parameters.unwrap();
        assert_eq!(params["additionalProperties"], false);
    }

    #[test]
    fn test_ensure_strict_nested() {
        let mut schema = serde_json::json!({
            "type": "object",
            "properties": {
                "inner": {
                    "type": "object",
                    "properties": {
                        "name": {"type": "string"}
                    }
                }
            }
        });

        ensure_strict(&mut schema);

        assert_eq!(schema["additionalProperties"], false);
        assert_eq!(schema["properties"]["inner"]["additionalProperties"], false);
        // Both levels have required
        assert!(
            schema["required"]
                .as_array()
                .unwrap()
                .contains(&serde_json::json!("inner"))
        );
        assert!(
            schema["properties"]["inner"]["required"]
                .as_array()
                .unwrap()
                .contains(&serde_json::json!("name"))
        );
    }

    #[test]
    fn test_text_format_generation() {
        let fmt = text_format_from_type::<MathResponse>();
        match fmt {
            crate::types::responses::ResponseTextFormat::JsonSchema {
                name,
                strict,
                schema,
                ..
            } => {
                assert_eq!(name, "MathResponse");
                assert_eq!(strict, Some(true));
                let schema = schema.unwrap();
                assert_eq!(schema["additionalProperties"], false);
            }
            _ => panic!("expected JsonSchema variant"),
        }
    }

    #[test]
    fn test_parse_response_success() {
        let json = r#"{
            "id": "resp-1", "object": "response", "created_at": 1.0,
            "model": "gpt-4o",
            "output": [{"type": "message", "id": "msg-1", "role": "assistant",
                "status": "completed",
                "content": [{"type": "output_text",
                    "text": "{\"steps\":[],\"final_answer\":\"42\"}"}]
            }],
            "status": "completed"
        }"#;
        let response: crate::types::responses::Response = serde_json::from_str(json).unwrap();
        let parsed: ParsedResponse<MathResponse> = parse_response(response).unwrap();
        assert_eq!(parsed.parsed.unwrap().final_answer, "42");
    }

    #[test]
    fn test_parse_response_failed() {
        let json = r#"{
            "id": "resp-err", "object": "response", "created_at": 1.0,
            "model": "gpt-4o", "output": [], "status": "failed",
            "error": {"code": "server_error", "message": "something broke"}
        }"#;
        let response: crate::types::responses::Response = serde_json::from_str(json).unwrap();
        let result = parse_response::<MathResponse>(response);
        assert!(result.is_err());
        assert!(format!("{}", result.unwrap_err()).contains("something broke"));
    }
}