From 4376f40526be2b113826dcc4b21f9402be9923c0 Mon Sep 17 00:00:00 2001 From: Alex Hancock Date: Tue, 13 Oct 2026 16:02:14 +0000 Subject: [PATCH] feat: surface provider x-request-id on responses and errors (#12587) --- crates/goose-agent/src/inference.rs | 5 + .../src/conversation/token_usage.rs | 9 + crates/goose-provider-types/src/errors.rs | 20 ++ crates/goose-providers/src/anthropic.rs | 8 +- crates/goose-providers/src/http_status.rs | 175 +++++++++++++++++- crates/goose-providers/src/openai.rs | 28 ++- .../goose-providers/src/openai_compatible.rs | 140 +++++++++++++- crates/goose-sdk/src/bindings.rs | 109 +++++++---- crates/goose-sdk/src/observability.rs | 2 + crates/goose/src/agents/gen_ai_telemetry.rs | 10 +- crates/goose/src/agents/reply_parts.rs | 1 + documentation/src/data/gdk-api.json | 12 ++ 12 files changed, 456 insertions(+), 63 deletions(-) diff --git a/crates/goose-agent/src/inference.rs b/crates/goose-agent/src/inference.rs index d24aaee86..1cc472436 100644 --- a/crates/goose-agent/src/inference.rs +++ b/crates/goose-agent/src/inference.rs @@ -133,6 +133,7 @@ pub fn chat_span( "gen_ai.response.model" = tracing::field::Empty, "gen_ai.response.finish_reasons" = tracing::field::Empty, "gen_ai.response.id" = tracing::field::Empty, + "gen_ai.request.id" = tracing::field::Empty, "gen_ai.usage.input_tokens" = tracing::field::Empty, "gen_ai.usage.output_tokens" = tracing::field::Empty, "goose.chat.purpose" = purpose, @@ -201,6 +202,9 @@ pub fn record_chat_usage(span: &tracing::Span, usage: &ProviderUsage) { if let Some(id) = &usage.response_id { span.record("gen_ai.response.id", id.as_str()); } + if let Some(id) = &usage.request_id { + span.record("gen_ai.request.id", id.as_str()); + } } #[derive(Default)] @@ -323,6 +327,7 @@ fn inference_span(provider: &dyn Provider, model_config: &ModelConfig) -> tracin "gen_ai.response.model" = tracing::field::Empty, "gen_ai.response.finish_reasons" = tracing::field::Empty, "gen_ai.response.id" = tracing::field::Empty, + "gen_ai.request.id" = tracing::field::Empty, "gen_ai.usage.input_tokens" = tracing::field::Empty, "gen_ai.usage.output_tokens" = tracing::field::Empty, "error.type" = tracing::field::Empty, diff --git a/crates/goose-provider-types/src/conversation/token_usage.rs b/crates/goose-provider-types/src/conversation/token_usage.rs index a5d2dd0fb..6596d41c4 100644 --- a/crates/goose-provider-types/src/conversation/token_usage.rs +++ b/crates/goose-provider-types/src/conversation/token_usage.rs @@ -17,6 +17,9 @@ pub struct ProviderUsage { pub finish_reasons: Option>, #[serde(default, skip_serializing_if = "Option::is_none")] pub response_id: Option, + /// The model vendor's own id for this call: Anthropic sends `request-id`, OpenAI `x-request-id`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub request_id: Option, /// Provider-specific response fields that have no canonical equivalent, kept /// unstructured so new fields flow through without changing this type. #[serde(default, skip_serializing_if = "Option::is_none")] @@ -59,6 +62,7 @@ impl ProviderUsage { cost_source: None, finish_reasons: None, response_id: None, + request_id: None, additional_data: None, } } @@ -83,6 +87,11 @@ impl ProviderUsage { self.response_id = Some(id); self } + + pub fn with_request_id(mut self, id: String) -> Self { + self.request_id = Some(id); + self + } } /// `input_tokens` is the total input including cache read/write tokens; diff --git a/crates/goose-provider-types/src/errors.rs b/crates/goose-provider-types/src/errors.rs index 0fe21c3bf..0bb1a22f2 100644 --- a/crates/goose-provider-types/src/errors.rs +++ b/crates/goose-provider-types/src/errors.rs @@ -84,6 +84,26 @@ impl ProviderError { } } + /// Mutable access to the detail text, for annotating an error after it was built. + pub fn details_mut(&mut self) -> Option<&mut String> { + match self { + ProviderError::NotConfigured => None, + ProviderError::Authentication(details) + | ProviderError::ContextLengthExceeded(details) + | ProviderError::ServerError(details) + | ProviderError::NetworkError(details) + | ProviderError::RequestFailed(details) + | ProviderError::InvalidValue(details) + | ProviderError::ExecutionError(details) + | ProviderError::UsageError(details) + | ProviderError::NotImplemented(details) + | ProviderError::EndpointNotFound(details) => Some(details), + ProviderError::RateLimitExceeded { details, .. } + | ProviderError::CreditsExhausted { details, .. } + | ProviderError::Refusal { details, .. } => Some(details), + } + } + pub fn is_endpoint_not_found(&self) -> bool { matches!(self, ProviderError::EndpointNotFound(_)) } diff --git a/crates/goose-providers/src/anthropic.rs b/crates/goose-providers/src/anthropic.rs index a632fc67e..2a2c8ba6a 100644 --- a/crates/goose-providers/src/anthropic.rs +++ b/crates/goose-providers/src/anthropic.rs @@ -27,6 +27,7 @@ use super::formats::anthropic::{ use super::openai_compatible::handle_status; use super::retry::ProviderRetry; use crate::conversation::message::Message; +use crate::http_status::extract_request_id; use crate::model::ModelConfig; use rmcp::model::Tool; @@ -242,6 +243,8 @@ impl AnthropicProvider { .inspect_err(|e| { let _ = log.error(e); })?; + // Must be read before `bytes_stream()` consumes the response. + let request_id = extract_request_id(response.headers()); let stream = response.bytes_stream().map_err(io::Error::other); Ok(Box::pin(try_stream! { let reader = StreamReader::new(stream); @@ -249,7 +252,10 @@ impl AnthropicProvider { let messages = response_to_streaming_message(framed); pin!(messages); while let Some(message) = futures::StreamExt::next(&mut messages).await { - let (message, usage) = message.map_err(ProviderError::from_stream_error)?; + let (message, mut usage) = message.map_err(ProviderError::from_stream_error)?; + if let Some(usage) = usage.as_mut() { + usage.request_id = request_id.clone(); + } if let Some(transformations) = usage .as_ref() .and_then(|usage| usage.additional_data.as_ref()) diff --git a/crates/goose-providers/src/http_status.rs b/crates/goose-providers/src/http_status.rs index 9eb441382..72e327cf2 100644 --- a/crates/goose-providers/src/http_status.rs +++ b/crates/goose-providers/src/http_status.rs @@ -245,9 +245,19 @@ pub fn map_http_error_to_provider_error( status: StatusCode, payload: Option, url: &str, +) -> ProviderError { + map_http_error(status, payload, url, None) +} + +/// Folds the request id into the message text so every variant carries it without a new field. +pub fn map_http_error( + status: StatusCode, + payload: Option, + url: &str, + request_id: Option<&str>, ) -> ProviderError { let extract_message = || -> String { - payload + let message = payload .as_ref() .and_then(|p| { p.get("error") @@ -256,7 +266,8 @@ pub fn map_http_error_to_provider_error( .and_then(|m| m.as_str()) .map(String::from) }) - .unwrap_or_else(|| payload.as_ref().map(|p| p.to_string()).unwrap_or_default()) + .unwrap_or_else(|| payload.as_ref().map(|p| p.to_string()).unwrap_or_default()); + format!("{message}{}", request_id_message_suffix(request_id)) }; let error = match status { @@ -372,6 +383,39 @@ async fn read_response_body_with_limit( } } +/// Provider ids are ~40 chars; the cap stops a huge header value inflating every telemetry row. +const MAX_REQUEST_ID_LENGTH: usize = 128; + +const PROVIDER_ID_LABEL: &str = "provider request id: "; + +fn header_value(headers: &HeaderMap, name: &str) -> Option { + let value = headers.get(name)?.to_str().ok()?.trim(); + if value.is_empty() { + return None; + } + Some(value.chars().take(MAX_REQUEST_ID_LENGTH).collect()) +} + +pub fn extract_request_id(headers: &HeaderMap) -> Option { + header_value(headers, "request-id").or_else(|| header_value(headers, "x-request-id")) +} + +/// Inverse of [`parse_request_id_suffix`] — change these together. +pub fn request_id_message_suffix(request_id: Option<&str>) -> String { + match request_id { + Some(id) => format!(" ({PROVIDER_ID_LABEL}{id})"), + None => String::new(), + } +} + +/// Recovers the id [`request_id_message_suffix`] folded into an error message, which is the only +/// channel `ProviderError` has for it since every variant carries a plain `String`. +pub fn parse_request_id_suffix(message: &str) -> Option { + let (_, after_open) = message.rsplit_once(" (")?; + let inner = after_open.strip_suffix(')')?; + inner.strip_prefix(PROVIDER_ID_LABEL).map(str::to_string) +} + pub async fn read_error_body(response: Response) -> Option { read_response_body_with_limit(response, MAX_PROVIDER_JSON_RESPONSE_BYTES) .await @@ -411,7 +455,8 @@ async fn handle_status_with_limit( .unwrap_or_default(); let body = String::from_utf8_lossy(&body); let payload = serde_json::from_str::(&body).ok(); - let mut err = map_http_error_to_provider_error(status, payload.clone(), &url); + let request_id = extract_request_id(&headers); + let mut err = map_http_error(status, payload.clone(), &url, request_id.as_deref()); if let ProviderError::RateLimitExceeded { details, .. } = &err { err = ProviderError::RateLimitExceeded { details: details.clone(), @@ -614,6 +659,130 @@ mod tests { json!({ "error": error }) } + #[tokio::test] + async fn error_carries_provider_request_id() { + let raw = b"HTTP/1.1 500 Internal Server Error\r\ncontent-type: application/json\r\nx-request-id: req_abc123\r\nconnection: close\r\n\r\n{\"error\":{\"message\":\"boom\"}}".to_vec(); + let response = response_from_raw(raw).await; + + let err = handle_status(response).await.unwrap_err(); + assert!( + err.to_string().contains("req_abc123"), + "request id should reach the user on failure, got: {err}" + ); + } + + #[tokio::test] + async fn rate_limit_keeps_retry_delay_and_request_id() { + let raw = b"HTTP/1.1 429 Too Many Requests\r\ncontent-type: application/json\r\nretry-after: 17\r\nx-request-id: req_rate\r\nconnection: close\r\n\r\n{\"error\":{\"message\":\"slow down\"}}".to_vec(); + let response = response_from_raw(raw).await; + + let err = handle_status(response).await.unwrap_err(); + match &err { + ProviderError::RateLimitExceeded { + details, + retry_delay, + } => { + assert_eq!(*retry_delay, Some(Duration::from_secs(17))); + assert!(details.contains("req_rate"), "got: {details}"); + } + other => panic!("expected rate limit, got: {other}"), + } + } + + #[test] + fn request_id_accepts_anthropic_header_name() { + let mut headers = HeaderMap::new(); + headers.insert("request-id", "req_anthropic".parse().unwrap()); + assert_eq!( + extract_request_id(&headers).as_deref(), + Some("req_anthropic") + ); + assert!(extract_request_id(&empty_headers()).is_none()); + } + + fn headers_of(pairs: &[(&str, &str)]) -> HeaderMap { + use reqwest::header::HeaderName; + let mut headers = HeaderMap::new(); + for (name, value) in pairs { + headers.insert( + HeaderName::from_bytes(name.as_bytes()).unwrap(), + value.parse().unwrap(), + ); + } + headers + } + + #[test] + fn vendor_request_id_wins_over_gateway_x_request_id() { + let id = extract_request_id(&headers_of(&[ + ("request-id", "req_011CAnthropic"), + ("x-request-id", "d4f1-gateway-uuid"), + ])); + assert_eq!(id.as_deref(), Some("req_011CAnthropic")); + } + + #[test] + fn lone_x_request_id_is_treated_as_the_provider_id() { + let id = extract_request_id(&headers_of(&[("x-request-id", "req_openai")])); + assert_eq!(id.as_deref(), Some("req_openai")); + } + + #[test] + fn blank_and_oversized_request_ids_are_rejected_and_capped() { + assert!(extract_request_id(&headers_of(&[("x-request-id", " ")])).is_none()); + assert!(extract_request_id(&empty_headers()).is_none()); + let long = "a".repeat(MAX_REQUEST_ID_LENGTH + 50); + let id = extract_request_id(&headers_of(&[("x-request-id", &long)])); + assert_eq!(id.map(|id| id.len()), Some(MAX_REQUEST_ID_LENGTH)); + } + + #[test] + fn message_suffix_round_trips_through_parse_suffix() { + let message = format!("boom{}", request_id_message_suffix(Some("req_p"))); + assert_eq!(parse_request_id_suffix(&message).as_deref(), Some("req_p")); + + let bare = format!("boom{}", request_id_message_suffix(None)); + assert_eq!(bare, "boom"); + assert!(parse_request_id_suffix(&bare).is_none()); + } + + #[test] + fn parse_suffix_ignores_unrelated_parentheses() { + assert!(parse_request_id_suffix("quota exceeded (try again later)").is_none()); + assert!(parse_request_id_suffix("plain message").is_none()); + } + + #[test] + fn parse_suffix_handles_multibyte_messages() { + let message = format!( + "모델 오류 — déjà vu 🚀{}", + request_id_message_suffix(Some("req_p")) + ); + assert_eq!(parse_request_id_suffix(&message).as_deref(), Some("req_p")); + assert!(parse_request_id_suffix("에러 (재시도)").is_none()); + } + + #[tokio::test] + async fn error_carries_the_vendor_id_not_the_gateways() { + let raw = b"HTTP/1.1 500 Internal Server Error\r\ncontent-type: application/json\r\nrequest-id: req_011CVendor\r\nx-request-id: gw-uuid\r\nconnection: close\r\n\r\n{\"error\":{\"message\":\"boom\"}}".to_vec(); + let err = handle_status(response_from_raw(raw).await) + .await + .unwrap_err(); + let text = err.to_string(); + assert!( + text.contains("provider request id: req_011CVendor"), + "got: {text}" + ); + assert!( + !text.contains("gw-uuid"), + "gateway id should be dropped: {text}" + ); + assert_eq!( + parse_request_id_suffix(&text).as_deref(), + Some("req_011CVendor") + ); + } + #[test] fn retry_after_prefers_body_seconds_over_header() { let payload = json!({ diff --git a/crates/goose-providers/src/openai.rs b/crates/goose-providers/src/openai.rs index ec551ed0b..49a304b2d 100644 --- a/crates/goose-providers/src/openai.rs +++ b/crates/goose-providers/src/openai.rs @@ -18,10 +18,11 @@ use crate::formats::openai_responses::{ create_responses_request_for_model, get_responses_usage, responses_api_to_message, ResponsesApiResponse, }; -use crate::http_status::read_json_response; +use crate::http_status::{extract_request_id, read_json_response}; use crate::images::ImageFormat; use crate::openai_compatible::{ - handle_response_openai_compat, handle_status, stream_openai_compat, stream_responses_compat, + annotate_request_id, handle_response_openai_compat, handle_status, stream_openai_compat, + stream_responses_compat, }; use crate::request_log::{start_log, LoggerHandleExt}; use crate::thinking::ThinkingEffort; @@ -332,18 +333,22 @@ impl OpenAiProvider { if self.supports_streaming { stream_responses_compat(response, log) } else { - let json: serde_json::Value = read_json_response(response).await?; + let request_id = extract_request_id(response.headers()); + let annotate = |e| annotate_request_id(e, request_id.as_deref()); + let json: serde_json::Value = read_json_response(response).await.map_err(annotate)?; let parsed: ResponsesApiResponse = serde_json::from_value(json.clone()).map_err(|e| { - ProviderError::ExecutionError(format!( + annotate(ProviderError::ExecutionError(format!( "Failed to parse responses API response: {}", e - )) + ))) })?; - let message = responses_api_to_message(&parsed)?; + let message = + responses_api_to_message(&parsed).map_err(|e| annotate(ProviderError::from(e)))?; let usage_data = get_responses_usage(&parsed); let usage_json = json.get("usage").unwrap_or(&serde_json::Value::Null); let mut usage = ProviderUsage::new(model_config.model_name.clone(), usage_data); + usage.request_id = request_id; usage.response_id = Some(parsed.id.clone()); let finish_reason = json .pointer("/incomplete_details/reason") @@ -856,15 +861,22 @@ impl Provider for OpenAiProvider { if self.supports_streaming { stream_openai_compat(response, log) } else { - let json: serde_json::Value = read_json_response(response).await?; + let request_id = extract_request_id(response.headers()); + let annotate = |e| annotate_request_id(e, request_id.as_deref()); + let json: serde_json::Value = + read_json_response(response).await.map_err(annotate)?; let message = response_to_message(&json).map_err(|e| { - ProviderError::RequestFailed(format!("Failed to parse message: {}", e)) + annotate(ProviderError::RequestFailed(format!( + "Failed to parse message: {}", + e + ))) })?; let usage_json = json.get("usage").unwrap_or(&serde_json::Value::Null); let usage_data = get_usage(usage_json); let mut usage = ProviderUsage::new(model_config.model_name.clone(), usage_data); + usage.request_id = request_id; record_response_metadata(&mut usage, &json); if let Some(cost) = get_cost(usage_json) { usage = usage.with_cost(cost, CostSource::ProviderReported); diff --git a/crates/goose-providers/src/openai_compatible.rs b/crates/goose-providers/src/openai_compatible.rs index e036a5b14..abdd6d8ee 100644 --- a/crates/goose-providers/src/openai_compatible.rs +++ b/crates/goose-providers/src/openai_compatible.rs @@ -128,13 +128,19 @@ impl OpenAiCompatibleProvider { if self.supports_streaming { stream_openai_compat(response, log) } else { - let json = read_json_response(response).await?; + let request_id = extract_request_id(response.headers()); + let annotate = |e| annotate_request_id(e, request_id.as_deref()); + let json = read_json_response(response).await.map_err(annotate)?; let message = response_to_message(&json).map_err(|e| { - ProviderError::RequestFailed(format!("Failed to parse message: {}", e)) + annotate(ProviderError::RequestFailed(format!( + "Failed to parse message: {}", + e + ))) })?; let usage_json = json.get("usage").unwrap_or(&Value::Null); let usage_data = get_usage(usage_json); let mut usage = ProviderUsage::new(model_config.model_name.clone(), usage_data); + usage.request_id = request_id; record_response_metadata(&mut usage, &json); if let Some(cost) = get_cost(usage_json) { usage = usage.with_cost(cost, CostSource::ProviderReported); @@ -228,16 +234,32 @@ impl Provider for OpenAiCompatibleProvider { // Re-exported from the dedicated `http_status` module — these helpers are // format-agnostic and used across all provider families. pub use super::http_status::{ - handle_response, handle_status, map_http_error_to_provider_error, sanitize_url, + extract_request_id, handle_response, handle_status, map_http_error_to_provider_error, + parse_request_id_suffix, request_id_message_suffix, sanitize_url, }; // Legacy alias kept for callers that haven't migrated their import path yet. pub use super::http_status::handle_response as handle_response_openai_compat; +/// Errors raised after a 200 (SSE error frames, malformed bodies) bypass `handle_status`, so the +/// header id has to be folded in by the caller that still holds it. +pub(crate) fn annotate_request_id( + mut error: ProviderError, + request_id: Option<&str>, +) -> ProviderError { + if let (Some(details), Some(id)) = (error.details_mut(), request_id) { + if parse_request_id_suffix(details).is_none() { + details.push_str(&request_id_message_suffix(Some(id))); + } + } + error +} + pub fn stream_openai_compat( response: Response, mut log: Option>, ) -> Result { + let request_id = extract_request_id(response.headers()); let stream = response.bytes_stream().map_err(std::io::Error::other); Ok(Box::pin(try_stream! { @@ -248,10 +270,16 @@ pub fn stream_openai_compat( let message_stream = response_to_streaming_message(framed); pin!(message_stream); while let Some(message) = message_stream.next().await { - let (message, usage) = message.map_err(|e| - e.downcast::() - .unwrap_or_else(ProviderError::stream_decode_error) + let (message, mut usage) = message.map_err(|e| + annotate_request_id( + e.downcast::() + .unwrap_or_else(ProviderError::stream_decode_error), + request_id.as_deref(), + ) )?; + if let Some(usage) = usage.as_mut() { + usage.request_id = request_id.clone(); + } log.write(&message, usage.as_ref().map(|f| f.usage).as_ref())?; yield (message, usage); } @@ -262,6 +290,7 @@ pub fn stream_responses_compat( response: Response, mut log: Option>, ) -> Result { + let request_id = extract_request_id(response.headers()); let stream = response.bytes_stream().map_err(std::io::Error::other); Ok(Box::pin(try_stream! { @@ -272,10 +301,16 @@ pub fn stream_responses_compat( let message_stream = responses_api_to_streaming_message(framed); pin!(message_stream); while let Some(message) = message_stream.next().await { - let (message, usage) = message.map_err(|e| - e.downcast::() - .unwrap_or_else(ProviderError::stream_decode_error) + let (message, mut usage) = message.map_err(|e| + annotate_request_id( + e.downcast::() + .unwrap_or_else(ProviderError::stream_decode_error), + request_id.as_deref(), + ) )?; + if let Some(usage) = usage.as_mut() { + usage.request_id = request_id.clone(); + } log.write(&message, usage.as_ref().map(|f| f.usage).as_ref())?; yield (message, usage); } @@ -289,6 +324,59 @@ mod tests { use serde_json::json; use test_case::test_case; + #[test] + fn stream_errors_carry_request_id_once() { + let error = annotate_request_id( + ProviderError::ServerError("boom".to_string()), + Some("req_stream"), + ); + assert_eq!( + parse_request_id_suffix(&error.to_string()).as_deref(), + Some("req_stream") + ); + let again = annotate_request_id(error, Some("req_other")); + assert!(!again.to_string().contains("req_other")); + } + + #[tokio::test] + async fn streaming_usage_carries_request_id() { + use wiremock::matchers::method; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + let body = concat!( + "data: {\"id\":\"chatcmpl-1\",\"choices\":[{\"delta\":{\"content\":\"hi\"},\"index\":0}]}\n\n", + "data: {\"id\":\"chatcmpl-1\",\"choices\":[{\"delta\":{},\"index\":0,\"finish_reason\":\"stop\"}],", + "\"usage\":{\"prompt_tokens\":1,\"completion_tokens\":2,\"total_tokens\":3}}\n\n", + "data: [DONE]\n\n", + ); + + let server = MockServer::start().await; + Mock::given(method("GET")) + .respond_with( + ResponseTemplate::new(200) + .insert_header("x-request-id", "req_stream") + .insert_header("content-type", "text/event-stream") + .set_body_string(body), + ) + .mount(&server) + .await; + + let response = reqwest::Client::new() + .get(server.uri()) + .send() + .await + .unwrap(); + let mut stream = stream_openai_compat(response, None).unwrap(); + + let mut seen = false; + while let Some(item) = futures::StreamExt::next(&mut stream).await { + if let (_, Some(usage)) = item.unwrap() { + seen |= usage.request_id.as_deref() == Some("req_stream"); + } + } + assert!(seen, "expected request id on streamed usage"); + } + #[test_case( StatusCode::PAYMENT_REQUIRED, Some(json!({"error": {"message": "Insufficient credits to complete this request"}})), @@ -412,6 +500,40 @@ mod tests { .expect("legitimate non-streaming response should be accepted"); } + #[test_case(wiremock::ResponseTemplate::new(200).set_body_string("not json") ; "malformed body")] + #[test_case(wiremock::ResponseTemplate::new(200).set_body_json(json!({"choices": []})) ; "invalid completion")] + #[tokio::test] + async fn nonstreaming_decode_errors_carry_request_id(template: wiremock::ResponseTemplate) { + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer}; + + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/chat/completions")) + .respond_with(template.insert_header("x-request-id", "req_nonstream")) + .mount(&server) + .await; + + let provider = OpenAiCompatibleProvider::new( + "test".to_string(), + ApiClient::new_with_tls(server.uri(), crate::api_client::AuthMethod::NoAuth, None) + .unwrap(), + String::new(), + ) + .with_supports_streaming(false); + + let Err(err) = provider + .stream(&ModelConfig::new("test-model"), "", &[], &[]) + .await + else { + panic!("expected a decode error"); + }; + assert_eq!( + parse_request_id_suffix(&err.to_string()).as_deref(), + Some("req_nonstream") + ); + } + #[tokio::test] async fn nonstreaming_completion_rejects_oversized_response_body() { use crate::http_status::MAX_PROVIDER_JSON_RESPONSE_BYTES; diff --git a/crates/goose-sdk/src/bindings.rs b/crates/goose-sdk/src/bindings.rs index a2adc3d87..7376892fc 100644 --- a/crates/goose-sdk/src/bindings.rs +++ b/crates/goose-sdk/src/bindings.rs @@ -26,6 +26,7 @@ use goose_providers::{ }, declarative::{DeclarativeProviderConfig, EnvKeyResolver}, documents::{document_media_type_is_supported, SUPPORTED_DOCUMENT_MEDIA_TYPES}, + http_status::{parse_request_id_suffix, request_id_message_suffix}, model::ModelConfig, openai::{ parse_openai_base_url, OpenAiProviderBuilder, OPEN_AI_DEFAULT_BASE_PATH, @@ -84,11 +85,18 @@ impl From for GooseError { goose_providers::errors::ProviderError::ContextLengthExceeded(message) => { Self::ContextLengthExceeded { details: message } } - goose_providers::errors::ProviderError::RateLimitExceeded { retry_delay, .. } => { + goose_providers::errors::ProviderError::RateLimitExceeded { + details, + retry_delay, + } => { let retry_after_ms = retry_delay.map(|delay| delay.as_millis() as u64); - let retry_after_suffix = retry_after_ms - .map(|ms| format!("; retry after {ms}ms")) - .unwrap_or_default(); + let retry_after_suffix = format!( + "{}{}", + retry_after_ms + .map(|ms| format!("; retry after {ms}ms")) + .unwrap_or_default(), + request_id_message_suffix(parse_request_id_suffix(&details).as_deref()), + ); Self::RateLimited { retry_after_ms, retry_after_suffix, @@ -551,6 +559,8 @@ pub struct Usage { pub cache_creation_input_tokens: Option, pub reasoning_tokens: Option, pub model: String, + /// The model vendor's own id for this call: Anthropic sends `request-id`, OpenAI `x-request-id`. + pub request_id: Option, pub provider_metadata_json: Option, /// Provider-specific response fields as a JSON object, present only when the /// provider reported fields with no canonical `Usage` equivalent. @@ -567,6 +577,7 @@ impl Usage { cache_creation_input_tokens: usage.usage.cache_write_input_tokens, reasoning_tokens: None, model: usage.model.clone(), + request_id: usage.request_id.clone(), provider_metadata_json: Some(serde_json::to_string(usage)?), additional_data_json: usage .additional_data @@ -610,6 +621,8 @@ pub struct GooseStreamError { pub kind: GooseStreamErrorKind, pub message: String, pub retry_after_ms: Option, + /// Recovered from the message text, the only channel `ProviderError` has for it. + pub request_id: Option, } #[derive(Debug, Clone, uniffi::Enum)] @@ -625,45 +638,47 @@ pub enum GooseStreamErrorKind { impl From<&GooseError> for GooseStreamError { fn from(error: &GooseError) -> Self { - match error { + let (kind, message, retry_after_ms) = match error { GooseError::RateLimited { retry_after_ms, retry_after_suffix, - } => Self { - kind: GooseStreamErrorKind::RateLimited, - message: format!("Rate limit exceeded{retry_after_suffix}"), - retry_after_ms: *retry_after_ms, - }, - GooseError::OutputTokenLimitExceeded { details } => Self { - kind: GooseStreamErrorKind::OutputTokenLimitExceeded, - message: details.clone(), - retry_after_ms: None, - }, - GooseError::ContextLengthExceeded { details } => Self { - kind: GooseStreamErrorKind::ContextLengthExceeded, - message: details.clone(), - retry_after_ms: None, - }, - GooseError::Authentication { details } => Self { - kind: GooseStreamErrorKind::Authentication, - message: details.clone(), - retry_after_ms: None, - }, - GooseError::Timeout { details } => Self { - kind: GooseStreamErrorKind::Timeout, - message: details.clone(), - retry_after_ms: None, - }, - GooseError::ProviderUnavailable { details } => Self { - kind: GooseStreamErrorKind::ProviderUnavailable, - message: details.clone(), - retry_after_ms: None, - }, - GooseError::Generic { details } => Self { - kind: GooseStreamErrorKind::Generic, - message: details.clone(), - retry_after_ms: None, - }, + } => ( + GooseStreamErrorKind::RateLimited, + format!("Rate limit exceeded{retry_after_suffix}"), + *retry_after_ms, + ), + GooseError::OutputTokenLimitExceeded { details } => ( + GooseStreamErrorKind::OutputTokenLimitExceeded, + details.clone(), + None, + ), + GooseError::ContextLengthExceeded { details } => ( + GooseStreamErrorKind::ContextLengthExceeded, + details.clone(), + None, + ), + GooseError::Authentication { details } => { + (GooseStreamErrorKind::Authentication, details.clone(), None) + } + GooseError::Timeout { details } => { + (GooseStreamErrorKind::Timeout, details.clone(), None) + } + GooseError::ProviderUnavailable { details } => ( + GooseStreamErrorKind::ProviderUnavailable, + details.clone(), + None, + ), + GooseError::Generic { details } => { + (GooseStreamErrorKind::Generic, details.clone(), None) + } + }; + + let request_id = parse_request_id_suffix(&message); + Self { + kind, + message, + retry_after_ms, + request_id, } } } @@ -1637,6 +1652,8 @@ fn message_to_chunks(message: Message) -> Vec { kind: GooseStreamErrorKind::Generic, message: error.to_string(), retry_after_ms: None, + // Local parse failure: no provider response, so no request id. + request_id: None, }, }), } @@ -1675,6 +1692,18 @@ mod tests { } } + #[test] + fn rate_limit_stream_error_keeps_request_id() { + let provider_error = goose_providers::errors::ProviderError::RateLimitExceeded { + details: "slow down (provider request id: req_rate)".to_string(), + retry_delay: Some(std::time::Duration::from_millis(1500)), + }; + let error = GooseStreamError::from(&GooseError::from(provider_error)); + assert!(matches!(error.kind, GooseStreamErrorKind::RateLimited)); + assert_eq!(error.retry_after_ms, Some(1500)); + assert_eq!(error.request_id.as_deref(), Some("req_rate")); + } + #[test] fn context_limit_override_filters_nonpositive_values() { let none = base_model_config(); diff --git a/crates/goose-sdk/src/observability.rs b/crates/goose-sdk/src/observability.rs index f43f3d1eb..f150d180a 100644 --- a/crates/goose-sdk/src/observability.rs +++ b/crates/goose-sdk/src/observability.rs @@ -348,6 +348,7 @@ mod tests { cache_creation_input_tokens: None, reasoning_tokens: None, model: "claude-sonnet-4".to_string(), + request_id: None, provider_metadata_json: None, additional_data_json: None, } @@ -462,6 +463,7 @@ mod tests { kind: crate::bindings::GooseStreamErrorKind::Generic, message: "later read".to_string(), retry_after_ms: None, + request_id: None, }); let events = registered.events(); diff --git a/crates/goose/src/agents/gen_ai_telemetry.rs b/crates/goose/src/agents/gen_ai_telemetry.rs index bd19e8930..36b7482d1 100644 --- a/crates/goose/src/agents/gen_ai_telemetry.rs +++ b/crates/goose/src/agents/gen_ai_telemetry.rs @@ -74,6 +74,9 @@ pub(super) fn record_provider_usage(span: &Span, usage: &ProviderUsage) { if let Some(id) = &usage.response_id { span.record("gen_ai.response.id", id.as_str()); } + if let Some(id) = &usage.request_id { + span.record("gen_ai.request.id", id.as_str()); + } } pub(super) fn record_request_params(span: &Span, model_config: &ModelConfig) { @@ -519,7 +522,7 @@ mod tests { } #[test] - fn record_provider_usage_includes_finish_reasons_and_response_id() { + fn record_provider_usage_includes_finish_reasons_and_ids() { let capture = test_support::SpanFieldCapture::new("test_span"); let _guard = capture.clone().set_default(); @@ -528,13 +531,15 @@ mod tests { Usage::new(Some(10), Some(20), None), ) .with_finish_reasons(vec!["stop".to_string()]) - .with_response_id("resp-123".to_string()); + .with_response_id("resp-123".to_string()) + .with_request_id("req-456".to_string()); let span = tracing::info_span!( "test_span", "gen_ai.response.model" = tracing::field::Empty, "gen_ai.response.finish_reasons" = tracing::field::Empty, "gen_ai.response.id" = tracing::field::Empty, + "gen_ai.request.id" = tracing::field::Empty, "gen_ai.usage.input_tokens" = tracing::field::Empty, "gen_ai.usage.output_tokens" = tracing::field::Empty, ); @@ -544,6 +549,7 @@ mod tests { assert_eq!(fields["gen_ai.response.model"], "test-model"); assert_eq!(fields["gen_ai.response.finish_reasons"], "[\"stop\"]"); assert_eq!(fields["gen_ai.response.id"], "resp-123"); + assert_eq!(fields["gen_ai.request.id"], "req-456"); assert_eq!(fields["gen_ai.usage.input_tokens"], 10); assert_eq!(fields["gen_ai.usage.output_tokens"], 20); } diff --git a/crates/goose/src/agents/reply_parts.rs b/crates/goose/src/agents/reply_parts.rs index 90750847e..c79bbe958 100644 --- a/crates/goose/src/agents/reply_parts.rs +++ b/crates/goose/src/agents/reply_parts.rs @@ -270,6 +270,7 @@ pub(crate) fn prepare_tools_for_provider( gen_ai.response.model = tracing::field::Empty, gen_ai.response.finish_reasons = tracing::field::Empty, gen_ai.response.id = tracing::field::Empty, + gen_ai.request.id = tracing::field::Empty, gen_ai.usage.input_tokens = tracing::field::Empty, gen_ai.usage.output_tokens = tracing::field::Empty, gen_ai.usage.cache_read.input_tokens = tracing::field::Empty, diff --git a/documentation/src/data/gdk-api.json b/documentation/src/data/gdk-api.json index 03fe65860..1ac209d0e 100644 --- a/documentation/src/data/gdk-api.json +++ b/documentation/src/data/gdk-api.json @@ -769,6 +769,12 @@ "default": null, "docs": "" }, + { + "name": "request_id", + "type": "Option", + "default": null, + "docs": "The model vendor's own id for this call: Anthropic sends `request-id`, OpenAI `x-request-id`." + }, { "name": "provider_metadata_json", "type": "Option", @@ -912,6 +918,12 @@ "type": "Option", "default": null, "docs": "" + }, + { + "name": "request_id", + "type": "Option", + "default": null, + "docs": "Recovered from the message text, the only channel `ProviderError` has for it." } ], "variants": [],