gpt5 0.2.3

A Rust client library for OpenAI's GPT-5 API with support for function calling, reasoning, and streaming
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
//! Integration tests for the GPT-5 Rust client library
//!
//! These tests verify the complete functionality of the library including
//! serialization, deserialization, and API interactions.

use gpt5::{
    ContentType, FormatType, Gpt5Client, Gpt5Model, Gpt5RequestBuilder, OutputType,
    ReasoningEffort, Role, Status, Tool, VerbosityLevel,
};
use reqwest::Client as HttpClient;
use serde_json::json;

/// Test Gpt5Model enum functionality
#[test]
fn test_gpt5_model_serialization() {
    assert_eq!(Gpt5Model::Gpt5.as_str(), "gpt-5");
    assert_eq!(Gpt5Model::Gpt5Mini.as_str(), "gpt-5-mini");
    assert_eq!(Gpt5Model::Gpt5Nano.as_str(), "gpt-5-nano");

    let custom = Gpt5Model::Custom("gpt-5-custom".to_string());
    assert_eq!(custom.as_str(), "gpt-5-custom");
}

/// Test ReasoningEffort enum serialization and deserialization
#[test]
fn test_reasoning_effort_serialization() {
    let low = ReasoningEffort::Low;
    let serialized = serde_json::to_string(&low).unwrap();
    assert_eq!(serialized, "\"low\"");

    let deserialized: ReasoningEffort = serde_json::from_str(&serialized).unwrap();
    assert_eq!(deserialized, ReasoningEffort::Low);

    // Test unknown value
    let unknown = ReasoningEffort::Unknown("custom".to_string());
    let serialized = serde_json::to_string(&unknown).unwrap();
    assert_eq!(serialized, "\"custom\"");
}

/// Test VerbosityLevel enum serialization and deserialization
#[test]
fn test_verbosity_level_serialization() {
    let low = VerbosityLevel::Low;
    let serialized = serde_json::to_string(&low).unwrap();
    assert_eq!(serialized, "\"low\"");

    let deserialized: VerbosityLevel = serde_json::from_str(&serialized).unwrap();
    assert_eq!(deserialized, VerbosityLevel::Low);
}

/// Test OutputType enum serialization and deserialization
#[test]
fn test_output_type_serialization() {
    let message = OutputType::Message;
    let serialized = serde_json::to_string(&message).unwrap();
    assert_eq!(serialized, "\"message\"");

    let deserialized: OutputType = serde_json::from_str(&serialized).unwrap();
    assert_eq!(deserialized, OutputType::Message);

    let function_call = OutputType::FunctionCall;
    let serialized = serde_json::to_string(&function_call).unwrap();
    assert_eq!(serialized, "\"function_call\"");
}

/// Test ContentType enum serialization and deserialization
#[test]
fn test_content_type_serialization() {
    let output_text = ContentType::OutputText;
    let serialized = serde_json::to_string(&output_text).unwrap();
    assert_eq!(serialized, "\"output_text\"");

    let deserialized: ContentType = serde_json::from_str(&serialized).unwrap();
    assert_eq!(deserialized, ContentType::OutputText);
}

/// Test Status enum serialization and deserialization
#[test]
fn test_status_serialization() {
    let completed = Status::Completed;
    let serialized = serde_json::to_string(&completed).unwrap();
    assert_eq!(serialized, "\"completed\"");

    let deserialized: Status = serde_json::from_str(&serialized).unwrap();
    assert_eq!(deserialized, Status::Completed);

    let in_progress = Status::InProgress;
    let serialized = serde_json::to_string(&in_progress).unwrap();
    assert_eq!(serialized, "\"in_progress\"");
}

/// Test Role enum serialization and deserialization
#[test]
fn test_role_serialization() {
    let user = Role::User;
    let serialized = serde_json::to_string(&user).unwrap();
    assert_eq!(serialized, "\"user\"");

    let deserialized: Role = serde_json::from_str(&serialized).unwrap();
    assert_eq!(deserialized, Role::User);

    let assistant = Role::Assistant;
    let serialized = serde_json::to_string(&assistant).unwrap();
    assert_eq!(serialized, "\"assistant\"");
}

/// Test FormatType enum serialization and deserialization
#[test]
fn test_format_type_serialization() {
    let markdown = FormatType::Markdown;
    let serialized = serde_json::to_string(&markdown).unwrap();
    assert_eq!(serialized, "\"markdown\"");

    let deserialized: FormatType = serde_json::from_str(&serialized).unwrap();
    assert_eq!(deserialized, FormatType::Markdown);
}

/// Test Gpt5Client creation
#[test]
fn test_gpt5_client_creation() {
    let client = Gpt5Client::new("test-api-key".to_string());
    // Client should be created successfully
    assert!(!client.api_key.is_empty());
}

/// Test Gpt5Client with custom base URL
#[test]
fn test_gpt5_client_with_base_url() {
    let client = Gpt5Client::new("test-api-key".to_string())
        .with_base_url("https://custom-api.example.com".to_string());

    // The base_url should be updated
    assert_eq!(client.base_url, "https://custom-api.example.com");
}

/// Test replacing the underlying HTTP client
#[test]
fn test_gpt5_client_with_custom_http_client() {
    let http_client = HttpClient::builder().build().expect("client builds");
    let client = Gpt5Client::new("test-api-key".to_string()).with_http_client(http_client);

    assert_eq!(client.api_key, "test-api-key");
}

/// Test Gpt5RequestBuilder basic functionality
#[test]
fn test_gpt5_request_builder_basic() {
    let request = Gpt5RequestBuilder::new(Gpt5Model::Gpt5Nano)
        .input("Hello, world!")
        .build();

    assert_eq!(request.model, "gpt-5-nano");
    assert_eq!(request.input, "Hello, world!");
    assert!(request.reasoning.is_none());
    assert!(request.tools.is_none());
    assert!(request.tool_choice.is_none());
    assert!(request.max_output_tokens.is_none());
    assert!(request.top_p.is_none());
    assert!(request.text.is_none());
    assert!(request.instructions.is_none());
}

/// Test configuring web search assistance
#[test]
fn test_gpt5_request_builder_web_search() {
    let request = Gpt5RequestBuilder::new(Gpt5Model::Gpt5)
        .input("Find the latest updates")
        .web_search_enabled(true)
        .web_search_query("open source rust news")
        .web_search_max_results(3)
        .build();

    let tools = request.tools.expect("web search tool should be present");
    let tool = tools
        .into_iter()
        .find(|tool| tool.tool_type == "web_search")
        .expect("expected a web_search tool");

    assert!(tool.name.is_none());
    assert!(tool.description.is_none());

    let config = request
        .web_search_config
        .expect("metadata should be stored for web search");
    assert_eq!(config.query.as_deref(), Some("open source rust news"));
    assert_eq!(config.max_results, Some(3));
}

/// Test that disabled and empty web search configuration is omitted
#[test]
fn test_gpt5_request_builder_web_search_disabled() {
    let request = Gpt5RequestBuilder::new(Gpt5Model::Gpt5Nano)
        .input("No search required")
        .web_search_enabled(false)
        .build();

    assert!(request
        .tools
        .map(|tools| tools.into_iter().all(|tool| tool.tool_type != "web_search"))
        .unwrap_or(true));
    assert!(request.web_search_config.is_none());
}

/// Test Gpt5RequestBuilder with all parameters
#[test]
fn test_gpt5_request_builder_complete() {
    let weather_tool = Tool {
        tool_type: "function".to_string(),
        name: Some("get_weather".to_string()),
        description: Some("Get current weather".to_string()),
        parameters: Some(json!({
            "type": "object",
            "properties": {
                "location": {"type": "string"}
            }
        })),
    };

    let request = Gpt5RequestBuilder::new(Gpt5Model::Gpt5)
        .input("What's the weather?")
        .instructions("Use the weather tool")
        .reasoning_effort(ReasoningEffort::Medium)
        .verbosity(VerbosityLevel::High)
        .tools(vec![weather_tool])
        .tool_choice("auto")
        .max_output_tokens(1000)
        .top_p(0.9)
        .build();

    assert_eq!(request.model, "gpt-5");
    assert_eq!(request.input, "What's the weather?");
    assert_eq!(
        request.instructions,
        Some("Use the weather tool".to_string())
    );
    assert!(request.reasoning.is_some());
    assert!(request.tools.is_some());
    assert_eq!(request.tool_choice, Some("auto".to_string()));
    assert_eq!(request.max_output_tokens, Some(1000));
    assert_eq!(request.top_p, Some(0.9));
    assert!(request.text.is_some());
}

/// Test Gpt5RequestBuilder validation
#[test]
fn test_gpt5_request_builder_validation() {
    // Test with empty input (should trigger warning in validation)
    let request = Gpt5RequestBuilder::new(Gpt5Model::Gpt5Nano)
        .input("")
        .max_output_tokens(5) // Very low token count
        .build();

    assert_eq!(request.input, "");
    assert_eq!(request.max_output_tokens, Some(5));
}

/// Test Tool struct creation and serialization
#[test]
fn test_tool_creation() {
    let tool = Tool {
        tool_type: "function".to_string(),
        name: Some("test_function".to_string()),
        description: Some("A test function".to_string()),
        parameters: Some(json!({
            "type": "object",
            "properties": {
                "param1": {"type": "string"}
            }
        })),
    };

    assert_eq!(tool.tool_type, "function");
    assert_eq!(tool.name.as_deref(), Some("test_function"));
    assert_eq!(tool.description.as_deref(), Some("A test function"));
}

/// Test Gpt5Request serialization
#[test]
fn test_gpt5_request_serialization() {
    let request = Gpt5RequestBuilder::new(Gpt5Model::Gpt5Nano)
        .input("Test input")
        .max_output_tokens(100)
        .build();

    let serialized = serde_json::to_string(&request).unwrap();
    let deserialized: gpt5::Gpt5Request = serde_json::from_str(&serialized).unwrap();

    assert_eq!(deserialized.model, request.model);
    assert_eq!(deserialized.input, request.input);
    assert_eq!(deserialized.max_output_tokens, request.max_output_tokens);
}

/// Test Gpt5Response deserialization with sample data
#[test]
fn test_gpt5_response_deserialization() {
    let sample_response = json!({
        "id": "resp_123",
        "object": "response",
        "created_at": 1234567890,
        "status": "completed",
        "model": "gpt-5-nano",
        "output": [
            {
                "type": "message",
                "id": "msg_123",
                "content": [
                    {
                        "type": "output_text",
                        "text": "Hello, world!"
                    }
                ]
            }
        ],
        "usage": {
            "input_tokens": 10,
            "output_tokens": 5,
            "total_tokens": 15
        }
    });

    let response: gpt5::Gpt5Response = serde_json::from_value(sample_response).unwrap();

    assert_eq!(response.id, Some("resp_123".to_string()));
    assert_eq!(response.object, Some("response".to_string()));
    assert_eq!(response.status, Some(Status::Completed));
    assert_eq!(response.model, Some("gpt-5-nano".to_string()));
    assert!(response.output.is_some());
    assert!(response.usage.is_some());
}

/// Test Gpt5Response text extraction
#[test]
fn test_gpt5_response_text_extraction() {
    let sample_response = json!({
        "output": [
            {
                "type": "message",
                "content": [
                    {
                        "type": "output_text",
                        "text": "Hello, world!"
                    }
                ]
            }
        ]
    });

    let response: gpt5::Gpt5Response = serde_json::from_value(sample_response).unwrap();
    let text = response.text();

    assert_eq!(text, Some("Hello, world!".to_string()));
}

/// Test Gpt5Response function calls extraction
#[test]
fn test_gpt5_response_function_calls() {
    let sample_response = json!({
        "output": [
            {
                "type": "function_call",
                "name": "get_weather",
                "arguments": "{\"location\": \"Boston\"}"
            },
            {
                "type": "message",
                "content": [
                    {
                        "type": "output_text",
                        "text": "I'll check the weather for you."
                    }
                ]
            }
        ]
    });

    let response: gpt5::Gpt5Response = serde_json::from_value(sample_response).unwrap();
    let function_calls = response.function_calls();

    assert_eq!(function_calls.len(), 1);
    assert_eq!(function_calls[0].name, Some("get_weather".to_string()));
    assert_eq!(
        function_calls[0].arguments,
        Some("{\"location\": \"Boston\"}".to_string())
    );
}

/// Test Gpt5Response completion status
#[test]
fn test_gpt5_response_completion_status() {
    let completed_response = json!({
        "status": "completed"
    });

    let response: gpt5::Gpt5Response = serde_json::from_value(completed_response).unwrap();
    assert!(response.is_completed());

    let incomplete_response = json!({
        "status": "incomplete"
    });

    let response: gpt5::Gpt5Response = serde_json::from_value(incomplete_response).unwrap();
    assert!(!response.is_completed());
}

/// Test Gpt5Response token usage
#[test]
fn test_gpt5_response_token_usage() {
    let sample_response = json!({
        "usage": {
            "input_tokens": 10,
            "output_tokens": 5,
            "total_tokens": 15,
            "output_tokens_details": {
                "reasoning_tokens": 3
            }
        }
    });

    let response: gpt5::Gpt5Response = serde_json::from_value(sample_response).unwrap();

    assert_eq!(response.total_tokens(), 15);
    assert_eq!(response.reasoning_tokens(), Some(3));
}

/// Test error response deserialization
#[test]
fn test_error_response_deserialization() {
    let error_response = json!({
        "error": {
            "message": "Invalid API key",
            "type": "invalid_request_error",
            "param": "api_key",
            "code": "invalid_api_key"
        }
    });

    let error: gpt5::OpenAiError = serde_json::from_value(error_response).unwrap();

    assert_eq!(error.error.message, "Invalid API key");
    assert_eq!(error.error.error_type, "invalid_request_error");
    assert_eq!(error.error.param, Some("api_key".to_string()));
    assert_eq!(error.error.code, Some("invalid_api_key".to_string()));
}

/// Test builder method chaining
#[test]
fn test_builder_method_chaining() {
    let request = Gpt5RequestBuilder::new(Gpt5Model::Gpt5)
        .input("Test")
        .instructions("Be helpful")
        .reasoning_effort(ReasoningEffort::High)
        .verbosity(VerbosityLevel::Medium)
        .max_output_tokens(500)
        .top_p(0.8)
        .param("custom_param", "custom_value")
        .build();

    assert_eq!(request.input, "Test");
    assert_eq!(request.instructions, Some("Be helpful".to_string()));
    assert!(request.reasoning.is_some());
    assert!(request.text.is_some());
    assert_eq!(request.max_output_tokens, Some(500));
    assert_eq!(request.top_p, Some(0.8));
    assert!(request.parameters.contains_key("custom_param"));
}

/// Test enum equality and partial equality
#[test]
fn test_enum_equality() {
    assert_eq!(ReasoningEffort::Low, ReasoningEffort::Low);
    assert_ne!(ReasoningEffort::Low, ReasoningEffort::High);

    assert_eq!(VerbosityLevel::Medium, VerbosityLevel::Medium);
    assert_ne!(VerbosityLevel::Low, VerbosityLevel::High);

    assert_eq!(Status::Completed, Status::Completed);
    assert_ne!(Status::Completed, Status::InProgress);
}

/// Test unknown enum values handling
#[test]
fn test_unknown_enum_values() {
    let unknown_reasoning = ReasoningEffort::Unknown("custom_effort".to_string());
    let serialized = serde_json::to_string(&unknown_reasoning).unwrap();
    assert_eq!(serialized, "\"custom_effort\"");

    let deserialized: ReasoningEffort = serde_json::from_str("\"custom_effort\"").unwrap();
    assert_eq!(
        deserialized,
        ReasoningEffort::Unknown("custom_effort".to_string())
    );
}

/// Test complex tool definition
#[test]
fn test_complex_tool_definition() {
    let complex_tool = Tool {
        tool_type: "function".to_string(),
        name: Some("analyze_data".to_string()),
        description: Some("Analyze complex data with multiple parameters".to_string()),
        parameters: Some(json!({
            "type": "object",
            "properties": {
                "data": {
                    "type": "array",
                    "items": {"type": "number"},
                    "description": "Array of numbers to analyze"
                },
                "method": {
                    "type": "string",
                    "enum": ["mean", "median", "mode"],
                    "description": "Analysis method to use"
                },
                "options": {
                    "type": "object",
                    "properties": {
                        "include_stats": {"type": "boolean"},
                        "confidence_level": {"type": "number", "minimum": 0, "maximum": 1}
                    }
                }
            },
            "required": ["data", "method"]
        })),
    };

    assert_eq!(complex_tool.name.as_deref(), Some("analyze_data"));
    assert!(complex_tool
        .parameters
        .as_ref()
        .expect("parameters missing")
        .is_object());
}

/// Test request with multiple tools
#[test]
fn test_multiple_tools() {
    let tool1 = Tool {
        tool_type: "function".to_string(),
        name: Some("tool1".to_string()),
        description: Some("First tool".to_string()),
        parameters: Some(json!({})),
    };

    let tool2 = Tool {
        tool_type: "function".to_string(),
        name: Some("tool2".to_string()),
        description: Some("Second tool".to_string()),
        parameters: Some(json!({})),
    };

    let request = Gpt5RequestBuilder::new(Gpt5Model::Gpt5)
        .input("Use both tools")
        .tools(vec![tool1, tool2])
        .tool_choice("auto")
        .build();

    assert!(request.tools.is_some());
    assert_eq!(request.tools.unwrap().len(), 2);
    assert_eq!(request.tool_choice, Some("auto".to_string()));
}