tkach 0.4.0

A provider-independent agent runtime for Rust with built-in tools
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
//! OpenAI Responses API provider.
//!
//! This is the provider to use for OpenAI reasoning/thinking streams.
//! `OpenAICompatible` targets Chat Completions (`/chat/completions`),
//! whose standard wire format has no reasoning-summary events. This
//! provider targets `/responses`, opts into reasoning summaries when
//! configured, and maps `response.reasoning_summary_text.*` events into
//! provider-neutral [`StreamEvent::ThinkingDelta`] /
//! [`StreamEvent::ThinkingBlock`] values.

use async_trait::async_trait;
use eventsource_stream::Eventsource;
use serde_json::{Value, json};

use super::openai_responses_proto as proto;
use crate::error::ProviderError;
use crate::provider::{LlmProvider, Request, Response};
use crate::stream::ProviderEventStream;

const DEFAULT_BASE_URL: &str = "https://api.openai.com/v1";

/// Provider for OpenAI's `/responses` API.
///
/// Use this when you want first-class OpenAI reasoning summaries. For
/// Chat Completions-compatible endpoints, use [`super::OpenAICompatible`]
/// instead; that provider deliberately does not expose non-standard
/// `reasoning_content` fields as thinking.
pub struct OpenAIResponses {
    api_key: String,
    base_url: String,
    client: reqwest::Client,
    reasoning: Option<ReasoningConfig>,
    include_encrypted_reasoning: bool,
}

#[derive(Debug, Clone)]
struct ReasoningConfig {
    effort: String,
    summary: String,
}

impl OpenAIResponses {
    pub fn new(api_key: impl Into<String>) -> Self {
        Self {
            api_key: api_key.into(),
            base_url: DEFAULT_BASE_URL.to_string(),
            client: reqwest::Client::new(),
            reasoning: None,
            include_encrypted_reasoning: true,
        }
    }

    /// Read `OPENAI_API_KEY` from the environment.
    pub fn from_env() -> Self {
        let api_key = std::env::var("OPENAI_API_KEY").expect("OPENAI_API_KEY env var is required");
        Self::new(api_key)
    }

    /// Override the endpoint root, without trailing `/responses`.
    pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
        self.base_url = base_url.into();
        self
    }

    /// Request reasoning effort + summaries from reasoning models.
    ///
    /// Typical values: effort `low|medium|high`, summary
    /// `auto|concise|detailed`. OpenAI validates the exact combinations
    /// per model.
    pub fn with_reasoning(mut self, effort: impl Into<String>, summary: impl Into<String>) -> Self {
        self.reasoning = Some(ReasoningConfig {
            effort: effort.into(),
            summary: summary.into(),
        });
        self
    }

    /// Do not request encrypted reasoning replay blobs.
    ///
    /// Keeping this enabled is useful for stateless multi-turn replay:
    /// OpenAI can return opaque `reasoning.encrypted_content` that should
    /// be persisted but never displayed.
    pub fn without_encrypted_reasoning(mut self) -> Self {
        self.include_encrypted_reasoning = false;
        self
    }

    fn responses_url(&self) -> String {
        format!("{}/responses", self.base_url.trim_end_matches('/'))
    }
}

#[async_trait]
impl LlmProvider for OpenAIResponses {
    async fn stream(&self, request: Request) -> Result<ProviderEventStream, ProviderError> {
        let mut body = build_request_body(
            &request,
            self.reasoning.as_ref(),
            self.include_encrypted_reasoning,
        );
        body["stream"] = json!(true);

        let response = self
            .client
            .post(self.responses_url())
            .bearer_auth(&self.api_key)
            .header("content-type", "application/json")
            .header("accept", "text/event-stream")
            .json(&body)
            .send()
            .await?;

        let status = response.status().as_u16();
        if status >= 400 {
            let retry_after_ms = proto::parse_retry_after(response.headers());
            let text = response.text().await.unwrap_or_default();
            return Err(proto::classify_error(status, text, retry_after_ms));
        }

        Ok(Box::pin(proto::responses_event_stream(
            response.bytes_stream().eventsource(),
        )))
    }

    async fn complete(&self, request: Request) -> Result<Response, ProviderError> {
        let body = build_request_body(
            &request,
            self.reasoning.as_ref(),
            self.include_encrypted_reasoning,
        );

        let response = self
            .client
            .post(self.responses_url())
            .bearer_auth(&self.api_key)
            .header("content-type", "application/json")
            .json(&body)
            .send()
            .await?;

        let status = response.status().as_u16();
        if status >= 400 {
            let retry_after_ms = proto::parse_retry_after(response.headers());
            let text = response.text().await.unwrap_or_default();
            return Err(proto::classify_error(status, text, retry_after_ms));
        }

        let text = response.text().await?;
        let value = serde_json::from_str::<Value>(&text)?;
        proto::response_error(&value).map_or_else(|| proto::convert_response_value(&value), Err)
    }
}

fn build_request_body(
    request: &Request,
    reasoning: Option<&ReasoningConfig>,
    include_encrypted_reasoning: bool,
) -> Value {
    let mut body = json!({
        "model": request.model,
        "store": false,
        "stream": false,
        "input": proto::build_input(&request.messages),
        "max_output_tokens": request.max_tokens,
    });

    if let Some(instructions) = proto::instructions(request) {
        body["instructions"] = json!(instructions);
    }
    if let Some(temperature) = request.temperature {
        body["temperature"] = json!(temperature);
    }
    if let Some(reasoning) = reasoning {
        body["reasoning"] = json!({
            "effort": reasoning.effort,
            "summary": reasoning.summary,
        });
    }
    if include_encrypted_reasoning {
        body["include"] = json!(["reasoning.encrypted_content"]);
    }

    let tools = proto::build_tools(&request.tools);
    if !tools.is_empty() {
        body["tools"] = Value::Array(tools);
        body["tool_choice"] = json!("auto");
        body["parallel_tool_calls"] = json!(true);
    }

    body
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::message::{Content, Message, StopReason, ThinkingMetadata, ThinkingProvider};
    use crate::provider::SystemBlock;
    use crate::stream::StreamEvent;
    use std::collections::VecDeque;

    #[test]
    fn request_includes_reasoning_and_encrypted_content() {
        let req = Request {
            model: "gpt-5".into(),
            system: Some(vec![SystemBlock::text("be brief")]),
            messages: vec![Message::user_text("solve")],
            tools: vec![],
            max_tokens: 128,
            temperature: None,
        };
        let reasoning = ReasoningConfig {
            effort: "medium".into(),
            summary: "auto".into(),
        };

        let body = build_request_body(&req, Some(&reasoning), true);

        assert_eq!(body["model"], "gpt-5");
        assert_eq!(body["instructions"], "be brief");
        assert_eq!(body["reasoning"]["effort"], "medium");
        assert_eq!(body["reasoning"]["summary"], "auto");
        assert_eq!(body["include"][0], "reasoning.encrypted_content");
        assert_eq!(body["input"][0]["role"], "user");
    }

    #[test]
    fn request_replays_openai_reasoning_and_tool_state() {
        let req = Request {
            model: "gpt-5".into(),
            system: None,
            messages: vec![
                Message::assistant(vec![
                    Content::thinking(
                        "summary",
                        ThinkingProvider::OpenAIResponses,
                        ThinkingMetadata::openai_responses(
                            Some("rs_1".into()),
                            Some(0),
                            0,
                            Some("enc".into()),
                        ),
                    ),
                    Content::ToolUse {
                        id: "call_1|fc_1".into(),
                        name: "bash".into(),
                        input: json!({"command":"echo hi"}),
                    },
                ]),
                Message::user(vec![Content::tool_result("call_1|fc_1", "hi", false)]),
            ],
            tools: vec![],
            max_tokens: 128,
            temperature: None,
        };

        let body = build_request_body(&req, None, true);
        let input = body["input"].as_array().unwrap();

        assert_eq!(input[0]["type"], "reasoning");
        assert_eq!(input[0]["id"], "rs_1");
        assert_eq!(input[0]["encrypted_content"], "enc");
        assert_eq!(input[1]["type"], "function_call");
        assert_eq!(input[1]["call_id"], "call_1");
        assert_eq!(input[1]["id"], "fc_1");
        assert_eq!(input[2]["type"], "function_call_output");
        assert_eq!(input[2]["call_id"], "call_1");

        // status is output-only on the Responses API; including it on
        // input items causes the backend to reject the request.
        assert!(input[0].get("status").is_none());
        assert!(input[1].get("status").is_none());
    }

    #[test]
    fn non_streaming_response_decodes_reasoning_text_and_tools() {
        let raw = json!({
            "status": "completed",
            "output": [
                {
                    "id": "rs_1",
                    "type": "reasoning",
                    "summary": [{"type":"summary_text", "text":"checked constraints"}],
                    "encrypted_content": "opaque"
                },
                {
                    "id": "msg_1",
                    "type": "message",
                    "content": [{"type":"output_text", "text":"answer"}]
                },
                {
                    "id": "fc_1",
                    "type": "function_call",
                    "call_id": "call_1",
                    "name": "bash",
                    "arguments": "{\"command\":\"echo hi\"}"
                }
            ],
            "usage": {"input_tokens": 10, "output_tokens": 7}
        });

        let response = proto::convert_response_value(&raw).unwrap();

        assert_eq!(response.stop_reason, StopReason::ToolUse);
        assert_eq!(response.usage.input_tokens, 10);
        assert!(matches!(
            &response.content[0],
            Content::Thinking {
                text,
                provider: ThinkingProvider::OpenAIResponses,
                metadata:
                    ThinkingMetadata::OpenAIResponses {
                        item_id: Some(item_id),
                        output_index: Some(0),
                        summary_index: 0,
                        encrypted_content: Some(encrypted),
                    },
            } if text == "checked constraints" && item_id == "rs_1" && encrypted == "opaque"
        ));
        assert!(matches!(&response.content[1], Content::Text { text, .. } if text == "answer"));
        assert!(matches!(
            &response.content[2],
            Content::ToolUse { id, name, input }
                if id == "call_1|fc_1" && name == "bash" && input["command"] == "echo hi"
        ));
    }

    #[test]
    fn streaming_reasoning_summary_emits_delta_and_final_block() {
        let mut parser = proto::ResponsesSseParser::default();
        let mut out = VecDeque::new();

        parser.process_value(
            json!({
                "type": "response.reasoning_summary_text.delta",
                "item_id": "rs_1",
                "output_index": 0,
                "summary_index": 0,
                "delta": "checked"
            }),
            &mut out,
        );
        parser.process_value(
            json!({
                "type": "response.reasoning_summary_text.done",
                "item_id": "rs_1",
                "output_index": 0,
                "summary_index": 0,
                "text": "checked constraints"
            }),
            &mut out,
        );
        parser.process_value(
            json!({
                "type": "response.output_item.done",
                "output_index": 0,
                "item": {
                    "id": "rs_1",
                    "type": "reasoning",
                    "summary": [{"type":"summary_text", "text":"checked constraints"}],
                    "encrypted_content": "opaque"
                }
            }),
            &mut out,
        );

        assert!(matches!(
            out.pop_front().unwrap().unwrap(),
            StreamEvent::ThinkingDelta { text } if text == "checked"
        ));
        assert!(matches!(
            out.pop_front().unwrap().unwrap(),
            StreamEvent::ThinkingBlock {
                text,
                provider: ThinkingProvider::OpenAIResponses,
                metadata:
                    ThinkingMetadata::OpenAIResponses {
                        item_id: Some(item_id),
                        output_index: Some(0),
                        summary_index: 0,
                        encrypted_content: Some(encrypted),
                    },
            } if text == "checked constraints" && item_id == "rs_1" && encrypted == "opaque"
        ));
        assert!(out.is_empty());
    }

    #[test]
    fn streaming_ignores_raw_reasoning_text_events() {
        let mut parser = proto::ResponsesSseParser::default();
        let mut out = VecDeque::new();

        parser.process_value(
            json!({
                "type": "response.reasoning_text.delta",
                "item_id": "rs_1",
                "output_index": 0,
                "content_index": 0,
                "delta": "raw chain of thought"
            }),
            &mut out,
        );

        assert!(out.is_empty());
    }

    #[test]
    fn streaming_tool_call_emits_atomic_tool_use() {
        let mut parser = proto::ResponsesSseParser::default();
        let mut out = VecDeque::new();

        parser.process_value(
            json!({
                "type": "response.output_item.added",
                "output_index": 0,
                "item": {
                    "id": "fc_1",
                    "type": "function_call",
                    "call_id": "call_1",
                    "name": "bash",
                    "arguments": ""
                }
            }),
            &mut out,
        );
        parser.process_value(
            json!({
                "type": "response.function_call_arguments.delta",
                "item_id": "fc_1",
                "output_index": 0,
                "delta": "{\"command\":"
            }),
            &mut out,
        );
        parser.process_value(
            json!({
                "type": "response.function_call_arguments.done",
                "item_id": "fc_1",
                "output_index": 0,
                "name": "bash",
                "arguments": "{\"command\":\"echo hi\"}"
            }),
            &mut out,
        );
        parser.process_value(
            json!({
                "type": "response.output_item.done",
                "output_index": 0,
                "item": {
                    "id": "fc_1",
                    "type": "function_call",
                    "call_id": "call_1",
                    "name": "bash",
                    "arguments": "{\"command\":\"echo hi\"}"
                }
            }),
            &mut out,
        );

        assert!(matches!(
            out.pop_front().unwrap().unwrap(),
            StreamEvent::ToolUse { id, name, input }
                if id == "call_1|fc_1" && name == "bash" && input["command"] == "echo hi"
        ));
        assert!(out.is_empty());
    }
}