From c4b7ff766628c303146613b7cf1ecbf3c78c0e93 Mon Sep 17 00:00:00 2001 From: "wujiaming.ai" Date: Fri, 27 Nov 2026 17:01:00 +0800 Subject: [PATCH 1/2] feat(tracing): capture protocol response IDs for model calls Record the provider-returned response ID for the three wire formats VeADK consumes: - Responses API: top-level id, or response.id on created/in_progress/ terminal events - Chat Completions: id on the completion and on every stream chunk - Messages: top-level message id, or message.id on message_start (the raw value LiteLLM would otherwise replace with a synthesized chatcmpl- id) The ID is published as a new veadk.response.id span attribute on the attempt span and the enclosing ADK model span, plus one new [llm-dispatch] log line per attempt. Existing gen_ai.response.id / X-Request-Id handling and all existing log lines are untouched. Extraction treats blank or non-string IDs, missing fields and empty response/message objects as absent, and isolates extraction/span/log failures so telemetry cannot fail a model call. Logged IDs are sanitized to one bounded line; spans keep the raw value. Coverage: 100% of changed executable lines and all new branches. Opt-in live E2E covers Ark and DeepSeek for all three formats in streaming and non-streaming modes. --- pytest.ini | 1 + tests/e2e/test_protocol_response_id_live.py | 271 +++++++ tests/models/test_model_timing_adapters.py | 13 +- tests/models/test_protocol_response_id.py | 731 ++++++++++++++++++ veadk/models/ark_llm.py | 6 + veadk/models/timed_lite_llm.py | 19 +- .../tracing/telemetry/protocol_response_id.py | 300 +++++++ 7 files changed, 1334 insertions(+), 7 deletions(-) create mode 100644 tests/e2e/test_protocol_response_id_live.py create mode 100644 tests/models/test_protocol_response_id.py create mode 100644 veadk/tracing/telemetry/protocol_response_id.py diff --git a/pytest.ini b/pytest.ini index 154508519..8b987cdc1 100644 --- a/pytest.ini +++ b/pytest.ini @@ -10,6 +10,7 @@ filterwarnings = asyncio_mode = strict markers = query_routing_live: real SystemOne and model API routing E2E (explicit opt-in) + protocol_response_id_live: real Ark Responses/Chat/Messages response-ID E2E (opt in with VEADK_PROTOCOL_RESPONSE_ID_LIVE=1) piagent_smoke: real Pi binary/model smoke test (opt in with PIAGENT_RUN_SMOKE=1) codex_smoke: real Codex binary/sandbox/socket smoke test, stubbed model backend (opt in with CODEX_RUN_SMOKE=1); binds real ports and spawns a subprocess, so it must not run under `pytest -n` codex_probe: real-model Codex canary that spends ~75K tokens (opt in with CODEX_RUN_PROBE=1 plus MODEL_AGENT_API_KEY/MODEL_AGENT_API_BASE/MODEL_AGENT_NAME); run once per Codex PR, never in CI diff --git a/tests/e2e/test_protocol_response_id_live.py b/tests/e2e/test_protocol_response_id_live.py new file mode 100644 index 000000000..864a8c13e --- /dev/null +++ b/tests/e2e/test_protocol_response_id_live.py @@ -0,0 +1,271 @@ +# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Real-provider E2E for protocol response IDs, explicitly enabled by env. + +Run with ``VEADK_PROTOCOL_RESPONSE_ID_LIVE=1`` plus either provider's key: + +- ``ARK_API_KEY``: Ark Responses / Chat / Messages (the Messages format uses + ``ANTHROPIC_BASE_URL``, which points at Ark's Anthropic-compatible endpoint). +- ``DEEPSEEK_API_KEY``: DeepSeek Responses / Chat / Messages (the Messages + format uses ``DEEPSEEK_ANTHROPIC_BASE``). + +Overrides: ``VEADK_RESPONSE_ID_MODEL``, ``ARK_BASE_URL``, +``DEEPSEEK_MODEL``, ``DEEPSEEK_API_BASE``, ``DEEPSEEK_ANTHROPIC_BASE``. + +These cases assert the additive contract only: the provider-returned body ID is +logged once per attempt and set as ``veadk.response.id`` on the attempt span and +the enclosing ADK model span. Existing dispatch logs must remain present. +""" + +import logging +import os +import re + +import pytest +from google.adk.agents import RunConfig +from google.adk.agents.run_config import StreamingMode +from google.adk.runners import Runner +from google.adk.sessions import InMemorySessionService +from google.genai import types +from opentelemetry import trace as trace_api +from opentelemetry.sdk.trace import TracerProvider +from opentelemetry.sdk.trace.export import SimpleSpanProcessor +from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter +from opentelemetry.util._once import Once + +from veadk import Agent +from veadk.tracing.telemetry.protocol_response_id import RESPONSE_ID_ATTRIBUTE +from veadk.utils.patches import patch_tracer + +ARK_BASE = os.getenv("ARK_BASE_URL", "https://ark.cn-beijing.volces.com/api/v3/") +ARK_ANTHROPIC_BASE = os.getenv( + "ANTHROPIC_BASE_URL", "https://ark.cn-beijing.volces.com/api/compatible" +) +DEEPSEEK_BASE = os.getenv("DEEPSEEK_API_BASE", "https://api.deepseek.com") +DEEPSEEK_ANTHROPIC_BASE = os.getenv( + "DEEPSEEK_ANTHROPIC_BASE", "https://api.deepseek.com/anthropic" +) + +_UUID = re.compile( + r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", re.I +) +_ARK_ID = re.compile(r"^[0-9A-Za-z_-]{8,}$") + +PROVIDERS = { + "ark": { + "key": os.getenv("ARK_API_KEY"), + "model": os.getenv("VEADK_RESPONSE_ID_MODEL", "deepseek-v4-1-flash-261017"), + "chat_base": ARK_BASE, + "responses_base": ARK_BASE, + "messages_base": ARK_ANTHROPIC_BASE, + "chat_id": _ARK_ID, + "messages_id": _ARK_ID, + # The Responses body ID is distinct from the Ark X-Request-Id. + "responses_id": re.compile(r"^resp_[0-9A-Za-z_-]+$"), + }, + "deepseek": { + "key": os.getenv("DEEPSEEK_API_KEY"), + "model": os.getenv("DEEPSEEK_MODEL", "deepseek-flash"), + "chat_base": DEEPSEEK_BASE, + "responses_base": DEEPSEEK_BASE, + "messages_base": DEEPSEEK_ANTHROPIC_BASE, + "chat_id": _UUID, + "messages_id": _UUID, + "responses_id": _UUID, + }, +} + +pytestmark = [ + pytest.mark.protocol_response_id_live, + pytest.mark.skipif( + os.getenv("VEADK_PROTOCOL_RESPONSE_ID_LIVE") != "1", + reason="requires explicit live enablement", + ), +] + +CASES = [ + pytest.param( + provider, + api, + stream, + marks=pytest.mark.skipif( + not PROVIDERS[provider]["key"], + reason=f"missing {provider} credentials", + ), + id=f"{provider}-{api}-{'stream' if stream else 'non_stream'}", + ) + for provider in ("ark", "deepseek") + for api in ("responses", "chat", "messages") + for stream in (False, True) +] + +ID_LOG = re.compile( + r"^\[llm-dispatch] response id model=(?P\S+) api=(?P\w+) " + r"stream=(?PTrue|False) response_id=(?P\S+)$" +) + + +class _ListHandler(logging.Handler): + def __init__(self, records): + super().__init__() + self._records = records + + def emit(self, record): + self._records.append(record.getMessage()) + + +@pytest.fixture +def spans(monkeypatch): + monkeypatch.setenv("ENABLE_APMPLUS", "false") + monkeypatch.setenv("ENABLE_COZELOOP", "false") + monkeypatch.setenv("ENABLE_TLS", "false") + monkeypatch.setattr(trace_api, "_TRACER_PROVIDER", None) + monkeypatch.setattr(trace_api, "_TRACER_PROVIDER_SET_ONCE", Once()) + provider = TracerProvider() + exporter = InMemorySpanExporter() + provider.add_span_processor(SimpleSpanProcessor(exporter)) + trace_api.set_tracer_provider(provider) + # ADK's module-level tracers must follow this test's replacement provider. + patch_tracer() + yield exporter + provider.shutdown() + + +@pytest.fixture +def messages(): + records = [] + handler = _ListHandler(records) + logger = logging.getLogger("veadk") + logger.addHandler(handler) + try: + yield records + finally: + logger.removeHandler(handler) + + +def _agent(provider, api): + config = PROVIDERS[provider] + common = { + "name": f"response_id_{provider}_{api}", + "model_name": config["model"], + "instruction": "Reply with the single word OK.", + "generate_content_config": types.GenerateContentConfig( + max_output_tokens=64, temperature=0 + ), + } + if api == "messages": + # The token goes through model_api_key so it is never added to + # model_extra_config, which VeADK logs at INFO level. + return Agent( + model_provider="anthropic", + model_api_key=config["key"], + model_api_base=config["messages_base"], + **common, + ) + return Agent( + model_provider="openai", + model_api_key=config["key"], + model_api_base=config["chat_base"] + if api == "chat" + else config["responses_base"], + enable_responses=api == "responses", + enable_responses_cache=False, + **common, + ) + + +async def _run_turn(agent, stream): + service = InMemorySessionService() + runner = Runner( + app_name="protocol_response_id_live", agent=agent, session_service=service + ) + session = await service.create_session( + app_name="protocol_response_id_live", user_id="live_test" + ) + events = [ + event + async for event in runner.run_async( + user_id="live_test", + session_id=session.id, + new_message=types.Content(role="user", parts=[types.Part(text="Say OK.")]), + run_config=RunConfig( + streaming_mode=StreamingMode.SSE if stream else StreamingMode.NONE + ), + ) + ] + return "".join( + part.text + for event in events + if event.content and not event.partial + for part in (event.content.parts or []) + if part.text + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize(("provider", "api", "stream"), CASES) +async def test_real_protocol_response_id(provider, api, stream, spans, messages): + config = PROVIDERS[provider] + exporter = spans + exporter.clear() + messages.clear() + + text = await _run_turn(_agent(provider, api), stream) + assert text.strip() + + id_logs = [ID_LOG.match(message) for message in messages] + id_logs = [match for match in id_logs if match is not None] + assert len(id_logs) == 1, [m for m in messages if "response id" in m] + entry = id_logs[0] + assert entry["api"] == api + assert entry["stream"] == str(stream) + assert entry["model"].endswith(config["model"]) + + response_id = entry["response_id"] + # A synthesized chatcmpl- ID would prove LiteLLM's Messages conversion was + # observed instead of the raw provider message. + assert not response_id.startswith("chatcmpl-") + assert config[f"{api}_id"].match(response_id), response_id + + exported = exporter.get_finished_spans() + with_id = { + span.name: span.attributes[RESPONSE_ID_ATTRIBUTE] + for span in exported + if RESPONSE_ID_ATTRIBUTE in span.attributes + } + assert with_id.get("model_request") == response_id + assert any( + name.startswith("generate_content") and value == response_id + for name, value in with_id.items() + ) + + # Existing dispatch logs keep their current shape. + if api == "responses": + assert any( + message.startswith("[llm-dispatch] responses.create begin") + for message in messages + ) + assert any( + message.startswith("[llm-dispatch] responses.create end") + for message in messages + ) + else: + assert any( + message.startswith("[llm-dispatch] acompletion enter") + for message in messages + ) + assert any( + message.startswith("[llm-dispatch] acompletion exit") + for message in messages + ) diff --git a/tests/models/test_model_timing_adapters.py b/tests/models/test_model_timing_adapters.py index cdff3ec65..1f2925ca8 100644 --- a/tests/models/test_model_timing_adapters.py +++ b/tests/models/test_model_timing_adapters.py @@ -36,6 +36,7 @@ from veadk.models.retrying_lite_llm import RetryingLiteLlm from veadk.models.timed_lite_llm import TimedLiteLLMClient from veadk.tracing.telemetry import timing +from veadk.tracing.telemetry.protocol_response_id import RESPONSE_ID_ATTRIBUTE @pytest.fixture @@ -109,7 +110,9 @@ async def complete(self, model, messages, tools, **kwargs): if stream: assert attempt.attributes[ttft] >= 0 assert attempt.start_time + attempt.attributes[ttft] * 1e9 <= attempt.end_time - assert not owner.attributes + # Timing data stays on the attempt span; the additive protocol response ID + # is the only attribute the owner span may receive. + assert set(owner.attributes) <= {RESPONSE_ID_ATTRIBUTE} assert not owner.events assert ( len([s for s in exporter.get_finished_spans() if s.name == "model_request"]) @@ -373,8 +376,12 @@ async def complete(self, model, messages, tools, **kwargs): assert ttft not in attempts[0].attributes assert attempts[1].status.status_code is StatusCode.UNSET assert ttft in attempts[1].attributes - assert not owner.attributes + assert set(owner.attributes) <= {RESPONSE_ID_ATTRIBUTE} assert all(s.parent.span_id == owner.context.span_id for s in attempts) assert all( - not any(key.startswith("veadk.") for key in s.attributes) for s in attempts + not any( + key.startswith("veadk.") and key != RESPONSE_ID_ATTRIBUTE + for key in s.attributes + ) + for s in attempts ) diff --git a/tests/models/test_protocol_response_id.py b/tests/models/test_protocol_response_id.py new file mode 100644 index 000000000..afbe45734 --- /dev/null +++ b/tests/models/test_protocol_response_id.py @@ -0,0 +1,731 @@ +# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Protocol response-ID capture for Responses, Chat and Messages formats.""" + +import json +import sys +from types import SimpleNamespace as NS + +import httpx +import pytest +from anthropic.types import Message as AnthropicMessage +from litellm import ModelResponse +from litellm.llms.anthropic.chat.handler import ModelResponseIterator +from litellm.llms.anthropic.chat.transformation import AnthropicConfig +from litellm.types.utils import ModelResponseStream +from opentelemetry import trace as trace_api +from opentelemetry.sdk.trace import TracerProvider +from opentelemetry.sdk.trace.export import SimpleSpanProcessor +from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter +from volcenginesdkarkruntime.types.responses import ( + Response, + ResponseCompletedEvent, + ResponseCreatedEvent, + ResponseTextDeltaEvent, +) + +from veadk.models.ark_llm import ArkLlm, ArkLlmClient +from veadk.models.timed_lite_llm import TimedLiteLLMClient +from veadk.tracing.telemetry import protocol_response_id as protocol +from veadk.tracing.telemetry import timing + +ATTR = protocol.RESPONSE_ID_ATTRIBUTE + + +@pytest.fixture +def tracing(monkeypatch): + provider = TracerProvider() + exporter = InMemorySpanExporter() + provider.add_span_processor(SimpleSpanProcessor(exporter)) + tracer = provider.get_tracer("protocol-response-id-test") + monkeypatch.setattr(trace_api, "_TRACER_PROVIDER", provider) + monkeypatch.setattr(timing.trace, "get_tracer", lambda *args, **kwargs: tracer) + yield tracer, exporter + provider.shutdown() + + +@pytest.fixture +def messages(monkeypatch): + captured = [] + monkeypatch.setattr( + protocol.logger, + "info", + lambda message, *args, **kwargs: captured.append(message), + ) + return captured + + +@pytest.fixture +def mock_http(monkeypatch): + """Route LiteLLM's httpx traffic to a mock handler; reject real network.""" + + original = httpx.AsyncClient.send + + def install(handler): + transport = httpx.MockTransport(handler) + + async def send(client, request, **kwargs): + if not str(request.url).startswith("https://mock.local"): + raise AssertionError(f"unexpected network call: {request.url}") + return await transport.handle_async_request(request) + + monkeypatch.setattr(httpx.AsyncClient, "send", send) + + yield install + monkeypatch.setattr(httpx.AsyncClient, "send", original) + + +@pytest.fixture(autouse=True) +def restore_litellm_seams(monkeypatch): + monkeypatch.setattr(protocol, "_patched", False) + for owner, name in ( + (ModelResponseIterator, "chunk_parser"), + (AnthropicConfig, "transform_parsed_response"), + ): + monkeypatch.setattr(owner, name, getattr(owner, name)) + yield + + +def _ark_response(response_id): + response = Response.model_validate( + { + "id": response_id or "fixture-placeholder", + "created_at": 1, + "model": "test", + "status": "completed", + "object": "response", + "output": [ + { + "id": "message-id", + "type": "message", + "role": "assistant", + "status": "completed", + "content": [{"type": "output_text", "text": "OK"}], + } + ], + "parallel_tool_calls": False, + "tool_choice": "auto", + "tools": [], + } + ) + response.id = response_id + return response + + +def _chat_body(response_id="chat-id"): + return { + "id": response_id, + "object": "chat.completion", + "created": 1, + "model": "test", + "choices": [ + { + "index": 0, + "message": {"role": "assistant", "content": "OK"}, + "finish_reason": "stop", + } + ], + "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}, + } + + +def _chat_chunk(response_id="chat-id"): + return { + "id": response_id, + "object": "chat.completion.chunk", + "created": 1, + "model": "test", + "choices": [{"index": 0, "delta": {"content": "OK"}, "finish_reason": None}], + } + + +def _anthropic_body(message_id="msg-id"): + return { + "id": message_id, + "type": "message", + "role": "assistant", + "model": "test", + "content": [{"type": "text", "text": "OK"}], + "stop_reason": "end_turn", + "stop_sequence": None, + "usage": {"input_tokens": 1, "output_tokens": 1}, + } + + +def _anthropic_sse(message_id): + return ( + "event: message_start\n" + f"data: {json.dumps({'type': 'message_start', 'message': {'id': message_id, 'type': 'message', 'role': 'assistant', 'model': 'test', 'content': [], 'stop_reason': None, 'stop_sequence': None, 'usage': {'input_tokens': 1, 'output_tokens': 0}}})}\n\n" + "event: content_block_start\n" + 'data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}\n\n' + "event: content_block_delta\n" + 'data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"OK"}}\n\n' + "event: content_block_stop\n" + 'data: {"type":"content_block_stop","index":0}\n\n' + "event: message_delta\n" + 'data: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":1}}\n\n' + "event: message_stop\n" + 'data: {"type":"message_stop"}\n\n' + ) + + +# --------------------------------------------------------------------------- +# Extraction +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (NS(type="message_start", message=NS(id="msg-1")), ("messages", "msg-1")), + ({"type": "message_start", "message": {"id": "msg-2"}}, ("messages", "msg-2")), + ( + NS(type="response.created", response=NS(id="resp-1")), + ("responses", "resp-1"), + ), + ( + ResponseCreatedEvent( + type="response.created", response=_ark_response("resp-2") + ), + ("responses", "resp-2"), + ), + (NS(object="response", id="resp-3"), ("responses", "resp-3")), + (ModelResponse(id="chat-1", choices=[]), ("chat", "chat-1")), + (ModelResponseStream(id="chat-2", choices=[]), ("chat", "chat-2")), + (_chat_body("chat-3"), ("chat", "chat-3")), + (_chat_chunk("chat-4"), ("chat", "chat-4")), + ( + AnthropicMessage.model_validate(_anthropic_body("msg-3")), + ("messages", "msg-3"), + ), + ({"id": "chat-5", "created": 1, "choices": []}, ("chat", "chat-5")), + ], +) +def test_extracts_body_ids_from_all_protocols(value, expected): + assert protocol.extract_response_id(value) == protocol.ProtocolResponseId(*expected) + + +@pytest.mark.parametrize( + "value", + [ + None, + {}, + {"id": "x"}, + { + "type": "message", + "id": "item-id", + "role": "assistant", + "status": "completed", + }, + {"type": "message_start", "message": None}, + {"type": "message_start", "message": {}}, + {"type": "message_delta", "delta": {}, "usage": {}}, + {"type": "response.created", "response": None}, + {"type": "response.created", "response": {}}, + {"type": "response.output_text.delta", "delta": "OK"}, + NS(type="response.completed", response=None), + {"object": "chat.completion", "id": None}, + {"created": 1, "choices": []}, + # Blank, non-string and missing IDs must never be published. + {"object": "response", "id": ""}, + {"object": "response", "id": " "}, + {"object": "response", "id": 123}, + {"object": "response"}, + {"type": "message_start", "message": {"id": ""}}, + {"type": "message_start", "message": {"id": 7}}, + {"type": "message", "model": "m", "stop_reason": None, "id": ""}, + {"type": "message", "id": "msg-1", "stop_reason": None}, + {"type": "message", "model": None, "stop_reason": None, "id": "msg-1"}, + {"created": 1, "choices": [{"index": 0}]}, + [], + "not-an-object", + 42, + ], +) +def test_ignores_values_without_a_protocol_response_id(value): + assert protocol.extract_response_id(value) is None + + +def test_blank_id_is_never_captured(messages): + capture = protocol.ProtocolResponseCapture(model="m", stream=False) + capture.observe(NS(object="chat.completion", id=" ")) + assert capture.response_id is None + assert messages == [] + + +def test_extraction_failure_is_swallowed(monkeypatch, messages): + debug = [] + monkeypatch.setattr( + protocol.logger, "debug", lambda message, *args, **kwargs: debug.append(message) + ) + + class Exploding: + def __getattribute__(self, name): + raise RuntimeError("boom") + + assert protocol.extract_response_id(Exploding()) is None + assert debug + + +def test_has_field_supports_mappings_and_objects(): + assert protocol._has_field({"stop_reason": None}, "stop_reason") + assert not protocol._has_field({}, "stop_reason") + assert protocol._has_field(NS(stop_reason=None), "stop_reason") + assert not protocol._has_field(NS(), "stop_reason") + + +# --------------------------------------------------------------------------- +# Capture publication +# --------------------------------------------------------------------------- + + +def test_capture_sets_span_attributes_and_logs_once(tracing, messages): + tracer, exporter = tracing + with tracer.start_as_current_span("call_llm") as owner: + attempt = tracer.start_span("model_request") + capture = protocol.ProtocolResponseCapture( + model="test-model", stream=True, attempt_span=attempt + ) + capture.observe(NS(type="message_start", message=NS(id="msg-1"))) + capture.observe(NS(type="message_start", message=NS(id="msg-1"))) + capture.observe(NS(object="chat.completion.chunk", id="other")) + attempt.end() + + assert owner.attributes[ATTR] == "msg-1" + assert attempt.attributes[ATTR] == "msg-1" + assert len(messages) == 1 + assert "api=messages" in messages[0] + assert "stream=True" in messages[0] + assert "response_id=msg-1" in messages[0] + + +def test_observe_ignores_events_without_an_id(messages): + capture = protocol.ProtocolResponseCapture(model="m", stream=True) + for value in ( + NS(type="response.output_text.delta", delta="OK"), + None, + {}, + NS(type="response.created", response={}), + ): + capture.observe(value) + assert capture.response_id is None + assert messages == [] + + +def test_log_sanitizes_control_characters_but_span_keeps_raw(tracing, messages): + tracer, _ = tracing + span = tracer.start_span("model_request") + raw = "resp\nid\x00with\x1fcontrols" + capture = protocol.ProtocolResponseCapture( + model="m", stream=False, attempt_span=span + ) + capture.observe(NS(object="response", id=raw)) + + assert span.attributes[ATTR] == raw + assert len(messages) == 1 + assert not any(char in messages[0] for char in "\n\x00\x1f") + assert "resp?id?with?controls" in messages[0] + + +def test_log_truncates_long_ids(messages): + raw = "i" * 200 + capture = protocol.ProtocolResponseCapture(model="m", stream=False) + capture.observe(NS(object="response", id=raw)) + logged = messages[0].rsplit("response_id=", 1)[1] + assert logged == "i" * protocol._LOG_ID_LIMIT + + +def test_capture_without_spans_still_logs(messages): + capture = protocol.ProtocolResponseCapture(model="test-model", stream=False) + capture.observe(NS(object="response", id="resp-1")) + assert len(messages) == 1 + assert "api=responses" in messages[0] + + +def test_capture_attaches_to_adk_model_span(tracing, messages): + tracer, _ = tracing + with tracer.start_as_current_span("generate_content openai/test") as owner: + protocol.ProtocolResponseCapture(model="m", stream=False).observe( + NS(object="response", id="resp-1") + ) + assert owner.attributes[ATTR] == "resp-1" + + +def test_capture_ignores_unrelated_caller_span(tracing, messages): + tracer, _ = tracing + with tracer.start_as_current_span("invoke_agent") as span: + protocol.ProtocolResponseCapture(model="m", stream=False).observe( + NS(object="response", id="resp-1") + ) + assert ATTR not in span.attributes + assert messages + + +def test_capture_clears_previous_attempt_value(tracing, messages): + tracer, _ = tracing + with tracer.start_as_current_span("call_llm") as owner: + owner.set_attribute(ATTR, "stale") + protocol.ProtocolResponseCapture(model="m", stream=False) + assert ATTR not in owner.attributes + + +def test_capture_survives_attribute_cleanup_failure(monkeypatch, messages): + debug = [] + monkeypatch.setattr( + protocol.logger, "debug", lambda message, *args, **kwargs: debug.append(message) + ) + + def broken_clear(span, key): + raise RuntimeError("span internals changed") + + monkeypatch.setattr(protocol, "_clear_attribute", broken_clear) + capture = protocol.ProtocolResponseCapture(model="m", stream=False) + assert capture.response_id is None + assert debug + + +def test_capture_ignores_non_recording_spans(tracing, messages): + tracer, _ = tracing + span = tracer.start_span("model_request") + span.end() + capture = protocol.ProtocolResponseCapture( + model="m", stream=False, attempt_span=span + ) + capture.observe(NS(object="response", id="resp-1")) + assert ATTR not in span.attributes + assert messages + + +def test_capture_survives_span_attribute_failure(messages): + class BrokenSpan: + def is_recording(self): + return True + + def set_attribute(self, *args, **kwargs): + raise RuntimeError("span is closed") + + capture = protocol.ProtocolResponseCapture( + model="m", stream=False, attempt_span=BrokenSpan() + ) + capture.observe(NS(object="chat.completion", id="chat-1")) + assert messages + + +def test_broken_owner_span_does_not_block_attempt_span(tracing, messages): + class BrokenSpan: + def is_recording(self): + return True + + def set_attribute(self, *args, **kwargs): + raise RuntimeError("span is closed") + + tracer, _ = tracing + attempt = tracer.start_span("model_request") + capture = protocol.ProtocolResponseCapture(model="m", stream=False) + capture.owner_span = BrokenSpan() + capture.attempt_span = attempt + capture.observe(NS(object="response", id="resp-1")) + assert attempt.attributes[ATTR] == "resp-1" + assert messages + + +def test_clear_attribute_tolerates_non_sdk_span(): + class RecordingSpan: + def is_recording(self): + return True + + protocol._clear_attribute(RecordingSpan(), ATTR) + + +def test_clear_attribute_tolerates_span_without_attribute_state(tracing): + tracer, _ = tracing + span = tracer.start_span("model_request") + span._attributes = None + protocol._clear_attribute(span, ATTR) + assert span.attributes == {} + + +def test_observe_response_requires_active_capture(messages): + protocol.observe_response(NS(object="response", id="resp-1")) + assert messages == [] + with protocol.ProtocolResponseCapture(model="m", stream=False): + protocol.observe_response(NS(object="response", id="resp-1")) + assert len(messages) == 1 + + +# --------------------------------------------------------------------------- +# LiteLLM transports (Chat / Messages) +# --------------------------------------------------------------------------- + + +def _install_http(mock_http, *, body=None, sse=None): + def handler(request): + if sse is not None: + return httpx.Response( + 200, + request=request, + headers={"content-type": "text/event-stream"}, + content=sse.encode(), + ) + return httpx.Response(200, request=request, json=body) + + mock_http(handler) + + +async def _call_litellm(tracer, *, model, api_base, stream): + client = TimedLiteLLMClient() + with tracer.start_as_current_span("call_llm") as owner: + response = await client.acompletion( + model=model, + messages=[{"role": "user", "content": "hi"}], + tools=[], + api_key="test-key", + api_base=api_base, + stream=stream, + ) + if stream: + async for _ in response: + pass + return owner + + +@pytest.mark.asyncio +async def test_chat_non_stream_capture(tracing, messages, mock_http): + tracer, _ = tracing + _install_http(mock_http, body=_chat_body("chat-real")) + owner = await _call_litellm( + tracer, model="openai/test", api_base="https://mock.local/v1", stream=False + ) + assert owner.attributes[ATTR] == "chat-real" + assert any("api=chat" in message for message in messages) + + +@pytest.mark.asyncio +async def test_chat_stream_capture(tracing, messages, mock_http): + tracer, _ = tracing + sse = f"data: {json.dumps(_chat_chunk('chat-stream'))}\n\ndata: [DONE]\n\n" + _install_http(mock_http, sse=sse) + owner = await _call_litellm( + tracer, model="openai/test", api_base="https://mock.local/v1", stream=True + ) + assert owner.attributes[ATTR] == "chat-stream" + assert any( + "api=chat" in message and "stream=True" in message for message in messages + ) + + +@pytest.mark.asyncio +async def test_messages_non_stream_capture_uses_real_message_id( + tracing, messages, mock_http +): + tracer, _ = tracing + _install_http(mock_http, body=_anthropic_body("msg-real")) + owner = await _call_litellm( + tracer, model="anthropic/test", api_base="https://mock.local", stream=False + ) + assert owner.attributes[ATTR] == "msg-real" + assert any("api=messages" in message for message in messages) + + +@pytest.mark.asyncio +async def test_messages_stream_capture_uses_message_start(tracing, messages, mock_http): + tracer, _ = tracing + _install_http(mock_http, sse=_anthropic_sse("msg-stream")) + owner = await _call_litellm( + tracer, model="anthropic/test", api_base="https://mock.local", stream=True + ) + assert owner.attributes[ATTR] == "msg-stream" + assert any( + "api=messages" in message and "stream=True" in message for message in messages + ) + + +# --------------------------------------------------------------------------- +# Ark Responses transport +# --------------------------------------------------------------------------- + + +class _ArkStream: + def __init__(self, events, error=None): + self._events = events + self._error = error + self.closed = False + + def __aiter__(self): + return self + + async def __anext__(self): + if self._events: + return self._events.pop(0) + if self._error is not None: + raise self._error + raise StopAsyncIteration + + async def close(self): + self.closed = True + + +def _responses_args(): + return {"model": "openai/test-model", "input": [], "api_key": "k"} + + +@pytest.mark.asyncio +async def test_ark_responses_non_stream_capture(tracing, messages, monkeypatch): + tracer, _ = tracing + model = ArkLlm(model="openai/test-model", api_key="k") + + async def aresponses(self, **kwargs): + return _ark_response("resp-real") + + monkeypatch.setattr(ArkLlmClient, "aresponses", aresponses) + with tracer.start_as_current_span("call_llm") as owner: + _ = [ + item + async for item in model.generate_content_via_responses(_responses_args()) + ] + + assert owner.attributes[ATTR] == "resp-real" + assert any("api=responses" in message for message in messages) + + +@pytest.mark.asyncio +async def test_ark_responses_stream_capture(tracing, messages, monkeypatch): + tracer, _ = tracing + model = ArkLlm(model="openai/test-model", api_key="k") + + async def aresponses(self, **kwargs): + return _ArkStream( + [ + ResponseCreatedEvent( + type="response.created", response=_ark_response("resp-stream") + ), + ResponseTextDeltaEvent( + type="response.output_text.delta", + delta="OK", + item_id="message-id", + output_index=0, + content_index=0, + ), + ResponseCompletedEvent( + type="response.completed", response=_ark_response("resp-stream") + ), + ] + ) + + monkeypatch.setattr(ArkLlmClient, "aresponses", aresponses) + with tracer.start_as_current_span("call_llm") as owner: + _ = [ + item + async for item in model.generate_content_via_responses( + _responses_args(), stream=True + ) + ] + + assert owner.attributes[ATTR] == "resp-stream" + assert any("api=responses" in message for message in messages) + + +@pytest.mark.asyncio +async def test_stream_failure_keeps_first_observed_id(tracing, messages, monkeypatch): + tracer, _ = tracing + model = ArkLlm(model="openai/test-model", api_key="k") + + async def aresponses(self, **kwargs): + return _ArkStream( + [ + ResponseCreatedEvent( + type="response.created", response=_ark_response("resp-early") + ) + ], + error=RuntimeError("stream broke"), + ) + + monkeypatch.setattr(ArkLlmClient, "aresponses", aresponses) + with tracer.start_as_current_span("call_llm") as owner: + with pytest.raises(RuntimeError, match="stream broke"): + async for _ in model.generate_content_via_responses( + _responses_args(), stream=True + ): + pass + + assert owner.attributes[ATTR] == "resp-early" + assert any("response_id=resp-early" in message for message in messages) + + +# --------------------------------------------------------------------------- +# Patch registration +# --------------------------------------------------------------------------- + + +def test_register_is_idempotent(monkeypatch): + monkeypatch.setattr(protocol, "_patched", False) + protocol.register_litellm_protocol_patches() + first = ModelResponseIterator.chunk_parser + protocol.register_litellm_protocol_patches() + assert ModelResponseIterator.chunk_parser is first + assert getattr(first, protocol._WRAPPED) + + +def test_register_rechecks_after_waiting_for_the_lock(monkeypatch): + """A concurrent registration that won the race must not wrap twice.""" + + monkeypatch.setattr(protocol, "_patched", False) + + class RacingLock: + def __enter__(self): + protocol._patched = True + + def __exit__(self, *exc_info): + return False + + monkeypatch.setattr(protocol, "_register_lock", RacingLock()) + protocol.register_litellm_protocol_patches() + assert protocol._patched is True + + +def test_register_tolerates_missing_litellm_seams(monkeypatch): + monkeypatch.setattr(protocol, "_patched", False) + monkeypatch.setitem(sys.modules, "litellm.llms.anthropic.chat.handler", None) + protocol.register_litellm_protocol_patches() + assert protocol._patched is False + + +def test_wrap_method_ignores_missing_attribute(): + owner = type("Owner", (), {}) + protocol._wrap_method(owner, "missing") + assert not hasattr(owner, "missing") + + +def test_wrap_method_does_not_double_wrap(): + calls = [] + + class Owner: + def method(self, completion_response): + calls.append(completion_response) + + protocol._wrap_method(Owner, "method") + first = Owner.method + protocol._wrap_method(Owner, "method") + assert Owner.method is first + Owner().method("original") + assert calls == ["original"] + + +def test_no_capture_leaves_litellm_id_untouched(monkeypatch): + """Installed seams are inert without an active capture context.""" + + monkeypatch.setattr(protocol, "_patched", False) + protocol.register_litellm_protocol_patches() + protocol.observe_response({"type": "message_start", "message": {"id": "msg"}}) diff --git a/veadk/models/ark_llm.py b/veadk/models/ark_llm.py index 988d816d6..ff7491e55 100644 --- a/veadk/models/ark_llm.py +++ b/veadk/models/ark_llm.py @@ -62,6 +62,7 @@ from veadk.config import settings from veadk.consts import DEFAULT_VIDEO_MODEL_API_BASE from veadk.tracing.telemetry.litellm_response_id import ResponseIdRecorder +from veadk.tracing.telemetry.protocol_response_id import ProtocolResponseCapture from veadk.tracing.telemetry.timing import ModelTiming, response_field from veadk.utils.adk_compat import ( get_previous_interaction_id, @@ -959,6 +960,9 @@ async def generate_content_via_responses( ) with ModelTiming(streaming=stream, model=model) as timing: recorder = ResponseIdRecorder(attempt=timing.span) + capture = ProtocolResponseCapture( + model=model, stream=stream, attempt_span=timing.span + ) if stream: responses_args["stream"] = True request_start = time.monotonic() @@ -978,6 +982,7 @@ async def generate_content_via_responses( f"elapsed_ms={_elapsed_ms(request_start)}", ) parts += 1 + capture.observe(part) recorder.observe(response_field(part, "response")) timing.observe_ark(part) llm_response = event_to_generate_content_response( @@ -1002,6 +1007,7 @@ async def generate_content_via_responses( f"[llm-dispatch] aresponses response model={model} stream=False " f"elapsed_ms={_elapsed_ms(request_start)}", ) + capture.observe(raw_response) recorder.observe(raw_response) llm_response = ark_response_to_generate_content_response(raw_response) yield llm_response diff --git a/veadk/models/timed_lite_llm.py b/veadk/models/timed_lite_llm.py index ab3c1c954..c04f44151 100644 --- a/veadk/models/timed_lite_llm.py +++ b/veadk/models/timed_lite_llm.py @@ -20,6 +20,10 @@ from litellm import CustomStreamWrapper from veadk.tracing.telemetry.litellm_response_id import ResponseIdRecorder +from veadk.tracing.telemetry.protocol_response_id import ( + ProtocolResponseCapture, + register_litellm_protocol_patches, +) from veadk.tracing.telemetry.timing import ( ModelTiming, response_field, @@ -79,6 +83,7 @@ def _stream_output_tokens(response) -> int | None: class TimedLiteLLMClient(LiteLLMClient): async def acompletion(self, model, messages, tools, **kwargs): + register_litellm_protocol_patches() streaming = bool(kwargs.get("stream")) message_count = _safe_len(messages) tool_count = _safe_len(tools) @@ -92,8 +97,11 @@ async def acompletion(self, model, messages, tools, **kwargs): if kwargs.get("n", 1) != 1: timing.disable_tpot() recorder = ResponseIdRecorder(attempt=timing.span) + capture = ProtocolResponseCapture( + model=model, stream=streaming, attempt_span=timing.span + ) try: - with recorder: + with recorder, capture: response = await super().acompletion(model, messages, tools, **kwargs) except BaseException as error: safe_warning( @@ -110,19 +118,21 @@ async def acompletion(self, model, messages, tools, **kwargs): f"elapsed_ms={_elapsed_ms(start)}", ) if not timing.streaming: + capture.observe(response) timing.__exit__(None, None, None) return response - return _TimedStream(response, timing, recorder) + return _TimedStream(response, timing, recorder, capture) class _TimedStream: """End an attempt even when a returned stream is closed before iteration.""" - def __init__(self, response, timing, recorder): + def __init__(self, response, timing, recorder, capture): self._response = response self._iterator = response.__aiter__() self._timing = timing self._recorder = recorder + self._capture = capture self._closed = False def __aiter__(self): @@ -132,7 +142,7 @@ async def __anext__(self): if self._closed: raise StopAsyncIteration try: - with self._recorder: + with self._recorder, self._capture: chunk = await anext(self._iterator) except StopAsyncIteration: await self._finish(None) @@ -144,6 +154,7 @@ async def __anext__(self): # Normalized IDs may be synthesized or lose provenance after copying. if not isinstance(self._response, CustomStreamWrapper): self._recorder.observe(chunk) + self._capture.observe(chunk) self._timing.observe(litellm_output_type(chunk)) return chunk diff --git a/veadk/tracing/telemetry/protocol_response_id.py b/veadk/tracing/telemetry/protocol_response_id.py new file mode 100644 index 000000000..3143da30e --- /dev/null +++ b/veadk/tracing/telemetry/protocol_response_id.py @@ -0,0 +1,300 @@ +# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Capture the response ID carried by the three model wire protocols. + +The ID is the one the provider returns in the response body: + +- Responses API: top-level ``id`` on a response, or ``response.id`` on the + ``response.created`` / ``response.in_progress`` / terminal events. Incremental + events such as ``response.output_text.delta`` carry no response ID. +- Chat Completions: ``id`` on the completion and on every stream chunk. +- Messages (Anthropic wire format): top-level ``id`` on a message, or + ``message.id`` on the ``message_start`` event. Later stream events carry no + message ID. + +This module is additive on purpose: it never reads or writes the existing +``gen_ai.response.id`` behavior (which follows ``X-Request-Id`` for Ark chat). +It publishes to a dedicated ``veadk.response.id`` span attribute and one new +``[llm-dispatch]`` log line per request attempt, so existing logs and fields +keep their current shape. + +Defensive rules: blank or non-string IDs, missing fields and empty response or +message objects are ignored; extraction and span writes are wrapped so a +malformed payload can never fail the model call. The log renders the ID as a +single bounded line while the span keeps the raw value. +""" + +from __future__ import annotations + +import functools +import re +import threading +from collections.abc import Mapping +from contextvars import ContextVar +from dataclasses import dataclass +from typing import Any + +from opentelemetry import trace +from opentelemetry.sdk.trace import Span as SDKSpan + +from veadk.tracing.telemetry.timing import response_field +from veadk.utils.logger import get_logger, safe_info + +logger = get_logger(__name__) + +RESPONSE_ID_ATTRIBUTE = "veadk.response.id" +_LOG_ID_LIMIT = 128 +_CONTROL_CHARS = re.compile(r"[\x00-\x1f\x7f]") +_WRAPPED = "_veadk_protocol_response_id_wrapped" +_register_lock = threading.Lock() +_patched = False + +_active_capture: ContextVar[ProtocolResponseCapture | None] = ContextVar( + "veadk_protocol_response_id_capture", default=None +) + + +@dataclass(frozen=True) +class ProtocolResponseId: + """A provider response ID and the wire protocol that carried it.""" + + api: str + value: str + + +def _text(value: Any) -> str | None: + if isinstance(value, str) and value.strip(): + return value + return None + + +def _with_id(api: str, value: Any) -> ProtocolResponseId | None: + response_id = _text(value) + if response_id is None: + return None + return ProtocolResponseId(api, response_id) + + +def _log_id(value: str) -> str: + """Keep the log line single-line and bounded; spans keep the raw ID.""" + + return _CONTROL_CHARS.sub("?", value)[:_LOG_ID_LIMIT] + + +def _has_field(value: Any, name: str) -> bool: + if isinstance(value, Mapping): + return name in value + return hasattr(value, name) + + +def _extract(value: Any) -> ProtocolResponseId | None: + event_type = _text(response_field(value, "type")) + + if event_type == "message_start": + return _with_id( + "messages", response_field(response_field(value, "message"), "id") + ) + + if event_type is not None and event_type.startswith("response."): + response = response_field(value, "response") + if response is not None: + return _with_id("responses", response_field(response, "id")) + return None + + object_type = _text(response_field(value, "object")) + if object_type == "response": + return _with_id("responses", response_field(value, "id")) + if object_type in ("chat.completion", "chat.completion.chunk"): + return _with_id("chat", response_field(value, "id")) + + if event_type == "message": + # Anthropic message objects carry `model` and `stop_reason`; Responses + # output items also use `type: message` but have neither field. + if response_field(value, "model") is not None and ( + _has_field(value, "stop_reason") or _has_field(value, "stop_sequence") + ): + return _with_id("messages", response_field(value, "id")) + return None + + # Tolerate OpenAI-compatible SDK objects that omit `object`: a completion + # shaped value still proved itself with an id, choices and created time. + if object_type is None and event_type is None: + if ( + response_field(value, "choices") is not None + and response_field(value, "created") is not None + ): + return _with_id("chat", response_field(value, "id")) + return None + + +def extract_response_id(value: Any) -> ProtocolResponseId | None: + """Return the provider response ID carried by ``value``, if any. + + ``value`` may be a raw SSE event, an SDK response object, or a mapping. The + function is best-effort telemetry: malformed or unknown shapes return + ``None`` and never affect the model call. + """ + + if value is None: + return None + try: + return _extract(value) + except Exception as error: # noqa: BLE001 - telemetry must not break calls + logger.debug("Skipping protocol response id extraction: %s", error) + return None + + +def _is_recording(span: trace.Span | None) -> bool: + return span is not None and span.is_recording() + + +def _clear_attribute(span: trace.Span | None, key: str) -> None: + """Drop a provisional value when a new attempt starts on the same span.""" + + if _is_recording(span) and isinstance(span, SDKSpan): + with span._lock: + if span.is_recording() and span._attributes is not None: + span._attributes.pop(key, None) + + +def _owner_span() -> trace.Span | None: + """Return the enclosing ADK model span, when there is one. + + ADK opens ``call_llm`` around the flow; its LiteLLM/Gemini model wrappers + open ``generate_content `` closer to the SDK call, which is the span + visible here. Other caller spans are left untouched. + """ + + current = trace.get_current_span() + name = getattr(current, "name", None) + if isinstance(name, str) and ( + name == "call_llm" or name.startswith("generate_content") + ): + return current + return None + + +class ProtocolResponseCapture: + """One model request attempt; publishes the first response ID it sees.""" + + def __init__( + self, + *, + model: Any, + stream: bool, + attempt_span: trace.Span | None = None, + ) -> None: + self.model = str(model) + self.stream = bool(stream) + self.attempt_span = attempt_span + self.owner_span = _owner_span() + self.response_id: ProtocolResponseId | None = None + try: + _clear_attribute(self.owner_span, RESPONSE_ID_ATTRIBUTE) + except Exception as error: # noqa: BLE001 - telemetry must not break calls + logger.debug("Unable to clear protocol response id from span: %s", error) + + def __enter__(self) -> ProtocolResponseCapture: + self._token = _active_capture.set(self) + return self + + def __exit__(self, *args: object) -> None: + _active_capture.reset(self._token) + + def observe(self, value: Any) -> None: + """Record one response or stream event; only the first ID is kept.""" + + if self.response_id is not None: + return + response_id = extract_response_id(value) + if response_id is None: + return + self.response_id = response_id + self._publish(response_id) + + def _publish(self, response_id: ProtocolResponseId) -> None: + # A broken owner span must not cost the attempt span its own ID. + for span in (self.owner_span, self.attempt_span): + try: + if _is_recording(span): + span.set_attribute(RESPONSE_ID_ATTRIBUTE, response_id.value) + except Exception as error: # noqa: BLE001 - telemetry must not break calls + logger.debug("Unable to record protocol response id on span: %s", error) + safe_info( + logger, + f"[llm-dispatch] response id model={self.model} api={response_id.api} " + f"stream={self.stream} response_id={_log_id(response_id.value)}", + ) + + +def observe_response(value: Any) -> None: + """Feed ``value`` to the active capture, if a model attempt is active.""" + + capture = _active_capture.get() + if capture is not None: + capture.observe(value) + + +def _wrap_method(owner: type, name: str) -> None: + original = getattr(owner, name, None) + if original is None or getattr(original, _WRAPPED, False): + return + + if name == "chunk_parser": + + @functools.wraps(original) + def chunk_parser(self, chunk, *args, **kwargs): + observe_response(chunk) + return original(self, chunk, *args, **kwargs) + + setattr(chunk_parser, _WRAPPED, True) + setattr(owner, name, chunk_parser) + return + + @functools.wraps(original) + def transform_parsed_response(self, completion_response, *args, **kwargs): + observe_response(completion_response) + return original(self, completion_response, *args, **kwargs) + + setattr(transform_parsed_response, _WRAPPED, True) + setattr(owner, name, transform_parsed_response) + + +def register_litellm_protocol_patches() -> None: + """Expose raw Anthropic messages to the active capture. + + LiteLLM normalizes the Messages wire format into chat-completions objects + and substitutes a generated ``chatcmpl-`` ID, so the real ``message.id`` is + only visible before that conversion. Registration is lazy and idempotent; + missing or incompatible LiteLLM layouts leave the non-Anthropic protocols + working unchanged. + """ + + global _patched + if _patched: + return + with _register_lock: + if _patched: + return + try: + from litellm.llms.anthropic.chat.handler import ModelResponseIterator + from litellm.llms.anthropic.chat.transformation import AnthropicConfig + except Exception as error: # noqa: BLE001 - optional compatibility seam + logger.debug("Anthropic response-id seam unavailable: %s", error) + return + + _wrap_method(ModelResponseIterator, "chunk_parser") + _wrap_method(AnthropicConfig, "transform_parsed_response") + _patched = True From 06689c1c3213b7ee82284e2666f50925a7a94f35 Mon Sep 17 00:00:00 2001 From: "wujiaming.ai" Date: Fri, 27 Nov 2026 17:11:32 +0800 Subject: [PATCH 2/2] test(tracing): compare parsed mock host instead of URL substring CodeQL py/incomplete-url-substring-sanitization flagged the mock network guard: startswith("https://mock.local") accepts lookalike hosts such as mock.local.evil.com. Compare the parsed scheme and host, and cover the rejected shapes with a regression test. --- tests/models/test_protocol_response_id.py | 25 +++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/tests/models/test_protocol_response_id.py b/tests/models/test_protocol_response_id.py index afbe45734..138f66cd0 100644 --- a/tests/models/test_protocol_response_id.py +++ b/tests/models/test_protocol_response_id.py @@ -77,8 +77,11 @@ def install(handler): transport = httpx.MockTransport(handler) async def send(client, request, **kwargs): - if not str(request.url).startswith("https://mock.local"): - raise AssertionError(f"unexpected network call: {request.url}") + # Compare the parsed scheme and host instead of matching a URL + # substring, so the guard cannot be bypassed by a lookalike host. + url = request.url + if url.scheme != "https" or url.host != "mock.local": + raise AssertionError(f"unexpected network call: {url}") return await transport.handle_async_request(request) monkeypatch.setattr(httpx.AsyncClient, "send", send) @@ -98,6 +101,24 @@ def restore_litellm_seams(monkeypatch): yield +@pytest.mark.asyncio +@pytest.mark.parametrize( + "url", + [ + "https://mock.local.evil.com/v1/chat/completions", + "http://mock.local/v1/chat/completions", + "https://evil.com/?next=https://mock.local", + ], +) +async def test_mock_http_rejects_non_mock_hosts(mock_http, url): + """The network guard compares the parsed host, not a URL substring.""" + + mock_http(lambda request: httpx.Response(200)) + async with httpx.AsyncClient() as client: + with pytest.raises(AssertionError, match="unexpected network call"): + await client.send(httpx.Request("GET", url)) + + def _ark_response(response_id): response = Response.model_validate( {