The agent engineering platform.
Python agentsaiai-agentsanthropicchatgptdeepagentsenterpriseframeworkgeminigenerative-ailangchainlanggraphllmmultiagentopen-sourceopenaipydanticpythonragtypescript
feat(anthropic): surface gateway response metadata (#39809)
Eugene Yurtsev11ab508b3d91
diff --git a/libs/partners/anthropic/langchain_anthropic/chat_models.py b/libs/partners/anthropic/langchain_anthropic/chat_models.pyindex 5e01cdfe10..daf4779f5e 100644--- a/libs/partners/anthropic/langchain_anthropic/chat_models.py+++ b/libs/partners/anthropic/langchain_anthropic/chat_models.py@@ -64,7 +64,11 @@ from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResufrom langchain_core.runnables import Runnable, RunnableMap, RunnablePassthroughfrom langchain_core.tools import BaseToolfrom langchain_core.utils import from_env, get_pydantic_field_names-from langchain_core.utils._gateway import _apply_gateway_config+from langchain_core.utils._gateway import (+ GATEWAY_METADATA_RESPONSE_KEY,+ _apply_gateway_config,+ _parse_gateway_metadata,+)from langchain_core.utils.function_calling import (convert_to_json_schema,convert_to_openai_tool,@@ -95,6 +99,21 @@ _MODEL_PROFILES = cast(ModelProfileRegistry, _PROFILES)_USER_AGENT: Final[str] = f"langchain-anthropic/{__version__}"+def _add_gateway_metadata(generation_info: dict[str, Any], raw_response: Any) -> None:+ """Add parsed LangSmith gateway metadata to `generation_info`, if present.++ Args:+ generation_info: Generation info to mutate in place.+ raw_response: The raw provider response, or None.+ """+ headers = getattr(raw_response, "headers", None)+ if headers is None:+ return+ gateway_metadata = _parse_gateway_metadata(headers)+ if gateway_metadata is not None:+ generation_info[GATEWAY_METADATA_RESPONSE_KEY] = gateway_metadata++def _get_default_model_profile(model_name: str) -> ModelProfile:"""Get the default profile for a model.@@ -1268,6 +1287,11 @@ class ChatAnthropic(BaseChatModel):"""Return type of chat model."""return "anthropic-chat"+ @property+ def _uses_gateway(self) -> bool:+ """Whether requests are routed through the LangSmith gateway."""+ return self.anthropic_api_key.get_secret_value().startswith("lsv2_")+@propertydef lc_secrets(self) -> dict[str, str]:"""Return a mapping of secret keys to environment variables."""@@ -1716,8 +1740,8 @@ class ChatAnthropic(BaseChatModel):def _create(self, payload: dict) -> Any:try:if "betas" in payload:- return self._client.beta.messages.create(**payload)- return self._client.messages.create(**payload)+ return self._client.beta.messages.with_raw_response.create(**payload)+ return self._client.messages.with_raw_response.create(**payload)except TypeError as e:_raise_if_authentication_error(e)raise@@ -1725,8 +1749,10 @@ class ChatAnthropic(BaseChatModel):async def _acreate(self, payload: dict) -> Any:try:if "betas" in payload:- return await self._async_client.beta.messages.create(**payload)- return await self._async_client.messages.create(**payload)+ return await self._async_client.beta.messages.with_raw_response.create(+ **payload+ )+ return await self._async_client.messages.with_raw_response.create(**payload)except TypeError as e:_raise_if_authentication_error(e)raise@@ -1745,7 +1771,11 @@ class ChatAnthropic(BaseChatModel):kwargs["stream"] = Truepayload = self._get_request_payload(messages, stop=stop, **kwargs)try:- stream = self._create(payload)+ raw_response = self._create(payload)+ base_generation_info: dict[str, Any] = {}+ if self._uses_gateway:+ _add_gateway_metadata(base_generation_info, raw_response)+ stream = raw_response.parse()coerce_content_to_string = (not _tools_in_params(payload)and not _documents_in_params(payload)@@ -1753,6 +1783,7 @@ class ChatAnthropic(BaseChatModel):and not _compact_in_params(payload))block_start_event = None+ is_first_chunk = Truefor event in stream:msg, block_start_event = self._make_message_chunk_from_anthropic_event(event,@@ -1761,7 +1792,13 @@ class ChatAnthropic(BaseChatModel):block_start_event=block_start_event,)if msg is not None:- chunk = ChatGenerationChunk(message=msg)+ chunk = ChatGenerationChunk(+ message=msg,+ generation_info=base_generation_info+ if is_first_chunk+ else None,+ )+ is_first_chunk = Falseif run_manager and isinstance(msg.content, str):run_manager.on_llm_new_token(msg.content, chunk=chunk)yield chunk@@ -1784,7 +1821,11 @@ class ChatAnthropic(BaseChatModel):kwargs["stream"] = Truepayload = self._get_request_payload(messages, stop=stop, **kwargs)try:- stream = await self._acreate(payload)+ raw_response = await self._acreate(payload)+ base_generation_info: dict[str, Any] = {}+ if self._uses_gateway:+ _add_gateway_metadata(base_generation_info, raw_response)+ stream = raw_response.parse()coerce_content_to_string = (not _tools_in_params(payload)and not _documents_in_params(payload)@@ -1792,6 +1833,7 @@ class ChatAnthropic(BaseChatModel):and not _compact_in_params(payload))block_start_event = None+ is_first_chunk = Trueasync for event in stream:msg, block_start_event = self._make_message_chunk_from_anthropic_event(event,@@ -1800,7 +1842,13 @@ class ChatAnthropic(BaseChatModel):block_start_event=block_start_event,)if msg is not None:- chunk = ChatGenerationChunk(message=msg)+ chunk = ChatGenerationChunk(+ message=msg,+ generation_info=base_generation_info+ if is_first_chunk+ else None,+ )+ is_first_chunk = Falseif run_manager and isinstance(msg.content, str):await run_manager.on_llm_new_token(msg.content, chunk=chunk)yield chunk@@ -2031,7 +2079,13 @@ class ChatAnthropic(BaseChatModel):message_chunk.response_metadata["model_provider"] = "anthropic"return message_chunk, block_start_event- def _format_output(self, data: Any, **kwargs: Any) -> ChatResult:+ def _format_output(+ self,+ data: Any,+ *,+ generation_info: dict[str, Any] | None = None,+ **kwargs: Any,+ ) -> ChatResult:"""Format the output from the Anthropic API to LC."""data_dict = data.model_dump()content = data_dict["content"]@@ -2085,7 +2139,9 @@ class ChatAnthropic(BaseChatModel):msg = AIMessage(content=content, response_metadata=response_metadata)msg.usage_metadata = _create_usage_metadata(data.usage)return ChatResult(- generations=[ChatGeneration(message=msg)],+ generations=[+ ChatGeneration(message=msg, generation_info=generation_info or None)+ ],llm_output=llm_output,)@@ -2098,12 +2154,17 @@ class ChatAnthropic(BaseChatModel):) -> ChatResult:payload = self._get_request_payload(messages, stop=stop, **kwargs)try:- data = self._create(payload)+ raw_response = self._create(payload)except anthropic.BadRequestError as e:_handle_anthropic_bad_request(e)except anthropic.APIError as e:_handle_anthropic_api_error(e)- return self._format_output(data, **kwargs)+ generation_info: dict[str, Any] = {}+ if self._uses_gateway:+ _add_gateway_metadata(generation_info, raw_response)+ return self._format_output(+ raw_response.parse(), generation_info=generation_info, **kwargs+ )async def _agenerate(self,@@ -2114,12 +2175,17 @@ class ChatAnthropic(BaseChatModel):) -> ChatResult:payload = self._get_request_payload(messages, stop=stop, **kwargs)try:- data = await self._acreate(payload)+ raw_response = await self._acreate(payload)except anthropic.BadRequestError as e:_handle_anthropic_bad_request(e)except anthropic.APIError as e:_handle_anthropic_api_error(e)- return self._format_output(data, **kwargs)+ generation_info: dict[str, Any] = {}+ if self._uses_gateway:+ _add_gateway_metadata(generation_info, raw_response)+ return self._format_output(+ raw_response.parse(), generation_info=generation_info, **kwargs+ )def _get_llm_for_structured_output_when_thinking_is_enabled(self,diff --git a/libs/partners/anthropic/tests/unit_tests/test_chat_models.py b/libs/partners/anthropic/tests/unit_tests/test_chat_models.pyindex e7fa2aa762..d0e2052567 100644--- a/libs/partners/anthropic/tests/unit_tests/test_chat_models.py+++ b/libs/partners/anthropic/tests/unit_tests/test_chat_models.py@@ -3,6 +3,7 @@from __future__ import annotationsimport copy+import jsonimport osimport warningsfrom collections.abc import Callable@@ -39,6 +40,7 @@ from langchain_core.runnables import RunnableBindingfrom langchain_core.tools import BaseTool, toolfrom langchain_core.tracers.base import BaseTracerfrom langchain_core.tracers.schemas import Run+from langchain_core.utils._gateway import GATEWAY_METADATA_RESPONSE_KEYfrom pydantic import BaseModel, Field, RootModel, SecretStr, ValidationErrorfrom pytest import CaptureFixture, MonkeyPatch@@ -62,6 +64,197 @@ os.environ["ANTHROPIC_API_KEY"] = "foo"MODEL_NAME = "claude-sonnet-4-5-20250929"+class _GatewayMetadataTracer(BaseTracer):+ """Captures gateway metadata promoted onto completed LLM runs."""++ def __init__(self) -> None:+ super().__init__()+ self.gateway_metadata: dict[str, Any] | None = None++ def _persist_run(self, run: Run) -> None:+ """No-op; runs are inspected as they complete."""++ def _on_llm_end(self, run: Run) -> None:+ metadata = run.extra.get("metadata", {})+ gateway_metadata = metadata.get("ls_gateway_info")+ if isinstance(gateway_metadata, dict):+ self.gateway_metadata = gateway_metadata+++_GATEWAY_METADATA = {"provider": "anthropic"}+_MESSAGE_RESPONSE = {+ "id": "msg_123",+ "content": [{"type": "text", "text": "Bar Baz", "citations": None}],+ "model": MODEL_NAME,+ "role": "assistant",+ "stop_reason": "end_turn",+ "stop_sequence": None,+ "usage": {"input_tokens": 2, "output_tokens": 1},+ "type": "message",+}+_STREAM_EVENTS: list[dict[str, Any]] = [+ {+ "type": "message_start",+ "message": {+ **_MESSAGE_RESPONSE,+ "content": [],+ "stop_reason": None,+ "usage": {"input_tokens": 2, "output_tokens": 0},+ },+ },+ {+ "type": "content_block_delta",+ "index": 0,+ "delta": {"type": "text_delta", "text": "Bar Baz"},+ },+ {+ "type": "message_delta",+ "delta": {"stop_reason": "end_turn", "stop_sequence": None},+ "usage": {"input_tokens": 2, "output_tokens": 1},+ },+ {"type": "message_stop"},+]+++def _gateway_handler(+ expected_beta: str | None,+) -> Callable[[httpx.Request], httpx.Response]:+ def handler(request: httpx.Request) -> httpx.Response:+ assert request.headers.get("anthropic-beta") == expected_beta+ headers = {"x-langsmith-gateway-metadata": json.dumps(_GATEWAY_METADATA)}+ if json.loads(request.content).get("stream"):+ stream = "".join(+ f"event: {event['type']}\ndata: {json.dumps(event)}\n\n"+ for event in _STREAM_EVENTS+ )+ return httpx.Response(+ 200,+ text=stream,+ headers={**headers, "content-type": "text/event-stream"},+ )+ return httpx.Response(200, json=_MESSAGE_RESPONSE, headers=headers)++ return handler+++def _sync_gateway_client(betas: list[str] | None) -> anthropic.Client:+ return anthropic.Client(+ api_key="lsv2_pt_example",+ http_client=httpx.Client(+ transport=httpx.MockTransport(+ _gateway_handler(",".join(betas) if betas else None)+ )+ ),+ )+++def _async_gateway_client(betas: list[str] | None) -> anthropic.AsyncClient:+ return anthropic.AsyncClient(+ api_key="lsv2_pt_example",+ http_client=httpx.AsyncClient(+ transport=httpx.MockTransport(+ _gateway_handler(",".join(betas) if betas else None)+ )+ ),+ )++[email protected]("betas", [None, ["test-beta"]])+def test_anthropic_invoke_surfaces_gateway_metadata(+ betas: list[str] | None,+) -> None:+ """Gateway metadata header is surfaced on `generation_info`, not the message."""+ llm = ChatAnthropic(+ model=MODEL_NAME,+ api_key="lsv2_pt_example",+ betas=betas,+ max_tokens=10,+ )+ client = _sync_gateway_client(betas)+ tracer = _GatewayMetadataTracer()+ try:+ with patch.object(llm, "_client", client):+ result = llm.invoke("bar", config={"callbacks": [tracer]})+ finally:+ client.close()++ assert tracer.gateway_metadata == _GATEWAY_METADATA+ assert GATEWAY_METADATA_RESPONSE_KEY not in result.response_metadata++[email protected]("betas", [None, ["test-beta"]])+async def test_anthropic_ainvoke_surfaces_gateway_metadata(+ betas: list[str] | None,+) -> None:+ """Async gateway responses surface metadata on `generation_info`."""+ llm = ChatAnthropic(+ model=MODEL_NAME,+ api_key="lsv2_pt_example",+ betas=betas,+ max_tokens=10,+ )+ client = _async_gateway_client(betas)+ tracer = _GatewayMetadataTracer()+ try:+ with patch.object(llm, "_async_client", client):+ result = await llm.ainvoke("bar", config={"callbacks": [tracer]})+ finally:+ await client.close()++ assert tracer.gateway_metadata == _GATEWAY_METADATA+ assert GATEWAY_METADATA_RESPONSE_KEY not in result.response_metadata++[email protected]("betas", [None, ["test-beta"]])+def test_anthropic_stream_surfaces_gateway_metadata(+ betas: list[str] | None,+) -> None:+ """Gateway metadata is attached to the first streaming generation chunk."""+ llm = ChatAnthropic(+ model=MODEL_NAME,+ api_key="lsv2_pt_example",+ betas=betas,+ max_tokens=10,+ )+ client = _sync_gateway_client(betas)+ try:+ with patch.object(llm, "_client", client):+ chunks = list(llm._stream([HumanMessage("bar")]))+ finally:+ client.close()++ assert [chunk.generation_info for chunk in chunks] == [+ {GATEWAY_METADATA_RESPONSE_KEY: _GATEWAY_METADATA},+ None,+ None,+ ]++[email protected]("betas", [None, ["test-beta"]])+async def test_anthropic_astream_surfaces_gateway_metadata(+ betas: list[str] | None,+) -> None:+ """Async gateway metadata is attached to the first streaming chunk."""+ llm = ChatAnthropic(+ model=MODEL_NAME,+ api_key="lsv2_pt_example",+ betas=betas,+ max_tokens=10,+ )+ client = _async_gateway_client(betas)+ try:+ with patch.object(llm, "_async_client", client):+ chunks = [chunk async for chunk in llm._astream([HumanMessage("bar")])]+ finally:+ await client.close()++ assert [chunk.generation_info for chunk in chunks] == [+ {GATEWAY_METADATA_RESPONSE_KEY: _GATEWAY_METADATA},+ None,+ None,+ ]++def test_initialization() -> None:"""Test chat model initialization."""with patch.dict(os.environ, {"ANTHROPIC_API_URL": "https://api.anthropic.com"}):@@ -2006,13 +2199,15 @@ def test_fine_grained_tool_streaming_beta() -> None:"fine-grained-tool-streaming-2025-05-14",}- # Test that _create routes to beta client when betas are present+ # Test that _create routes to the beta raw-response client when betas are presentmodel = ChatAnthropic(model=MODEL_NAME, betas=["fine-grained-tool-streaming-2025-05-14"])payload = {"betas": ["fine-grained-tool-streaming-2025-05-14"], "stream": True}- with patch.object(model._client.beta.messages, "create") as mock_beta_create:+ with patch.object(+ model._client.beta.messages.with_raw_response, "create"+ ) as mock_beta_create:model._create(payload)mock_beta_create.assert_called_once_with(**payload)@@ -4082,7 +4277,7 @@ def test_anthropic_error_classification()with ( # noqa: PT012- patch.object(llm._client.messages, "create") as mock_create,+ patch.object(llm._client.messages.with_raw_response, "create") as mock_create,pytest.raises(sdk_error_type) as exc_info,):mock_create.side_effect = sdk_error@@ -4102,7 +4297,9 @@ def test_anthropic_transport_error_classification() -> None:(anthropic.APIConnectionError(request=request), ModelConnectionError),):with ( # noqa: PT012- patch.object(llm._client.messages, "create") as mock_create,+ patch.object(+ llm._client.messages.with_raw_response, "create"+ ) as mock_create,pytest.raises(type(sdk_error)) as exc_info,):mock_create.side_effect = sdk_error@@ -4117,7 +4314,7 @@ def test_context_overflow_error_invoke_sync() -> None:llm = ChatAnthropic(model=MODEL_NAME)with ( # noqa: PT012- patch.object(llm._client.messages, "create") as mock_create,+ patch.object(llm._client.messages.with_raw_response, "create") as mock_create,pytest.raises(ContextOverflowError) as exc_info,):mock_create.side_effect = _CONTEXT_OVERFLOW_BAD_REQUEST_ERROR@@ -4131,7 +4328,9 @@ async def test_context_overflow_error_invoke_async() -> None:llm = ChatAnthropic(model=MODEL_NAME)with ( # noqa: PT012- patch.object(llm._async_client.messages, "create") as mock_create,+ patch.object(+ llm._async_client.messages.with_raw_response, "create"+ ) as mock_create,pytest.raises(ContextOverflowError) as exc_info,):mock_create.side_effect = _CONTEXT_OVERFLOW_BAD_REQUEST_ERROR@@ -4145,7 +4344,7 @@ def test_context_overflow_error_stream_sync() -> None:llm = ChatAnthropic(model=MODEL_NAME)with ( # noqa: PT012- patch.object(llm._client.messages, "create") as mock_create,+ patch.object(llm._client.messages.with_raw_response, "create") as mock_create,pytest.raises(ContextOverflowError) as exc_info,):mock_create.side_effect = _CONTEXT_OVERFLOW_BAD_REQUEST_ERROR@@ -4159,7 +4358,9 @@ async def test_context_overflow_error_stream_async() -> None:llm = ChatAnthropic(model=MODEL_NAME)with ( # noqa: PT012- patch.object(llm._async_client.messages, "create") as mock_create,+ patch.object(+ llm._async_client.messages.with_raw_response, "create"+ ) as mock_create,pytest.raises(ContextOverflowError) as exc_info,):mock_create.side_effect = _CONTEXT_OVERFLOW_BAD_REQUEST_ERROR@@ -4174,7 +4375,7 @@ def test_context_overflow_error_backwards_compatibility() -> None:llm = ChatAnthropic(model=MODEL_NAME)with ( # noqa: PT012- patch.object(llm._client.messages, "create") as mock_create,+ patch.object(llm._client.messages.with_raw_response, "create") as mock_create,pytest.raises(anthropic.BadRequestError) as exc_info,):mock_create.side_effect = _CONTEXT_OVERFLOW_BAD_REQUEST_ERROR@@ -4576,8 +4777,8 @@ def test_anthropic_stream_events_v3_lifecycle() -> None:thinking={"type": "enabled", "budget_tokens": 1024},)- def mock_create(_payload: Any) -> list:- return events+ def mock_create(_payload: Any) -> Any:+ return SimpleNamespace(parse=lambda: events)with patch.object(llm, "_create", mock_create):stream_events = list(llm.stream_events("Test query", version="v3"))@@ -4721,7 +4922,7 @@ def test_missing_credentials_error_sync(monkeypatch: pytest.MonkeyPatch) -> Nonellm = ChatAnthropic(model=MODEL_NAME)with ( # noqa: PT012- patch.object(llm._client.messages, "create") as mock_create,+ patch.object(llm._client.messages.with_raw_response, "create") as mock_create,pytest.raises(TypeError, match="ANTHROPIC_API_KEY") as exc_info,):mock_create.side_effect = _MISSING_CREDENTIALS_TYPE_ERROR@@ -4738,7 +4939,9 @@ async def test_missing_credentials_error_async(llm = ChatAnthropic(model=MODEL_NAME)with ( # noqa: PT012- patch.object(llm._async_client.messages, "create") as mock_create,+ patch.object(+ llm._async_client.messages.with_raw_response, "create"+ ) as mock_create,pytest.raises(TypeError, match="ANTHROPIC_API_KEY") as exc_info,):mock_create.side_effect = _MISSING_CREDENTIALS_TYPE_ERROR@@ -4753,7 +4956,7 @@ def test_unrelated_type_error_propagates_unchanged() -> None:unrelated_error = TypeError("some unrelated client error")with ( # noqa: PT012- patch.object(llm._client.messages, "create") as mock_create,+ patch.object(llm._client.messages.with_raw_response, "create") as mock_create,pytest.raises(TypeError) as exc_info,):mock_create.side_effect = unrelated_errordiff --git a/libs/partners/anthropic/uv.lock b/libs/partners/anthropic/uv.lockindex 7b2ec2e6ef..01b59738e8 100644--- a/libs/partners/anthropic/uv.lock+++ b/libs/partners/anthropic/uv.lock@@ -552,7 +552,7 @@ wheels = [[[package]]name = "langchain"-version = "1.3.15"+version = "1.3.16"source = { editable = "../../langchain_v1" }dependencies = [{ name = "langchain-core" },@@ -690,7 +690,7 @@ typing = [[[package]]name = "langchain-core"-version = "1.6.0"+version = "1.6.1"source = { editable = "../../core" }dependencies = [{ name = "httpx" },