Skip to main content

agent_framework_openai/
responses.rs

1//! [`OpenAIChatClient`]: a [`ChatClient`] for the OpenAI Responses API
2//! (`POST /v1/responses`).
3//!
4//! The Responses API uses an item-based `input`/`output` shape rather than
5//! the `messages` array used by Chat Completions, and supports a dedicated
6//! `previous_response_id` for service-side conversation state. Wire framing
7//! (SSE parsing style, error handling) mirrors [`crate::OpenAIChatCompletionClient`].
8//!
9//! ```no_run
10//! use agent_framework_openai::responses::OpenAIChatClient;
11//! use agent_framework_core::prelude::*;
12//!
13//! # async fn demo() -> Result<()> {
14//! let client = OpenAIChatClient::new("sk-...", "gpt-4o-mini");
15//! let agent = Agent::builder(client)
16//!     .instructions("You are concise.")
17//!     .build();
18//! let reply = agent.run_once("Say hi").await?;
19//! println!("{}", reply.text());
20//! # Ok(())
21//! # }
22//! ```
23
24use std::collections::{HashMap, VecDeque};
25use std::sync::Arc;
26
27use agent_framework_core::client::{ChatClient, ChatStream};
28use agent_framework_core::error::{Error, Result};
29use agent_framework_core::streaming::Utf8StreamDecoder;
30use agent_framework_core::tools::ToolDefinition;
31use agent_framework_core::types::{
32    Annotation, ChatOptions, ChatResponse, ChatResponseUpdate, Content, DataContent, FinishReason,
33    FunctionApprovalRequestContent, FunctionArguments, FunctionCallContent, FunctionResultContent,
34    McpServerToolCallContent, McpServerToolResultContent, Message, ResponseFormat, Role,
35    TextContent, TextReasoningContent, TextSpanRegion, ToolMode, UriContent, UsageContent,
36    UsageDetails,
37};
38use futures::StreamExt;
39use serde_json::{json, Map, Value};
40
41use crate::convert::{
42    audio_format, data_content_media_type, function_arguments_to_string, result_to_string,
43    top_level_media_type, DEFAULT_FILENAME,
44};
45use crate::{ByteStream, DEFAULT_BASE_URL};
46
47/// An OpenAI Responses API chat client (`POST /v1/responses`).
48#[derive(Clone)]
49pub struct OpenAIChatClient {
50    inner: Arc<Inner>,
51}
52
53#[derive(Clone)]
54struct Inner {
55    http: reqwest::Client,
56    api_key: String,
57    base_url: String,
58    model: String,
59    organization: Option<String>,
60}
61
62impl std::fmt::Debug for OpenAIChatClient {
63    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64        f.debug_struct("OpenAIChatClient")
65            .field("base_url", &self.inner.base_url)
66            .field("model", &self.inner.model)
67            .field("organization", &self.inner.organization)
68            .finish_non_exhaustive()
69    }
70}
71
72impl OpenAIChatClient {
73    /// Create a client for the given API key and default model.
74    pub fn new(api_key: impl Into<String>, model: impl Into<String>) -> Self {
75        Self {
76            inner: Arc::new(Inner {
77                http: reqwest::Client::new(),
78                api_key: api_key.into(),
79                base_url: DEFAULT_BASE_URL.to_string(),
80                model: model.into(),
81                organization: None,
82            }),
83        }
84    }
85
86    /// Build a client from the `OPENAI_API_KEY` (and optional
87    /// `OPENAI_BASE_URL`) environment variables.
88    pub fn from_env(model: impl Into<String>) -> Result<Self> {
89        let key = std::env::var("OPENAI_API_KEY")
90            .map_err(|_| Error::Configuration("OPENAI_API_KEY is not set".into()))?;
91        let mut client = Self::new(key, model);
92        if let Ok(base) = std::env::var("OPENAI_BASE_URL") {
93            client = client.with_base_url(base);
94        }
95        Ok(client)
96    }
97
98    /// Override the base URL (for Azure OpenAI or compatible servers).
99    pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
100        Arc::make_mut(&mut self.inner).base_url = base_url.into();
101        self
102    }
103
104    /// Set the organization header.
105    pub fn with_organization(mut self, org: impl Into<String>) -> Self {
106        Arc::make_mut(&mut self.inner).organization = Some(org.into());
107        self
108    }
109
110    /// The default model id.
111    pub fn model(&self) -> &str {
112        &self.inner.model
113    }
114
115    fn build_body(&self, messages: &[Message], options: &ChatOptions, stream: bool) -> Value {
116        let mut body = Map::new();
117        let model = options
118            .model
119            .clone()
120            .unwrap_or_else(|| self.inner.model.clone());
121        body.insert("model".into(), json!(model));
122
123        let (instructions, rest) = extract_instructions(messages, options.instructions.as_deref());
124        if let Some(instructions) = instructions {
125            body.insert("instructions".into(), json!(instructions));
126        }
127        let input = if uses_service_side_storage(options) {
128            messages_to_continuation_input(rest)
129        } else {
130            messages_to_input(rest)
131        };
132        body.insert("input".into(), json!(input));
133
134        if let Some(conversation_id) = &options.conversation_id {
135            body.insert("previous_response_id".into(), json!(conversation_id));
136        }
137        if let Some(t) = options.temperature {
138            body.insert("temperature".into(), json!(t));
139        }
140        if let Some(t) = options.top_p {
141            body.insert("top_p".into(), json!(t));
142        }
143        if let Some(mt) = options.max_tokens {
144            body.insert("max_output_tokens".into(), json!(mt));
145        }
146        if let Some(store) = options.store {
147            body.insert("store".into(), json!(store));
148        }
149        if let Some(user) = &options.user {
150            body.insert("user".into(), json!(user));
151        }
152        if let Some(metadata) = &options.metadata {
153            body.insert("metadata".into(), json!(metadata));
154        }
155
156        if !options.tools.is_empty() {
157            let tools: Vec<Value> = options.tools.iter().map(tool_to_responses_spec).collect();
158            body.insert("tools".into(), json!(tools));
159            if let Some(allow_multi) = options.allow_multiple_tool_calls {
160                body.insert("parallel_tool_calls".into(), json!(allow_multi));
161            }
162        }
163        if let Some(tool_choice) = &options.tool_choice {
164            body.insert("tool_choice".into(), tool_choice_to_responses(tool_choice));
165        }
166        if let Some(fmt) = &options.response_format {
167            body.insert(
168                "text".into(),
169                json!({ "format": response_format_to_text(fmt) }),
170            );
171        }
172
173        // Inserted before the `additional_properties` pass below, whose
174        // A caller's own `include` entries are already folded in here.
175        if let Some(include) = responses_include(options, true) {
176            body.insert("include".into(), include);
177        }
178
179        for (k, v) in &options.additional_properties {
180            // `include` belongs to `responses_include` alone. Letting it
181            // through would resurrect a value that function deliberately
182            // dropped — an explicit empty array would land as `include: []`,
183            // the one shape it exists to avoid.
184            if k == "include" {
185                continue;
186            }
187            body.entry(k.clone()).or_insert_with(|| v.clone());
188        }
189
190        if stream {
191            body.insert("stream".into(), json!(true));
192        }
193        Value::Object(body)
194    }
195
196    async fn post(&self, body: &Value) -> Result<reqwest::Response> {
197        let url = format!("{}/responses", self.inner.base_url.trim_end_matches('/'));
198        let mut req = self
199            .inner
200            .http
201            .post(&url)
202            .bearer_auth(&self.inner.api_key)
203            .json(body);
204        if let Some(org) = &self.inner.organization {
205            req = req.header("OpenAI-Organization", org);
206        }
207        let resp = req
208            .send()
209            .await
210            .map_err(|e| Error::service(format!("request failed: {e}")))?;
211        if !resp.status().is_success() {
212            let status = resp.status();
213            let retry_after = crate::parse_retry_after(resp.headers());
214            let text = resp.text().await.unwrap_or_default();
215            return Err(crate::classify_service_error(
216                status.as_u16(),
217                &text,
218                format!("OpenAI API error {status}: {text}"),
219                retry_after,
220            ));
221        }
222        Ok(resp)
223    }
224}
225
226#[async_trait::async_trait]
227impl ChatClient for OpenAIChatClient {
228    async fn get_response(
229        &self,
230        messages: Vec<Message>,
231        options: ChatOptions,
232    ) -> Result<ChatResponse> {
233        let body = self.build_body(&messages, &options, false);
234        let resp = self.post(&body).await?;
235        let value: Value = resp
236            .json()
237            .await
238            .map_err(|e| Error::service(format!("invalid response json: {e}")))?;
239        if let Some(err) = response_failure_error(&value) {
240            return Err(err);
241        }
242        Ok(parse_response(&value, options.store))
243    }
244
245    async fn get_streaming_response(
246        &self,
247        messages: Vec<Message>,
248        options: ChatOptions,
249    ) -> Result<ChatStream> {
250        let body = self.build_body(&messages, &options, true);
251        let resp = self.post(&body).await?;
252        Ok(parse_responses_sse_stream(resp, options.store).boxed())
253    }
254
255    fn model(&self) -> Option<&str> {
256        Some(&self.inner.model)
257    }
258}
259
260// region: request conversion
261
262/// The `include` entry that asks a reasoning model to return its *encrypted*
263/// reasoning item alongside the summary.
264pub const ENCRYPTED_REASONING_INCLUDE: &str = "reasoning.encrypted_content";
265
266/// Build the Responses request's `include` array.
267///
268/// A reasoning item must be replayed verbatim on the follow-up turn of a tool
269/// loop, and the service only accepts it when it carries its `id` *and*
270/// `encrypted_content`. When the conversation is held service-side the model
271/// already has that item, but on a stateless request nothing is stored — so
272/// unless the request asks for `reasoning.encrypted_content`, the item comes
273/// back without it and the replay in [`messages_to_input`] has nothing valid
274/// to re-send. This adds it implicitly in exactly that case, mirroring
275/// upstream's `_prepare_options`.
276///
277/// A caller's own `include` entries (passed through
278/// `ChatOptions::additional_properties`) are always preserved, and an explicit
279/// `reasoning.encrypted_content` is honored even when `implicit` is `false` —
280/// `implicit` gates only whether it is added on the caller's behalf. Foundry
281/// passes `false` here: it does not want encrypted reasoning unless asked for
282/// it by name (upstream #7536).
283///
284/// Returns `None` when the array would be empty, so a request that needs no
285/// `include` does not carry an empty one.
286///
287/// `pub` for the same reason as [`extract_instructions`]: `agent-framework-azure`'s
288/// Responses client builds its own body and reuses this step rather than
289/// reimplementing it.
290pub fn responses_include(options: &ChatOptions, implicit: bool) -> Option<Value> {
291    let mut include: Vec<Value> = options
292        .additional_properties
293        .get("include")
294        .and_then(Value::as_array)
295        .cloned()
296        .unwrap_or_default();
297
298    // Upstream keys this off the service-side-storage indicators, not `store`:
299    // a request continuing a stored conversation needs nothing echoed back.
300    let uses_service_side_storage = uses_service_side_storage(options);
301
302    let already_present = include
303        .iter()
304        .any(|v| v.as_str() == Some(ENCRYPTED_REASONING_INCLUDE));
305    if implicit && !uses_service_side_storage && !already_present {
306        include.push(json!(ENCRYPTED_REASONING_INCLUDE));
307    }
308
309    (!include.is_empty()).then(|| json!(include))
310}
311
312/// Whether a request continues a service-stored response chain: it carries a
313/// non-empty `conversation_id`, sent as `previous_response_id`
314/// (upstream's `request_uses_service_side_storage`).
315///
316/// `pub` so `agent-framework-azure`'s Responses client makes the same call
317/// when choosing between [`messages_to_input`] and
318/// [`messages_to_continuation_input`].
319pub fn uses_service_side_storage(options: &ChatOptions) -> bool {
320    options
321        .conversation_id
322        .as_deref()
323        .is_some_and(|id| !id.is_empty())
324}
325
326/// Split a leading system message (and/or `ChatOptions::instructions`) out
327/// into the Responses API's top-level `instructions` field, returning the
328/// remaining messages to convert into `input` items.
329///
330/// `pub` (rather than private) so `agent-framework-azure`'s Responses client
331/// can reuse this exact instructions-extraction step ahead of
332/// [`messages_to_input`] when building the Azure OpenAI Responses request
333/// body, instead of reimplementing it.
334pub fn extract_instructions<'a>(
335    messages: &'a [Message],
336    options_instructions: Option<&str>,
337) -> (Option<String>, &'a [Message]) {
338    let mut parts = Vec::new();
339    if let Some(instr) = options_instructions {
340        if !instr.is_empty() {
341            parts.push(instr.to_string());
342        }
343    }
344    let mut rest = messages;
345    if let Some(first) = messages.first() {
346        if first.role == Role::system() {
347            let text = first.text();
348            if !text.is_empty() {
349                parts.push(text);
350            }
351            rest = &messages[1..];
352        }
353    }
354    if parts.is_empty() {
355        (None, rest)
356    } else {
357        (Some(parts.join("\n\n")), rest)
358    }
359}
360
361/// Convert framework messages into the Responses API's `input` item array.
362///
363/// `pub` so `agent-framework-azure`'s Responses client can reuse this
364/// conversion verbatim rather than reimplementing it (Azure OpenAI's
365/// Responses API shares the exact same `input` item wire shape).
366pub fn messages_to_input(messages: &[Message]) -> Vec<Value> {
367    convert_messages(messages, false)
368}
369
370/// Convert framework messages into `input` items for a request that continues
371/// a stored response chain (`previous_response_id`, see
372/// [`uses_service_side_storage`]).
373///
374/// The service already holds every item the earlier responses produced, and
375/// rejects an inline copy of one with a server-issued `id` as a duplicate
376/// ("Duplicate item found with id ..."). So hosted `mcp_call` items (and the
377/// results folded into them), `mcp_approval_request` items and reasoning items
378/// are left out here, as upstream's `_prepare_message_for_openai` does under
379/// `request_uses_service_side_storage` (microsoft/agent-framework#3295).
380/// Approval responses and function results still go out: they are new input
381/// the service pairs to its stored items by id.
382pub fn messages_to_continuation_input(messages: &[Message]) -> Vec<Value> {
383    convert_messages(messages, true)
384}
385
386fn convert_messages(messages: &[Message], continues_stored: bool) -> Vec<Value> {
387    let mut out = Vec::new();
388    for msg in messages {
389        let role = msg.role.as_str();
390        if role == Role::TOOL {
391            for content in &msg.contents {
392                match content {
393                    Content::FunctionResult(fr) => out.push(function_result_to_item(fr)),
394                    Content::McpServerToolResult(r) => attach_mcp_output(&mut out, r),
395                    _ => {}
396                }
397            }
398            continue;
399        }
400
401        let mut buffered: Vec<Value> = Vec::new();
402        for content in &msg.contents {
403            match content {
404                // A refusal is its own output content part — `{"type":
405                // "refusal", "refusal": "..."}` — sitting beside `output_text`
406                // in an output message. Re-emitting it as `output_text` would
407                // replay a decline to the provider as an answer. Only
408                // meaningful on the assistant side: an *input* message's
409                // content list admits only input_text/input_image/input_file,
410                // so a refusal on any other role has no wire form and is
411                // dropped rather than mis-encoded.
412                Content::Text(t) if t.refusal => {
413                    if role == Role::ASSISTANT {
414                        buffered.push(json!({ "type": "refusal", "refusal": t.text }));
415                    }
416                }
417                Content::Text(t) => {
418                    let text_type = if role == Role::ASSISTANT {
419                        "output_text"
420                    } else {
421                        "input_text"
422                    };
423                    buffered.push(json!({ "type": text_type, "text": t.text }));
424                }
425                Content::Uri(u) => {
426                    if let Some(part) = content_to_input_part(&u.uri, Some(&u.media_type)) {
427                        buffered.push(part);
428                    }
429                }
430                Content::Data(d) => {
431                    if let Some(part) =
432                        content_to_input_part(&d.uri, data_content_media_type(d).as_deref())
433                    {
434                        buffered.push(part);
435                    }
436                }
437                Content::HostedFile(h) => {
438                    buffered.push(json!({ "type": "input_file", "file_id": h.file_id }));
439                }
440                Content::FunctionCall(fc) => {
441                    flush_text(&mut out, &mut buffered, role);
442                    out.push(json!({
443                        "type": "function_call",
444                        "call_id": fc.call_id,
445                        "name": fc.name,
446                        "arguments": function_arguments_to_string(&fc.arguments),
447                    }));
448                }
449                Content::FunctionResult(fr) => {
450                    flush_text(&mut out, &mut buffered, role);
451                    out.push(function_result_to_item(fr));
452                }
453                Content::FunctionApprovalResponse(r) => {
454                    flush_text(&mut out, &mut buffered, role);
455                    out.push(json!({
456                        "type": "mcp_approval_response",
457                        "approval_request_id": r.id,
458                        "approve": r.approved,
459                    }));
460                }
461                // Already stored service-side under continuation; re-sending
462                // its `id` would duplicate it.
463                Content::FunctionApprovalRequest(_) if continues_stored => {}
464                Content::FunctionApprovalRequest(r) => {
465                    flush_text(&mut out, &mut buffered, role);
466                    out.push(json!({
467                        "type": "mcp_approval_request",
468                        "id": r.id,
469                        "name": r.function_call.name,
470                        "arguments": function_arguments_to_string(&r.function_call.arguments),
471                    }));
472                }
473                // A hosted MCP call and its result are one `mcp_call` input
474                // item carrying both `arguments` and `output`
475                // (`_prepare_content_for_openai` + `_coalesce_pending_mcp_results`).
476                // Replayed after its approval pair, it tells the service the
477                // approved call already ran, so local history does not ask
478                // for it again. Under continuation the service already has
479                // the item by its `id`, so it is not re-sent (and its result,
480                // finding no call to attach to, is dropped with it).
481                Content::McpServerToolCall(call) => {
482                    if !continues_stored && !call.call_id.is_empty() {
483                        flush_text(&mut out, &mut buffered, role);
484                        out.push(json!({
485                            "type": "mcp_call",
486                            "id": call.call_id,
487                            "server_label": call.server_name.clone().unwrap_or_default(),
488                            "name": call.tool_name,
489                            "arguments": function_arguments_to_string(&call.arguments),
490                        }));
491                        // Links the completed call to its replayed approval
492                        // request/response pair.
493                        if let (Some(id), Some(Value::Object(item))) =
494                            (&call.approval_request_id, out.last_mut())
495                        {
496                            item.insert("approval_request_id".into(), Value::String(id.clone()));
497                        }
498                    }
499                }
500                Content::McpServerToolResult(result) => {
501                    flush_text(&mut out, &mut buffered, role);
502                    attach_mcp_output(&mut out, result);
503                }
504                Content::TextReasoning(tr) => {
505                    // Re-emit the original reasoning item verbatim (store:false
506                    // replay). A summary-only reasoning content with no
507                    // preserved item has no valid input form (it lacks the
508                    // required id/encrypted_content), so it is dropped.
509                    // Under continuation the service already holds the item.
510                    let raw = tr.raw_representation.as_ref().filter(|_| !continues_stored);
511                    if let Some(raw) = raw {
512                        flush_text(&mut out, &mut buffered, role);
513                        out.push(raw.clone());
514                    }
515                }
516                _ => {}
517            }
518        }
519        flush_text(&mut out, &mut buffered, role);
520    }
521    out
522}
523
524/// Set a hosted MCP result's output on the latest `mcp_call` input item with
525/// its id that has none yet. A result with no such call is dropped: the
526/// Responses API has no standalone MCP output item
527/// (`_coalesce_pending_mcp_results`).
528fn attach_mcp_output(out: &mut [Value], result: &McpServerToolResultContent) {
529    if result.call_id.is_empty() {
530        return;
531    }
532    let target = out.iter_mut().rev().find(|item| {
533        item.get("type").and_then(Value::as_str) == Some("mcp_call")
534            && item.get("id").and_then(Value::as_str) == Some(result.call_id.as_str())
535    });
536    if let Some(Value::Object(item)) = target {
537        let unfinished = item.get("output").is_none_or(Value::is_null)
538            && item.get("error").is_none_or(Value::is_null);
539        if !unfinished {
540            return;
541        }
542        // A failed call can carry an error and no output; replaying its
543        // error is what marks it as finished rather than still running.
544        let error = result.error.as_ref().filter(|e| !e.is_null());
545        if result.output.is_some() || error.is_none() {
546            item.insert(
547                "output".into(),
548                Value::String(stringify_mcp_output(result.output.as_ref())),
549            );
550        }
551        if let Some(error) = error {
552            item.insert("error".into(), error.clone());
553        }
554    }
555}
556
557/// Render a hosted MCP result as the string `mcp_call.output` field
558/// (`_stringify_mcp_output`): a string as is, text entries joined, anything
559/// else as JSON.
560fn stringify_mcp_output(output: Option<&Value>) -> String {
561    match output {
562        None | Some(Value::Null) => String::new(),
563        Some(Value::String(s)) => s.clone(),
564        Some(Value::Array(entries)) => entries
565            .iter()
566            .map(|entry| match entry {
567                Value::String(s) => s.clone(),
568                other => match other.get("text").and_then(Value::as_str) {
569                    Some(text) => text.to_string(),
570                    None => other.to_string(),
571                },
572            })
573            .collect(),
574        Some(other) => other.to_string(),
575    }
576}
577
578/// Parse a hosted `mcp_call` output item into its call and, once it has run,
579/// its result (`_create_response_content`'s `mcp_call` arm). The item's `id`
580/// is the call id, falling back to `call_id`. A call that failed carries its
581/// `error` on the result, with or without an `output`.
582fn mcp_call_item_contents(item: &Value) -> Vec<Content> {
583    let call_id = item
584        .get("id")
585        .and_then(Value::as_str)
586        .filter(|s| !s.is_empty())
587        .or_else(|| item.get("call_id").and_then(Value::as_str))
588        .unwrap_or_default()
589        .to_string();
590    let mut contents = vec![Content::McpServerToolCall(McpServerToolCallContent {
591        call_id: call_id.clone(),
592        tool_name: item
593            .get("name")
594            .and_then(Value::as_str)
595            .unwrap_or_default()
596            .to_string(),
597        server_name: item
598            .get("server_label")
599            .and_then(Value::as_str)
600            .map(String::from),
601        arguments: item
602            .get("arguments")
603            .and_then(Value::as_str)
604            .map(|a| FunctionArguments::Raw(a.to_string())),
605        approval_request_id: item
606            .get("approval_request_id")
607            .and_then(Value::as_str)
608            .filter(|s| !s.is_empty())
609            .map(String::from),
610    })];
611    let output = item.get("output").filter(|o| !o.is_null()).cloned();
612    let error = item.get("error").filter(|e| !e.is_null()).cloned();
613    if output.is_some() || error.is_some() {
614        contents.push(Content::McpServerToolResult(McpServerToolResultContent {
615            call_id,
616            output,
617            error,
618        }));
619    }
620    contents
621}
622
623/// Map a URI/data content item to a Responses API input content part, or `None`
624/// when it has no wire mapping (mirrors upstream `_openai_content_parser`).
625/// Handles images (`input_image`), audio (`input_audio`), and `application/*`
626/// data (`input_file`).
627fn content_to_input_part(uri: &str, media_type: Option<&str>) -> Option<Value> {
628    let media_type = media_type?;
629    match top_level_media_type(media_type).as_str() {
630        // `detail` defaults to "auto"; the Rust content types carry no override.
631        "image" => Some(json!({
632            "type": "input_image",
633            "image_url": uri,
634            "detail": "auto",
635        })),
636        "audio" => {
637            let format = audio_format(media_type)?;
638            // `input_audio.data` is the raw base64 payload, not a data URI —
639            // same wire rule as the Chat Completions converter.
640            Some(json!({
641                "type": "input_audio",
642                "input_audio": {
643                    "data": crate::convert::strip_data_uri_prefix(uri),
644                    "format": format,
645                },
646            }))
647        }
648        "application" => Some(json!({
649            "type": "input_file",
650            "file_data": uri,
651            "filename": DEFAULT_FILENAME,
652        })),
653        _ => None,
654    }
655}
656
657fn flush_text(out: &mut Vec<Value>, buffered: &mut Vec<Value>, role: &str) {
658    if !buffered.is_empty() {
659        out.push(json!({ "type": "message", "role": role, "content": std::mem::take(buffered) }));
660    }
661}
662
663fn function_result_to_item(fr: &FunctionResultContent) -> Value {
664    json!({
665        "type": "function_call_output",
666        "call_id": fr.call_id,
667        "output": result_to_string(fr),
668    })
669}
670
671/// The flat Responses-API tool spec: `{"type":"function","name":...}`, unlike
672/// Chat Completions' `{"type":"function","function":{...}}` nesting.
673///
674/// `pub` so `agent-framework-azure`'s Responses client can reuse this
675/// mapping rather than reimplementing it.
676pub fn tool_to_responses_spec(tool: &ToolDefinition) -> Value {
677    use agent_framework_core::tools::ToolKind;
678    match &tool.kind {
679        ToolKind::HostedWebSearch => {
680            let mut spec = Map::new();
681            spec.insert("type".into(), json!("web_search"));
682            if let Some(loc) = tool.parameters.get("user_location") {
683                spec.insert("user_location".into(), user_location_to_responses(loc));
684            }
685            Value::Object(spec)
686        }
687        ToolKind::HostedCodeInterpreter => {
688            let mut spec = Map::new();
689            spec.insert("type".into(), json!("code_interpreter"));
690            // A caller-supplied `container` wins; otherwise default to `auto`
691            // and attach any `file_ids` (`_responses_client.py:264-278`).
692            if let Some(container) = tool.parameters.get("container") {
693                spec.insert("container".into(), container.clone());
694            } else {
695                let mut container = Map::new();
696                container.insert("type".into(), json!("auto"));
697                if let Some(file_ids) = tool.parameters.get("file_ids") {
698                    container.insert("file_ids".into(), file_ids.clone());
699                }
700                spec.insert("container".into(), Value::Object(container));
701            }
702            Value::Object(spec)
703        }
704        ToolKind::HostedFileSearch { max_results } => {
705            let mut spec = Map::new();
706            spec.insert("type".into(), json!("file_search"));
707            // The Responses API requires vector-store ids; the marker itself
708            // carries none, so honor ids supplied via the definition's
709            // parameters object when present.
710            if let Some(ids) = tool.parameters.get("vector_store_ids") {
711                spec.insert("vector_store_ids".into(), ids.clone());
712            }
713            // Prefer the marker's `max_results`; fall back to a parameters key.
714            let max = (*max_results)
715                .map(|n| json!(n))
716                .or_else(|| tool.parameters.get("max_results").cloned());
717            if let Some(n) = max {
718                spec.insert("max_num_results".into(), n);
719            }
720            Value::Object(spec)
721        }
722        ToolKind::HostedMcp { url, allowed_tools } => {
723            let mut spec = Map::new();
724            spec.insert("type".into(), json!("mcp"));
725            spec.insert("server_label".into(), json!(tool.name.replace(' ', "_")));
726            spec.insert("server_url".into(), json!(url));
727            if !tool.description.is_empty() {
728                spec.insert("server_description".into(), json!(tool.description));
729            }
730            if let Some(headers) = tool.parameters.get("headers") {
731                spec.insert("headers".into(), headers.clone());
732            }
733            if let Some(allowed) = allowed_tools {
734                spec.insert("allowed_tools".into(), json!(allowed));
735            }
736            spec.insert("require_approval".into(), mcp_require_approval(tool));
737            Value::Object(spec)
738        }
739        ToolKind::HostedImageGeneration => {
740            let mut spec = Map::new();
741            spec.insert("type".into(), json!("image_generation"));
742            // Pass through any caller-supplied generation options (size,
743            // quality, background, …) carried on the marker's parameters.
744            if let Value::Object(params) = &tool.parameters {
745                for (k, v) in params {
746                    if k != "type" && k != "properties" {
747                        spec.insert(k.clone(), v.clone());
748                    }
749                }
750            }
751            Value::Object(spec)
752        }
753        ToolKind::Function => json!({
754            "type": "function",
755            "name": tool.name,
756            "description": tool.description,
757            "parameters": tool.parameters,
758        }),
759    }
760}
761
762/// Build the Responses `web_search.user_location` object from a hosted-tool
763/// `user_location` parameter (`_responses_client.py:310-329`).
764fn user_location_to_responses(location: &Value) -> Value {
765    let mut loc = Map::new();
766    loc.insert("type".into(), json!("approximate"));
767    for key in ["city", "country", "region", "timezone"] {
768        if let Some(v) = location.get(key) {
769            loc.insert(key.into(), v.clone());
770        }
771    }
772    Value::Object(loc)
773}
774
775/// Build the Responses MCP `require_approval` value. A `parameters.approval_mode`
776/// override — either the string `"always_require"`/`"never_require"` or an
777/// object `{"always": [...], "never": [...]}` — takes precedence over the
778/// definition's [`ApprovalMode`]; mirrors `get_mcp_tool`
779/// (`_responses_client.py:365-386`).
780fn mcp_require_approval(tool: &ToolDefinition) -> Value {
781    use agent_framework_core::tools::ApprovalMode;
782    match tool.parameters.get("approval_mode") {
783        Some(Value::String(s)) => {
784            return json!(if s == "always_require" {
785                "always"
786            } else {
787                "never"
788            });
789        }
790        Some(Value::Object(modes)) => {
791            let mut req = Map::new();
792            if let Some(always) = modes.get("always") {
793                req.insert("always".into(), json!({ "tool_names": always }));
794            }
795            if let Some(never) = modes.get("never") {
796                req.insert("never".into(), json!({ "tool_names": never }));
797            }
798            if !req.is_empty() {
799                return Value::Object(req);
800            }
801        }
802        _ => {}
803    }
804    json!(match tool.approval_mode {
805        ApprovalMode::AlwaysRequire => "always",
806        ApprovalMode::NeverRequire => "never",
807    })
808}
809
810/// `pub` so `agent-framework-azure`'s Responses client can reuse this
811/// mapping rather than reimplementing it.
812pub fn tool_choice_to_responses(mode: &ToolMode) -> Value {
813    match mode {
814        ToolMode::Auto => json!("auto"),
815        ToolMode::None => json!("none"),
816        ToolMode::Required(Some(name)) => json!({ "type": "function", "name": name }),
817        ToolMode::Required(None) => json!("required"),
818    }
819}
820
821/// Convert a `ChatOptions::response_format` into a Responses API
822/// `text.format` object. Unlike Chat Completions (which nests the schema
823/// under `json_schema`), the Responses API uses a flat object.
824///
825/// `pub` so `agent-framework-azure`'s Responses client can reuse this
826/// mapping rather than reimplementing it.
827pub fn response_format_to_text(format: &ResponseFormat) -> Value {
828    match format {
829        ResponseFormat::Text => json!({ "type": "text" }),
830        ResponseFormat::JsonObject => json!({ "type": "json_object" }),
831        ResponseFormat::JsonSchema {
832            name,
833            description,
834            schema,
835            strict,
836        } => {
837            let mut obj = Map::new();
838            obj.insert("type".into(), json!("json_schema"));
839            obj.insert("name".into(), json!(name));
840            if let Some(d) = description {
841                obj.insert("description".into(), json!(d));
842            }
843            obj.insert("schema".into(), schema.clone());
844            if let Some(st) = strict {
845                obj.insert("strict".into(), json!(st));
846            }
847            Value::Object(obj)
848        }
849    }
850}
851
852// endregion
853
854// region: response conversion
855
856/// Parse a full (non-streaming) Responses API response.
857///
858/// Map a Responses body whose `status` is `"failed"` to a classified error,
859/// or `None` for a non-failed response. A failed run reports `status:
860/// "failed"` with a 2xx HTTP status, so the error is pulled from the body:
861/// `error.code == "content_filter"` becomes [`Error::ServiceContentFilter`]
862/// (matching the HTTP-level classification in `classify_service_error`),
863/// anything else a generic service error.
864///
865/// `pub` so `agent-framework-azure`'s Responses client can share the exact
866/// classification.
867pub fn response_failure_error(value: &Value) -> Option<Error> {
868    if value.get("status").and_then(Value::as_str) != Some("failed") {
869        return None;
870    }
871    let error = value.get("error");
872    let msg = error
873        .and_then(|e| e.get("message"))
874        .and_then(Value::as_str)
875        .unwrap_or("response failed")
876        .to_string();
877    let code = error.and_then(|e| e.get("code")).and_then(Value::as_str);
878    Some(match code {
879        Some("content_filter") => Error::service_content_filter(msg),
880        _ => Error::service(msg),
881    })
882}
883
884/// `pub` so `agent-framework-azure`'s Responses client (whose wire format is
885/// otherwise identical) can reuse this parser — including `parse_output_item`,
886/// `parse_annotations`, and usage/finish-reason handling — rather than
887/// reimplementing it.
888pub fn parse_response(value: &Value, store: Option<bool>) -> ChatResponse {
889    let mut response = ChatResponse {
890        response_id: value.get("id").and_then(Value::as_str).map(String::from),
891        model: value.get("model").and_then(Value::as_str).map(String::from),
892        ..Default::default()
893    };
894
895    let mut contents: Vec<Content> = Vec::new();
896    if let Some(items) = value.get("output").and_then(Value::as_array) {
897        for item in items {
898            parse_output_item(item, &mut contents);
899        }
900    }
901
902    let mut message = Message::with_contents(Role::assistant(), contents);
903    message.message_id = response.response_id.clone();
904    response.messages.push(message);
905
906    response.finish_reason = finish_reason_from_response(value);
907
908    if let Some(usage) = value.get("usage") {
909        response.usage_details = Some(parse_responses_usage(usage));
910    }
911    if store != Some(false) {
912        response.conversation_id = response.response_id.clone();
913    }
914    response
915}
916
917fn parse_output_item(item: &Value, contents: &mut Vec<Content>) {
918    match item.get("type").and_then(Value::as_str) {
919        Some("message") => {
920            if let Some(parts) = item.get("content").and_then(Value::as_array) {
921                for part in parts {
922                    match part.get("type").and_then(Value::as_str) {
923                        Some("output_text") => {
924                            if let Some(text) = part.get("text").and_then(Value::as_str) {
925                                let mut tc = TextContent::new(text);
926                                tc.annotations = parse_annotations(part);
927                                contents.push(Content::Text(tc));
928                            }
929                        }
930                        Some("refusal") => {
931                            if let Some(text) = part.get("refusal").and_then(Value::as_str) {
932                                // Marked, so `Message::text` withholds it
933                                // rather than presenting it as the answer.
934                                contents.push(Content::Text(TextContent::refusal(text)));
935                            }
936                        }
937                        _ => {}
938                    }
939                }
940            }
941        }
942        Some("function_call") => {
943            let call_id = item
944                .get("call_id")
945                .and_then(Value::as_str)
946                .unwrap_or_default()
947                .to_string();
948            let name = item
949                .get("name")
950                .and_then(Value::as_str)
951                .unwrap_or_default()
952                .to_string();
953            let args = item
954                .get("arguments")
955                .and_then(Value::as_str)
956                .unwrap_or("{}")
957                .to_string();
958            contents.push(Content::FunctionCall(FunctionCallContent::new(
959                call_id,
960                name,
961                Some(FunctionArguments::Raw(args)),
962            )));
963        }
964        Some("reasoning") => {
965            let summaries: Vec<String> = item
966                .get("summary")
967                .and_then(Value::as_array)
968                .map(|arr| {
969                    arr.iter()
970                        .filter_map(|s| s.get("text").and_then(Value::as_str))
971                        .map(str::to_string)
972                        .collect()
973                })
974                .unwrap_or_default();
975            // Preserve the raw reasoning item so a store:false tool-loop replay
976            // can re-send it verbatim — reasoning models require the original
977            // item (id + encrypted_content), not just the summary, on the
978            // follow-up turn. `messages_to_input` re-emits it from
979            // `raw_representation`; it is attached to exactly one content so a
980            // multi-summary item yields exactly one reasoning input item.
981            let raw = Some(item.clone());
982            if summaries.is_empty() {
983                // No summary (e.g. encrypted reasoning) — still carry the item.
984                contents.push(Content::TextReasoning(TextReasoningContent {
985                    text: String::new(),
986                    annotations: None,
987                    raw_representation: raw,
988                    protected_data: None,
989                }));
990            } else {
991                let n = summaries.len();
992                for (i, text) in summaries.into_iter().enumerate() {
993                    contents.push(Content::TextReasoning(TextReasoningContent {
994                        text,
995                        annotations: None,
996                        raw_representation: (i == n - 1).then(|| raw.clone()).flatten(),
997                        protected_data: None,
998                    }));
999                }
1000            }
1001        }
1002        // Code-interpreter runs surface `logs` as text and `image` outputs as
1003        // URIs; a bare `code` (no outputs) is a text fallback
1004        // (`_create_response_content:748-764`).
1005        Some("code_interpreter_call") => {
1006            let outputs = item
1007                .get("outputs")
1008                .and_then(Value::as_array)
1009                .filter(|a| !a.is_empty());
1010            if let Some(outputs) = outputs {
1011                for output in outputs {
1012                    match output.get("type").and_then(Value::as_str) {
1013                        Some("logs") => {
1014                            if let Some(logs) = output.get("logs").and_then(Value::as_str) {
1015                                contents.push(Content::Text(TextContent::new(logs)));
1016                            }
1017                        }
1018                        Some("image") => {
1019                            if let Some(url) = output.get("url").and_then(Value::as_str) {
1020                                contents.push(Content::Uri(UriContent {
1021                                    uri: url.to_string(),
1022                                    media_type: "image".to_string(),
1023                                }));
1024                            }
1025                        }
1026                        _ => {}
1027                    }
1028                }
1029            } else if let Some(code) = item.get("code").and_then(Value::as_str) {
1030                contents.push(Content::Text(TextContent::new(code)));
1031            }
1032        }
1033        // A generated image is returned as base64; default to image/png unless
1034        // the result is a data URI that states its own type
1035        // (`_create_response_content:788-811`).
1036        Some("image_generation_call") => {
1037            if let Some(result) = item.get("result").and_then(Value::as_str) {
1038                let (uri, media_type) = if result.starts_with("data:") {
1039                    let media_type = if result.contains(';') {
1040                        result
1041                            .strip_prefix("data:")
1042                            .and_then(|r| r.split(';').next())
1043                            .filter(|s| !s.is_empty())
1044                            .map(String::from)
1045                    } else {
1046                        None
1047                    };
1048                    (result.to_string(), media_type)
1049                } else {
1050                    (
1051                        format!("data:image/png;base64,{result}"),
1052                        Some("image/png".to_string()),
1053                    )
1054                };
1055                contents.push(Content::Data(DataContent { uri, media_type }));
1056            }
1057        }
1058        // An MCP approval request round-trips its `id` as the call id so a
1059        // later `FunctionApprovalResponse` refers back to it
1060        // (`_create_response_content:775-787`).
1061        Some("mcp_call") => contents.extend(mcp_call_item_contents(item)),
1062        Some("mcp_approval_request") => {
1063            let id = item
1064                .get("id")
1065                .and_then(Value::as_str)
1066                .unwrap_or_default()
1067                .to_string();
1068            let name = item
1069                .get("name")
1070                .and_then(Value::as_str)
1071                .unwrap_or_default()
1072                .to_string();
1073            let args = item
1074                .get("arguments")
1075                .and_then(Value::as_str)
1076                .unwrap_or("{}")
1077                .to_string();
1078            contents.push(Content::FunctionApprovalRequest(
1079                FunctionApprovalRequestContent {
1080                    id: id.clone(),
1081                    function_call: FunctionCallContent::new(
1082                        id,
1083                        name,
1084                        Some(FunctionArguments::Raw(args)),
1085                    ),
1086                },
1087            ));
1088        }
1089        _ => {}
1090    }
1091}
1092
1093/// Parse the `annotations` on an `output_text` part into [`Annotation`]s
1094/// (`_create_response_content:667-724`). The core annotation type has no free
1095/// `additional_properties`, so upstream's `index`/`container_id` extras are
1096/// dropped.
1097fn parse_annotations(part: &Value) -> Option<Vec<Annotation>> {
1098    let arr = part.get("annotations").and_then(Value::as_array)?;
1099    let mut out = Vec::new();
1100    for ann in arr {
1101        let str_field = |k: &str| ann.get(k).and_then(Value::as_str).map(String::from);
1102        let regions = || {
1103            Some(vec![TextSpanRegion {
1104                start_index: ann.get("start_index").and_then(Value::as_i64),
1105                end_index: ann.get("end_index").and_then(Value::as_i64),
1106            }])
1107        };
1108        match ann.get("type").and_then(Value::as_str) {
1109            Some("file_path") => out.push(Annotation {
1110                file_id: str_field("file_id"),
1111                ..Default::default()
1112            }),
1113            Some("file_citation") => out.push(Annotation {
1114                url: str_field("filename"),
1115                file_id: str_field("file_id"),
1116                ..Default::default()
1117            }),
1118            Some("url_citation") => out.push(Annotation {
1119                title: str_field("title"),
1120                url: str_field("url"),
1121                annotated_regions: regions(),
1122                ..Default::default()
1123            }),
1124            Some("container_file_citation") => out.push(Annotation {
1125                file_id: str_field("file_id"),
1126                url: str_field("filename"),
1127                annotated_regions: regions(),
1128                ..Default::default()
1129            }),
1130            _ => {}
1131        }
1132    }
1133    if out.is_empty() {
1134        None
1135    } else {
1136        Some(out)
1137    }
1138}
1139
1140fn finish_reason_from_response(value: &Value) -> Option<FinishReason> {
1141    let has_function_call = value
1142        .get("output")
1143        .and_then(Value::as_array)
1144        .map(|items| {
1145            items
1146                .iter()
1147                .any(|i| i.get("type").and_then(Value::as_str) == Some("function_call"))
1148        })
1149        .unwrap_or(false);
1150    if has_function_call {
1151        return Some(FinishReason::tool_calls());
1152    }
1153    let status = value.get("status").and_then(Value::as_str)?;
1154    Some(match status {
1155        "completed" => FinishReason::stop(),
1156        "incomplete" => match value
1157            .get("incomplete_details")
1158            .and_then(|d| d.get("reason"))
1159            .and_then(Value::as_str)
1160        {
1161            Some("max_output_tokens") => FinishReason::new(FinishReason::LENGTH),
1162            Some("content_filter") => FinishReason::new(FinishReason::CONTENT_FILTER),
1163            Some(other) => FinishReason::new(other),
1164            None => FinishReason::new("incomplete"),
1165        },
1166        other => FinishReason::new(other),
1167    })
1168}
1169
1170fn parse_responses_usage(usage: &Value) -> UsageDetails {
1171    let mut details = UsageDetails {
1172        input_token_count: usage.get("input_tokens").and_then(Value::as_u64),
1173        output_token_count: usage.get("output_tokens").and_then(Value::as_u64),
1174        total_token_count: usage.get("total_tokens").and_then(Value::as_u64),
1175        ..Default::default()
1176    };
1177    if let Some(cached) = usage
1178        .get("input_tokens_details")
1179        .and_then(|d| d.get("cached_tokens"))
1180        .and_then(Value::as_u64)
1181    {
1182        details
1183            .additional_counts
1184            .insert("openai.cached_input_tokens".into(), cached);
1185        // Mirror upstream: also surface as the typed, cross-language field.
1186        details.cache_read_input_token_count = Some(cached);
1187    }
1188    // Cache *writes* are reported separately from cache reads. Absent when the
1189    // provider does not report them (older API versions).
1190    if let Some(cache_write) = usage
1191        .get("input_tokens_details")
1192        .and_then(|d| d.get("cache_write_tokens"))
1193        .and_then(Value::as_u64)
1194    {
1195        details
1196            .additional_counts
1197            .insert("openai.cache_write_tokens".into(), cache_write);
1198        details.cache_creation_input_token_count = Some(cache_write);
1199    }
1200    if let Some(reasoning) = usage
1201        .get("output_tokens_details")
1202        .and_then(|d| d.get("reasoning_tokens"))
1203        .and_then(Value::as_u64)
1204    {
1205        details
1206            .additional_counts
1207            .insert("openai.reasoning_tokens".into(), reasoning);
1208        details.reasoning_output_token_count = Some(reasoning);
1209    }
1210    details
1211}
1212
1213// endregion
1214
1215// region: streaming
1216
1217/// Turn a Responses API SSE HTTP response into a stream of updates.
1218///
1219/// `pub` so `agent-framework-azure`'s Responses client can reuse this exact
1220/// SSE event parser (Azure OpenAI's Responses API streams the same event
1221/// shapes) rather than reimplementing it.
1222pub fn parse_responses_sse_stream(
1223    resp: reqwest::Response,
1224    store: Option<bool>,
1225) -> impl futures::Stream<Item = Result<ChatResponseUpdate>> + Send {
1226    let byte_stream: ByteStream = Box::pin(resp.bytes_stream());
1227    futures::stream::unfold(
1228        ResponsesSseState {
1229            byte_stream,
1230            buffer: String::new(),
1231            utf8: Utf8StreamDecoder::new(),
1232            queued: VecDeque::new(),
1233            call_ids: HashMap::new(),
1234            done: false,
1235            store,
1236        },
1237        |mut state| async move {
1238            loop {
1239                if let Some(update) = state.queued.pop_front() {
1240                    return Some((Ok(update), state));
1241                }
1242                if state.done {
1243                    return None;
1244                }
1245                match state.byte_stream.next().await {
1246                    Some(Ok(bytes)) => {
1247                        let decoded = state.utf8.push(&bytes);
1248                        state.buffer.push_str(&decoded);
1249                        while let Some(pos) = state.buffer.find('\n') {
1250                            let line = state.buffer[..pos].trim().to_string();
1251                            state.buffer.drain(..=pos);
1252                            let Some(data) = line.strip_prefix("data:") else {
1253                                continue;
1254                            };
1255                            let data = data.trim();
1256                            if data.is_empty() {
1257                                continue;
1258                            }
1259                            let Ok(value) = serde_json::from_str::<Value>(data) else {
1260                                continue;
1261                            };
1262                            match parse_responses_event(&value, &mut state.call_ids, state.store) {
1263                                EventOutcome::Update(update) => state.queued.push_back(update),
1264                                EventOutcome::Error(e) => {
1265                                    state.done = true;
1266                                    return Some((Err(e), state));
1267                                }
1268                                EventOutcome::None => {}
1269                            }
1270                        }
1271                    }
1272                    Some(Err(e)) => {
1273                        state.done = true;
1274                        return Some((Err(Error::service(format!("stream error: {e}"))), state));
1275                    }
1276                    None => return None,
1277                }
1278            }
1279        },
1280    )
1281}
1282
1283struct ResponsesSseState {
1284    byte_stream: ByteStream,
1285    buffer: String,
1286    utf8: Utf8StreamDecoder,
1287    queued: VecDeque<ChatResponseUpdate>,
1288    /// `output_index` -> `call_id`, resolved when the call is first announced
1289    /// via `response.output_item.added` and used to route later
1290    /// `response.function_call_arguments.delta` fragments.
1291    call_ids: HashMap<i64, String>,
1292    done: bool,
1293    store: Option<bool>,
1294}
1295
1296// A transient control-flow value: produced per SSE event and immediately
1297// destructured in the stream loop, never stored in bulk. Boxing the `Update`
1298// variant to equalize sizes would add a heap allocation on every streamed
1299// token, so the size skew is accepted here.
1300#[allow(clippy::large_enum_variant)]
1301enum EventOutcome {
1302    Update(ChatResponseUpdate),
1303    Error(Error),
1304    None,
1305}
1306
1307/// Wrap streamed reasoning text as a [`TextReasoningContent`] update, or
1308/// [`EventOutcome::None`] when empty.
1309fn reasoning_update(text: &str) -> EventOutcome {
1310    if text.is_empty() {
1311        return EventOutcome::None;
1312    }
1313    EventOutcome::Update(ChatResponseUpdate {
1314        contents: vec![Content::TextReasoning(TextReasoningContent {
1315            text: text.to_string(),
1316            annotations: None,
1317            ..Default::default()
1318        })],
1319        role: Some(Role::assistant()),
1320        ..Default::default()
1321    })
1322}
1323
1324/// Parse one Responses API SSE event (already-decoded JSON `data:` payload).
1325fn parse_responses_event(
1326    value: &Value,
1327    call_ids: &mut HashMap<i64, String>,
1328    store: Option<bool>,
1329) -> EventOutcome {
1330    let event_type = value.get("type").and_then(Value::as_str).unwrap_or("");
1331    match event_type {
1332        "response.created" => {
1333            let resp = value.get("response");
1334            let response_id = resp
1335                .and_then(|r| r.get("id"))
1336                .and_then(Value::as_str)
1337                .map(String::from);
1338            let model = resp
1339                .and_then(|r| r.get("model"))
1340                .and_then(Value::as_str)
1341                .map(String::from);
1342            if response_id.is_none() && model.is_none() {
1343                return EventOutcome::None;
1344            }
1345            EventOutcome::Update(ChatResponseUpdate {
1346                role: Some(Role::assistant()),
1347                response_id,
1348                model,
1349                ..Default::default()
1350            })
1351        }
1352        "response.output_text.delta" => {
1353            let text = value.get("delta").and_then(Value::as_str).unwrap_or("");
1354            if text.is_empty() {
1355                return EventOutcome::None;
1356            }
1357            EventOutcome::Update(ChatResponseUpdate {
1358                contents: vec![Content::Text(TextContent::new(text))],
1359                role: Some(Role::assistant()),
1360                ..Default::default()
1361            })
1362        }
1363        // A refusal streams on its own channel. Only the incremental `.delta`
1364        // is consumed: the terminal `response.refusal.done` repeats the whole
1365        // refusal, which aggregation would append to the fragments already
1366        // collected, doubling it — the same reason the text channel above
1367        // does not consume its `.done`. Dropping these events entirely, as
1368        // this parser used to, let a streamed decline reach the caller as an
1369        // empty response.
1370        "response.refusal.delta" => {
1371            let text = value.get("delta").and_then(Value::as_str).unwrap_or("");
1372            if text.is_empty() {
1373                return EventOutcome::None;
1374            }
1375            EventOutcome::Update(ChatResponseUpdate {
1376                contents: vec![Content::Text(TextContent::refusal(text))],
1377                role: Some(Role::assistant()),
1378                ..Default::default()
1379            })
1380        }
1381        // Reasoning (chain-of-thought / summary) streams as its own text
1382        // channel. Both the incremental `.delta` and the terminal `.done`
1383        // (full text) map to `TextReasoningContent`, mirroring upstream
1384        // `_create_streaming_response_content` (`_responses_client.py:917-928`).
1385        "response.reasoning_text.delta" | "response.reasoning_summary_text.delta" => {
1386            reasoning_update(value.get("delta").and_then(Value::as_str).unwrap_or(""))
1387        }
1388        // `.done` carries the *full* completed text, not another increment —
1389        // the deltas above already streamed it, so emitting it again would
1390        // duplicate the reasoning in the aggregated response (adjacent
1391        // reasoning contents coalesce by appending). Treated as terminal
1392        // metadata, like `response.output_text.done`.
1393        "response.reasoning_text.done" | "response.reasoning_summary_text.done" => {
1394            EventOutcome::None
1395        }
1396        "response.output_item.added" => {
1397            let item = value.get("item");
1398            let item_type = item.and_then(|i| i.get("type")).and_then(Value::as_str);
1399            // A hosted MCP call is emitted whole from `done` (below): on
1400            // `added` its arguments are still empty and only stream in
1401            // through `response.mcp_call_arguments.*`, so a call recorded
1402            // here would replay with `{}` arguments.
1403            if item_type != Some("function_call") {
1404                return EventOutcome::None;
1405            }
1406            let output_index = value
1407                .get("output_index")
1408                .and_then(Value::as_i64)
1409                .unwrap_or(0);
1410            let call_id = item
1411                .and_then(|i| i.get("call_id"))
1412                .and_then(Value::as_str)
1413                .unwrap_or_default()
1414                .to_string();
1415            let name = item
1416                .and_then(|i| i.get("name"))
1417                .and_then(Value::as_str)
1418                .unwrap_or_default()
1419                .to_string();
1420            call_ids.insert(output_index, call_id.clone());
1421            EventOutcome::Update(ChatResponseUpdate {
1422                contents: vec![Content::FunctionCall(FunctionCallContent::new(
1423                    call_id, name, None,
1424                ))],
1425                role: Some(Role::assistant()),
1426                ..Default::default()
1427            })
1428        }
1429        "response.function_call_arguments.delta" => {
1430            let output_index = value
1431                .get("output_index")
1432                .and_then(Value::as_i64)
1433                .unwrap_or(0);
1434            let delta = value.get("delta").and_then(Value::as_str).unwrap_or("");
1435            match call_ids.get(&output_index) {
1436                Some(call_id) => EventOutcome::Update(ChatResponseUpdate {
1437                    contents: vec![Content::FunctionCall(FunctionCallContent::new(
1438                        call_id.clone(),
1439                        "",
1440                        Some(FunctionArguments::Raw(delta.to_string())),
1441                    ))],
1442                    role: Some(Role::assistant()),
1443                    ..Default::default()
1444                }),
1445                None => EventOutcome::None,
1446            }
1447        }
1448        // `response.incomplete` is the terminal event for a turn cut off by
1449        // the content filter or the token budget — the same payload as
1450        // `response.completed`, under a name that says it did not finish.
1451        // Handled here rather than ignored, or a truncated or filtered
1452        // stream would lose its finish reason, usage and response id
1453        // entirely, which is exactly the information the distinct event
1454        // name exists to deliver.
1455        "response.completed" | "response.incomplete" => {
1456            let resp = value.get("response");
1457            let response_id = resp
1458                .and_then(|r| r.get("id"))
1459                .and_then(Value::as_str)
1460                .map(String::from);
1461            let model = resp
1462                .and_then(|r| r.get("model"))
1463                .and_then(Value::as_str)
1464                .map(String::from);
1465            let mut contents = Vec::new();
1466            if let Some(usage) = resp.and_then(|r| r.get("usage")) {
1467                contents.push(Content::Usage(UsageContent {
1468                    details: parse_responses_usage(usage),
1469                }));
1470            }
1471            let finish_reason = resp.and_then(finish_reason_from_response);
1472            let conversation_id = if store != Some(false) {
1473                response_id.clone()
1474            } else {
1475                None
1476            };
1477            EventOutcome::Update(ChatResponseUpdate {
1478                contents,
1479                role: Some(Role::assistant()),
1480                response_id,
1481                model,
1482                conversation_id,
1483                finish_reason,
1484                ..Default::default()
1485            })
1486        }
1487        "response.failed" | "error" => {
1488            let resp = value.get("response");
1489            let err_obj = resp
1490                .and_then(|r| r.get("error"))
1491                .or_else(|| value.get("error"));
1492            let msg = err_obj
1493                .and_then(|e| e.get("message"))
1494                .and_then(Value::as_str)
1495                .unwrap_or("response failed")
1496                .to_string();
1497            // Same classification as the non-streaming `response_failure_error`
1498            // so callers branching on content filters see one behavior for
1499            // streamed and non-streamed Responses.
1500            let code = err_obj.and_then(|e| e.get("code")).and_then(Value::as_str);
1501            EventOutcome::Error(match code {
1502                Some("content_filter") => Error::service_content_filter(msg),
1503                _ => Error::service(msg),
1504            })
1505        }
1506        "response.output_item.done" => {
1507            let Some(item) = value
1508                .get("item")
1509                .filter(|i| i.get("type").and_then(Value::as_str) == Some("mcp_call"))
1510            else {
1511                return EventOutcome::None;
1512            };
1513            // The completed item carries the final arguments and the
1514            // output or error, so the call and its result come from here.
1515            EventOutcome::Update(ChatResponseUpdate {
1516                contents: mcp_call_item_contents(item),
1517                role: Some(Role::assistant()),
1518                ..Default::default()
1519            })
1520        }
1521        // Recognized but carry no additional content: the arguments are
1522        // already fully accumulated via `.delta` events, and item/part
1523        // lifecycle markers don't themselves map to a `Content`.
1524        "response.function_call_arguments.done"
1525        | "response.mcp_call_arguments.delta"
1526        | "response.mcp_call_arguments.done"
1527        | "response.content_part.added"
1528        | "response.content_part.done"
1529        | "response.in_progress" => EventOutcome::None,
1530        _ => EventOutcome::None,
1531    }
1532}
1533
1534// endregion
1535
1536#[cfg(test)]
1537mod tests {
1538    use super::*;
1539    use agent_framework_core::tools::{ApprovalMode, ToolDefinition, ToolKind};
1540    use agent_framework_core::types::{
1541        FunctionApprovalResponseContent, FunctionResultContent, HostedFileContent,
1542    };
1543
1544    fn user(text: &str) -> Message {
1545        Message::user(text)
1546    }
1547
1548    fn user_with(contents: Vec<Content>) -> Message {
1549        Message::with_contents(Role::user(), contents)
1550    }
1551
1552    /// Parse a single Responses output item into its content list.
1553    fn parse_item(item: Value) -> Vec<Content> {
1554        let mut contents = Vec::new();
1555        parse_output_item(&item, &mut contents);
1556        contents
1557    }
1558
1559    fn client() -> OpenAIChatClient {
1560        OpenAIChatClient::new("test-key", "gpt-4o-mini")
1561    }
1562
1563    // region: request body building
1564
1565    #[test]
1566    fn build_body_simple_text() {
1567        let c = client();
1568        let body = c.build_body(&[user("Hello there")], &ChatOptions::new(), false);
1569        assert_eq!(
1570            body,
1571            json!({
1572                "model": "gpt-4o-mini",
1573                "input": [
1574                    { "type": "message", "role": "user", "content": [
1575                        { "type": "input_text", "text": "Hello there" }
1576                    ]}
1577                ],
1578                // Nothing is stored service-side on this request, so the
1579                // encrypted reasoning item is requested for the replay path.
1580                "include": ["reasoning.encrypted_content"],
1581            })
1582        );
1583    }
1584
1585    #[test]
1586    fn responses_usage_parses_cache_write_tokens() {
1587        // Cache *writes* are reported separately from cache reads (upstream #7369).
1588        let d = parse_responses_usage(&json!({
1589            "input_tokens": 2000,
1590            "output_tokens": 60,
1591            "total_tokens": 2060,
1592            "input_tokens_details": { "cached_tokens": 0, "cache_write_tokens": 1024 },
1593        }));
1594        assert_eq!(d.cache_creation_input_token_count, Some(1024));
1595        assert_eq!(d.cache_read_input_token_count, Some(0));
1596        assert_eq!(
1597            d.additional_counts.get("openai.cache_write_tokens"),
1598            Some(&1024)
1599        );
1600    }
1601
1602    #[test]
1603    fn responses_usage_omits_cache_write_tokens_when_not_reported() {
1604        let d = parse_responses_usage(&json!({
1605            "input_tokens": 100,
1606            "output_tokens": 20,
1607            "input_tokens_details": { "cached_tokens": 40 },
1608        }));
1609        assert_eq!(d.cache_creation_input_token_count, None);
1610        assert!(!d
1611            .additional_counts
1612            .contains_key("openai.cache_write_tokens"));
1613    }
1614
1615    #[test]
1616    fn build_body_extracts_leading_system_message_as_instructions() {
1617        let c = client();
1618        let messages = vec![Message::system("Be terse."), user("Hi")];
1619        let body = c.build_body(&messages, &ChatOptions::new(), false);
1620        assert_eq!(body["instructions"], json!("Be terse."));
1621        assert_eq!(
1622            body["input"],
1623            json!([
1624                { "type": "message", "role": "user", "content": [
1625                    { "type": "input_text", "text": "Hi" }
1626                ]}
1627            ])
1628        );
1629    }
1630
1631    #[test]
1632    fn build_body_combines_options_instructions_and_system_message() {
1633        let c = client();
1634        let messages = vec![Message::system("Also be nice."), user("Hi")];
1635        let options = ChatOptions::new().with_instructions("Be terse.");
1636        let body = c.build_body(&messages, &options, false);
1637        assert_eq!(body["instructions"], json!("Be terse.\n\nAlso be nice."));
1638    }
1639
1640    #[test]
1641    fn build_body_assistant_text_uses_output_text_type() {
1642        let c = client();
1643        let messages = vec![user("Hi"), Message::assistant("Hello!")];
1644        let body = c.build_body(&messages, &ChatOptions::new(), false);
1645        assert_eq!(
1646            body["input"][1],
1647            json!({ "type": "message", "role": "assistant", "content": [
1648                { "type": "output_text", "text": "Hello!" }
1649            ]})
1650        );
1651    }
1652
1653    #[test]
1654    fn build_body_function_call_round_trip() {
1655        let c = client();
1656        let call = FunctionCallContent::new(
1657            "call_1",
1658            "get_weather",
1659            Some(FunctionArguments::Raw(r#"{"city":"Paris"}"#.to_string())),
1660        );
1661        let assistant_msg =
1662            Message::with_contents(Role::assistant(), vec![Content::FunctionCall(call)]);
1663        let tool_msg = Message::with_contents(
1664            Role::tool(),
1665            vec![Content::FunctionResult(FunctionResultContent::new(
1666                "call_1",
1667                Some(json!("18C and sunny")),
1668            ))],
1669        );
1670        let body = c.build_body(
1671            &[user("weather?"), assistant_msg, tool_msg],
1672            &ChatOptions::new(),
1673            false,
1674        );
1675        assert_eq!(
1676            body["input"],
1677            json!([
1678                { "type": "message", "role": "user", "content": [
1679                    { "type": "input_text", "text": "weather?" }
1680                ]},
1681                { "type": "function_call", "call_id": "call_1", "name": "get_weather", "arguments": "{\"city\":\"Paris\"}" },
1682                { "type": "function_call_output", "call_id": "call_1", "output": "18C and sunny" },
1683            ])
1684        );
1685    }
1686
1687    #[test]
1688    fn build_body_tools_are_flat_not_nested() {
1689        let c = client();
1690        let tool = ToolDefinition {
1691            name: "get_weather".into(),
1692            description: "Get the weather".into(),
1693            parameters: json!({ "type": "object", "properties": {} }),
1694            kind: ToolKind::Function,
1695            approval_mode: ApprovalMode::NeverRequire,
1696            executor: None,
1697        };
1698        let options = ChatOptions::new().with_tool(tool);
1699        let body = c.build_body(&[user("hi")], &options, false);
1700        assert_eq!(
1701            body["tools"],
1702            json!([{
1703                "type": "function",
1704                "name": "get_weather",
1705                "description": "Get the weather",
1706                "parameters": { "type": "object", "properties": {} },
1707            }])
1708        );
1709    }
1710
1711    #[test]
1712    fn build_body_tool_choice_required_named() {
1713        let c = client();
1714        let options =
1715            ChatOptions::new().with_tool_choice(ToolMode::Required(Some("get_weather".into())));
1716        let body = c.build_body(&[user("hi")], &options, false);
1717        assert_eq!(
1718            body["tool_choice"],
1719            json!({ "type": "function", "name": "get_weather" })
1720        );
1721    }
1722
1723    #[test]
1724    fn stateless_request_asks_for_the_encrypted_reasoning_item() {
1725        // A reasoning item is only replayable on the next turn if it carries
1726        // `encrypted_content`, and the service only returns that when asked.
1727        let c = client();
1728        let body = c.build_body(&[user("hi")], &ChatOptions::new(), false);
1729        assert_eq!(body["include"], json!(["reasoning.encrypted_content"]));
1730    }
1731
1732    #[test]
1733    fn a_service_side_conversation_needs_no_encrypted_reasoning() {
1734        // The service already holds the reasoning item, so echoing it back is
1735        // pointless — and upstream keys this off the storage indicators, not
1736        // off `store`.
1737        let mut options = ChatOptions::new();
1738        options.conversation_id = Some("resp_abc123".into());
1739        let body = client().build_body(&[user("hi")], &options, false);
1740        assert!(
1741            body.get("include").is_none(),
1742            "no include expected, got: {}",
1743            body
1744        );
1745    }
1746
1747    #[test]
1748    fn an_empty_conversation_id_is_not_service_side_storage() {
1749        // An empty id is no id: it would not continue anything server-side, so
1750        // the request is still stateless and still needs the item echoed back.
1751        let mut options = ChatOptions::new();
1752        options.conversation_id = Some(String::new());
1753        let body = client().build_body(&[user("hi")], &options, false);
1754        assert_eq!(body["include"], json!(["reasoning.encrypted_content"]));
1755    }
1756
1757    #[test]
1758    fn a_callers_own_include_entries_survive_and_are_not_duplicated() {
1759        // The caller's entries are preserved alongside the implicit one...
1760        let mut options = ChatOptions::new();
1761        options
1762            .additional_properties
1763            .insert("include".into(), json!(["file_search_call.results"]));
1764        let body = client().build_body(&[user("hi")], &options, false);
1765        assert_eq!(
1766            body["include"],
1767            json!(["file_search_call.results", "reasoning.encrypted_content"])
1768        );
1769
1770        // ...and asking for the encrypted item by name does not get it twice.
1771        let mut options = ChatOptions::new();
1772        options
1773            .additional_properties
1774            .insert("include".into(), json!(["reasoning.encrypted_content"]));
1775        let body = client().build_body(&[user("hi")], &options, false);
1776        assert_eq!(body["include"], json!(["reasoning.encrypted_content"]));
1777    }
1778
1779    #[test]
1780    fn an_explicit_empty_include_is_omitted_not_sent_as_an_empty_array() {
1781        // `responses_include` drops an empty array, and the
1782        // `additional_properties` pass must not put it back: `include` is
1783        // that function's alone. Reached here via a stored conversation, which
1784        // suppresses the implicit entry that would otherwise fill the array.
1785        let mut options = ChatOptions::new();
1786        options.conversation_id = Some("resp_abc123".into());
1787        options
1788            .additional_properties
1789            .insert("include".into(), json!([]));
1790        let body = client().build_body(&[user("hi")], &options, false);
1791        assert!(
1792            body.get("include").is_none(),
1793            "an empty include should be omitted entirely, got: {}",
1794            body
1795        );
1796    }
1797
1798    #[test]
1799    fn other_additional_properties_still_pass_through() {
1800        // Only `include` is intercepted; everything else the caller sets still
1801        // reaches the body.
1802        let mut options = ChatOptions::new();
1803        options
1804            .additional_properties
1805            .insert("safety_identifier".into(), json!("user-123"));
1806        let body = client().build_body(&[user("hi")], &options, false);
1807        assert_eq!(body["safety_identifier"], json!("user-123"));
1808    }
1809
1810    #[test]
1811    fn build_body_conversation_id_becomes_previous_response_id() {
1812        let c = client();
1813        let mut options = ChatOptions::new();
1814        options.conversation_id = Some("resp_abc123".into());
1815        let body = c.build_body(&[user("hi")], &options, false);
1816        assert_eq!(body["previous_response_id"], json!("resp_abc123"));
1817    }
1818
1819    #[test]
1820    fn build_body_max_tokens_becomes_max_output_tokens() {
1821        let c = client();
1822        let options = ChatOptions::new().with_max_tokens(256);
1823        let body = c.build_body(&[user("hi")], &options, false);
1824        assert_eq!(body["max_output_tokens"], json!(256));
1825        assert!(body.get("max_tokens").is_none());
1826    }
1827
1828    #[test]
1829    fn build_body_response_format_becomes_text_format() {
1830        let c = client();
1831        let mut options = ChatOptions::new();
1832        options.response_format = Some(ResponseFormat::JsonSchema {
1833            name: "answer".into(),
1834            description: None,
1835            schema: json!({"type": "object"}),
1836            strict: Some(true),
1837        });
1838        let body = c.build_body(&[user("hi")], &options, false);
1839        assert_eq!(
1840            body["text"]["format"],
1841            json!({ "type": "json_schema", "name": "answer", "schema": {"type": "object"}, "strict": true })
1842        );
1843    }
1844
1845    #[test]
1846    fn build_body_stream_flag() {
1847        let c = client();
1848        let body = c.build_body(&[user("hi")], &ChatOptions::new(), true);
1849        assert_eq!(body["stream"], json!(true));
1850    }
1851
1852    // endregion
1853
1854    // region: response parsing
1855
1856    #[test]
1857    fn parse_response_text_and_usage() {
1858        let value = json!({
1859            "id": "resp_123",
1860            "model": "gpt-4o-mini",
1861            "status": "completed",
1862            "output": [
1863                { "type": "message", "role": "assistant", "content": [
1864                    { "type": "output_text", "text": "Hello!" }
1865                ]}
1866            ],
1867            "usage": { "input_tokens": 10, "output_tokens": 5, "total_tokens": 15 },
1868        });
1869        let resp = parse_response(&value, None);
1870        assert_eq!(resp.response_id.as_deref(), Some("resp_123"));
1871        assert_eq!(resp.conversation_id.as_deref(), Some("resp_123"));
1872        assert_eq!(resp.text(), "Hello!");
1873        assert_eq!(resp.finish_reason, Some(FinishReason::stop()));
1874        let usage = resp.usage_details.unwrap();
1875        assert_eq!(usage.input_token_count, Some(10));
1876        assert_eq!(usage.output_token_count, Some(5));
1877        assert_eq!(usage.total_token_count, Some(15));
1878    }
1879
1880    #[test]
1881    fn parse_response_store_false_omits_conversation_id() {
1882        let value = json!({
1883            "id": "resp_123",
1884            "status": "completed",
1885            "output": [],
1886        });
1887        let resp = parse_response(&value, Some(false));
1888        assert_eq!(resp.conversation_id, None);
1889    }
1890
1891    #[test]
1892    fn parse_response_function_call_sets_tool_calls_finish_reason() {
1893        let value = json!({
1894            "id": "resp_123",
1895            "status": "completed",
1896            "output": [
1897                { "type": "function_call", "call_id": "call_1", "name": "get_weather", "arguments": "{\"city\":\"Paris\"}" }
1898            ],
1899        });
1900        let resp = parse_response(&value, None);
1901        assert_eq!(resp.finish_reason, Some(FinishReason::tool_calls()));
1902        let calls = resp.function_calls();
1903        assert_eq!(calls.len(), 1);
1904        assert_eq!(calls[0].call_id, "call_1");
1905        assert_eq!(calls[0].name, "get_weather");
1906    }
1907
1908    #[test]
1909    fn parse_response_incomplete_max_output_tokens_is_length() {
1910        let value = json!({
1911            "id": "resp_123",
1912            "status": "incomplete",
1913            "incomplete_details": { "reason": "max_output_tokens" },
1914            "output": [],
1915        });
1916        let resp = parse_response(&value, None);
1917        assert_eq!(
1918            resp.finish_reason,
1919            Some(FinishReason::new(FinishReason::LENGTH))
1920        );
1921    }
1922
1923    /// `response.incomplete` is the terminal event for a stream cut off by
1924    /// the content filter or the token budget. Ignoring it — which this
1925    /// did — dropped the finish reason, usage and response id for exactly
1926    /// the streams whose distinct event name exists to report them, and
1927    /// left a client unable to tell a truncated answer from a complete one.
1928    #[test]
1929    fn a_streamed_response_incomplete_carries_its_terminal_metadata() {
1930        let mut call_ids = HashMap::new();
1931        let event = json!({
1932            "type": "response.incomplete",
1933            "response": {
1934                "id": "resp_123",
1935                "model": "gpt-4o",
1936                "status": "incomplete",
1937                "incomplete_details": { "reason": "content_filter" },
1938                "output": [],
1939                "usage": { "input_tokens": 3, "output_tokens": 5, "total_tokens": 8 },
1940            },
1941        });
1942        let EventOutcome::Update(update) = parse_responses_event(&event, &mut call_ids, None)
1943        else {
1944            panic!("response.incomplete must produce a terminal update");
1945        };
1946        assert_eq!(
1947            update.finish_reason,
1948            Some(FinishReason::new(FinishReason::CONTENT_FILTER))
1949        );
1950        assert_eq!(update.response_id.as_deref(), Some("resp_123"));
1951        assert_eq!(update.model.as_deref(), Some("gpt-4o"));
1952        let usage = update
1953            .contents
1954            .iter()
1955            .find_map(|c| match c {
1956                Content::Usage(u) => Some(&u.details),
1957                _ => None,
1958            })
1959            .expect("usage rides the terminal update");
1960        assert_eq!(usage.input_token_count, Some(3));
1961        assert_eq!(usage.output_token_count, Some(5));
1962    }
1963
1964    /// And a `response.completed` is unchanged by sharing the arm.
1965    #[test]
1966    fn a_streamed_response_completed_still_carries_its_metadata() {
1967        let mut call_ids = HashMap::new();
1968        let event = json!({
1969            "type": "response.completed",
1970            "response": {
1971                "id": "resp_456",
1972                "status": "completed",
1973                "output": [],
1974            },
1975        });
1976        let EventOutcome::Update(update) = parse_responses_event(&event, &mut call_ids, None)
1977        else {
1978            panic!("response.completed produces a terminal update");
1979        };
1980        assert_eq!(update.finish_reason, Some(FinishReason::stop()));
1981        assert_eq!(update.response_id.as_deref(), Some("resp_456"));
1982    }
1983
1984    #[test]
1985    fn parse_response_reasoning_becomes_text_reasoning() {
1986        let value = json!({
1987            "id": "resp_123",
1988            "status": "completed",
1989            "output": [
1990                { "type": "reasoning", "summary": [{ "type": "summary_text", "text": "thinking..." }] },
1991                { "type": "message", "role": "assistant", "content": [{ "type": "output_text", "text": "done" }] },
1992            ],
1993        });
1994        let resp = parse_response(&value, None);
1995        let contents = &resp.messages[0].contents;
1996        assert!(matches!(&contents[0], Content::TextReasoning(t) if t.text == "thinking..."));
1997        assert!(matches!(&contents[1], Content::Text(t) if t.text == "done"));
1998    }
1999
2000    #[test]
2001    fn reasoning_item_round_trips_through_input_for_store_false_replay() {
2002        // A store:false tool-loop replay must re-send the original reasoning
2003        // item (id + encrypted_content), not just its summary text.
2004        let reasoning_item = json!({
2005            "type": "reasoning",
2006            "id": "rs_abc",
2007            "encrypted_content": "ENC",
2008            "summary": [{ "type": "summary_text", "text": "thinking..." }],
2009        });
2010        let value = json!({
2011            "id": "resp_1",
2012            "status": "completed",
2013            "output": [
2014                reasoning_item,
2015                { "type": "function_call", "call_id": "c1", "name": "f", "arguments": "{}" },
2016            ],
2017        });
2018        let resp = parse_response(&value, Some(false));
2019        // The parsed reasoning content preserves the raw item.
2020        let reasoning = resp.messages[0]
2021            .contents
2022            .iter()
2023            .find_map(|c| match c {
2024                Content::TextReasoning(t) => Some(t),
2025                _ => None,
2026            })
2027            .expect("reasoning content");
2028        assert_eq!(
2029            reasoning.raw_representation.as_ref().unwrap()["id"],
2030            "rs_abc"
2031        );
2032
2033        // Replaying that assistant message back through the input mapper
2034        // re-emits the reasoning item verbatim, ahead of the function call.
2035        let input = messages_to_input(&resp.messages);
2036        let reasoning_pos = input
2037            .iter()
2038            .position(|i| i.get("type") == Some(&json!("reasoning")))
2039            .expect("reasoning item re-emitted");
2040        assert_eq!(input[reasoning_pos]["id"], "rs_abc");
2041        assert_eq!(input[reasoning_pos]["encrypted_content"], "ENC");
2042        let call_pos = input
2043            .iter()
2044            .position(|i| i.get("type") == Some(&json!("function_call")))
2045            .expect("function call present");
2046        assert!(reasoning_pos < call_pos, "reasoning must precede the call");
2047    }
2048
2049    #[test]
2050    fn summary_only_reasoning_is_not_re_emitted_as_input() {
2051        // A reasoning content with no preserved raw item (e.g. from streaming
2052        // display) has no valid input form and must be dropped, not sent as a
2053        // bogus reasoning item lacking id/encrypted_content.
2054        let msg = Message::with_contents(
2055            Role::assistant(),
2056            vec![Content::TextReasoning(TextReasoningContent {
2057                text: "just display".into(),
2058                annotations: None,
2059                raw_representation: None,
2060                protected_data: None,
2061            })],
2062        );
2063        let input = messages_to_input(&[msg]);
2064        assert!(input
2065            .iter()
2066            .all(|i| i.get("type") != Some(&json!("reasoning"))));
2067    }
2068
2069    // endregion
2070
2071    // region: streaming
2072
2073    fn sse_body(events: &[(&str, Value)]) -> String {
2074        let mut out = String::new();
2075        for (event, data) in events {
2076            out.push_str(&format!("event: {event}\ndata: {}\n\n", data));
2077        }
2078        out
2079    }
2080
2081    async fn collect_updates(text: String) -> Vec<ChatResponseUpdate> {
2082        // Build a fake reqwest::Response backed by the given SSE text using a
2083        // tiny local HTTP server would be overkill; instead we drive the
2084        // event parser directly through the same state machine by feeding
2085        // the byte stream via `futures::stream::once`.
2086        let stream =
2087            futures::stream::once(async move { Ok::<_, reqwest::Error>(bytes::Bytes::from(text)) });
2088        let byte_stream: ByteStream = Box::pin(stream);
2089        let mut state = ResponsesSseState {
2090            byte_stream,
2091            buffer: String::new(),
2092            utf8: Utf8StreamDecoder::new(),
2093            queued: VecDeque::new(),
2094            call_ids: HashMap::new(),
2095            done: false,
2096            store: None,
2097        };
2098        let mut updates = Vec::new();
2099        // Drain the single chunk manually (mirrors the real unfold body).
2100        if let Some(Ok(bytes)) = state.byte_stream.next().await {
2101            let decoded = state.utf8.push(&bytes);
2102            state.buffer.push_str(&decoded);
2103            while let Some(pos) = state.buffer.find('\n') {
2104                let line = state.buffer[..pos].trim().to_string();
2105                state.buffer.drain(..=pos);
2106                let Some(data) = line.strip_prefix("data:") else {
2107                    continue;
2108                };
2109                let data = data.trim();
2110                if data.is_empty() {
2111                    continue;
2112                }
2113                let value: Value = serde_json::from_str(data).unwrap();
2114                if let EventOutcome::Update(u) =
2115                    parse_responses_event(&value, &mut state.call_ids, state.store)
2116                {
2117                    updates.push(u);
2118                }
2119            }
2120        }
2121        updates
2122    }
2123
2124    #[tokio::test]
2125    async fn stream_text_only_accumulates() {
2126        let text = sse_body(&[
2127            (
2128                "response.created",
2129                json!({ "type": "response.created", "response": { "id": "resp_1", "model": "gpt-4o-mini" } }),
2130            ),
2131            (
2132                "response.output_text.delta",
2133                json!({ "type": "response.output_text.delta", "delta": "Hel" }),
2134            ),
2135            (
2136                "response.output_text.delta",
2137                json!({ "type": "response.output_text.delta", "delta": "lo!" }),
2138            ),
2139            (
2140                "response.completed",
2141                json!({ "type": "response.completed", "response": { "id": "resp_1", "model": "gpt-4o-mini", "status": "completed", "output": [], "usage": { "input_tokens": 3, "output_tokens": 2 } } }),
2142            ),
2143        ]);
2144        let updates = collect_updates(text).await;
2145        let resp = ChatResponse::from_updates(updates);
2146        assert_eq!(resp.text(), "Hello!");
2147        assert_eq!(resp.response_id.as_deref(), Some("resp_1"));
2148        assert_eq!(resp.finish_reason, Some(FinishReason::stop()));
2149        let usage = resp.usage_details.unwrap();
2150        assert_eq!(usage.input_token_count, Some(3));
2151        assert_eq!(usage.output_token_count, Some(2));
2152    }
2153
2154    #[tokio::test]
2155    async fn stream_tool_call_accumulates_arguments() {
2156        let text = sse_body(&[
2157            (
2158                "response.output_item.added",
2159                json!({ "type": "response.output_item.added", "output_index": 0, "item": { "type": "function_call", "call_id": "call_1", "name": "get_weather" } }),
2160            ),
2161            (
2162                "response.function_call_arguments.delta",
2163                json!({ "type": "response.function_call_arguments.delta", "output_index": 0, "delta": "{\"city\":" }),
2164            ),
2165            (
2166                "response.function_call_arguments.delta",
2167                json!({ "type": "response.function_call_arguments.delta", "output_index": 0, "delta": "\"Paris\"}" }),
2168            ),
2169            (
2170                "response.completed",
2171                json!({ "type": "response.completed", "response": { "id": "resp_2", "status": "completed", "output": [{"type":"function_call","call_id":"call_1","name":"get_weather","arguments":"{\"city\":\"Paris\"}"}] } }),
2172            ),
2173        ]);
2174        let updates = collect_updates(text).await;
2175        let resp = ChatResponse::from_updates(updates);
2176        let calls = resp.function_calls();
2177        assert_eq!(calls.len(), 1);
2178        assert_eq!(calls[0].call_id, "call_1");
2179        assert_eq!(calls[0].name, "get_weather");
2180        assert_eq!(
2181            calls[0].parse_arguments().unwrap().get("city").unwrap(),
2182            &json!("Paris")
2183        );
2184        assert_eq!(resp.finish_reason, Some(FinishReason::tool_calls()));
2185    }
2186
2187    #[tokio::test]
2188    async fn stream_failed_event_is_error() {
2189        let text = sse_body(&[(
2190            "response.failed",
2191            json!({ "type": "response.failed", "response": { "error": { "message": "boom" } } }),
2192        )]);
2193        let stream =
2194            futures::stream::once(async move { Ok::<_, reqwest::Error>(bytes::Bytes::from(text)) });
2195        let byte_stream: ByteStream = Box::pin(stream);
2196        let mut state = ResponsesSseState {
2197            byte_stream,
2198            buffer: String::new(),
2199            utf8: Utf8StreamDecoder::new(),
2200            queued: VecDeque::new(),
2201            call_ids: HashMap::new(),
2202            done: false,
2203            store: None,
2204        };
2205        let bytes = state.byte_stream.next().await.unwrap().unwrap();
2206        let decoded = state.utf8.push(&bytes);
2207        state.buffer.push_str(&decoded);
2208        let mut saw_error = false;
2209        while let Some(pos) = state.buffer.find('\n') {
2210            let line = state.buffer[..pos].trim().to_string();
2211            state.buffer.drain(..=pos);
2212            let Some(data) = line.strip_prefix("data:") else {
2213                continue;
2214            };
2215            let data = data.trim();
2216            if data.is_empty() {
2217                continue;
2218            }
2219            let value: Value = serde_json::from_str(data).unwrap();
2220            if let EventOutcome::Error(e) =
2221                parse_responses_event(&value, &mut state.call_ids, state.store)
2222            {
2223                assert!(e.to_string().contains("boom"));
2224                saw_error = true;
2225            }
2226        }
2227        assert!(
2228            saw_error,
2229            "expected a response.failed event to surface an error"
2230        );
2231    }
2232
2233    #[test]
2234    fn stream_failed_event_classifies_content_filter() {
2235        // Streamed and non-streamed Responses failures must classify alike
2236        // (mirrors `response_failure_error`).
2237        let mut call_ids = HashMap::new();
2238        let filtered = parse_responses_event(
2239            &json!({
2240                "type": "response.failed",
2241                "response": { "error": { "code": "content_filter", "message": "blocked" } }
2242            }),
2243            &mut call_ids,
2244            None,
2245        );
2246        let EventOutcome::Error(err) = filtered else {
2247            panic!("expected an error outcome");
2248        };
2249        assert!(matches!(err, Error::ServiceContentFilter { .. }));
2250
2251        let generic = parse_responses_event(
2252            &json!({
2253                "type": "response.failed",
2254                "response": { "error": { "code": "server_error", "message": "boom" } }
2255            }),
2256            &mut call_ids,
2257            None,
2258        );
2259        let EventOutcome::Error(err) = generic else {
2260            panic!("expected an error outcome");
2261        };
2262        assert!(matches!(err, Error::Service(_)));
2263    }
2264
2265    // endregion
2266
2267    // region: env-var constructor
2268
2269    /// Guards `OPENAI_API_KEY` / `OPENAI_BASE_URL` mutation: `cargo test` runs
2270    /// tests in the same process on multiple threads, and env vars are
2271    /// process-global, so concurrent set/remove across tests would be racy
2272    /// without serializing access.
2273    static ENV_MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(());
2274
2275    #[test]
2276    fn from_env_reads_api_key_and_base_url() {
2277        let _guard = ENV_MUTEX.lock().unwrap();
2278        // SAFETY: serialized by ENV_MUTEX against the other env-var test in
2279        // this module; no other test in this crate touches these variables.
2280        unsafe {
2281            std::env::set_var("OPENAI_API_KEY", "sk-test-123");
2282            std::env::set_var("OPENAI_BASE_URL", "https://example.test/v1");
2283        }
2284        let client = OpenAIChatClient::from_env("gpt-4o-mini").unwrap();
2285        assert_eq!(client.inner.api_key, "sk-test-123");
2286        assert_eq!(client.inner.base_url, "https://example.test/v1");
2287        unsafe {
2288            std::env::remove_var("OPENAI_API_KEY");
2289            std::env::remove_var("OPENAI_BASE_URL");
2290        }
2291    }
2292
2293    #[test]
2294    fn from_env_errors_when_api_key_missing() {
2295        let _guard = ENV_MUTEX.lock().unwrap();
2296        // SAFETY: serialized by ENV_MUTEX; see above.
2297        unsafe {
2298            std::env::remove_var("OPENAI_API_KEY");
2299            std::env::remove_var("OPENAI_BASE_URL");
2300        }
2301        let result = OpenAIChatClient::from_env("gpt-4o-mini");
2302        assert!(result.is_err());
2303    }
2304    #[test]
2305    fn build_body_maps_hosted_tools_to_responses_types() {
2306        use agent_framework_core::tools::{
2307            hosted_code_interpreter, hosted_file_search, hosted_mcp, hosted_web_search,
2308        };
2309        let c = client();
2310        let mut options = ChatOptions::new();
2311        options.tools = vec![
2312            hosted_web_search(),
2313            hosted_code_interpreter(),
2314            hosted_file_search(Some(7)),
2315            hosted_mcp(
2316                "docs",
2317                "https://mcp.example/sse",
2318                Some(vec!["search".into()]),
2319            ),
2320        ];
2321        let body = c.build_body(&[user("hi")], &options, false);
2322        let tools = body["tools"].as_array().unwrap();
2323        assert_eq!(tools[0], json!({ "type": "web_search" }));
2324        assert_eq!(
2325            tools[1],
2326            json!({ "type": "code_interpreter", "container": { "type": "auto" } })
2327        );
2328        assert_eq!(tools[2]["type"], "file_search");
2329        assert_eq!(tools[2]["max_num_results"], json!(7));
2330        assert_eq!(tools[3]["type"], "mcp");
2331        assert_eq!(tools[3]["server_url"], "https://mcp.example/sse");
2332        assert_eq!(tools[3]["allowed_tools"], json!(["search"]));
2333        assert_eq!(tools[3]["require_approval"], "never");
2334    }
2335
2336    // endregion
2337
2338    // region: multimodal input (Responses)
2339
2340    #[test]
2341    fn input_image_uri_becomes_input_image_part() {
2342        let msg = user_with(vec![Content::Uri(UriContent {
2343            uri: "https://example.com/cat.png".into(),
2344            media_type: "image/png".into(),
2345        })]);
2346        let input = messages_to_input(&[msg]);
2347        assert_eq!(
2348            input[0],
2349            json!({ "type": "message", "role": "user", "content": [
2350                { "type": "input_image", "image_url": "https://example.com/cat.png", "detail": "auto" }
2351            ]})
2352        );
2353    }
2354
2355    #[test]
2356    fn input_audio_file_and_hosted_file_parts() {
2357        let msg = user_with(vec![
2358            Content::Data(DataContent {
2359                uri: "data:audio/wav;base64,QQ".into(),
2360                media_type: Some("audio/wav".into()),
2361            }),
2362            Content::Data(DataContent {
2363                uri: "data:application/pdf;base64,JV".into(),
2364                media_type: Some("application/pdf".into()),
2365            }),
2366            Content::HostedFile(HostedFileContent {
2367                file_id: "file-123".into(),
2368            }),
2369        ]);
2370        let input = messages_to_input(&[msg]);
2371        // `input_audio.data` is the raw base64 payload (data-URI prefix
2372        // stripped), the same wire rule as Chat Completions; file inputs keep
2373        // the full data URI in `file_data`.
2374        assert_eq!(
2375            input[0]["content"],
2376            json!([
2377                { "type": "input_audio", "input_audio": { "data": "QQ", "format": "wav" } },
2378                { "type": "input_file", "file_data": "data:application/pdf;base64,JV", "filename": "file" },
2379                { "type": "input_file", "file_id": "file-123" },
2380            ])
2381        );
2382    }
2383
2384    #[test]
2385    fn approval_response_becomes_mcp_approval_response_item() {
2386        let resp = FunctionApprovalResponseContent {
2387            approved: true,
2388            id: "appr_1".into(),
2389            function_call: FunctionCallContent::new("appr_1", "search", None),
2390        };
2391        let msg = user_with(vec![Content::FunctionApprovalResponse(resp)]);
2392        let input = messages_to_input(&[msg]);
2393        assert_eq!(
2394            input[0],
2395            json!({
2396                "type": "mcp_approval_response",
2397                "approval_request_id": "appr_1",
2398                "approve": true,
2399            })
2400        );
2401    }
2402
2403    #[test]
2404    fn approval_request_becomes_mcp_approval_request_item() {
2405        let req = FunctionApprovalRequestContent {
2406            id: "appr_1".into(),
2407            function_call: FunctionCallContent::new(
2408                "appr_1",
2409                "search",
2410                Some(FunctionArguments::Raw(r#"{"q":"x"}"#.into())),
2411            ),
2412        };
2413        let msg = Message::with_contents(
2414            Role::assistant(),
2415            vec![Content::FunctionApprovalRequest(req)],
2416        );
2417        let input = messages_to_input(&[msg]);
2418        assert_eq!(
2419            input[0],
2420            json!({
2421                "type": "mcp_approval_request",
2422                "id": "appr_1",
2423                "name": "search",
2424                "arguments": r#"{"q":"x"}"#,
2425            })
2426        );
2427    }
2428
2429    // endregion
2430
2431    // region: output parsing (annotations, code interpreter, images, approvals)
2432
2433    #[test]
2434    fn output_text_url_citation_annotation() {
2435        let contents = parse_item(json!({
2436            "type": "message", "role": "assistant", "content": [{
2437                "type": "output_text", "text": "See source.",
2438                "annotations": [{
2439                    "type": "url_citation", "title": "Src", "url": "https://ex.com",
2440                    "start_index": 0, "end_index": 3,
2441                }],
2442            }],
2443        }));
2444        let Content::Text(t) = &contents[0] else {
2445            panic!("expected text content");
2446        };
2447        let ann = t.annotations.as_ref().unwrap();
2448        assert_eq!(ann[0].title.as_deref(), Some("Src"));
2449        assert_eq!(ann[0].url.as_deref(), Some("https://ex.com"));
2450        let region = &ann[0].annotated_regions.as_ref().unwrap()[0];
2451        assert_eq!(region.start_index, Some(0));
2452        assert_eq!(region.end_index, Some(3));
2453    }
2454
2455    #[test]
2456    fn output_text_file_and_container_citations() {
2457        let contents = parse_item(json!({
2458            "type": "message", "role": "assistant", "content": [{
2459                "type": "output_text", "text": "x",
2460                "annotations": [
2461                    { "type": "file_citation", "filename": "doc.pdf", "file_id": "file-1", "index": 2 },
2462                    { "type": "file_path", "file_id": "file-2", "index": 0 },
2463                    { "type": "container_file_citation", "filename": "c.txt", "file_id": "file-3",
2464                      "container_id": "cont-1", "start_index": 1, "end_index": 4 },
2465                ],
2466            }],
2467        }));
2468        let Content::Text(t) = &contents[0] else {
2469            panic!("expected text content");
2470        };
2471        let ann = t.annotations.as_ref().unwrap();
2472        assert_eq!(ann[0].url.as_deref(), Some("doc.pdf"));
2473        assert_eq!(ann[0].file_id.as_deref(), Some("file-1"));
2474        assert_eq!(ann[1].file_id.as_deref(), Some("file-2"));
2475        assert_eq!(ann[2].file_id.as_deref(), Some("file-3"));
2476        assert_eq!(ann[2].url.as_deref(), Some("c.txt"));
2477        assert_eq!(
2478            ann[2].annotated_regions.as_ref().unwrap()[0].end_index,
2479            Some(4)
2480        );
2481    }
2482
2483    #[test]
2484    fn code_interpreter_outputs_become_text_and_uri() {
2485        let contents = parse_item(json!({
2486            "type": "code_interpreter_call",
2487            "outputs": [
2488                { "type": "logs", "logs": "hello stdout" },
2489                { "type": "image", "url": "https://ex.com/plot.png" },
2490            ],
2491        }));
2492        assert!(matches!(&contents[0], Content::Text(t) if t.text == "hello stdout"));
2493        assert!(
2494            matches!(&contents[1], Content::Uri(u) if u.uri == "https://ex.com/plot.png" && u.media_type == "image")
2495        );
2496    }
2497
2498    #[test]
2499    fn code_interpreter_without_outputs_falls_back_to_code() {
2500        let contents = parse_item(json!({
2501            "type": "code_interpreter_call", "code": "print(1)",
2502        }));
2503        assert!(matches!(&contents[0], Content::Text(t) if t.text == "print(1)"));
2504    }
2505
2506    #[test]
2507    fn image_generation_raw_base64_becomes_png_data() {
2508        let contents = parse_item(json!({
2509            "type": "image_generation_call", "result": "AAAABBBB",
2510        }));
2511        let Content::Data(d) = &contents[0] else {
2512            panic!("expected data content");
2513        };
2514        assert_eq!(d.uri, "data:image/png;base64,AAAABBBB");
2515        assert_eq!(d.media_type.as_deref(), Some("image/png"));
2516    }
2517
2518    #[test]
2519    fn image_generation_data_uri_keeps_stated_media_type() {
2520        let contents = parse_item(json!({
2521            "type": "image_generation_call", "result": "data:image/webp;base64,ZZZ",
2522        }));
2523        let Content::Data(d) = &contents[0] else {
2524            panic!("expected data content");
2525        };
2526        assert_eq!(d.uri, "data:image/webp;base64,ZZZ");
2527        assert_eq!(d.media_type.as_deref(), Some("image/webp"));
2528    }
2529
2530    #[test]
2531    fn mcp_approval_request_output_round_trips_into_response() {
2532        let contents = parse_item(json!({
2533            "type": "mcp_approval_request",
2534            "id": "appr_9", "name": "search", "arguments": r#"{"q":"rust"}"#,
2535            "server_label": "docs",
2536        }));
2537        let Content::FunctionApprovalRequest(req) = &contents[0] else {
2538            panic!("expected approval request");
2539        };
2540        assert_eq!(req.id, "appr_9");
2541        assert_eq!(req.function_call.call_id, "appr_9");
2542        assert_eq!(req.function_call.name, "search");
2543
2544        // The id round-trips into the request's response item (item 5).
2545        let msg = user_with(vec![Content::FunctionApprovalResponse(
2546            req.create_response(true),
2547        )]);
2548        let input = messages_to_input(&[msg]);
2549        assert_eq!(input[0]["type"], json!("mcp_approval_response"));
2550        assert_eq!(input[0]["approval_request_id"], json!("appr_9"));
2551        assert_eq!(input[0]["approve"], json!(true));
2552    }
2553
2554    #[test]
2555    fn mcp_call_output_item_parses_into_call_and_result() {
2556        let contents = parse_item(json!({
2557            "type": "mcp_call", "id": "mcp_1", "name": "search",
2558            "server_label": "docs", "arguments": r#"{"q":"rust"}"#,
2559            "output": "found it",
2560        }));
2561        let [Content::McpServerToolCall(call), Content::McpServerToolResult(result)] =
2562            contents.as_slice()
2563        else {
2564            panic!("expected hosted call and result, got {contents:?}");
2565        };
2566        assert_eq!(call.call_id, "mcp_1");
2567        assert_eq!(call.tool_name, "search");
2568        assert_eq!(call.server_name.as_deref(), Some("docs"));
2569        assert_eq!(result.call_id, "mcp_1");
2570        assert_eq!(result.output, Some(json!("found it")));
2571    }
2572
2573    /// A hosted approval replayed from local history carries the completed
2574    /// `mcp_call` after its request/response pair, so the service sees the
2575    /// approved call as already run instead of an approval still to act on.
2576    #[test]
2577    fn replayed_hosted_approval_carries_its_completed_mcp_call() {
2578        let request = parse_item(json!({
2579            "type": "mcp_approval_request",
2580            "id": "appr_9", "name": "search", "arguments": r#"{"q":"rust"}"#,
2581            "server_label": "docs",
2582        }));
2583        let Content::FunctionApprovalRequest(req) = &request[0] else {
2584            panic!("expected approval request");
2585        };
2586        let response = req.create_response(true);
2587        let completed = parse_item(json!({
2588            "type": "mcp_call", "id": "mcp_1", "approval_request_id": "appr_9",
2589            "name": "search", "server_label": "docs",
2590            "arguments": r#"{"q":"rust"}"#, "output": "found it",
2591        }));
2592        let history = vec![
2593            Message::with_contents(Role::assistant(), request),
2594            user_with(vec![Content::FunctionApprovalResponse(response)]),
2595            Message::with_contents(Role::assistant(), completed),
2596            user("and now?"),
2597        ];
2598        let input = messages_to_input(&history);
2599        let types: Vec<_> = input.iter().map(|i| i["type"].clone()).collect();
2600        assert_eq!(
2601            types,
2602            vec![
2603                json!("mcp_approval_request"),
2604                json!("mcp_approval_response"),
2605                json!("mcp_call"),
2606                json!("message"),
2607            ]
2608        );
2609        assert_eq!(input[2]["id"], json!("mcp_1"));
2610        assert_eq!(input[2]["server_label"], json!("docs"));
2611        assert_eq!(input[2]["name"], json!("search"));
2612        assert_eq!(input[2]["arguments"], json!(r#"{"q":"rust"}"#));
2613        assert_eq!(input[2]["output"], json!("found it"));
2614        assert_eq!(input[2]["approval_request_id"], json!("appr_9"));
2615    }
2616
2617    #[test]
2618    fn orphan_mcp_result_is_dropped_from_input() {
2619        let input = messages_to_input(&[Message::with_contents(
2620            Role::assistant(),
2621            vec![Content::McpServerToolResult(McpServerToolResultContent {
2622                call_id: "mcp_missing".into(),
2623                output: Some(json!("x")),
2624                error: None,
2625            })],
2626        )]);
2627        assert!(input.is_empty(), "{input:?}");
2628    }
2629
2630    /// A streamed `mcp_call` starts with empty arguments on `added`; the
2631    /// final arguments only arrive on the completed item, so the call is
2632    /// recorded from `done` and replays with them rather than `{}`.
2633    #[test]
2634    fn streamed_mcp_call_records_the_completed_arguments() {
2635        let mut ids = HashMap::new();
2636        let added = parse_responses_event(
2637            &json!({"type": "response.output_item.added", "output_index": 0, "item": {
2638                "type": "mcp_call", "id": "mcp_2", "name": "search",
2639                "server_label": "docs", "arguments": "",
2640            }}),
2641            &mut ids,
2642            None,
2643        );
2644        assert!(matches!(added, EventOutcome::None));
2645        for event in [
2646            json!({"type": "response.mcp_call_arguments.delta", "output_index": 0,
2647                   "item_id": "mcp_2", "delta": "{\"q\":"}),
2648            json!({"type": "response.mcp_call_arguments.done", "output_index": 0,
2649                   "item_id": "mcp_2", "arguments": "{\"q\":\"rust\"}"}),
2650        ] {
2651            assert!(matches!(
2652                parse_responses_event(&event, &mut ids, None),
2653                EventOutcome::None
2654            ));
2655        }
2656        let EventOutcome::Update(done) = parse_responses_event(
2657            &json!({"type": "response.output_item.done", "output_index": 0, "item": {
2658                "type": "mcp_call", "id": "mcp_2", "name": "search",
2659                "server_label": "docs", "arguments": "{\"q\":\"rust\"}", "output": "ok",
2660                "approval_request_id": "appr_2",
2661            }}),
2662            &mut ids,
2663            None,
2664        ) else {
2665            panic!("expected an update on done");
2666        };
2667        let response = ChatResponse::from_updates(vec![done]);
2668        let input = messages_to_input(&response.messages);
2669        assert_eq!(
2670            input,
2671            vec![json!({
2672                "type": "mcp_call", "id": "mcp_2", "server_label": "docs",
2673                "name": "search", "arguments": "{\"q\":\"rust\"}", "output": "ok",
2674                "approval_request_id": "appr_2",
2675            })]
2676        );
2677    }
2678
2679    /// A turn continuing a stored response (`previous_response_id`) with the
2680    /// local history provider still attached must not re-send items the
2681    /// service already holds by their server-issued `id` (hosted `mcp_call`,
2682    /// `mcp_approval_request`, reasoning): OpenAI rejects them as duplicates.
2683    /// The new approval response and the text still go out; a stateless
2684    /// request keeps replaying everything.
2685    #[test]
2686    fn continuation_request_does_not_resend_stored_hosted_items() {
2687        let mut assistant = vec![
2688            Content::TextReasoning(TextReasoningContent {
2689                text: String::new(),
2690                annotations: None,
2691                raw_representation: Some(json!({
2692                    "type": "reasoning", "id": "rs_1", "summary": [],
2693                })),
2694                protected_data: None,
2695            }),
2696            Content::FunctionApprovalRequest(FunctionApprovalRequestContent {
2697                id: "mcpr_1".into(),
2698                function_call: FunctionCallContent::new(
2699                    "mcpr_1",
2700                    "search",
2701                    Some(FunctionArguments::Raw("{}".into())),
2702                ),
2703            }),
2704        ];
2705        assistant.extend(mcp_call_item_contents(&json!({
2706            "type": "mcp_call", "id": "mcp_1", "name": "search",
2707            "server_label": "docs", "arguments": "{}", "output": "ok",
2708        })));
2709        assistant.push(Content::text("done"));
2710        let history = vec![
2711            user("find it"),
2712            Message::with_contents(Role::assistant(), assistant),
2713            user_with(vec![Content::FunctionApprovalResponse(
2714                FunctionApprovalResponseContent {
2715                    approved: true,
2716                    id: "mcpr_2".into(),
2717                    function_call: FunctionCallContent::new("mcpr_2", "search", None),
2718                },
2719            )]),
2720        ];
2721        let types = |body: &Value| -> Vec<String> {
2722            body["input"]
2723                .as_array()
2724                .unwrap()
2725                .iter()
2726                .map(|item| item["type"].as_str().unwrap_or("message").to_string())
2727                .collect()
2728        };
2729
2730        let c = client();
2731        let mut options = ChatOptions::new();
2732        options.conversation_id = Some("resp_1".into());
2733        let body = c.build_body(&history, &options, false);
2734        assert_eq!(body["previous_response_id"], json!("resp_1"));
2735        assert_eq!(
2736            types(&body),
2737            ["message", "message", "mcp_approval_response"],
2738            "{body}"
2739        );
2740
2741        let body = c.build_body(&history, &ChatOptions::new(), false);
2742        assert_eq!(
2743            types(&body),
2744            [
2745                "message",
2746                "reasoning",
2747                "mcp_approval_request",
2748                "mcp_call",
2749                "message",
2750                "mcp_approval_response",
2751            ],
2752            "{body}"
2753        );
2754    }
2755
2756    /// An `mcp_call` that failed carries an `error` and no `output`; the
2757    /// error is kept and replayed, so the call does not look unfinished.
2758    #[test]
2759    fn failed_mcp_call_replays_its_error() {
2760        let item = json!({
2761            "type": "mcp_call", "id": "mcp_3", "name": "search",
2762            "server_label": "docs", "arguments": "{}",
2763            "status": "failed", "error": "server unreachable",
2764        });
2765        let contents = mcp_call_item_contents(&item);
2766        let [Content::McpServerToolCall(_), Content::McpServerToolResult(result)] =
2767            contents.as_slice()
2768        else {
2769            panic!("expected call + result, got {contents:?}");
2770        };
2771        assert_eq!(result.output, None);
2772        assert_eq!(result.error, Some(json!("server unreachable")));
2773        let input = messages_to_input(&[Message::with_contents(Role::assistant(), contents)]);
2774        assert_eq!(
2775            input,
2776            vec![json!({
2777                "type": "mcp_call", "id": "mcp_3", "server_label": "docs",
2778                "name": "search", "arguments": "{}", "error": "server unreachable",
2779            })]
2780        );
2781    }
2782
2783    // endregion
2784
2785    // region: streaming reasoning
2786
2787    fn reasoning_event(value: Value) -> EventOutcome {
2788        let mut ids = HashMap::new();
2789        parse_responses_event(&value, &mut ids, None)
2790    }
2791
2792    #[test]
2793    fn a_replayed_refusal_becomes_a_refusal_content_part() {
2794        // Beside `output_text` in an output message, a refusal has its own
2795        // part type. Re-emitting it as `output_text` replays a decline to the
2796        // provider as an answer.
2797        let input = messages_to_input(&[Message::with_contents(
2798            Role::assistant(),
2799            vec![
2800                Content::Text(TextContent::new("here is half")),
2801                Content::Text(TextContent::refusal("I can't do the rest")),
2802            ],
2803        )]);
2804        let content = &input[0]["content"];
2805        assert_eq!(
2806            content[0],
2807            json!({"type": "output_text", "text": "here is half"})
2808        );
2809        assert_eq!(
2810            content[1],
2811            json!({"type": "refusal", "refusal": "I can't do the rest"})
2812        );
2813    }
2814
2815    #[test]
2816    fn a_refusal_on_a_non_assistant_role_is_dropped_rather_than_mis_encoded() {
2817        // An *input* message's content list admits only
2818        // input_text/input_image/input_file — there is no refusal part — so
2819        // emitting one would be rejected by the API. Dropping it is the only
2820        // correct option, and it cannot arise from a parsed provider response
2821        // anyway (refusals are assistant output).
2822        let input = messages_to_input(&[Message::with_contents(
2823            Role::user(),
2824            vec![
2825                Content::Text(TextContent::new("hello")),
2826                Content::Text(TextContent::refusal("stray")),
2827            ],
2828        )]);
2829        let content = &input[0]["content"];
2830        assert_eq!(content.as_array().map(Vec::len), Some(1));
2831        assert_eq!(content[0], json!({"type": "input_text", "text": "hello"}));
2832    }
2833
2834    #[test]
2835    fn a_streamed_refusal_is_marked_and_its_done_event_is_not_duplicated() {
2836        // Before this, `response.refusal.delta` fell through the catch-all
2837        // and a streamed decline reached the caller as an empty response —
2838        // the non-streaming path marked refusals while the streaming path
2839        // dropped them.
2840        let EventOutcome::Update(delta) =
2841            reasoning_event(json!({ "type": "response.refusal.delta", "delta": "I can't" }))
2842        else {
2843            panic!("expected update");
2844        };
2845        assert!(matches!(&delta.contents[0], Content::Text(t) if t.refusal && t.text == "I can't"));
2846
2847        // `.done` repeats the whole refusal; emitting it would double the
2848        // text already streamed, exactly as for the text channel.
2849        let done =
2850            reasoning_event(json!({ "type": "response.refusal.done", "refusal": "I can't help" }));
2851        assert!(matches!(done, EventOutcome::None));
2852    }
2853
2854    #[test]
2855    fn reasoning_text_delta_streams_and_done_is_terminal_metadata() {
2856        let EventOutcome::Update(delta) =
2857            reasoning_event(json!({ "type": "response.reasoning_text.delta", "delta": "Th" }))
2858        else {
2859            panic!("expected update");
2860        };
2861        assert!(matches!(&delta.contents[0], Content::TextReasoning(t) if t.text == "Th"));
2862
2863        // `.done` carries the full text the deltas already streamed — emitting
2864        // it again would duplicate the reasoning in the aggregate.
2865        let done =
2866            reasoning_event(json!({ "type": "response.reasoning_text.done", "text": "Think" }));
2867        assert!(matches!(done, EventOutcome::None));
2868    }
2869
2870    #[test]
2871    fn reasoning_summary_text_events_map_to_reasoning_content() {
2872        let EventOutcome::Update(delta) = reasoning_event(
2873            json!({ "type": "response.reasoning_summary_text.delta", "delta": "sum" }),
2874        ) else {
2875            panic!("expected update");
2876        };
2877        assert!(matches!(&delta.contents[0], Content::TextReasoning(t) if t.text == "sum"));
2878
2879        let done = reasoning_event(
2880            json!({ "type": "response.reasoning_summary_text.done", "text": "summary" }),
2881        );
2882        assert!(matches!(done, EventOutcome::None));
2883    }
2884
2885    #[test]
2886    fn response_failure_error_classifies_content_filter() {
2887        let filtered = json!({
2888            "status": "failed",
2889            "error": { "code": "content_filter", "message": "blocked" }
2890        });
2891        assert!(matches!(
2892            response_failure_error(&filtered),
2893            Some(Error::ServiceContentFilter { .. })
2894        ));
2895
2896        let generic = json!({
2897            "status": "failed",
2898            "error": { "code": "server_error", "message": "boom" }
2899        });
2900        assert!(matches!(
2901            response_failure_error(&generic),
2902            Some(Error::Service(_))
2903        ));
2904
2905        assert!(response_failure_error(&json!({ "status": "completed" })).is_none());
2906    }
2907
2908    #[test]
2909    fn input_audio_data_strips_data_uri_prefix() {
2910        let part = content_to_input_part("data:audio/wav;base64,QUJD", Some("audio/wav"))
2911            .expect("audio part");
2912        assert_eq!(part["input_audio"]["data"], "QUJD");
2913        assert_eq!(part["input_audio"]["format"], "wav");
2914    }
2915
2916    // endregion
2917
2918    // region: hosted-tool config passthrough
2919
2920    fn hosted(kind: ToolKind, name: &str, params: Value) -> ToolDefinition {
2921        ToolDefinition {
2922            name: name.into(),
2923            description: String::new(),
2924            parameters: params,
2925            kind,
2926            approval_mode: ApprovalMode::NeverRequire,
2927            executor: None,
2928        }
2929    }
2930
2931    #[test]
2932    fn web_search_passes_through_user_location() {
2933        let tool = hosted(
2934            ToolKind::HostedWebSearch,
2935            "web_search",
2936            json!({ "user_location": { "city": "Paris", "country": "FR" } }),
2937        );
2938        assert_eq!(
2939            tool_to_responses_spec(&tool),
2940            json!({
2941                "type": "web_search",
2942                "user_location": { "type": "approximate", "city": "Paris", "country": "FR" },
2943            })
2944        );
2945    }
2946
2947    #[test]
2948    fn file_search_passes_vector_store_ids_and_max_results_param() {
2949        let tool = hosted(
2950            ToolKind::HostedFileSearch { max_results: None },
2951            "file_search",
2952            json!({ "vector_store_ids": ["vs_1"], "max_results": 12 }),
2953        );
2954        let spec = tool_to_responses_spec(&tool);
2955        assert_eq!(spec["vector_store_ids"], json!(["vs_1"]));
2956        assert_eq!(spec["max_num_results"], json!(12));
2957    }
2958
2959    #[test]
2960    fn image_generation_maps_to_responses_tool_with_passthrough_params() {
2961        let tool = hosted(
2962            ToolKind::HostedImageGeneration,
2963            "image_generation",
2964            json!({ "size": "1024x1024", "quality": "high" }),
2965        );
2966        let spec = tool_to_responses_spec(&tool);
2967        assert_eq!(spec["type"], json!("image_generation"));
2968        assert_eq!(spec["size"], json!("1024x1024"));
2969        assert_eq!(spec["quality"], json!("high"));
2970    }
2971
2972    #[test]
2973    fn code_interpreter_passes_file_ids_and_container_override() {
2974        let with_files = hosted(
2975            ToolKind::HostedCodeInterpreter,
2976            "ci",
2977            json!({ "file_ids": ["file-1", "file-2"] }),
2978        );
2979        assert_eq!(
2980            tool_to_responses_spec(&with_files)["container"],
2981            json!({ "type": "auto", "file_ids": ["file-1", "file-2"] })
2982        );
2983        let with_container = hosted(
2984            ToolKind::HostedCodeInterpreter,
2985            "ci",
2986            json!({ "container": { "type": "secure", "id": "c1" } }),
2987        );
2988        assert_eq!(
2989            tool_to_responses_spec(&with_container)["container"],
2990            json!({ "type": "secure", "id": "c1" })
2991        );
2992    }
2993
2994    #[test]
2995    fn mcp_passes_headers_and_string_approval_mode_override() {
2996        let tool = hosted(
2997            ToolKind::HostedMcp {
2998                url: "https://mcp/sse".into(),
2999                allowed_tools: None,
3000            },
3001            "docs",
3002            json!({ "headers": { "Authorization": "Bearer x" }, "approval_mode": "always_require" }),
3003        );
3004        // The enum default is NeverRequire; the parameter overrides it.
3005        let spec = tool_to_responses_spec(&tool);
3006        assert_eq!(spec["headers"], json!({ "Authorization": "Bearer x" }));
3007        assert_eq!(spec["require_approval"], json!("always"));
3008    }
3009
3010    #[test]
3011    fn mcp_object_approval_mode_maps_to_tool_name_lists() {
3012        let tool = hosted(
3013            ToolKind::HostedMcp {
3014                url: "https://mcp/sse".into(),
3015                allowed_tools: None,
3016            },
3017            "docs",
3018            json!({ "approval_mode": { "always": ["delete"], "never": ["read"] } }),
3019        );
3020        assert_eq!(
3021            tool_to_responses_spec(&tool)["require_approval"],
3022            json!({ "always": { "tool_names": ["delete"] }, "never": { "tool_names": ["read"] } })
3023        );
3024    }
3025
3026    // endregion
3027}