Skip to content

The agent engineering platform.

feat(core): incorporate gateway metadata to traces (#39703)

Eugene Yurtsev5650448a03d6
diff --git a/libs/core/langchain_core/language_models/chat_models.py b/libs/core/langchain_core/language_models/chat_models.py
index ae75c67604..07303a3ac3 100644
--- a/libs/core/langchain_core/language_models/chat_models.py
+++ b/libs/core/langchain_core/language_models/chat_models.py
@@ -87,6 +87,7 @@ from langchain_core.tracers._streaming import (
_StreamingCallbackHandler,
_V2StreamingCallbackHandler,
)
+from langchain_core.utils._gateway import GATEWAY_METADATA_RESPONSE_KEY
from langchain_core.utils.function_calling import (
convert_to_json_schema,
convert_to_openai_tool,
@@ -2693,8 +2694,17 @@ class SimpleChatModel(BaseChatModel):
def _gen_info_and_msg_metadata(
generation: ChatGeneration | ChatGenerationChunk,
) -> dict[str, Any]:
+ """Extract metadata for the response metadata.
+
+ Removes GATEWAY_METADATA from the generation info.
+ """
+ generation_info = generation.generation_info or {}
return {
- **(generation.generation_info or {}),
+ **{
+ key: value
+ for key, value in generation_info.items()
+ if key != GATEWAY_METADATA_RESPONSE_KEY
+ },
**generation.message.response_metadata,
}
diff --git a/libs/core/langchain_core/tracers/core.py b/libs/core/langchain_core/tracers/core.py
index 5e073259d9..6af82ea9d9 100644
--- a/libs/core/langchain_core/tracers/core.py
+++ b/libs/core/langchain_core/tracers/core.py
@@ -16,6 +16,7 @@ from typing import (
from langchain_core.exceptions import TracerException
from langchain_core.load import dumpd
from langchain_core.tracers.schemas import Run
+from langchain_core.utils._gateway import GATEWAY_METADATA_RESPONSE_KEY
if TYPE_CHECKING:
from collections.abc import Coroutine, Sequence
@@ -36,6 +37,31 @@ logger = logging.getLogger(__name__)
SCHEMA_FORMAT_TYPE = Literal["original", "streaming_events"]
+# Key under which gateway metadata is attached to a run's metadata for tracing.
+_GATEWAY_RUN_METADATA_KEY = "ls_gateway_info"
+
+
+def _extract_gateway_metadata(response: LLMResult) -> dict[str, Any] | None:
+ """Extract LangSmith gateway metadata from a model response.
+
+ When a request is routed through the LangSmith gateway, the gateway returns
+ metadata (e.g. the resolved provider and model) that integrations surface on
+ the generation's `generation_info` under `GATEWAY_METADATA_RESPONSE_KEY`.
+
+ Args:
+ response: The `LLMResult` produced by the model.
+
+ Returns:
+ The gateway metadata, or `None` if the response carries none.
+ """
+ for generations in response.generations:
+ for generation in generations:
+ generation_info = getattr(generation, "generation_info", None) or {}
+ gateway_metadata = generation_info.get(GATEWAY_METADATA_RESPONSE_KEY)
+ if isinstance(gateway_metadata, dict):
+ return gateway_metadata
+ return None
+
class _TracerCore(ABC):
"""Abstract base class for tracers.
@@ -319,8 +345,18 @@ class _TracerCore(ABC):
if tool_call_count > 0:
llm_run.extra["tool_call_count"] = tool_call_count
+ self._attach_gateway_metadata(llm_run, response)
+
return llm_run
+ def _attach_gateway_metadata(self, run: Run, response: LLMResult) -> None:
+ """Promote LangSmith gateway metadata from the response to run metadata."""
+ gateway_metadata = _extract_gateway_metadata(response)
+ if gateway_metadata is None:
+ return
+ metadata = run.extra.setdefault("metadata", {})
+ metadata[_GATEWAY_RUN_METADATA_KEY] = gateway_metadata
+
def _errored_llm_run(
self, error: BaseException, run_id: UUID, response: LLMResult | None = None
) -> Run:
@@ -340,6 +376,7 @@ class _TracerCore(ABC):
output_generation["message"] = dumpd(
cast("ChatGeneration", generation).message
)
+ self._attach_gateway_metadata(llm_run, response)
llm_run.end_time = datetime.now(timezone.utc)
llm_run.events.append({"name": "error", "time": llm_run.end_time})
diff --git a/libs/core/langchain_core/utils/_gateway.py b/libs/core/langchain_core/utils/_gateway.py
index 6bcab95890..55eea0f518 100644
--- a/libs/core/langchain_core/utils/_gateway.py
+++ b/libs/core/langchain_core/utils/_gateway.py
@@ -10,7 +10,9 @@ This module is private: the API is not stable and may change without notice.
from __future__ import annotations
+import json
import os
+from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, NamedTuple
from pydantic import SecretStr
@@ -20,6 +22,16 @@ if TYPE_CHECKING:
from pydantic import BaseModel
+# Key under which integrations place parsed gateway metadata on a generation's
+# `generation_info`. This is the contract consumed by the LangSmith tracer, which
+# promotes it to run metadata. Defined here so integrations and the tracer agree
+# on a single name.
+GATEWAY_METADATA_RESPONSE_KEY = "lc_gateway_metadata"
+
+# HTTP response header the LangSmith gateway uses to return per-request metadata
+# (e.g. the resolved provider and model). The value is JSON-encoded.
+GATEWAY_METADATA_HEADER = "X-LangSmith-Gateway-Metadata"
+
_LANGSMITH_GATEWAY_ENV = "LANGSMITH_GATEWAY"
_LANGSMITH_GATEWAY_API_KEY_ENV = "LANGSMITH_GATEWAY_API_KEY"
_LANGSMITH_API_KEY_ENV = "LANGSMITH_API_KEY"
@@ -233,3 +245,30 @@ def _apply_gateway_config(
if config.api_key is not None:
values[api_key_field] = config.api_key
return config
+
+
+def _parse_gateway_metadata(headers: Any) -> dict[str, Any] | None:
+ """Parse LangSmith gateway metadata from HTTP response headers.
+
+ Provider integrations call this on the raw response headers so the parsed
+ result can be surfaced under `GATEWAY_METADATA_RESPONSE_KEY` and later
+ promoted to run metadata by the LangSmith tracer.
+
+ Args:
+ headers: The response headers.
+
+ Returns:
+ The deserialized gateway metadata, or None when the header is absent,
+ not a mapping, or not a JSON object.
+ """
+ if not isinstance(headers, Mapping):
+ return None
+
+ raw = headers.get(GATEWAY_METADATA_HEADER)
+ if not raw:
+ return None
+ try:
+ parsed = json.loads(raw)
+ except (json.JSONDecodeError, TypeError):
+ return None
+ return parsed if isinstance(parsed, dict) else None
diff --git a/libs/core/tests/unit_tests/tracers/test_automatic_metadata.py b/libs/core/tests/unit_tests/tracers/test_automatic_metadata.py
index c9d4797e74..47f8362811 100644
--- a/libs/core/tests/unit_tests/tracers/test_automatic_metadata.py
+++ b/libs/core/tests/unit_tests/tracers/test_automatic_metadata.py
@@ -9,6 +9,7 @@ from langchain_core.messages.tool import ToolCall
from langchain_core.outputs import ChatGeneration, LLMResult
from langchain_core.tracers.core import _TracerCore
from langchain_core.tracers.schemas import Run
+from langchain_core.utils._gateway import GATEWAY_METADATA_RESPONSE_KEY
class MockTracerCore(_TracerCore):
@@ -153,3 +154,79 @@ def test_complete_llm_run_handles_null_tool_calls() -> None:
completed_run = tracer._complete_llm_run(response=response, run_id=run.id)
assert "tool_call_count" not in completed_run.extra
+
+
+def _make_run(run_id: str) -> Run:
+ run = MagicMock(spec=Run)
+ run.id = run_id
+ run.run_type = "llm"
+ run.extra = {}
+ run.outputs = {}
+ run.events = []
+ run.end_time = None
+ run.inputs = {}
+ return run
+
+
+def test_complete_llm_run_attaches_gateway_metadata() -> None:
+ """Gateway metadata on `generation_info` is promoted to run metadata."""
+ tracer = MockTracerCore()
+ run = _make_run("test-gateway-run-id")
+ tracer.run_map[str(run.id)] = run
+
+ gateway_info = {"provider": "openai", "model": "gpt-5.6-sol"}
+ message = AIMessage(content="Test")
+ response = LLMResult(
+ generations=[
+ [
+ ChatGeneration(
+ message=message,
+ generation_info={GATEWAY_METADATA_RESPONSE_KEY: gateway_info},
+ )
+ ]
+ ]
+ )
+
+ completed_run = tracer._complete_llm_run(response=response, run_id=run.id)
+
+ assert completed_run.extra["metadata"]["ls_gateway_info"] == gateway_info
+
+
+def test_complete_llm_run_no_gateway_metadata() -> None:
+ """No gateway metadata is attached when the response carries none."""
+ tracer = MockTracerCore()
+ run = _make_run("test-no-gateway-run-id")
+ tracer.run_map[str(run.id)] = run
+
+ message = AIMessage(content="Test", response_metadata={"model_provider": "openai"})
+ response = LLMResult(generations=[[ChatGeneration(message=message)]])
+
+ completed_run = tracer._complete_llm_run(response=response, run_id=run.id)
+
+ assert "metadata" not in completed_run.extra
+
+
+def test_errored_llm_run_attaches_gateway_metadata() -> None:
+ """Gateway metadata is attached on the error path too."""
+ tracer = MockTracerCore()
+ run = _make_run("test-gateway-error-run-id")
+ tracer.run_map[str(run.id)] = run
+
+ gateway_info = {"error": "rate_limit_exceeded"}
+ message = AIMessage(content="")
+ response = LLMResult(
+ generations=[
+ [
+ ChatGeneration(
+ message=message,
+ generation_info={GATEWAY_METADATA_RESPONSE_KEY: gateway_info},
+ )
+ ]
+ ]
+ )
+
+ errored_run = tracer._errored_llm_run(
+ error=ValueError("boom"), run_id=run.id, response=response
+ )
+
+ assert errored_run.extra["metadata"]["ls_gateway_info"] == gateway_info
diff --git a/libs/core/tests/unit_tests/utils/test_gateway.py b/libs/core/tests/unit_tests/utils/test_gateway.py
index 362422cfa7..7e03fca654 100644
--- a/libs/core/tests/unit_tests/utils/test_gateway.py
+++ b/libs/core/tests/unit_tests/utils/test_gateway.py
@@ -8,6 +8,7 @@ from pydantic import BaseModel, ConfigDict, Field, SecretStr
from langchain_core.utils._gateway import (
GatewayConfig,
_apply_gateway_config,
+ _parse_gateway_metadata,
_resolve_gateway_base_url,
_resolve_gateway_config,
)
@@ -316,3 +317,17 @@ def test_apply_omits_key_when_unresolved() -> None:
values, config = _apply({})
assert "api_key" not in values
assert config.api_key is None
+
+
+def test_parse_gateway_metadata_deserializes_json() -> None:
+ headers = {"X-LangSmith-Gateway-Metadata": '{"provider": "openai"}'}
+ assert _parse_gateway_metadata(headers) == {"provider": "openai"}
+
+
+def test_parse_gateway_metadata_absent() -> None:
+ assert _parse_gateway_metadata({"content-type": "application/json"}) is None
+
+
+def test_parse_gateway_metadata_non_json() -> None:
+ headers = {"X-LangSmith-Gateway-Metadata": "not-json"}
+ assert _parse_gateway_metadata(headers) is None