openai-protocol 1.7.0

OpenAI-compatible API protocol definitions and types
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
//! Builder for ResponsesResponse
//!
//! Provides an ergonomic fluent API for constructing ResponsesResponse instances.

use std::collections::HashMap;

use serde_json::Value;

use crate::responses::*;

/// Builder for ResponsesResponse
///
/// Provides a fluent interface for constructing responses with sensible defaults.
#[must_use = "Builder does nothing until .build() is called"]
#[derive(Clone, Debug)]
pub struct ResponsesResponseBuilder {
    id: String,
    object: String,
    created_at: i64,
    status: ResponseStatus,
    error: Option<Value>,
    incomplete_details: Option<Value>,
    instructions: Option<String>,
    max_output_tokens: Option<u32>,
    model: String,
    output: Vec<ResponseOutputItem>,
    parallel_tool_calls: bool,
    previous_response_id: Option<String>,
    reasoning: Option<ReasoningInfo>,
    store: bool,
    temperature: Option<f32>,
    text: Option<TextConfig>,
    tool_choice: String,
    tools: Vec<ResponseTool>,
    top_p: Option<f32>,
    truncation: Option<String>,
    usage: Option<ResponsesUsage>,
    user: Option<String>,
    safety_identifier: Option<String>,
    metadata: HashMap<String, Value>,
}

impl ResponsesResponseBuilder {
    /// Create a new builder with required fields
    ///
    /// # Arguments
    /// - `id`: Response ID (e.g., "resp_abc123")
    /// - `model`: Model name used for generation
    pub fn new(id: impl Into<String>, model: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            object: "response".to_string(),
            created_at: chrono::Utc::now().timestamp(),
            status: ResponseStatus::InProgress,
            error: None,
            incomplete_details: None,
            instructions: None,
            max_output_tokens: None,
            model: model.into(),
            output: Vec::new(),
            parallel_tool_calls: true,
            previous_response_id: None,
            reasoning: None,
            store: true,
            temperature: None,
            text: None,
            tool_choice: "auto".to_string(),
            tools: Vec::new(),
            top_p: None,
            truncation: None,
            usage: None,
            user: None,
            safety_identifier: None,
            metadata: HashMap::new(),
        }
    }

    /// Copy common fields from a ResponsesRequest
    ///
    /// This populates fields like instructions, max_output_tokens, temperature, etc.
    /// from the original request, making it easy to construct a response that mirrors
    /// the request parameters.
    ///
    /// Note: `safety_identifier` is intentionally NOT copied as it is for content moderation
    /// and should be set independently from the request's `user` field (which is for billing/tracking).
    pub fn copy_from_request(mut self, request: &ResponsesRequest) -> Self {
        self.instructions.clone_from(&request.instructions);
        self.max_output_tokens = request.max_output_tokens;
        self.parallel_tool_calls = request.parallel_tool_calls.unwrap_or(true);
        self.previous_response_id
            .clone_from(&request.previous_response_id);
        self.store = request.store.unwrap_or(true);
        self.temperature = request.temperature;
        self.tool_choice = if let Some(ref tc) = request.tool_choice {
            serde_json::to_string(tc).unwrap_or_else(|_| "auto".to_string())
        } else {
            "auto".to_string()
        };
        self.tools = request.tools.clone().unwrap_or_default();
        self.top_p = request.top_p;
        self.user.clone_from(&request.user);
        self.metadata = request.metadata.clone().unwrap_or_default();
        self
    }

    /// Set the object type (default: "response")
    pub fn object(mut self, object: impl Into<String>) -> Self {
        self.object = object.into();
        self
    }

    /// Set the creation timestamp (default: current time)
    pub fn created_at(mut self, timestamp: i64) -> Self {
        self.created_at = timestamp;
        self
    }

    /// Set the response status
    pub fn status(mut self, status: ResponseStatus) -> Self {
        self.status = status;
        self
    }

    /// Set error information (if status is failed)
    pub fn error(mut self, error: Value) -> Self {
        self.error = Some(error);
        self
    }

    /// Set incomplete details (if response was truncated)
    pub fn incomplete_details(mut self, details: Value) -> Self {
        self.incomplete_details = Some(details);
        self
    }

    /// Set system instructions
    pub fn instructions(mut self, instructions: impl Into<String>) -> Self {
        self.instructions = Some(instructions.into());
        self
    }

    /// Set max output tokens
    pub fn max_output_tokens(mut self, tokens: u32) -> Self {
        self.max_output_tokens = Some(tokens);
        self
    }

    /// Set output items
    pub fn output(mut self, output: Vec<ResponseOutputItem>) -> Self {
        self.output = output;
        self
    }

    /// Add a single output item
    pub fn add_output(mut self, item: ResponseOutputItem) -> Self {
        self.output.push(item);
        self
    }

    /// Set whether parallel tool calls are enabled
    pub fn parallel_tool_calls(mut self, enabled: bool) -> Self {
        self.parallel_tool_calls = enabled;
        self
    }

    /// Set previous response ID (if continuation)
    pub fn previous_response_id(mut self, id: impl Into<String>) -> Self {
        self.previous_response_id = Some(id.into());
        self
    }

    /// Set reasoning information
    pub fn reasoning(mut self, reasoning: ReasoningInfo) -> Self {
        self.reasoning = Some(reasoning);
        self
    }

    /// Set whether the response is stored
    pub fn store(mut self, store: bool) -> Self {
        self.store = store;
        self
    }

    /// Set temperature setting
    pub fn temperature(mut self, temperature: f32) -> Self {
        self.temperature = Some(temperature);
        self
    }

    /// Set text format settings if provided (handles Option)
    pub fn maybe_text(mut self, text: Option<TextConfig>) -> Self {
        if let Some(t) = text {
            self.text = Some(t);
        }
        self
    }

    /// Set tool choice setting
    pub fn tool_choice(mut self, tool_choice: impl Into<String>) -> Self {
        self.tool_choice = tool_choice.into();
        self
    }

    /// Set available tools
    pub fn tools(mut self, tools: Vec<ResponseTool>) -> Self {
        self.tools = tools;
        self
    }

    /// Set top-p setting
    pub fn top_p(mut self, top_p: f32) -> Self {
        self.top_p = Some(top_p);
        self
    }

    /// Set truncation strategy
    pub fn truncation(mut self, truncation: impl Into<String>) -> Self {
        self.truncation = Some(truncation.into());
        self
    }

    /// Set usage information
    pub fn usage(mut self, usage: ResponsesUsage) -> Self {
        self.usage = Some(usage);
        self
    }

    /// Set usage if provided (handles Option)
    pub fn maybe_usage(mut self, usage: Option<ResponsesUsage>) -> Self {
        if let Some(u) = usage {
            self.usage = Some(u);
        }
        self
    }

    /// Copy from request if provided (handles Option)
    pub fn maybe_copy_from_request(mut self, request: Option<&ResponsesRequest>) -> Self {
        if let Some(req) = request {
            self = self.copy_from_request(req);
        }
        self
    }

    /// Set user identifier
    pub fn user(mut self, user: impl Into<String>) -> Self {
        self.user = Some(user.into());
        self
    }

    /// Set safety identifier
    pub fn safety_identifier(mut self, identifier: impl Into<String>) -> Self {
        self.safety_identifier = Some(identifier.into());
        self
    }

    /// Set metadata
    pub fn metadata(mut self, metadata: HashMap<String, Value>) -> Self {
        self.metadata = metadata;
        self
    }

    /// Add a single metadata entry
    pub fn add_metadata(mut self, key: impl Into<String>, value: Value) -> Self {
        self.metadata.insert(key.into(), value);
        self
    }

    /// Build the ResponsesResponse
    pub fn build(self) -> ResponsesResponse {
        ResponsesResponse {
            id: self.id,
            object: self.object,
            created_at: self.created_at,
            status: self.status,
            error: self.error,
            incomplete_details: self.incomplete_details,
            instructions: self.instructions,
            max_output_tokens: self.max_output_tokens,
            model: self.model,
            output: self.output,
            parallel_tool_calls: self.parallel_tool_calls,
            previous_response_id: self.previous_response_id,
            reasoning: self.reasoning,
            store: self.store,
            temperature: self.temperature,
            text: self.text,
            tool_choice: self.tool_choice,
            tools: self.tools,
            top_p: self.top_p,
            truncation: self.truncation,
            usage: self.usage,
            user: self.user,
            safety_identifier: self.safety_identifier,
            metadata: self.metadata,
        }
    }
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_build_minimal() {
        let response = ResponsesResponse::builder("resp_123", "gpt-4").build();

        assert_eq!(response.id, "resp_123");
        assert_eq!(response.model, "gpt-4");
        assert_eq!(response.object, "response");
        assert_eq!(response.status, ResponseStatus::InProgress);
        assert!(response.output.is_empty());
        assert!(response.parallel_tool_calls);
        assert!(response.store);
    }

    #[test]
    fn test_build_complete() {
        let response = ResponsesResponse::builder("resp_123", "gpt-4")
            .status(ResponseStatus::Completed)
            .instructions("You are a helpful assistant")
            .max_output_tokens(1000)
            .temperature(0.7)
            .top_p(0.9)
            .parallel_tool_calls(false)
            .store(false)
            .build();

        assert_eq!(response.status, ResponseStatus::Completed);
        assert_eq!(
            response.instructions.as_ref().unwrap(),
            "You are a helpful assistant"
        );
        assert_eq!(response.max_output_tokens, Some(1000));
        assert_eq!(response.temperature, Some(0.7));
        assert_eq!(response.top_p, Some(0.9));
        assert!(!response.parallel_tool_calls);
        assert!(!response.store);
    }

    #[test]
    fn test_copy_from_request() {
        let request = ResponsesRequest {
            model: "gpt-4".to_string(),
            input: ResponseInput::Text("test".to_string()),
            instructions: Some("Be helpful".to_string()),
            max_output_tokens: Some(500),
            temperature: Some(0.8),
            top_p: Some(0.95),
            parallel_tool_calls: Some(false),
            store: Some(false),
            user: Some("user_123".to_string()),
            metadata: Some(HashMap::from([(
                "key".to_string(),
                serde_json::json!("value"),
            )])),
            ..Default::default()
        };

        let response = ResponsesResponse::builder("resp_456", "gpt-4")
            .copy_from_request(&request)
            .status(ResponseStatus::Completed)
            .build();

        assert_eq!(response.instructions.as_ref().unwrap(), "Be helpful");
        assert_eq!(response.max_output_tokens, Some(500));
        assert_eq!(response.temperature, Some(0.8));
        assert_eq!(response.top_p, Some(0.95));
        assert!(!response.parallel_tool_calls);
        assert!(!response.store);
        assert_eq!(response.user.as_ref().unwrap(), "user_123");
        assert_eq!(
            response.metadata.get("key").unwrap(),
            &serde_json::json!("value")
        );
    }

    #[test]
    fn test_add_output_items() {
        let response = ResponsesResponse::builder("resp_789", "gpt-4")
            .add_output(ResponseOutputItem::Message {
                id: "msg_1".to_string(),
                role: "assistant".to_string(),
                content: vec![],
                status: "completed".to_string(),
            })
            .add_output(ResponseOutputItem::Message {
                id: "msg_2".to_string(),
                role: "assistant".to_string(),
                content: vec![],
                status: "completed".to_string(),
            })
            .build();

        assert_eq!(response.output.len(), 2);
    }

    #[test]
    fn test_add_metadata() {
        let response = ResponsesResponse::builder("resp_101", "gpt-4")
            .add_metadata("key1", serde_json::json!("value1"))
            .add_metadata("key2", serde_json::json!(42))
            .build();

        assert_eq!(response.metadata.len(), 2);
        assert_eq!(response.metadata.get("key1").unwrap(), "value1");
        assert_eq!(response.metadata.get("key2").unwrap(), 42);
    }
}