| 1 | //! OpenAI Responses API bridge for the OpenAI Codex / ChatGPT provider. |
| 2 | //! |
| 3 | //! Implements a dedicated Responses API client that maps CodeWhale's internal |
| 4 | //! message/tool types to the Responses wire format and parses streaming SSE |
| 5 | //! events back into CodeWhale's `StreamEvent` / `MessageResponse` types. |
| 6 | //! |
| 7 | //! This is intentionally separate from the Chat Completions path |
| 8 | //! (`client/chat.rs`) to avoid protocol hacks. |
| 9 | |
| 10 | use anyhow::{Context, Result, bail}; |
| 11 | use serde_json::{Value, json}; |
| 12 | |
| 13 | use crate::llm_client::StreamEventBox; |
| 14 | use codewhale_config::ProviderKind; |
| 15 | use codewhale_config::responses_dialect::{ |
| 16 | AudioUsageFieldPolicy, CacheUsageFieldPolicy, CompletionPolicy, DoneMarkerPolicy, |
| 17 | EncryptedReasoningReplayPolicy, IncludePolicy, IncompleteResponsePolicy, InstructionsPlacement, |
| 18 | MalformedEventPolicy, OutputTokenFieldPolicy, ParallelToolCallPolicy, |
| 19 | PlainReasoningReplayPolicy, ReasoningEffortMapping, ReasoningSummaryPolicy, |
| 20 | ReasoningUsageFieldPolicy, ResponsesDialectProfile, SamplingPolicy, StorePolicy, |
| 21 | SystemRoleReplayPolicy, ToolEnvelopePolicy, |
| 22 | }; |
| 23 | use codewhale_models::tool_projection::{ |
| 24 | RouteToolProjection, ToolSchemaProjection, description_with_constraint_note, forced_tool_name, |
| 25 | project_tool_schema, |
| 26 | }; |
| 27 | use codewhale_models::{ |
| 28 | ContentBlock, ContentBlockStart, Delta, MessageDelta, MessageRequest, MessageResponse, |
| 29 | OpaqueReasoningState, StreamEvent, Tool, Usage, |
| 30 | }; |
| 31 | use codewhale_runtime::logging; |
| 32 | |
| 33 | use super::CodewhaleClient; |
| 34 | use super::chat::REASONING_REPLAY_PLACEHOLDER; |
| 35 | use super::deepseek_tools::{ |
| 36 | deepseek_web_tool_kind, validate_and_apply_safety_check_and_title, |
| 37 | validate_deepseek_web_tool_choice, validate_deepseek_web_tools, |
| 38 | }; |
| 39 | use super::prepared::WireDialect; |
| 40 | use super::role_placement::{RolePlacement, role_placement}; |
| 41 | use super::wire::{ |
| 42 | ERROR_BODY_MAX_BYTES, TOOL_NAME_LIMIT_64, ToolNameWire, bounded_error_text, |
| 43 | check_history_tool_names, documented_tool_name_limit, from_api_tool_name, |
| 44 | over_limit_tool_name_message, system_to_instructions, to_api_tool_name, |
| 45 | tool_name_exceeds_limit, tool_name_limit, |
| 46 | }; |
| 47 | use super::wire::{extract_sse_data_value, next_sse_line, push_sse_event_data}; |
| 48 | use crate::llm_client::LlmError; |
| 49 | |
| 50 | #[derive(Clone, Copy)] |
| 51 | pub(super) struct ResponsesReplayContext<'a> { |
| 52 | pub(super) provider_id: &'a str, |
| 53 | pub(super) wire_model_id: &'a str, |
| 54 | pub(super) reasoning_api_id: Option<&'a str>, |
| 55 | } |
| 56 | |
| 57 | #[cfg(test)] |
| 58 | fn profile_for_provider(provider: ProviderKind) -> &'static ResponsesDialectProfile { |
| 59 | let profile_id = match provider { |
| 60 | ProviderKind::OpenaiCodex => "codex", |
| 61 | ProviderKind::Concentrate => "concentrate", |
| 62 | ProviderKind::Deepseek => "deepseek_stateless_plain_reasoning", |
| 63 | _ => "standard", |
| 64 | }; |
| 65 | codewhale_config::responses_dialect::profile(profile_id) |
| 66 | .unwrap_or_else(|| panic!("responses profile {profile_id}")) |
| 67 | } |
| 68 | |
| 69 | #[cfg(test)] |
| 70 | pub(super) fn build_responses_body_for_provider( |
| 71 | request: &MessageRequest, |
| 72 | provider: ProviderKind, |
| 73 | reasoning_api: Option<&str>, |
| 74 | ) -> Value { |
| 75 | build_responses_wire_body( |
| 76 | request, |
| 77 | profile_for_provider(provider), |
| 78 | ResponsesReplayContext { |
| 79 | provider_id: provider.as_str(), |
| 80 | wire_model_id: request.model.as_str(), |
| 81 | reasoning_api_id: reasoning_api, |
| 82 | }, |
| 83 | ) |
| 84 | .expect("responses body builds") |
| 85 | .0 |
| 86 | } |
| 87 | |
| 88 | #[cfg(test)] |
| 89 | pub(super) fn responses_input_for_provider( |
| 90 | request: &MessageRequest, |
| 91 | provider: ProviderKind, |
| 92 | reasoning_api: Option<&str>, |
| 93 | ) -> Vec<Value> { |
| 94 | convert_messages_to_responses_input( |
| 95 | request, |
| 96 | profile_for_provider(provider), |
| 97 | ResponsesReplayContext { |
| 98 | provider_id: provider.as_str(), |
| 99 | wire_model_id: request.model.as_str(), |
| 100 | reasoning_api_id: reasoning_api, |
| 101 | }, |
| 102 | ) |
| 103 | } |
| 104 | |
| 105 | /// Build a Responses request body from the admitted dialect profile. |
| 106 | /// |
| 107 | /// Output limits are already applied to `request.max_tokens`. A mismatched |
| 108 | /// encrypted reasoning state is dropped and is not rewritten as plain text. |
| 109 | pub(super) fn build_responses_wire_body( |
| 110 | request: &MessageRequest, |
| 111 | profile: &ResponsesDialectProfile, |
| 112 | context: ResponsesReplayContext<'_>, |
| 113 | ) -> Result<(Value, Vec<String>)> { |
| 114 | let model = &request.model; |
| 115 | let mut body = json!({ |
| 116 | "model": model, |
| 117 | "stream": true, |
| 118 | }); |
| 119 | if profile.request.store == StorePolicy::ExplicitFalse { |
| 120 | body["store"] = json!(false); |
| 121 | } |
| 122 | // Every Responses route receives the same resolved request envelope as |
| 123 | // Chat and Messages. Omitting this field let auxiliary Responses calls |
| 124 | // escape the central route cap and made preview unable to prove the wire |
| 125 | // allowance. Profiles that omit the field still keep that internal cap; |
| 126 | // they only leave it off the JSON. |
| 127 | if request.max_tokens > 0 |
| 128 | && profile.request.max_output_tokens == OutputTokenFieldPolicy::WhenPositive |
| 129 | { |
| 130 | body["max_output_tokens"] = json!(request.max_tokens); |
| 131 | } |
| 132 | if profile.request.sampling == SamplingPolicy::TemperatureAndTopP { |
| 133 | if let Some(temperature) = request.temperature { |
| 134 | body["temperature"] = json!(temperature); |
| 135 | } |
| 136 | if let Some(top_p) = request.top_p { |
| 137 | body["top_p"] = json!(top_p); |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | let instructions = system_to_instructions(request.system.clone()) |
| 142 | .filter(|text| !text.trim().is_empty()) |
| 143 | .unwrap_or_else(|| "You are a helpful assistant.".to_string()); |
| 144 | |
| 145 | let provider_kind = ProviderKind::parse(context.provider_id); |
| 146 | let mut input = convert_messages_to_responses_input(request, profile, context); |
| 147 | if profile.request.instructions == InstructionsPlacement::LeadingSystemInput { |
| 148 | input.insert( |
| 149 | 0, |
| 150 | json!({ |
| 151 | "type": "message", |
| 152 | "role": "system", |
| 153 | "content": [{ "type": "input_text", "text": instructions }], |
| 154 | }), |
| 155 | ); |
| 156 | } else { |
| 157 | body["instructions"] = json!(instructions); |
| 158 | } |
| 159 | body["input"] = json!(input); |
| 160 | |
| 161 | if request |
| 162 | .messages |
| 163 | .iter() |
| 164 | .any(|m| m.role == codewhale_models::Role::LatestReminder) |
| 165 | { |
| 166 | bail!("latest_reminder is not supported in the Responses API"); |
| 167 | } |
| 168 | let is_deepseek_route = provider_kind.is_some_and(|provider| { |
| 169 | matches!( |
| 170 | provider, |
| 171 | ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic |
| 172 | ) |
| 173 | }) || profile.id.as_str() == "deepseek_stateless_plain_reasoning"; |
| 174 | validate_and_apply_safety_check_and_title(request, &mut body, is_deepseek_route)?; |
| 175 | |
| 176 | let tool_name_limit = provider_kind.map_or(TOOL_NAME_LIMIT_64, |provider| { |
| 177 | tool_name_limit(provider, ToolNameWire::OpenAiCompatible) |
| 178 | }); |
| 179 | check_history_tool_names( |
| 180 | request, |
| 181 | provider_kind.and_then(|provider| { |
| 182 | documented_tool_name_limit(provider, ToolNameWire::OpenAiCompatible) |
| 183 | }), |
| 184 | )?; |
| 185 | let mut omitted_tool_names = Vec::new(); |
| 186 | let mut omitted_logical_names = Vec::new(); |
| 187 | if let Some(tools) = request.tools.as_ref() { |
| 188 | let has_deepseek_web_tools = |
| 189 | validate_deepseek_web_tools(tools, WireDialect::OpenAiResponses)?; |
| 190 | let mut responses_tools = Vec::new(); |
| 191 | for tool in tools { |
| 192 | if let Some(kind) = deepseek_web_tool_kind(tool) { |
| 193 | let mut obj = json!({ "type": kind }); |
| 194 | if let Some(subkind) = tool.input_schema.get("kind").and_then(Value::as_str) { |
| 195 | obj["kind"] = json!(subkind); |
| 196 | } |
| 197 | responses_tools.push(obj); |
| 198 | continue; |
| 199 | } |
| 200 | if tool_name_exceeds_limit(&tool.name, tool_name_limit) { |
| 201 | omitted_logical_names.push(tool.name.clone()); |
| 202 | omitted_tool_names.push(to_api_tool_name(&tool.name)); |
| 203 | continue; |
| 204 | } |
| 205 | match project_tool_schema( |
| 206 | RouteToolProjection::RelaxedNonStrict, |
| 207 | &tool.input_schema, |
| 208 | tool.strict, |
| 209 | ) { |
| 210 | ToolSchemaProjection::Exact { |
| 211 | parameters, |
| 212 | strict, |
| 213 | constraint_note, |
| 214 | } |
| 215 | | ToolSchemaProjection::Relaxed { |
| 216 | parameters, |
| 217 | strict, |
| 218 | constraint_note, |
| 219 | } => responses_tools.push(responses_function_envelope( |
| 220 | tool, |
| 221 | parameters, |
| 222 | strict, |
| 223 | constraint_note, |
| 224 | )), |
| 225 | ToolSchemaProjection::Omitted { .. } => { |
| 226 | omitted_logical_names.push(tool.name.clone()); |
| 227 | omitted_tool_names.push(to_api_tool_name(&tool.name)); |
| 228 | } |
| 229 | } |
| 230 | } |
| 231 | if let Some(choice) = request.tool_choice.as_ref() { |
| 232 | validate_deepseek_web_tool_choice(choice, has_deepseek_web_tools)?; |
| 233 | } |
| 234 | if let Some(name) = request.tool_choice.as_ref().and_then(forced_tool_name) |
| 235 | && omitted_logical_names.iter().any(|omitted| omitted == name) |
| 236 | { |
| 237 | if tool_name_exceeds_limit(name, tool_name_limit) { |
| 238 | anyhow::bail!(over_limit_tool_name_message(name, tool_name_limit)); |
| 239 | } |
| 240 | anyhow::bail!( |
| 241 | "cannot force an omitted tool because its input schema is incompatible with this route" |
| 242 | ); |
| 243 | } |
| 244 | if !responses_tools.is_empty() { |
| 245 | body["tools"] = match profile.tools.envelope { |
| 246 | ToolEnvelopePolicy::NamespaceWrapped if !has_deepseek_web_tools => { |
| 247 | let Some(namespace) = profile.tools.namespace else { |
| 248 | anyhow::bail!( |
| 249 | "responses profile {} wraps tools without a namespace", |
| 250 | profile.id.as_str() |
| 251 | ); |
| 252 | }; |
| 253 | json!([{ "type": "namespace", "name": namespace, |
| 254 | "description": "Codewhale tools running under the user's local permissions.", |
| 255 | "tools": responses_tools }]) |
| 256 | } |
| 257 | ToolEnvelopePolicy::NamespaceWrapped | ToolEnvelopePolicy::FunctionArray => { |
| 258 | json!(responses_tools) |
| 259 | } |
| 260 | }; |
| 261 | let tool_choice = request.tool_choice.as_ref().and_then(Value::as_str); |
| 262 | body["tool_choice"] = if tool_choice == Some("none") { |
| 263 | json!("none") |
| 264 | } else { |
| 265 | json!("auto") |
| 266 | }; |
| 267 | // The plan preview decoder tracks one active function-call block. |
| 268 | body["parallel_tool_calls"] = |
| 269 | json!(profile.tools.parallel_calls == ParallelToolCallPolicy::Allow); |
| 270 | } |
| 271 | } |
| 272 | |
| 273 | // The roster owns each model's available levels. This builder only chooses |
| 274 | // which existing effort function the profile names. |
| 275 | if let Some(raw) = request.reasoning_effort.as_deref() |
| 276 | && let Some(effort) = match profile.reasoning.effort_mapping { |
| 277 | ReasoningEffortMapping::Codex => codex_responses_reasoning_effort(raw), |
| 278 | ReasoningEffortMapping::Deepseek => responses_reasoning_effort(raw, true), |
| 279 | ReasoningEffortMapping::OpenaiCompatible => compatible_responses_reasoning_effort(raw), |
| 280 | } |
| 281 | { |
| 282 | body["reasoning"] = match profile.reasoning.summary { |
| 283 | ReasoningSummaryPolicy::Omit => json!({ "effort": effort }), |
| 284 | ReasoningSummaryPolicy::Auto => json!({ |
| 285 | "effort": effort, |
| 286 | "summary": "auto", |
| 287 | }), |
| 288 | }; |
| 289 | } |
| 290 | |
| 291 | if profile.request.include == IncludePolicy::EncryptedReasoning { |
| 292 | body["include"] = json!(["reasoning.encrypted_content"]); |
| 293 | } |
| 294 | |
| 295 | Ok((body, omitted_tool_names)) |
| 296 | } |
| 297 | |
| 298 | impl CodewhaleClient { |
| 299 | /// Handle a streaming Responses request for the resolved provider route. |
| 300 | pub(super) async fn handle_responses_stream( |
| 301 | &self, |
| 302 | prepared: &super::PreparedOutboundRequest, |
| 303 | ) -> Result<StreamEventBox> { |
| 304 | // Body, endpoint, and route shape all come from the shared |
| 305 | // prepared-request seam (`prepare_outbound_request`). |
| 306 | let body = &prepared.body; |
| 307 | let Some(profile_id) = self.responses_profile_id else { |
| 308 | bail!( |
| 309 | "responses client for {} has no dialect profile", |
| 310 | self.api_provider.as_str() |
| 311 | ); |
| 312 | }; |
| 313 | let Some(profile) = codewhale_config::responses_dialect::profile(profile_id.as_str()) |
| 314 | else { |
| 315 | bail!( |
| 316 | "responses profile {} is not in the dialect table", |
| 317 | profile_id.as_str() |
| 318 | ); |
| 319 | }; |
| 320 | admit_shared_responses_usage(profile); |
| 321 | let malformed_json = profile.stream.malformed_json; |
| 322 | let done_marker = profile.stream.done_marker; |
| 323 | let incomplete = profile.stream.incomplete; |
| 324 | let tool_namespace = profile.tools.namespace; |
| 325 | let strict_terminal = matches!( |
| 326 | profile.stream.completion, |
| 327 | CompletionPolicy::RequireSuccessfulResponseCompleted |
| 328 | ); |
| 329 | let codex_identity = self.api_provider == ProviderKind::OpenaiCodex; |
| 330 | let url = prepared.endpoint.url.clone(); |
| 331 | // The synthetic MessageStart below is emitted from inside the stream |
| 332 | // closure, which outlives `prepared`. Clone the wire model — the id |
| 333 | // actually placed on the body by the shared seam, after route |
| 334 | // remapping — rather than borrowing the request that no longer exists |
| 335 | // at this layer. |
| 336 | let wire_model = prepared.wire_model.clone(); |
| 337 | let reasoning_api = match profile.replay.encrypted_state { |
| 338 | EncryptedReasoningReplayPolicy::AccountApiModelScoped => { |
| 339 | self.chatgpt_reasoning_api.as_deref() |
| 340 | } |
| 341 | EncryptedReasoningReplayPolicy::ProviderApiModelScoped => Some("openai-responses"), |
| 342 | EncryptedReasoningReplayPolicy::Disabled => None, |
| 343 | }; |
| 344 | let reasoning_origin = reasoning_api.map(|api| { |
| 345 | ( |
| 346 | self.api_provider.as_str().to_string(), |
| 347 | api.to_string(), |
| 348 | wire_model.clone(), |
| 349 | ) |
| 350 | }); |
| 351 | |
| 352 | // The bearer Authorization header is already installed as a default |
| 353 | // header on both HTTP clients, so it must not be duplicated here. |
| 354 | // The public API does not use Codex backend identity or beta headers. |
| 355 | // |
| 356 | // Provider backoff stays outside each response-header wait. The |
| 357 | // returned SSE body carries no reqwest total timeout. |
| 358 | let request_body = |
| 359 | serde_json::to_vec(&body).context("Failed to serialize Responses API request body")?; |
| 360 | let response = self |
| 361 | .send_stream_open_with_retry(|policy| { |
| 362 | super::stream_entry::client_for_policy( |
| 363 | &self.http_client, |
| 364 | self.http1_fallback_client(), |
| 365 | policy, |
| 366 | ) |
| 367 | .post(&url) |
| 368 | .header("Content-Type", "application/json") |
| 369 | .header("Accept", "text/event-stream") |
| 370 | .body(request_body.clone()) |
| 371 | }) |
| 372 | .await |
| 373 | .context("Responses API request failed")?; |
| 374 | |
| 375 | let status = response.status(); |
| 376 | crate::client::record_provider_response(self.api_provider, status.as_u16()); |
| 377 | if !status.is_success() { |
| 378 | let raw = bounded_error_text(response, ERROR_BODY_MAX_BYTES).await; |
| 379 | let raw = self.redact_model_bound_text(&raw); |
| 380 | return Err(LlmError::from_http_response(status.as_u16(), &raw).into()); |
| 381 | } |
| 382 | |
| 383 | let stream_idle_timeout = self.stream_idle_timeout; |
| 384 | let first_byte = super::stream_entry::first_byte_timeout(stream_idle_timeout); |
| 385 | let provider_label = self.api_provider.provider().display_name(); |
| 386 | let error_secrets = self.model_bound_secret_values.clone(); |
| 387 | let byte_stream = response.bytes_stream(); |
| 388 | |
| 389 | let stream = async_stream::stream! { |
| 390 | use futures_util::StreamExt; |
| 391 | |
| 392 | // Emit synthetic MessageStart. |
| 393 | yield Ok(StreamEvent::MessageStart { |
| 394 | message: MessageResponse { |
| 395 | tool_projection_warning: None, |
| 396 | id: String::new(), |
| 397 | r#type: "message".to_string(), |
| 398 | role: "assistant".to_string(), |
| 399 | content: vec![], |
| 400 | model: wire_model.clone(), |
| 401 | stop_reason: None, |
| 402 | stop_sequence: None, |
| 403 | container: None, |
| 404 | usage: Usage::default(), |
| 405 | title: None, |
| 406 | stop_details: None, |
| 407 | refusal: None, |
| 408 | }, |
| 409 | }); |
| 410 | |
| 411 | let mut current_block_index: Option<u32> = None; |
| 412 | // Whether reasoning text has already been emitted for the current |
| 413 | // reasoning block. Used to insert a paragraph break between |
| 414 | // consecutive summary parts, which the wire protocol delivers |
| 415 | // back-to-back with no separator. |
| 416 | let mut reasoning_text_emitted = false; |
| 417 | let mut saw_tool_call = false; |
| 418 | let mut usage_data: Option<Usage> = None; |
| 419 | // Raw byte buffer: decode only COMPLETE lines (or the stream-end |
| 420 | // tail) via the shared take_sse_line / flush_sse_line helpers so a |
| 421 | // multi-byte UTF-8 char split across HTTP/2 DATA is never |
| 422 | // corrupted to U+FFFD. Genuine invalid bytes fail closed. |
| 423 | let mut buffer: Vec<u8> = Vec::new(); |
| 424 | // `data:` fields of the event being assembled, dispatched at the |
| 425 | // blank line that ends it (or at stream end). |
| 426 | let mut event_data = String::new(); |
| 427 | let mut done = false; |
| 428 | let mut ended = false; |
| 429 | let mut content_block_counter: u32 = 0; |
| 430 | let stream_start = std::time::Instant::now(); |
| 431 | let mut last_chunk_at = std::time::Instant::now(); |
| 432 | let mut bytes_received: usize = 0; |
| 433 | |
| 434 | tokio::pin!(byte_stream); |
| 435 | |
| 436 | while !done { |
| 437 | if !ended { |
| 438 | let wait = super::stream_entry::next_chunk_timeout( |
| 439 | stream_idle_timeout, |
| 440 | first_byte, |
| 441 | bytes_received, |
| 442 | ); |
| 443 | match tokio::time::timeout(wait, byte_stream.next()).await { |
| 444 | Ok(Some(Ok(chunk))) => { |
| 445 | bytes_received += chunk.len(); |
| 446 | last_chunk_at = std::time::Instant::now(); |
| 447 | buffer.extend_from_slice(&chunk); |
| 448 | } |
| 449 | Ok(Some(Err(e))) => { |
| 450 | yield Err(anyhow::anyhow!("Stream read error: {e}")); |
| 451 | return; |
| 452 | } |
| 453 | Ok(None) => ended = true, |
| 454 | Err(_) => { |
| 455 | yield Err(anyhow::anyhow!(super::stream_entry::body_timeout_message( |
| 456 | wait, |
| 457 | bytes_received, |
| 458 | stream_start.elapsed(), |
| 459 | last_chunk_at.elapsed(), |
| 460 | provider_label, |
| 461 | ))); |
| 462 | return; |
| 463 | } |
| 464 | } |
| 465 | } |
| 466 | |
| 467 | // Process complete SSE lines, and the unterminated tail at stream end. |
| 468 | loop { |
| 469 | let data = match next_sse_line(&mut buffer, ended) { |
| 470 | // A blank line ends the event. |
| 471 | Ok(Some(line)) if line.is_empty() => std::mem::take(&mut event_data), |
| 472 | Ok(Some(line)) => { |
| 473 | if line.starts_with(':') { |
| 474 | // SSE comment keep-alive: the provider is alive (#6184). |
| 475 | yield Ok(StreamEvent::Ping); |
| 476 | } else if let Some(value) = extract_sse_data_value(&line) |
| 477 | && let Err(err) = push_sse_event_data(&mut event_data, value) |
| 478 | { |
| 479 | if strict_terminal { |
| 480 | yield Err(LlmError::ParseError(err.to_string()).into()); |
| 481 | return; |
| 482 | } |
| 483 | yield Err(anyhow::anyhow!("{err}")); |
| 484 | return; |
| 485 | } |
| 486 | continue; |
| 487 | } |
| 488 | // The final event may arrive without its blank line. |
| 489 | Ok(None) if ended && !event_data.is_empty() => { |
| 490 | std::mem::take(&mut event_data) |
| 491 | } |
| 492 | Ok(None) => break, |
| 493 | Err(err) => { |
| 494 | if strict_terminal { |
| 495 | yield Err(LlmError::ParseError(err.to_string()).into()); |
| 496 | return; |
| 497 | } |
| 498 | yield Err(anyhow::anyhow!("{err}")); |
| 499 | return; |
| 500 | } |
| 501 | }; |
| 502 | if data.is_empty() { |
| 503 | continue; |
| 504 | } |
| 505 | |
| 506 | { |
| 507 | let data = data.as_str(); |
| 508 | if data == "[DONE]" { |
| 509 | if done_marker == DoneMarkerPolicy::Terminal { |
| 510 | done = true; |
| 511 | } |
| 512 | break; |
| 513 | } |
| 514 | |
| 515 | let event: Value = match serde_json::from_str(data) { |
| 516 | Ok(v) => v, |
| 517 | Err(e) => { |
| 518 | if malformed_json == MalformedEventPolicy::Fail { |
| 519 | yield Err(LlmError::ParseError("Invalid ChatGPT response event".into()).into()); |
| 520 | return; |
| 521 | } |
| 522 | logging::warn(format!( |
| 523 | "Failed to parse Responses SSE event: {e}" |
| 524 | )); |
| 525 | continue; |
| 526 | } |
| 527 | }; |
| 528 | |
| 529 | let event_type = |
| 530 | event.get("type").and_then(|t| t.as_str()).unwrap_or(""); |
| 531 | |
| 532 | match event_type { |
| 533 | "response.output_item.added" => { |
| 534 | if let Some(item) = event.get("item") { |
| 535 | let item_type = item |
| 536 | .get("type") |
| 537 | .and_then(|v| v.as_str()) |
| 538 | .unwrap_or(""); |
| 539 | |
| 540 | match item_type { |
| 541 | "message" => { |
| 542 | content_block_counter += 1; |
| 543 | yield Ok(StreamEvent::ContentBlockStart { |
| 544 | index: content_block_counter - 1, |
| 545 | content_block: ContentBlockStart::Text { |
| 546 | text: String::new(), |
| 547 | }, |
| 548 | }); |
| 549 | current_block_index = |
| 550 | Some(content_block_counter - 1); |
| 551 | } |
| 552 | "function_call" => { |
| 553 | if let Some(namespace) = tool_namespace |
| 554 | && item.get("namespace").and_then(Value::as_str) |
| 555 | != Some(namespace) |
| 556 | { |
| 557 | yield Err(LlmError::ParseError("ChatGPT returned a function outside the Codewhale tool namespace".into()).into()); |
| 558 | return; |
| 559 | } |
| 560 | let call_id = item |
| 561 | .get("call_id") |
| 562 | .and_then(|v| v.as_str()) |
| 563 | .unwrap_or("") |
| 564 | .to_string(); |
| 565 | let item_id = item |
| 566 | .get("id") |
| 567 | .and_then(|v| v.as_str()) |
| 568 | .unwrap_or("") |
| 569 | .to_string(); |
| 570 | let name = item |
| 571 | .get("name") |
| 572 | .and_then(|v| v.as_str()) |
| 573 | .unwrap_or("") |
| 574 | .to_string(); |
| 575 | saw_tool_call = true; |
| 576 | // call_id and item_id are folded |
| 577 | // into a composite tool-use id so |
| 578 | // the function_call_output can be |
| 579 | // routed back to the right call. |
| 580 | let composite_id = |
| 581 | format!("{call_id}|{item_id}"); |
| 582 | content_block_counter += 1; |
| 583 | yield Ok(StreamEvent::ContentBlockStart { |
| 584 | index: content_block_counter - 1, |
| 585 | content_block: |
| 586 | ContentBlockStart::ToolUse { |
| 587 | id: composite_id, |
| 588 | name: from_api_tool_name(&name), |
| 589 | input: json!({}), |
| 590 | caller: None, |
| 591 | thought_signature: None, |
| 592 | }, |
| 593 | }); |
| 594 | current_block_index = |
| 595 | Some(content_block_counter - 1); |
| 596 | } |
| 597 | "reasoning" => { |
| 598 | reasoning_text_emitted = false; |
| 599 | content_block_counter += 1; |
| 600 | yield Ok(StreamEvent::ContentBlockStart { |
| 601 | index: content_block_counter - 1, |
| 602 | content_block: |
| 603 | ContentBlockStart::Thinking { |
| 604 | thinking: String::new(), |
| 605 | }, |
| 606 | }); |
| 607 | current_block_index = |
| 608 | Some(content_block_counter - 1); |
| 609 | } |
| 610 | "web_search_call" => { |
| 611 | content_block_counter += 1; |
| 612 | let id = item |
| 613 | .get("id") |
| 614 | .and_then(Value::as_str) |
| 615 | .unwrap_or_default() |
| 616 | .to_string(); |
| 617 | let status = item |
| 618 | .get("status") |
| 619 | .and_then(Value::as_str) |
| 620 | .unwrap_or("in_progress") |
| 621 | .to_string(); |
| 622 | let kind = item |
| 623 | .get("kind") |
| 624 | .and_then(Value::as_str) |
| 625 | .map(str::to_string); |
| 626 | let action = item.get("action").cloned(); |
| 627 | yield Ok(StreamEvent::ContentBlockStart { |
| 628 | index: content_block_counter - 1, |
| 629 | content_block: ContentBlockStart::WebSearchCall { |
| 630 | id, |
| 631 | status, |
| 632 | kind, |
| 633 | action, |
| 634 | }, |
| 635 | }); |
| 636 | current_block_index = |
| 637 | Some(content_block_counter - 1); |
| 638 | } |
| 639 | _ => {} |
| 640 | } |
| 641 | } |
| 642 | } |
| 643 | "response.output_text.delta" => { |
| 644 | if let Some(delta_text) = |
| 645 | event.get("delta").and_then(|d| d.as_str()) |
| 646 | && let Some(idx) = current_block_index |
| 647 | { |
| 648 | yield Ok(StreamEvent::ContentBlockDelta { |
| 649 | index: idx, |
| 650 | delta: Delta::TextDelta { |
| 651 | text: delta_text.to_string(), |
| 652 | }, |
| 653 | }); |
| 654 | } |
| 655 | } |
| 656 | "response.function_call_arguments.delta" => { |
| 657 | if let Some(delta_text) = |
| 658 | event.get("delta").and_then(|d| d.as_str()) |
| 659 | && let Some(idx) = current_block_index |
| 660 | { |
| 661 | yield Ok(StreamEvent::ContentBlockDelta { |
| 662 | index: idx, |
| 663 | delta: Delta::InputJsonDelta { |
| 664 | partial_json: delta_text.to_string(), |
| 665 | }, |
| 666 | }); |
| 667 | } |
| 668 | } |
| 669 | "response.reasoning_summary_text.delta" |
| 670 | | "response.reasoning_text.delta" => { |
| 671 | if let Some(delta_text) = |
| 672 | event.get("delta").and_then(|d| d.as_str()) |
| 673 | && let Some(idx) = current_block_index |
| 674 | { |
| 675 | if !delta_text.is_empty() { |
| 676 | reasoning_text_emitted = true; |
| 677 | } |
| 678 | yield Ok(StreamEvent::ContentBlockDelta { |
| 679 | index: idx, |
| 680 | delta: Delta::ThinkingDelta { |
| 681 | thinking: delta_text.to_string(), |
| 682 | }, |
| 683 | }); |
| 684 | } |
| 685 | } |
| 686 | "response.reasoning_summary_part.added" => { |
| 687 | // Consecutive summary parts arrive with no |
| 688 | // separator in the text deltas, so without a |
| 689 | // boundary they concatenate as |
| 690 | // "…done.**Next Phase**…". Insert a paragraph |
| 691 | // break before every part after the first. |
| 692 | if reasoning_text_emitted |
| 693 | && let Some(idx) = current_block_index |
| 694 | { |
| 695 | yield Ok(StreamEvent::ContentBlockDelta { |
| 696 | index: idx, |
| 697 | delta: Delta::ThinkingDelta { |
| 698 | thinking: "\n\n".to_string(), |
| 699 | }, |
| 700 | }); |
| 701 | } |
| 702 | } |
| 703 | "response.output_text.annotation.added" => { |
| 704 | if let Some(citation) = event.get("annotation").cloned() |
| 705 | && let Some(idx) = current_block_index |
| 706 | { |
| 707 | yield Ok(StreamEvent::ContentBlockDelta { |
| 708 | index: idx, |
| 709 | delta: Delta::CitationsDelta { citation }, |
| 710 | }); |
| 711 | } |
| 712 | } |
| 713 | "response.refusal.delta" => { |
| 714 | if let Some(refusal) = event.get("delta").and_then(Value::as_str) |
| 715 | && let Some(idx) = current_block_index |
| 716 | { |
| 717 | yield Ok(StreamEvent::ContentBlockDelta { |
| 718 | index: idx, |
| 719 | delta: Delta::RefusalDelta { |
| 720 | refusal: refusal.to_string(), |
| 721 | }, |
| 722 | }); |
| 723 | } |
| 724 | } |
| 725 | "response.web_search_call.in_progress" |
| 726 | | "response.web_search_call.searching" |
| 727 | | "response.web_search_call.completed" => { |
| 728 | if let Some(idx) = current_block_index { |
| 729 | let status = event_type |
| 730 | .strip_prefix("response.web_search_call.") |
| 731 | .map(str::to_string); |
| 732 | yield Ok(StreamEvent::ContentBlockDelta { |
| 733 | index: idx, |
| 734 | delta: Delta::WebSearchCallDelta { |
| 735 | status, |
| 736 | kind: None, |
| 737 | action: event.get("action").cloned(), |
| 738 | sources: event.get("sources").cloned(), |
| 739 | page: event.get("page").cloned(), |
| 740 | signature: event |
| 741 | .get("signature") |
| 742 | .and_then(Value::as_str) |
| 743 | .map(str::to_string), |
| 744 | error: event.get("error").cloned(), |
| 745 | }, |
| 746 | }); |
| 747 | } |
| 748 | } |
| 749 | "response.output_item.done" => { |
| 750 | if let Some(idx) = current_block_index { |
| 751 | if let Some(item) = event.get("item") { |
| 752 | let item_type = item |
| 753 | .get("type") |
| 754 | .and_then(Value::as_str) |
| 755 | .unwrap_or(""); |
| 756 | if item_type == "web_search_call" { |
| 757 | yield Ok(StreamEvent::ContentBlockDelta { |
| 758 | index: idx, |
| 759 | delta: Delta::WebSearchCallDelta { |
| 760 | status: item |
| 761 | .get("status") |
| 762 | .and_then(Value::as_str) |
| 763 | .map(str::to_string), |
| 764 | kind: item |
| 765 | .get("kind") |
| 766 | .and_then(Value::as_str) |
| 767 | .map(str::to_string), |
| 768 | action: item.get("action").cloned(), |
| 769 | sources: item |
| 770 | .get("sources") |
| 771 | .cloned() |
| 772 | .or_else(|| { |
| 773 | item.pointer("/action/sources").cloned() |
| 774 | }), |
| 775 | page: item.get("page").cloned(), |
| 776 | signature: item |
| 777 | .get("signature") |
| 778 | .and_then(Value::as_str) |
| 779 | .map(str::to_string), |
| 780 | error: item.get("error").cloned(), |
| 781 | }, |
| 782 | }); |
| 783 | } else if item_type == "message" |
| 784 | && let Some(parts) = |
| 785 | item.get("content").and_then(Value::as_array) |
| 786 | { |
| 787 | for part in parts { |
| 788 | if part.get("type").and_then(Value::as_str) |
| 789 | == Some("refusal") |
| 790 | && let Some(refusal) = part |
| 791 | .get("refusal") |
| 792 | .and_then(Value::as_str) |
| 793 | .filter(|s| !s.is_empty()) |
| 794 | { |
| 795 | yield Ok(StreamEvent::ContentBlockDelta { |
| 796 | index: idx, |
| 797 | delta: Delta::RefusalDelta { |
| 798 | refusal: refusal.to_string(), |
| 799 | }, |
| 800 | }); |
| 801 | } |
| 802 | } |
| 803 | } else if let Some((provider, api, model)) = |
| 804 | reasoning_origin.as_ref() |
| 805 | && item_type == "reasoning" |
| 806 | && let Some(encrypted_content) = item |
| 807 | .get("encrypted_content") |
| 808 | .and_then(Value::as_str) |
| 809 | .filter(|value| !value.is_empty()) |
| 810 | { |
| 811 | yield Ok(StreamEvent::ContentBlockDelta { |
| 812 | index: idx, |
| 813 | delta: Delta::ReasoningStateDelta { |
| 814 | state: OpaqueReasoningState { |
| 815 | provider: provider.clone(), |
| 816 | api: api.clone(), |
| 817 | model: model.clone(), |
| 818 | id: item |
| 819 | .get("id") |
| 820 | .and_then(Value::as_str) |
| 821 | .map(str::to_string), |
| 822 | encrypted_content: encrypted_content |
| 823 | .to_string(), |
| 824 | }, |
| 825 | }, |
| 826 | }); |
| 827 | } |
| 828 | } |
| 829 | yield Ok(StreamEvent::ContentBlockStop { index: idx }); |
| 830 | current_block_index = None; |
| 831 | } |
| 832 | } |
| 833 | "response.completed" | "response.incomplete" => { |
| 834 | if strict_terminal && !event.get("response").is_some_and(Value::is_object) { |
| 835 | yield Err(LlmError::ParseError("ChatGPT completion event has no response".into()).into()); |
| 836 | return; |
| 837 | } |
| 838 | if strict_terminal && event_type == "response.completed" && string_at(&event, "/response/status") != Some("completed") { |
| 839 | yield Err(LlmError::ParseError("ChatGPT completion event has an unsuccessful status".into()).into()); |
| 840 | return; |
| 841 | } |
| 842 | if event_type == "response.incomplete" |
| 843 | && incomplete == IncompleteResponsePolicy::Fail |
| 844 | { |
| 845 | if let Some(usage_val) = event.pointer("/response/usage") { |
| 846 | yield Ok(StreamEvent::MessageDelta { |
| 847 | delta: MessageDelta { |
| 848 | stop_reason: None, |
| 849 | stop_sequence: None, |
| 850 | title: None, |
| 851 | stop_details: None, |
| 852 | refusal: None, |
| 853 | }, |
| 854 | usage: Some(parse_responses_usage(usage_val)), |
| 855 | }); |
| 856 | } |
| 857 | let (code, msg) = responses_event_error_details(&event); |
| 858 | let code = super::redact_model_bound_text(&code, &error_secrets); |
| 859 | let msg = super::redact_model_bound_text(&msg, &error_secrets); |
| 860 | yield Err(LlmError::ParseError(format!("ChatGPT response incomplete [{code}]: {msg}")).into()); |
| 861 | return; |
| 862 | } |
| 863 | if let Some(resp) = event.get("response") { |
| 864 | if let Some(usage_val) = resp.get("usage") { |
| 865 | usage_data = |
| 866 | Some(parse_responses_usage(usage_val)); |
| 867 | } |
| 868 | let stop_reason = responses_stop_reason(resp, saw_tool_call); |
| 869 | let title = resp |
| 870 | .get("title") |
| 871 | .and_then(Value::as_str) |
| 872 | .map(str::to_string); |
| 873 | let stop_details = resp.get("incomplete_details").cloned(); |
| 874 | yield Ok(StreamEvent::MessageDelta { |
| 875 | delta: MessageDelta { |
| 876 | stop_reason: Some(stop_reason), |
| 877 | stop_sequence: None, |
| 878 | title, |
| 879 | stop_details, |
| 880 | refusal: None, |
| 881 | }, |
| 882 | usage: usage_data.take(), |
| 883 | }); |
| 884 | } else { |
| 885 | yield Ok(StreamEvent::MessageDelta { |
| 886 | delta: MessageDelta { |
| 887 | stop_reason: Some( |
| 888 | "incomplete:unknown_status".to_string(), |
| 889 | ), |
| 890 | stop_sequence: None, |
| 891 | title: None, |
| 892 | stop_details: None, |
| 893 | refusal: None, |
| 894 | }, |
| 895 | usage: usage_data.take(), |
| 896 | }); |
| 897 | } |
| 898 | // DeepSeek terminates semantic Responses |
| 899 | // streams with this event and deliberately does |
| 900 | // not send `data: [DONE]`. |
| 901 | done = true; |
| 902 | } |
| 903 | "error" | "response.failed" => { |
| 904 | let (code, msg) = responses_event_error_details(&event); |
| 905 | if strict_terminal { |
| 906 | if let Some(usage_val) = event.pointer("/response/usage") { |
| 907 | yield Ok(StreamEvent::MessageDelta { |
| 908 | delta: MessageDelta { |
| 909 | stop_reason: None, |
| 910 | stop_sequence: None, |
| 911 | title: None, |
| 912 | stop_details: None, |
| 913 | refusal: None, |
| 914 | }, |
| 915 | usage: Some(parse_responses_usage(usage_val)), |
| 916 | }); |
| 917 | } |
| 918 | if codex_identity |
| 919 | && let Some(error) = |
| 920 | LlmError::from_subscription_sharing_error_code(&code) |
| 921 | { |
| 922 | yield Err(error.into()); |
| 923 | return; |
| 924 | } |
| 925 | } |
| 926 | let code = super::redact_model_bound_text(&code, &error_secrets); |
| 927 | let msg = super::redact_model_bound_text(&msg, &error_secrets); |
| 928 | if strict_terminal { |
| 929 | yield Err(LlmError::ModelError(format!("Responses API error [{code}]: {msg}")).into()); |
| 930 | return; |
| 931 | } |
| 932 | yield Err(anyhow::anyhow!( |
| 933 | "Responses API error [{code}]: {msg}" |
| 934 | )); |
| 935 | return; |
| 936 | } |
| 937 | _ => { |
| 938 | // Ignore unknown event types. |
| 939 | } |
| 940 | } |
| 941 | } |
| 942 | } |
| 943 | |
| 944 | if ended { |
| 945 | break; |
| 946 | } |
| 947 | } |
| 948 | |
| 949 | // A strict completion profile requires a successful response.completed |
| 950 | // event. Other Responses profiles also accept their documented |
| 951 | // terminal markers. A bare HTTP EOF is truncation, and a |
| 952 | // MessageStop here would hand the turn a partial answer as done. |
| 953 | if !done { |
| 954 | if strict_terminal { |
| 955 | yield Err(LlmError::ParseError("ChatGPT Responses stream closed before a successful completion event".into()).into()); |
| 956 | return; |
| 957 | } |
| 958 | yield Err(anyhow::anyhow!( |
| 959 | "Responses stream closed before a successful completion event" |
| 960 | )); |
| 961 | return; |
| 962 | } |
| 963 | yield Ok(StreamEvent::MessageStop); |
| 964 | }; |
| 965 | |
| 966 | Ok(Box::pin(stream)) |
| 967 | } |
| 968 | |
| 969 | /// Non-streaming Responses request: drive the streaming handler and fold |
| 970 | /// its events into a single `MessageResponse`. |
| 971 | /// |
| 972 | /// The official ChatGPT plan preview requires streaming. The blocking |
| 973 | /// entry point (`create_message`, used by `exec`) folds that same wire path. |
| 974 | pub(super) async fn handle_responses_message( |
| 975 | &self, |
| 976 | prepared: &super::PreparedOutboundRequest, |
| 977 | ) -> Result<MessageResponse> { |
| 978 | use futures_util::StreamExt; |
| 979 | |
| 980 | let model = prepared.wire_model.clone(); |
| 981 | let mut stream = self.handle_responses_stream(prepared).await?; |
| 982 | |
| 983 | let mut response = MessageResponse { |
| 984 | tool_projection_warning: None, |
| 985 | id: String::new(), |
| 986 | r#type: "message".to_string(), |
| 987 | role: "assistant".to_string(), |
| 988 | content: Vec::new(), |
| 989 | model, |
| 990 | stop_reason: None, |
| 991 | stop_sequence: None, |
| 992 | container: None, |
| 993 | usage: Usage::default(), |
| 994 | title: None, |
| 995 | stop_details: None, |
| 996 | refusal: None, |
| 997 | }; |
| 998 | // Accumulated tool-call argument JSON, parallel to `response.content`. |
| 999 | let mut tool_args: Vec<String> = Vec::new(); |
| 1000 | |
| 1001 | while let Some(event) = stream.next().await { |
| 1002 | match event? { |
| 1003 | StreamEvent::MessageStart { message } => { |
| 1004 | response.id = message.id; |
| 1005 | response.usage = message.usage; |
| 1006 | if message.title.is_some() { |
| 1007 | response.title = message.title; |
| 1008 | } |
| 1009 | } |
| 1010 | StreamEvent::ContentBlockStart { content_block, .. } => { |
| 1011 | let block = match content_block { |
| 1012 | ContentBlockStart::Text { text } => ContentBlock::Text { |
| 1013 | text, |
| 1014 | cache_control: None, |
| 1015 | }, |
| 1016 | ContentBlockStart::Thinking { thinking } => ContentBlock::Thinking { |
| 1017 | thinking, |
| 1018 | signature: None, |
| 1019 | state: None, |
| 1020 | redacted_data: None, |
| 1021 | }, |
| 1022 | // Redacted thinking does not occur on Responses |
| 1023 | // routes (encrypted reasoning rides the reasoning |
| 1024 | // item's `encrypted_content` instead); keep the |
| 1025 | // match total without inventing a block shape. |
| 1026 | ContentBlockStart::RedactedThinking { .. } => { |
| 1027 | continue; |
| 1028 | } |
| 1029 | ContentBlockStart::ToolUse { |
| 1030 | id, |
| 1031 | name, |
| 1032 | input, |
| 1033 | caller, |
| 1034 | thought_signature, |
| 1035 | } => ContentBlock::ToolUse { |
| 1036 | execution_id: None, |
| 1037 | id, |
| 1038 | name, |
| 1039 | input, |
| 1040 | caller, |
| 1041 | thought_signature, |
| 1042 | }, |
| 1043 | ContentBlockStart::ServerToolUse { |
| 1044 | id, |
| 1045 | name, |
| 1046 | input, |
| 1047 | kind, |
| 1048 | caller, |
| 1049 | } => ContentBlock::ServerToolUse { |
| 1050 | id, |
| 1051 | name, |
| 1052 | input, |
| 1053 | kind, |
| 1054 | caller, |
| 1055 | }, |
| 1056 | ContentBlockStart::WebSearchToolResult { |
| 1057 | tool_use_id, |
| 1058 | content, |
| 1059 | kind, |
| 1060 | } => ContentBlock::WebSearchToolResult { |
| 1061 | tool_use_id, |
| 1062 | content, |
| 1063 | kind, |
| 1064 | }, |
| 1065 | ContentBlockStart::WebFetchToolResult { |
| 1066 | tool_use_id, |
| 1067 | content, |
| 1068 | kind, |
| 1069 | signature, |
| 1070 | } => ContentBlock::WebFetchToolResult { |
| 1071 | tool_use_id, |
| 1072 | content, |
| 1073 | kind, |
| 1074 | signature, |
| 1075 | }, |
| 1076 | ContentBlockStart::WebSearchCall { |
| 1077 | id, |
| 1078 | status, |
| 1079 | kind, |
| 1080 | action, |
| 1081 | } => ContentBlock::WebSearchCall { |
| 1082 | id, |
| 1083 | status, |
| 1084 | kind, |
| 1085 | action, |
| 1086 | sources: None, |
| 1087 | page: None, |
| 1088 | signature: None, |
| 1089 | error: None, |
| 1090 | }, |
| 1091 | ContentBlockStart::ServerToolCalls { steps } => { |
| 1092 | ContentBlock::ServerToolCalls { steps } |
| 1093 | } |
| 1094 | }; |
| 1095 | response.content.push(block); |
| 1096 | tool_args.push(String::new()); |
| 1097 | } |
| 1098 | StreamEvent::ContentBlockDelta { index, delta } => { |
| 1099 | let i = index as usize; |
| 1100 | match delta { |
| 1101 | Delta::TextDelta { text } => { |
| 1102 | if let Some(ContentBlock::Text { text: existing, .. }) = |
| 1103 | response.content.get_mut(i) |
| 1104 | { |
| 1105 | existing.push_str(&text); |
| 1106 | } |
| 1107 | } |
| 1108 | Delta::ThinkingDelta { thinking } => { |
| 1109 | if let Some(ContentBlock::Thinking { |
| 1110 | thinking: existing, .. |
| 1111 | }) = response.content.get_mut(i) |
| 1112 | { |
| 1113 | existing.push_str(&thinking); |
| 1114 | } |
| 1115 | } |
| 1116 | Delta::InputJsonDelta { partial_json } => { |
| 1117 | if let Some(buf) = tool_args.get_mut(i) { |
| 1118 | buf.push_str(&partial_json); |
| 1119 | } |
| 1120 | } |
| 1121 | Delta::ToolCallIdDelta { id } => { |
| 1122 | if let Some(ContentBlock::ToolUse { id: existing, .. }) = |
| 1123 | response.content.get_mut(i) |
| 1124 | { |
| 1125 | *existing = id; |
| 1126 | } |
| 1127 | } |
| 1128 | Delta::SignatureDelta { .. } | Delta::ThoughtSignatureDelta { .. } => {} |
| 1129 | Delta::ReasoningStateDelta { state } => { |
| 1130 | if let Some(ContentBlock::Thinking { |
| 1131 | state: existing, .. |
| 1132 | }) = response.content.get_mut(i) |
| 1133 | { |
| 1134 | *existing = Some(state); |
| 1135 | } |
| 1136 | } |
| 1137 | Delta::CitationsDelta { .. } => {} |
| 1138 | Delta::RefusalDelta { refusal } => { |
| 1139 | response |
| 1140 | .refusal |
| 1141 | .get_or_insert_with(String::new) |
| 1142 | .push_str(&refusal); |
| 1143 | } |
| 1144 | Delta::WebSearchCallDelta { |
| 1145 | status, |
| 1146 | kind, |
| 1147 | action, |
| 1148 | sources, |
| 1149 | page, |
| 1150 | signature, |
| 1151 | error, |
| 1152 | } => { |
| 1153 | if let Some(ContentBlock::WebSearchCall { |
| 1154 | status: existing_status, |
| 1155 | kind: existing_kind, |
| 1156 | action: existing_action, |
| 1157 | sources: existing_sources, |
| 1158 | page: existing_page, |
| 1159 | signature: existing_signature, |
| 1160 | error: existing_error, |
| 1161 | .. |
| 1162 | }) = response.content.get_mut(i) |
| 1163 | { |
| 1164 | if let Some(status) = status { |
| 1165 | *existing_status = status; |
| 1166 | } |
| 1167 | if kind.is_some() { |
| 1168 | *existing_kind = kind; |
| 1169 | } |
| 1170 | if action.is_some() { |
| 1171 | *existing_action = action; |
| 1172 | } |
| 1173 | if sources.is_some() { |
| 1174 | *existing_sources = sources; |
| 1175 | } |
| 1176 | if page.is_some() { |
| 1177 | *existing_page = page; |
| 1178 | } |
| 1179 | if signature.is_some() { |
| 1180 | *existing_signature = signature; |
| 1181 | } |
| 1182 | if error.is_some() { |
| 1183 | *existing_error = error; |
| 1184 | } |
| 1185 | } |
| 1186 | } |
| 1187 | Delta::ServerToolCallsDelta { steps } => { |
| 1188 | if let Some(ContentBlock::ServerToolCalls { steps: existing }) = |
| 1189 | response.content.get_mut(i) |
| 1190 | { |
| 1191 | *existing = steps; |
| 1192 | } |
| 1193 | } |
| 1194 | } |
| 1195 | } |
| 1196 | StreamEvent::ContentBlockStop { index } => { |
| 1197 | let i = index as usize; |
| 1198 | if let Some(buf) = tool_args.get(i) |
| 1199 | && !buf.trim().is_empty() |
| 1200 | && let Ok(parsed) = serde_json::from_str::<Value>(buf) |
| 1201 | && let Some(ContentBlock::ToolUse { input, .. }) = |
| 1202 | response.content.get_mut(i) |
| 1203 | { |
| 1204 | *input = parsed; |
| 1205 | } |
| 1206 | } |
| 1207 | StreamEvent::MessageDelta { delta, usage } => { |
| 1208 | if let Some(stop_reason) = delta.stop_reason { |
| 1209 | response.stop_reason = Some(stop_reason); |
| 1210 | } |
| 1211 | if let Some(title) = delta.title { |
| 1212 | response.title = Some(title); |
| 1213 | } |
| 1214 | if let Some(stop_details) = delta.stop_details { |
| 1215 | response.stop_details = Some(stop_details); |
| 1216 | } |
| 1217 | if let Some(refusal) = delta.refusal { |
| 1218 | response.refusal = Some(refusal); |
| 1219 | } |
| 1220 | if let Some(usage) = usage { |
| 1221 | response.usage = usage; |
| 1222 | } |
| 1223 | } |
| 1224 | StreamEvent::MessageStop => break, |
| 1225 | _ => {} |
| 1226 | } |
| 1227 | } |
| 1228 | |
| 1229 | Ok(response) |
| 1230 | } |
| 1231 | } |
| 1232 | |
| 1233 | pub(super) fn responses_tool_output(content: &str, content_blocks: Option<&[Value]>) -> Value { |
| 1234 | let (image, omitted) = crate::image_attach::provider_tool_result_image_refs(content_blocks); |
| 1235 | let content = codewhale_models::image_window::tool_result_text_with_omission(content, omitted); |
| 1236 | let Some((mime_type, data)) = image else { |
| 1237 | return json!(content); |
| 1238 | }; |
| 1239 | let mut output = Vec::with_capacity(2); |
| 1240 | if !content.is_empty() { |
| 1241 | output.push(json!({ "type": "input_text", "text": content })); |
| 1242 | } |
| 1243 | output.push(json!({ |
| 1244 | "type": "input_image", |
| 1245 | "image_url": format!("data:{mime_type};base64,{data}"), |
| 1246 | "detail": "auto", |
| 1247 | })); |
| 1248 | json!(output) |
| 1249 | } |
| 1250 | |
| 1251 | /// Convert Codewhale messages to Responses API input items. |
| 1252 | pub(super) fn convert_messages_to_responses_input( |
| 1253 | request: &MessageRequest, |
| 1254 | profile: &ResponsesDialectProfile, |
| 1255 | context: ResponsesReplayContext<'_>, |
| 1256 | ) -> Vec<Value> { |
| 1257 | let plain_with_placeholder = |
| 1258 | profile.replay.plain_reasoning == PlainReasoningReplayPolicy::PlainTextWithToolPlaceholder; |
| 1259 | let mut items = Vec::new(); |
| 1260 | |
| 1261 | for msg in &request.messages { |
| 1262 | // Channel selection lives in the shared placement table; this adapter |
| 1263 | // owns only the shape of each channel's items. |
| 1264 | let placement = role_placement(&msg.role, WireDialect::OpenAiResponses); |
| 1265 | match placement { |
| 1266 | RolePlacement::User => { |
| 1267 | let mut content_items = Vec::new(); |
| 1268 | for block in &msg.content { |
| 1269 | match block { |
| 1270 | ContentBlock::Text { text, .. } => { |
| 1271 | content_items.push(json!({ |
| 1272 | "type": "input_text", |
| 1273 | "text": text, |
| 1274 | })); |
| 1275 | } |
| 1276 | ContentBlock::ImageUrl { image_url } => { |
| 1277 | content_items.push(json!({ |
| 1278 | "type": "input_image", |
| 1279 | "image_url": image_url.url, |
| 1280 | })); |
| 1281 | } |
| 1282 | ContentBlock::File { file_id } => { |
| 1283 | content_items.push(json!({ |
| 1284 | "type": "input_file", |
| 1285 | "file_id": file_id, |
| 1286 | })); |
| 1287 | } |
| 1288 | ContentBlock::ToolResult { |
| 1289 | tool_use_id, |
| 1290 | content, |
| 1291 | content_blocks, |
| 1292 | .. |
| 1293 | } => { |
| 1294 | if !content_items.is_empty() { |
| 1295 | items.push(json!({ |
| 1296 | "type": "message", |
| 1297 | "role": "user", |
| 1298 | "content": content_items, |
| 1299 | })); |
| 1300 | content_items = Vec::new(); |
| 1301 | } |
| 1302 | let (call_id, _item_id) = parse_tool_use_id(tool_use_id); |
| 1303 | items.push(json!({ |
| 1304 | "type": "function_call_output", |
| 1305 | "call_id": call_id, |
| 1306 | "output": responses_tool_output(content, content_blocks.as_deref()), |
| 1307 | })); |
| 1308 | } |
| 1309 | _ => {} |
| 1310 | } |
| 1311 | } |
| 1312 | if !content_items.is_empty() { |
| 1313 | items.push(json!({ |
| 1314 | "type": "message", |
| 1315 | "role": "user", |
| 1316 | "content": content_items, |
| 1317 | })); |
| 1318 | } |
| 1319 | } |
| 1320 | RolePlacement::Assistant | RolePlacement::InterruptedAssistant => { |
| 1321 | let reasoning_item = |block: &ContentBlock| -> Option<Value> { |
| 1322 | let ContentBlock::Thinking { |
| 1323 | thinking, state, .. |
| 1324 | } = block |
| 1325 | else { |
| 1326 | return None; |
| 1327 | }; |
| 1328 | if let Some(state) = state { |
| 1329 | let api_matches = match profile.replay.encrypted_state { |
| 1330 | EncryptedReasoningReplayPolicy::AccountApiModelScoped => { |
| 1331 | context.reasoning_api_id.is_some_and(|api| state.api == api) |
| 1332 | } |
| 1333 | EncryptedReasoningReplayPolicy::ProviderApiModelScoped => { |
| 1334 | state.api == "openai-responses" |
| 1335 | } |
| 1336 | EncryptedReasoningReplayPolicy::Disabled => false, |
| 1337 | }; |
| 1338 | let matches = state.provider == context.provider_id |
| 1339 | && api_matches |
| 1340 | && state.model == context.wire_model_id; |
| 1341 | if !matches { |
| 1342 | return None; |
| 1343 | } |
| 1344 | let mut item = json!({ |
| 1345 | "type": "reasoning", |
| 1346 | "summary": [], |
| 1347 | "encrypted_content": state.encrypted_content, |
| 1348 | }); |
| 1349 | if let Some(id) = state.id.as_ref() { |
| 1350 | item["id"] = json!(id); |
| 1351 | } |
| 1352 | return Some(item); |
| 1353 | } |
| 1354 | matches!( |
| 1355 | profile.replay.plain_reasoning, |
| 1356 | PlainReasoningReplayPolicy::PlainText |
| 1357 | | PlainReasoningReplayPolicy::PlainTextWithToolPlaceholder |
| 1358 | ) |
| 1359 | .then(|| { |
| 1360 | let text = if thinking.trim().is_empty() { |
| 1361 | REASONING_REPLAY_PLACEHOLDER |
| 1362 | } else { |
| 1363 | thinking.as_str() |
| 1364 | }; |
| 1365 | json!({ |
| 1366 | "type": "reasoning", |
| 1367 | "content": [{ |
| 1368 | "type": "reasoning_text", |
| 1369 | "text": text, |
| 1370 | }], |
| 1371 | }) |
| 1372 | }) |
| 1373 | }; |
| 1374 | if plain_with_placeholder { |
| 1375 | let before = items.len(); |
| 1376 | items.extend(msg.content.iter().filter_map(&reasoning_item)); |
| 1377 | if items.len() == before |
| 1378 | && msg |
| 1379 | .content |
| 1380 | .iter() |
| 1381 | .any(|block| matches!(block, ContentBlock::ToolUse { .. })) |
| 1382 | { |
| 1383 | items.push(json!({ |
| 1384 | "type": "reasoning", |
| 1385 | "content": [{ |
| 1386 | "type": "reasoning_text", |
| 1387 | "text": REASONING_REPLAY_PLACEHOLDER, |
| 1388 | }], |
| 1389 | })); |
| 1390 | } |
| 1391 | } |
| 1392 | for block in &msg.content { |
| 1393 | match block { |
| 1394 | ContentBlock::Text { text, .. } => { |
| 1395 | let text = if placement == RolePlacement::InterruptedAssistant { |
| 1396 | format!( |
| 1397 | "{}{}", |
| 1398 | codewhale_models::INTERRUPTED_ASSISTANT_CONTEXT_PREFIX, |
| 1399 | text |
| 1400 | ) |
| 1401 | } else { |
| 1402 | text.clone() |
| 1403 | }; |
| 1404 | items.push(json!({ |
| 1405 | "type": "message", |
| 1406 | "role": "assistant", |
| 1407 | "content": [{ |
| 1408 | "type": "output_text", |
| 1409 | "text": text, |
| 1410 | }], |
| 1411 | })); |
| 1412 | } |
| 1413 | ContentBlock::ToolUse { |
| 1414 | id, name, input, .. |
| 1415 | } => { |
| 1416 | let (call_id, _item_id) = parse_tool_use_id(id); |
| 1417 | let mut item = json!({ |
| 1418 | "type": "function_call", |
| 1419 | "call_id": call_id, |
| 1420 | "name": to_api_tool_name(name), |
| 1421 | "arguments": serde_json::to_string(input).unwrap_or_default(), |
| 1422 | }); |
| 1423 | if let Some(namespace) = profile.tools.namespace { |
| 1424 | item["namespace"] = json!(namespace); |
| 1425 | } |
| 1426 | items.push(item); |
| 1427 | } |
| 1428 | ContentBlock::Thinking { .. } if !plain_with_placeholder => { |
| 1429 | if let Some(item) = reasoning_item(block) { |
| 1430 | items.push(item); |
| 1431 | } |
| 1432 | } |
| 1433 | ContentBlock::WebSearchCall { |
| 1434 | id, |
| 1435 | status, |
| 1436 | kind, |
| 1437 | action, |
| 1438 | sources, |
| 1439 | page, |
| 1440 | signature, |
| 1441 | error, |
| 1442 | } => { |
| 1443 | let mut item = json!({ "type": "web_search_call" }); |
| 1444 | if !id.is_empty() { |
| 1445 | item["id"] = json!(id); |
| 1446 | } |
| 1447 | if !status.is_empty() { |
| 1448 | item["status"] = json!(status); |
| 1449 | } |
| 1450 | if let Some(kind) = kind { |
| 1451 | item["kind"] = json!(kind); |
| 1452 | } |
| 1453 | if let Some(action) = action { |
| 1454 | item["action"] = action.clone(); |
| 1455 | } |
| 1456 | if let Some(sources) = sources { |
| 1457 | item["sources"] = sources.clone(); |
| 1458 | } |
| 1459 | if let Some(page) = page { |
| 1460 | item["page"] = page.clone(); |
| 1461 | } |
| 1462 | if let Some(signature) = signature { |
| 1463 | item["signature"] = json!(signature); |
| 1464 | } |
| 1465 | if let Some(error) = error { |
| 1466 | item["error"] = error.clone(); |
| 1467 | } |
| 1468 | items.push(item); |
| 1469 | } |
| 1470 | _ => {} |
| 1471 | } |
| 1472 | } |
| 1473 | } |
| 1474 | // `System` and `Developer` are typed placements for load-bearing |
| 1475 | // in-history context. `Omitted` also receives compatible transcript |
| 1476 | // spellings that predate the closed Role enum; preserve the |
| 1477 | // representable `tool`, `system`, and `developer` wire shapes |
| 1478 | // instead of silently deleting them. |
| 1479 | RolePlacement::System | RolePlacement::Developer | RolePlacement::Omitted => { |
| 1480 | match msg.role.as_str() { |
| 1481 | "tool" => { |
| 1482 | for block in &msg.content { |
| 1483 | if let ContentBlock::ToolResult { |
| 1484 | tool_use_id, |
| 1485 | content, |
| 1486 | content_blocks, |
| 1487 | .. |
| 1488 | } = block |
| 1489 | { |
| 1490 | let (call_id, _item_id) = parse_tool_use_id(tool_use_id); |
| 1491 | items.push(json!({ |
| 1492 | "type": "function_call_output", |
| 1493 | "call_id": call_id, |
| 1494 | "output": responses_tool_output( |
| 1495 | content, |
| 1496 | content_blocks.as_deref(), |
| 1497 | ), |
| 1498 | })); |
| 1499 | } |
| 1500 | } |
| 1501 | } |
| 1502 | role @ ("system" | "developer") => { |
| 1503 | let content_items: Vec<Value> = msg |
| 1504 | .content |
| 1505 | .iter() |
| 1506 | .filter_map(|block| match block { |
| 1507 | ContentBlock::Text { text, .. } => Some(json!({ |
| 1508 | "type": "input_text", |
| 1509 | "text": text, |
| 1510 | })), |
| 1511 | _ => None, |
| 1512 | }) |
| 1513 | .collect(); |
| 1514 | if !content_items.is_empty() { |
| 1515 | items.push(json!({ |
| 1516 | "type": "message", |
| 1517 | "role": if profile.replay.system_role |
| 1518 | == SystemRoleReplayPolicy::SystemToDeveloper |
| 1519 | && role == "system" |
| 1520 | { |
| 1521 | "developer" |
| 1522 | } else { |
| 1523 | role |
| 1524 | }, |
| 1525 | "content": content_items, |
| 1526 | })); |
| 1527 | } |
| 1528 | } |
| 1529 | other => { |
| 1530 | logging::warn(format!( |
| 1531 | "Responses adapter dropped a message with unsupported role {other:?}" |
| 1532 | )); |
| 1533 | } |
| 1534 | } |
| 1535 | } |
| 1536 | // The outbound seam refuses rejected pairs before body building; |
| 1537 | // keeping this arm empty is fail-closed defense in depth. |
| 1538 | RolePlacement::Rejected | RolePlacement::LatestReminder => {} |
| 1539 | } |
| 1540 | } |
| 1541 | |
| 1542 | items |
| 1543 | } |
| 1544 | |
| 1545 | fn responses_function_envelope( |
| 1546 | tool: &Tool, |
| 1547 | parameters: Value, |
| 1548 | strict: Option<bool>, |
| 1549 | constraint_note: Option<String>, |
| 1550 | ) -> Value { |
| 1551 | let mut value = json!({ |
| 1552 | "type": "function", |
| 1553 | "name": to_api_tool_name(&tool.name), |
| 1554 | "description": description_with_constraint_note(&tool.description, constraint_note), |
| 1555 | "parameters": parameters, |
| 1556 | }); |
| 1557 | if let Some(strict) = strict { |
| 1558 | value["strict"] = json!(strict); |
| 1559 | } |
| 1560 | value |
| 1561 | } |
| 1562 | |
| 1563 | #[cfg(test)] |
| 1564 | fn tool_to_responses_function(tool: &Tool) -> Value { |
| 1565 | let (ToolSchemaProjection::Exact { |
| 1566 | parameters, |
| 1567 | strict, |
| 1568 | constraint_note, |
| 1569 | } |
| 1570 | | ToolSchemaProjection::Relaxed { |
| 1571 | parameters, |
| 1572 | strict, |
| 1573 | constraint_note, |
| 1574 | }) = project_tool_schema( |
| 1575 | RouteToolProjection::RelaxedNonStrict, |
| 1576 | &tool.input_schema, |
| 1577 | tool.strict, |
| 1578 | ) |
| 1579 | else { |
| 1580 | panic!("responses projection never omits"); |
| 1581 | }; |
| 1582 | responses_function_envelope(tool, parameters, strict, constraint_note) |
| 1583 | } |
| 1584 | |
| 1585 | fn codex_responses_reasoning_effort(raw: &str) -> Option<&'static str> { |
| 1586 | crate::reasoning_preference::ReasoningEffort::parse_strict(raw) |
| 1587 | .unwrap_or(crate::reasoning_preference::ReasoningEffort::Medium) |
| 1588 | .api_value_for_provider(ProviderKind::OpenaiCodex) |
| 1589 | } |
| 1590 | |
| 1591 | fn compatible_responses_reasoning_effort(raw: &str) -> Option<&'static str> { |
| 1592 | match raw.trim().to_ascii_lowercase().as_str() { |
| 1593 | "off" | "disabled" | "none" | "false" => Some("low"), |
| 1594 | "minimal" => Some("low"), |
| 1595 | "low" => Some("low"), |
| 1596 | "high" => Some("high"), |
| 1597 | "xhigh" | "max" | "maximum" | "ultra" | "ultracode" => Some("xhigh"), |
| 1598 | _ => Some("medium"), |
| 1599 | } |
| 1600 | } |
| 1601 | |
| 1602 | /// DeepSeek's Responses wire spelling of the shared tier table |
| 1603 | /// (`client::deepseek_effort`), which is the single annotated source for the |
| 1604 | /// tier ladder — including the documented `"none"` off tier, so the picker's |
| 1605 | /// Off entry stays off instead of collapsing into a still-thinking low. |
| 1606 | /// |
| 1607 | /// Unknown tiers normalize to the table's default tier. |
| 1608 | pub(super) fn responses_reasoning_effort(raw: &str, is_deepseek: bool) -> Option<&'static str> { |
| 1609 | if !is_deepseek { |
| 1610 | return compatible_responses_reasoning_effort(raw); |
| 1611 | } |
| 1612 | if raw.trim().eq_ignore_ascii_case("auto") { |
| 1613 | return None; |
| 1614 | } |
| 1615 | Some(super::deepseek_effort::deepseek_effort_tier_or_default(raw).responses_effort()) |
| 1616 | } |
| 1617 | |
| 1618 | fn responses_event_error_details(event: &Value) -> (String, String) { |
| 1619 | let event_type = string_at(event, "/type").unwrap_or("error"); |
| 1620 | let code = first_string_at( |
| 1621 | event, |
| 1622 | &[ |
| 1623 | "/code", |
| 1624 | "/error/code", |
| 1625 | "/response/error/code", |
| 1626 | "/response/incomplete_details/reason", |
| 1627 | "/response/status", |
| 1628 | ], |
| 1629 | ) |
| 1630 | .unwrap_or("unknown"); |
| 1631 | let message = LlmError::from_subscription_sharing_error_code(code).map_or_else( |
| 1632 | || { |
| 1633 | first_string_at( |
| 1634 | event, |
| 1635 | &[ |
| 1636 | "/message", |
| 1637 | "/error/message", |
| 1638 | "/response/error/message", |
| 1639 | "/response/incomplete_details/reason", |
| 1640 | ], |
| 1641 | ) |
| 1642 | .map_or_else( |
| 1643 | || format!("{event_type} event received"), |
| 1644 | |message| { |
| 1645 | if message == code && event_type == "response.incomplete" { |
| 1646 | format!("response incomplete: {message}") |
| 1647 | } else { |
| 1648 | message.to_string() |
| 1649 | } |
| 1650 | }, |
| 1651 | ) |
| 1652 | }, |
| 1653 | |error| error.to_string(), |
| 1654 | ); |
| 1655 | (code.to_string(), message) |
| 1656 | } |
| 1657 | |
| 1658 | fn responses_stop_reason(response: &Value, saw_tool_call: bool) -> String { |
| 1659 | match string_at(response, "/status") { |
| 1660 | Some("completed") if saw_tool_call => "tool_use".to_string(), |
| 1661 | Some("completed") => "end_turn".to_string(), |
| 1662 | Some("incomplete") => format!( |
| 1663 | "incomplete:{}", |
| 1664 | string_at(response, "/incomplete_details/reason").unwrap_or("max_tokens") |
| 1665 | ), |
| 1666 | Some(other) => format!("incomplete:unknown_status:{other}"), |
| 1667 | None => "incomplete:unknown_status".to_string(), |
| 1668 | } |
| 1669 | } |
| 1670 | |
| 1671 | fn first_string_at<'a>(value: &'a Value, paths: &[&str]) -> Option<&'a str> { |
| 1672 | paths.iter().find_map(|path| string_at(value, path)) |
| 1673 | } |
| 1674 | |
| 1675 | fn string_at<'a>(value: &'a Value, path: &str) -> Option<&'a str> { |
| 1676 | value.pointer(path).and_then(Value::as_str).and_then(|s| { |
| 1677 | let trimmed = s.trim(); |
| 1678 | (!trimmed.is_empty()).then_some(trimmed) |
| 1679 | }) |
| 1680 | } |
| 1681 | |
| 1682 | /// Parse a composite tool_use_id back to (call_id, item_id). |
| 1683 | /// Composite format: "call_id|item_id" |
| 1684 | pub(super) fn parse_tool_use_id(id: &str) -> (String, String) { |
| 1685 | if let Some(pipe_pos) = id.find('|') { |
| 1686 | (id[..pipe_pos].to_string(), id[pipe_pos + 1..].to_string()) |
| 1687 | } else { |
| 1688 | (id.to_string(), String::new()) |
| 1689 | } |
| 1690 | } |
| 1691 | |
| 1692 | fn admit_shared_responses_usage(profile: &ResponsesDialectProfile) { |
| 1693 | match ( |
| 1694 | profile.usage.cache_fields, |
| 1695 | profile.usage.reasoning_fields, |
| 1696 | profile.usage.audio_fields, |
| 1697 | ) { |
| 1698 | ( |
| 1699 | CacheUsageFieldPolicy::TopLevelThenNestedFallback, |
| 1700 | ReasoningUsageFieldPolicy::OutputTokensDetails, |
| 1701 | AudioUsageFieldPolicy::NestedDetails, |
| 1702 | ) => {} |
| 1703 | } |
| 1704 | } |
| 1705 | |
| 1706 | /// Parse usage from a Responses API usage object. |
| 1707 | fn parse_responses_usage(val: &Value) -> Usage { |
| 1708 | let reported_input = val |
| 1709 | .get("input_tokens") |
| 1710 | .and_then(|v| v.as_u64()) |
| 1711 | .map(super::saturating_u32); |
| 1712 | let output = val |
| 1713 | .get("output_tokens") |
| 1714 | .and_then(|v| v.as_u64()) |
| 1715 | .map_or(0, super::saturating_u32); |
| 1716 | // Cache telemetry arrives in two dialects. DeepSeek's Responses payload |
| 1717 | // uses the same top-level `prompt_cache_hit_tokens` / |
| 1718 | // `prompt_cache_miss_tokens` fields as its Chat-Completions endpoint, |
| 1719 | // while OpenAI-style payloads nest `cached_tokens` under |
| 1720 | // `input_tokens_details`. Prefer the top-level hit, falling back to the |
| 1721 | // nested form when the payload only reports that. |
| 1722 | let nested_cached_tokens = val |
| 1723 | .get("input_tokens_details") |
| 1724 | .and_then(|d| d.get("cached_tokens")) |
| 1725 | .and_then(|v| v.as_u64()); |
| 1726 | let prompt_cache_hit_tokens = val |
| 1727 | .get("prompt_cache_hit_tokens") |
| 1728 | .and_then(|v| v.as_u64()) |
| 1729 | .or(nested_cached_tokens) |
| 1730 | .map(super::saturating_u32); |
| 1731 | // DeepSeek reports the miss explicitly; otherwise mirror the |
| 1732 | // Chat-Completions parser: derive the miss as input minus the cached hit |
| 1733 | // when the payload reported both total and cached input tokens. Responses nests |
| 1734 | // reasoning under `output_tokens_details` (not `completion_tokens_details`). |
| 1735 | let prompt_cache_miss_tokens = val |
| 1736 | .get("prompt_cache_miss_tokens") |
| 1737 | .and_then(|v| v.as_u64()) |
| 1738 | .map(super::saturating_u32) |
| 1739 | .or_else(|| { |
| 1740 | reported_input |
| 1741 | .zip(prompt_cache_hit_tokens) |
| 1742 | .map(|(input, hit)| input.saturating_sub(hit)) |
| 1743 | }); |
| 1744 | // Cache-creation tokens, kept as their own class so pricing can apply the |
| 1745 | // write rate where the provider publishes one. DeepSeek-style payloads |
| 1746 | // nest these under `input_tokens_details`; accept a top-level spelling |
| 1747 | // too for providers that flatten the object. |
| 1748 | let prompt_cache_write_tokens = val |
| 1749 | .get("prompt_cache_write_tokens") |
| 1750 | .and_then(|v| v.as_u64()) |
| 1751 | .or_else(|| { |
| 1752 | val.get("input_tokens_details") |
| 1753 | .and_then(|d| d.get("cache_write_tokens")) |
| 1754 | .and_then(|v| v.as_u64()) |
| 1755 | }) |
| 1756 | .map(super::saturating_u32); |
| 1757 | // `output_tokens` is already the total billable completion count, with |
| 1758 | // reasoning a subset of it. A payload reporting more reasoning than output |
| 1759 | // violates that, so the value is rejected as invalid telemetry rather than |
| 1760 | // being trusted or turned into extra billable output (#4318). |
| 1761 | let reasoning_tokens = val |
| 1762 | .get("output_tokens_details") |
| 1763 | .and_then(|d| d.get("reasoning_tokens")) |
| 1764 | .and_then(|v| v.as_u64()) |
| 1765 | .map(super::saturating_u32) |
| 1766 | .filter(|reasoning| *reasoning <= output); |
| 1767 | // `input_tokens` stays the provider-reported *total* (cache-hit + miss + |
| 1768 | // write + uncategorized): `token_usage_for_pricing` partitions it into |
| 1769 | // billable classes and the context budget measures the window with it. |
| 1770 | // Reducing it here to miss-only would double-subtract at those surfaces. |
| 1771 | Usage { |
| 1772 | input_tokens: reported_input.unwrap_or_default(), |
| 1773 | output_tokens: output, |
| 1774 | prompt_cache_hit_tokens, |
| 1775 | prompt_cache_miss_tokens, |
| 1776 | prompt_cache_write_tokens, |
| 1777 | reasoning_tokens, |
| 1778 | reasoning_replay_tokens: None, |
| 1779 | server_tool_use: super::wire::parse_server_tool_usage(Some(val)), |
| 1780 | safety_tokens: super::wire::parse_safety_tokens(Some(val)), |
| 1781 | |
| 1782 | input_audio_tokens: val |
| 1783 | .pointer("/input_tokens_details/audio_tokens") |
| 1784 | .and_then(Value::as_u64) |
| 1785 | .map(super::saturating_u32), |
| 1786 | output_audio_tokens: val |
| 1787 | .pointer("/output_tokens_details/audio_tokens") |
| 1788 | .and_then(Value::as_u64) |
| 1789 | .map(super::saturating_u32), |
| 1790 | |
| 1791 | request_usages: Vec::new(), |
| 1792 | } |
| 1793 | } |
| 1794 | |
| 1795 | #[cfg(test)] |
| 1796 | mod tests; |
| 1797 |