The agent engineering platform.
Python agentsaiai-agentsanthropicchatgptdeepagentsenterpriseframeworkgeminigenerative-ailangchainlanggraphllmmultiagentopen-sourceopenaipydanticpythonragtypescript
feat(anthropic,fireworks,openai): support langsmith gateway through env var (#38742)
ccurmed35a4ef183b6
diff --git a/libs/core/langchain_core/utils/_gateway.py b/libs/core/langchain_core/utils/_gateway.pynew file mode 100644index 0000000000..d41d383d5c--- /dev/null+++ b/libs/core/langchain_core/utils/_gateway.py@@ -0,0 +1,229 @@+"""Private helpers for resolving LangSmith gateway configuration.++The [LangSmith LLM gateway](https://docs.langchain.com/langsmith/llm-gateway)+lets a chat model reach a provider through a proxy configured via environment+variables. These helpers centralize the (non-trivial) precedence rules so that+each provider integration resolves its base URL and API key identically.++This module is private: the API is not stable and may change without notice.+"""++from __future__ import annotations++import os+from typing import TYPE_CHECKING, Any, NamedTuple++from pydantic import SecretStr++if TYPE_CHECKING:+ from collections.abc import Sequence++ from pydantic import BaseModel++_LANGSMITH_GATEWAY_ENV = "LANGSMITH_GATEWAY"+_LANGSMITH_GATEWAY_API_KEY_ENV = "LANGSMITH_GATEWAY_API_KEY"+_LANGSMITH_GATEWAY_DEFAULT_BASE = "https://gateway.smith.langchain.com"++_TRUE_VALUES = ("true", "1", "yes")+_FALSE_VALUES = ("false", "0", "no")+++class GatewayConfig(NamedTuple):+ """Resolved gateway configuration.++ Attributes:+ base_url: The base URL the client should use, or None to defer to the+ provider SDK's own default.+ api_key: The API key to use. A ``SecretStr`` when derived from the+ environment; the caller's value returned unchanged when one was+ passed explicitly; None when no key could be resolved.+ base_url_from_gateway: Whether ``base_url`` was populated from the+ LangSmith gateway (as opposed to an explicit value, a provider env+ var, or a default).+ """++ base_url: str | None+ api_key: Any+ base_url_from_gateway: bool+++def _first_env(names: str | Sequence[str]) -> str | None:+ """Return the first non-empty value among ``names``, or None."""+ if isinstance(names, str):+ names = (names,)+ for name in names:+ value = os.getenv(name)+ if value:+ return value+ return None+++def _resolve_gateway_base_url(provider_path: str) -> str | None:+ """Resolve the LangSmith gateway base URL for a provider.++ ``LANGSMITH_GATEWAY`` accepts either a boolean-ish string or an explicit+ base URL:++ - ``true`` / ``1`` / ``yes`` -> the default gateway host.+ - ``false`` / ``0`` / ``no`` / unset -> the gateway is disabled (None).+ - anything else -> treated as a custom gateway base URL.++ The provider-specific path is appended in all enabled cases.++ Args:+ provider_path: Path segment for the provider, e.g. ``"openai/v1"`` or+ ``"anthropic"``.++ Returns:+ The provider base URL on the gateway, or None if the gateway is+ disabled.+ """+ raw = os.getenv(_LANGSMITH_GATEWAY_ENV)+ if raw is None or raw.lower() in _FALSE_VALUES:+ return None+ base = (+ _LANGSMITH_GATEWAY_DEFAULT_BASE+ if raw.lower() in _TRUE_VALUES+ else raw.rstrip("/")+ )+ return f"{base}/{provider_path}"+++def _resolve_gateway_config(+ *,+ base_url: str | None,+ api_key: Any,+ provider_path: str,+ base_url_env: str | Sequence[str] = (),+ api_key_env: str | Sequence[str] = (),+ default_base_url: str | None = None,+) -> GatewayConfig:+ """Resolve a provider's base URL and API key, applying gateway settings.++ Precedence:++ - **base_url:** explicit ``base_url`` > ``base_url_env`` > LangSmith gateway+ > ``default_base_url``.+ - **api_key:** explicit ``api_key`` (returned unchanged) > the gateway key if+ the base URL came from the gateway, otherwise the provider key > the other.+ The gateway key is only a candidate when the gateway is enabled.++ The provenance flip on the key means an ``OPENAI_API_KEY``-style provider key+ is preferred whenever the caller pointed the base URL at a non-gateway+ endpoint (so a stray gateway key is not sent to the provider), while the+ gateway key wins for the common "just enable the gateway" setup even if a+ provider key happens to be present in the environment.++ Args:+ base_url: Explicitly-provided base URL (e.g. a ``base_url`` kwarg), or+ None if not set by the caller.+ api_key: Explicitly-provided API key, or None if not set by the caller.+ Returned unchanged when not None, so a caller-supplied value (secret+ or callable) always wins.+ provider_path: Path segment appended to the gateway host.+ base_url_env: Env var name(s) for the provider base URL, in priority+ order.+ api_key_env: Env var name(s) for the provider API key, in priority order.+ default_base_url: Base URL used when nothing else is set.++ Returns:+ The resolved `GatewayConfig`.+ """+ gateway_base_url = _resolve_gateway_base_url(provider_path)++ resolved_base_url = base_url+ base_url_from_gateway = False+ if resolved_base_url is None:+ resolved_base_url = _first_env(base_url_env)+ if resolved_base_url is None:+ if gateway_base_url is not None:+ resolved_base_url = gateway_base_url+ base_url_from_gateway = True+ else:+ resolved_base_url = default_base_url++ if api_key is not None:+ resolved_api_key: Any = api_key+ else:+ gateway_api_key = (+ os.getenv(_LANGSMITH_GATEWAY_API_KEY_ENV)+ if gateway_base_url is not None+ else None+ )+ provider_api_key = _first_env(api_key_env)+ chosen = (+ (gateway_api_key or provider_api_key)+ if base_url_from_gateway+ else (provider_api_key or gateway_api_key)+ )+ resolved_api_key = SecretStr(chosen) if chosen else None++ return GatewayConfig(resolved_base_url, resolved_api_key, base_url_from_gateway)+++def _pop_provided(values: dict[str, Any], cls: type[BaseModel], field: str) -> Any:+ """Pop a caller-provided field value by name or alias; None if absent.++ Handles models with ``populate_by_name=True``, where a field may be supplied+ under either its name or its alias. Both keys are removed so the resolved+ value can be written back canonically under the field name. The alias is read+ from the model rather than hard-coded, so callers pass only field names.+ """+ value = values.pop(field, None)+ alias = cls.model_fields[field].alias+ if alias is not None:+ alias_value = values.pop(alias, None)+ if value is None:+ value = alias_value+ return value+++def _apply_gateway_config(+ values: dict[str, Any],+ cls: type[BaseModel],+ *,+ base_url_field: str,+ api_key_field: str,+ provider_path: str,+ base_url_env: str | Sequence[str] = (),+ api_key_env: str | Sequence[str] = (),+ default_base_url: str | None = None,+) -> GatewayConfig:+ """Resolve gateway settings from a model's raw input in a "before" validator.++ Reads the caller-provided base URL and API key (by field name or alias),+ resolves them against the gateway and provider env vars via+ `_resolve_gateway_config`, then writes the results back into ``values`` under+ the canonical field names. This lets a provider integration keep a+ non-optional key field: the resolved value is injected before field+ validation runs, so the field always receives a concrete value.++ The resolved API key is written only when non-None, so the field's own+ default applies when no key is found. Returns the `GatewayConfig` so the+ caller can, for example, raise when a required key is missing.++ Args:+ values: The raw input mapping passed to the model, mutated in place.+ cls: The model class, used to look up field aliases.+ base_url_field: Name of the base URL field (e.g. ``"anthropic_api_url"``).+ api_key_field: Name of the API key field (e.g. ``"anthropic_api_key"``).+ provider_path: Path segment appended to the gateway host.+ base_url_env: Env var name(s) for the provider base URL.+ api_key_env: Env var name(s) for the provider API key.+ default_base_url: Base URL used when nothing else is set.++ Returns:+ The resolved `GatewayConfig`.+ """+ config = _resolve_gateway_config(+ base_url=_pop_provided(values, cls, base_url_field),+ api_key=_pop_provided(values, cls, api_key_field),+ provider_path=provider_path,+ base_url_env=base_url_env,+ api_key_env=api_key_env,+ default_base_url=default_base_url,+ )+ values[base_url_field] = config.base_url+ if config.api_key is not None:+ values[api_key_field] = config.api_key+ return configdiff --git a/libs/core/tests/unit_tests/utils/test_gateway.py b/libs/core/tests/unit_tests/utils/test_gateway.pynew file mode 100644index 0000000000..4437956f7a--- /dev/null+++ b/libs/core/tests/unit_tests/utils/test_gateway.py@@ -0,0 +1,279 @@+"""Tests for LangSmith gateway configuration resolution."""++from typing import Any++import pytest+from pydantic import BaseModel, ConfigDict, Field, SecretStr++from langchain_core.utils._gateway import (+ GatewayConfig,+ _apply_gateway_config,+ _resolve_gateway_base_url,+ _resolve_gateway_config,+)++# A representative provider path; the helper is provider-agnostic.+_PATH = "openai/v1"+_BASE_ENV = "OPENAI_API_BASE"+_KEY_ENV = "OPENAI_API_KEY"+_DEFAULT_GATEWAY = "https://gateway.smith.langchain.com/openai/v1"++[email protected](autouse=True)+def _clear_env(monkeypatch: pytest.MonkeyPatch) -> None:+ """Ensure a hermetic environment for every test."""+ for var in (+ "LANGSMITH_GATEWAY",+ "LANGSMITH_GATEWAY_API_KEY",+ _BASE_ENV,+ _KEY_ENV,+ ):+ monkeypatch.delenv(var, raising=False)+++def _config(**overrides: object) -> GatewayConfig:+ kwargs: dict[str, Any] = {+ "base_url": None,+ "api_key": None,+ "provider_path": _PATH,+ "base_url_env": _BASE_ENV,+ "api_key_env": _KEY_ENV,+ }+ kwargs.update(overrides)+ return _resolve_gateway_config(**kwargs)+++# --- _resolve_gateway_base_url --------------------------------------------++[email protected]("value", ["true", "1", "yes", "TRUE", "Yes"])+def test_base_url_truthy(monkeypatch: pytest.MonkeyPatch, value: str) -> None:+ monkeypatch.setenv("LANGSMITH_GATEWAY", value)+ assert _resolve_gateway_base_url(_PATH) == _DEFAULT_GATEWAY++[email protected]("value", ["false", "0", "no", "FALSE"])+def test_base_url_falsy(monkeypatch: pytest.MonkeyPatch, value: str) -> None:+ monkeypatch.setenv("LANGSMITH_GATEWAY", value)+ assert _resolve_gateway_base_url(_PATH) is None+++def test_base_url_unset(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv("LANGSMITH_GATEWAY", raising=False)+ assert _resolve_gateway_base_url(_PATH) is None+++def test_base_url_custom(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("LANGSMITH_GATEWAY", "https://eu.gateway.example.com/")+ assert (+ _resolve_gateway_base_url(_PATH) == "https://eu.gateway.example.com/openai/v1"+ )+++# --- api key + base url resolution matrix ---------------------------------+# Each case mirrors a documented requirement scenario.+++def test_gateway_on_with_gateway_key(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("LANGSMITH_GATEWAY", "true")+ monkeypatch.setenv("LANGSMITH_GATEWAY_API_KEY", "gateway-key")+ config = _config()+ assert config.base_url == _DEFAULT_GATEWAY+ assert config.base_url_from_gateway is True+ assert isinstance(config.api_key, SecretStr)+ assert config.api_key.get_secret_value() == "gateway-key"+++def test_gateway_key_ignored_when_gateway_off(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ # Gateway key set but LANGSMITH_GATEWAY unset -> never used.+ monkeypatch.setenv("LANGSMITH_GATEWAY_API_KEY", "gateway-key")+ monkeypatch.setenv(_KEY_ENV, "provider-key")+ config = _config()+ assert config.base_url is None+ assert config.base_url_from_gateway is False+ assert isinstance(config.api_key, SecretStr)+ assert config.api_key.get_secret_value() == "provider-key"+++def test_gateway_off_explicitly(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("LANGSMITH_GATEWAY", "false")+ monkeypatch.setenv("LANGSMITH_GATEWAY_API_KEY", "gateway-key")+ config = _config()+ assert config.base_url is None+ assert config.api_key is None+++def test_gateway_key_beats_provider_key_on_gateway(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("LANGSMITH_GATEWAY", "true")+ monkeypatch.setenv("LANGSMITH_GATEWAY_API_KEY", "gateway-key")+ monkeypatch.setenv(_KEY_ENV, "provider-key")+ config = _config()+ assert config.base_url == _DEFAULT_GATEWAY+ assert config.api_key.get_secret_value() == "gateway-key"+++def test_gateway_on_falls_back_to_provider_key(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("LANGSMITH_GATEWAY", "true")+ monkeypatch.setenv(_KEY_ENV, "provider-key")+ config = _config()+ assert config.base_url == _DEFAULT_GATEWAY+ assert config.api_key.get_secret_value() == "provider-key"+++def test_provider_base_url_uses_provider_key(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ # Base URL overridden away from the gateway -> provider key wins.+ monkeypatch.setenv("LANGSMITH_GATEWAY", "true")+ monkeypatch.setenv("LANGSMITH_GATEWAY_API_KEY", "gateway-key")+ monkeypatch.setenv(_BASE_ENV, "https://api.openai.com/v1")+ monkeypatch.setenv(_KEY_ENV, "provider-key")+ config = _config()+ assert config.base_url == "https://api.openai.com/v1"+ assert config.base_url_from_gateway is False+ assert config.api_key.get_secret_value() == "provider-key"+++def test_provider_base_url_falls_back_to_gateway_key(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ # Base URL overridden, no provider key -> gateway key used as fallback.+ monkeypatch.setenv("LANGSMITH_GATEWAY", "true")+ monkeypatch.setenv("LANGSMITH_GATEWAY_API_KEY", "gateway-key")+ monkeypatch.setenv(_BASE_ENV, "https://api.openai.com/v1")+ config = _config()+ assert config.base_url == "https://api.openai.com/v1"+ assert config.api_key.get_secret_value() == "gateway-key"+++def test_custom_gateway_url(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("LANGSMITH_GATEWAY", "https://eu.gateway.example.com")+ monkeypatch.setenv("LANGSMITH_GATEWAY_API_KEY", "gateway-key")+ config = _config()+ assert config.base_url == "https://eu.gateway.example.com/openai/v1"+ assert config.base_url_from_gateway is True+ assert config.api_key.get_secret_value() == "gateway-key"+++def test_explicit_kwargs_override_everything(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("LANGSMITH_GATEWAY", "https://eu.gateway.example.com")+ monkeypatch.setenv("LANGSMITH_GATEWAY_API_KEY", "gateway-key")+ monkeypatch.setenv(_KEY_ENV, "provider-key")+ explicit_key = SecretStr("explicit-key")+ config = _config(+ base_url="https://apac.gateway.example.com",+ api_key=explicit_key,+ )+ assert config.base_url == "https://apac.gateway.example.com"+ assert config.base_url_from_gateway is False+ assert config.api_key is explicit_key+++def test_explicit_base_url_pairs_with_gateway_key(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ # Explicit base URL, no explicit key: gateway key still resolved from env.+ monkeypatch.setenv("LANGSMITH_GATEWAY", "https://eu.gateway.example.com")+ monkeypatch.setenv("LANGSMITH_GATEWAY_API_KEY", "gateway-key")+ config = _config(base_url="https://apac.gateway.example.com")+ assert config.base_url == "https://apac.gateway.example.com"+ assert config.api_key.get_secret_value() == "gateway-key"+++def test_no_gateway_uses_provider_defaults(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv(_BASE_ENV, "https://provider.example.com")+ monkeypatch.setenv(_KEY_ENV, "provider-key")+ config = _config(default_base_url="https://default.example.com")+ assert config.base_url == "https://provider.example.com"+ assert config.api_key.get_secret_value() == "provider-key"+++def test_default_base_url_when_nothing_set() -> None:+ config = _config(default_base_url="https://default.example.com")+ assert config.base_url == "https://default.example.com"+ assert config.base_url_from_gateway is False+ assert config.api_key is None+++def test_multiple_base_url_env_vars_priority(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("SECOND_BASE", "https://second.example.com")+ config = _config(base_url_env=["FIRST_BASE", "SECOND_BASE"])+ assert config.base_url == "https://second.example.com"+++# --- _apply_gateway_config (before-validator path) ------------------------+++class _Model(BaseModel):+ """Stand-in for a provider chat model with aliased fields."""++ model_config = ConfigDict(populate_by_name=True)++ api_base: str | None = Field(default=None, alias="base_url")+ api_key: SecretStr = Field(default=SecretStr(""), alias="api_key_alias")+++def _apply(values: dict[str, Any]) -> tuple[dict[str, Any], GatewayConfig]:+ config = _apply_gateway_config(+ values,+ _Model,+ base_url_field="api_base",+ api_key_field="api_key",+ provider_path="openai/v1",+ base_url_env=_BASE_ENV,+ api_key_env=_KEY_ENV,+ )+ return values, config+++def test_apply_writes_resolved_values_by_field_name(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("LANGSMITH_GATEWAY", "true")+ monkeypatch.setenv("LANGSMITH_GATEWAY_API_KEY", "gateway-key")+ values, config = _apply({})+ assert values["api_base"] == _DEFAULT_GATEWAY+ assert isinstance(values["api_key"], SecretStr)+ assert values["api_key"].get_secret_value() == "gateway-key"+ assert config.base_url_from_gateway is True+++def test_apply_reads_explicit_via_alias(monkeypatch: pytest.MonkeyPatch) -> None:+ # Values provided under aliases are consumed and rewritten under field names.+ monkeypatch.setenv("LANGSMITH_GATEWAY", "true")+ monkeypatch.setenv("LANGSMITH_GATEWAY_API_KEY", "gateway-key")+ values, _ = _apply(+ {"base_url": "https://explicit.example.com", "api_key_alias": "explicit-key"}+ )+ assert "base_url" not in values+ assert "api_key_alias" not in values+ assert values["api_base"] == "https://explicit.example.com"+ assert values["api_key"] == "explicit-key"+++def test_apply_reads_explicit_via_field_name(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("LANGSMITH_GATEWAY", "true")+ monkeypatch.setenv("LANGSMITH_GATEWAY_API_KEY", "gateway-key")+ values, _ = _apply({"api_base": "https://explicit.example.com"})+ assert values["api_base"] == "https://explicit.example.com"+++def test_apply_omits_key_when_unresolved() -> None:+ # No key anywhere: the field is left unset so its own default applies.+ values, config = _apply({})+ assert "api_key" not in values+ assert config.api_key is Nonediff --git a/libs/partners/anthropic/langchain_anthropic/chat_models.py b/libs/partners/anthropic/langchain_anthropic/chat_models.pyindex 7830b450f0..103e655d3c 100644--- a/libs/partners/anthropic/langchain_anthropic/chat_models.py+++ b/libs/partners/anthropic/langchain_anthropic/chat_models.py@@ -48,7 +48,8 @@ from langchain_core.output_parsers.base import OutputParserLikefrom langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResultfrom langchain_core.runnables import Runnable, RunnableMap, RunnablePassthroughfrom langchain_core.tools import BaseTool-from langchain_core.utils import from_env, get_pydantic_field_names, secret_from_env+from langchain_core.utils import from_env, get_pydantic_field_names+from langchain_core.utils._gateway import _apply_gateway_configfrom langchain_core.utils.function_calling import (convert_to_json_schema,convert_to_openai_tool,@@ -959,24 +960,21 @@ class ChatAnthropic(BaseChatModel):stop_sequences: list[str] | None = Field(None, alias="stop")"""Default stop sequences."""- anthropic_api_url: str | None = Field(- alias="base_url",- default_factory=from_env(- ["ANTHROPIC_API_URL", "ANTHROPIC_BASE_URL"],- default="https://api.anthropic.com",- ),- )+ anthropic_api_url: str | None = Field(default=None, alias="base_url")"""Base URL for API requests. Only specify if using a proxy or service emulator.If a value isn't passed in, will attempt to read the value first from`ANTHROPIC_API_URL` and if that is not set, `ANTHROPIC_BASE_URL`.++ If `LANGSMITH_GATEWAY` is set, it is used as a fallback after those env vars."""- anthropic_api_key: SecretStr = Field(- alias="api_key",- default_factory=secret_from_env("ANTHROPIC_API_KEY", default=""),- )- """Automatically read from env var `ANTHROPIC_API_KEY` if not provided."""+ anthropic_api_key: SecretStr = Field(default=SecretStr(""), alias="api_key")+ """Automatically read from env var `ANTHROPIC_API_KEY` if not provided.++ If `LANGSMITH_GATEWAY` is enabled and the base URL points at the gateway,+ `LANGSMITH_GATEWAY_API_KEY` is used instead.+ """anthropic_proxy: str | None = Field(default_factory=from_env("ANTHROPIC_PROXY", default=None)@@ -1208,6 +1206,31 @@ class ChatAnthropic(BaseChatModel):self._add_version("langchain-anthropic", __version__)return self+ @model_validator(mode="before")+ @classmethod+ def _resolve_gateway(cls, values: Any) -> Any:+ """Resolve the base URL and API key, applying LangSmith gateway settings.++ An explicit ``base_url``/``api_key`` always wins. Otherwise the base URL+ falls back to ``ANTHROPIC_API_URL``/``ANTHROPIC_BASE_URL``, then the+ LangSmith gateway, then the Anthropic default. The gateway key is+ preferred only when the base URL came from the gateway; for any other+ endpoint the provider key wins, and the gateway key is a candidate only+ when the gateway is enabled.+ """+ if isinstance(values, dict):+ _apply_gateway_config(+ values,+ cls,+ base_url_field="anthropic_api_url",+ api_key_field="anthropic_api_key",+ provider_path="anthropic",+ base_url_env=["ANTHROPIC_API_URL", "ANTHROPIC_BASE_URL"],+ api_key_env="ANTHROPIC_API_KEY",+ default_base_url="https://api.anthropic.com",+ )+ return values+def _resolve_model_profile(self) -> ModelProfile | None:profile = _get_default_model_profile(self.model) or Noneif profile is not None and self.betas and "context-1m-2025-08-07" in self.betas:diff --git a/libs/partners/anthropic/tests/unit_tests/test_chat_models.py b/libs/partners/anthropic/tests/unit_tests/test_chat_models.pyindex e03cc48ead..c2de631c28 100644--- a/libs/partners/anthropic/tests/unit_tests/test_chat_models.py+++ b/libs/partners/anthropic/tests/unit_tests/test_chat_models.py@@ -3786,3 +3786,94 @@ def test_anthropic_stream_events_v3_lifecycle() -> None:message_finish = cast("dict[str, Any]", stream_events[-1])assert message_finish["event"] == "message-finish"assert message_finish["metadata"]["stop_reason"] == "tool_use"+++def test_langsmith_gateway_true(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("LANGSMITH_GATEWAY", "true")+ monkeypatch.delenv("ANTHROPIC_API_URL", raising=False)+ monkeypatch.delenv("ANTHROPIC_BASE_URL", raising=False)+ llm = ChatAnthropic(model=MODEL_NAME, api_key="test")+ assert llm.anthropic_api_url == "https://gateway.smith.langchain.com/anthropic"+++def test_langsmith_gateway_false(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("LANGSMITH_GATEWAY", "false")+ monkeypatch.delenv("ANTHROPIC_API_URL", raising=False)+ monkeypatch.delenv("ANTHROPIC_BASE_URL", raising=False)+ llm = ChatAnthropic(model=MODEL_NAME, api_key="test")+ assert llm.anthropic_api_url == "https://api.anthropic.com"+++def test_langsmith_gateway_unset(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv("LANGSMITH_GATEWAY", raising=False)+ monkeypatch.delenv("ANTHROPIC_API_URL", raising=False)+ monkeypatch.delenv("ANTHROPIC_BASE_URL", raising=False)+ llm = ChatAnthropic(model=MODEL_NAME, api_key="test")+ assert llm.anthropic_api_url == "https://api.anthropic.com"+++def test_langsmith_gateway_custom_url(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("LANGSMITH_GATEWAY", "https://my-gateway.example.com/")+ monkeypatch.delenv("ANTHROPIC_API_URL", raising=False)+ monkeypatch.delenv("ANTHROPIC_BASE_URL", raising=False)+ llm = ChatAnthropic(model=MODEL_NAME, api_key="test")+ assert llm.anthropic_api_url == "https://my-gateway.example.com/anthropic"+++def test_langsmith_gateway_provider_env_overrides_gateway(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("LANGSMITH_GATEWAY", "true")+ monkeypatch.delenv("ANTHROPIC_API_URL", raising=False)+ monkeypatch.setenv("ANTHROPIC_BASE_URL", "https://api.anthropic.com")+ llm = ChatAnthropic(model=MODEL_NAME, api_key="test")+ assert llm.anthropic_api_url == "https://api.anthropic.com"+++def test_langsmith_gateway_api_key(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("LANGSMITH_GATEWAY", "true")+ monkeypatch.setenv("LANGSMITH_GATEWAY_API_KEY", "gateway-key")+ monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False)+ monkeypatch.delenv("ANTHROPIC_API_URL", raising=False)+ monkeypatch.delenv("ANTHROPIC_BASE_URL", raising=False)+ llm = ChatAnthropic(model=MODEL_NAME)+ assert llm.anthropic_api_key.get_secret_value() == "gateway-key"+++def test_langsmith_gateway_api_key_not_used_without_gateway(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.delenv("LANGSMITH_GATEWAY", raising=False)+ monkeypatch.setenv("LANGSMITH_GATEWAY_API_KEY", "gateway-key")+ monkeypatch.setenv("ANTHROPIC_API_KEY", "provider-key")+ monkeypatch.delenv("ANTHROPIC_API_URL", raising=False)+ monkeypatch.delenv("ANTHROPIC_BASE_URL", raising=False)+ llm = ChatAnthropic(model=MODEL_NAME)+ assert llm.anthropic_api_key.get_secret_value() == "provider-key"+++def test_langsmith_gateway_api_key_overrides_provider_key(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("LANGSMITH_GATEWAY", "true")+ monkeypatch.setenv("LANGSMITH_GATEWAY_API_KEY", "gateway-key")+ monkeypatch.setenv("ANTHROPIC_API_KEY", "provider-key")+ monkeypatch.delenv("ANTHROPIC_API_URL", raising=False)+ monkeypatch.delenv("ANTHROPIC_BASE_URL", raising=False)+ llm = ChatAnthropic(model=MODEL_NAME)+ assert llm.anthropic_api_key.get_secret_value() == "gateway-key"+++def test_langsmith_gateway_provider_base_url_uses_provider_key(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ # Base URL overridden away from the gateway -> provider key wins over the+ # gateway key, even though the gateway is enabled.+ monkeypatch.setenv("LANGSMITH_GATEWAY", "true")+ monkeypatch.setenv("LANGSMITH_GATEWAY_API_KEY", "gateway-key")+ monkeypatch.setenv("ANTHROPIC_API_KEY", "provider-key")+ monkeypatch.delenv("ANTHROPIC_API_URL", raising=False)+ monkeypatch.setenv("ANTHROPIC_BASE_URL", "https://api.anthropic.com")+ llm = ChatAnthropic(model=MODEL_NAME)+ assert llm.anthropic_api_url == "https://api.anthropic.com"+ assert llm.anthropic_api_key.get_secret_value() == "provider-key"diff --git a/libs/partners/fireworks/langchain_fireworks/chat_models.py b/libs/partners/fireworks/langchain_fireworks/chat_models.pyindex 76ec530ab5..fd5fd07957 100644--- a/libs/partners/fireworks/langchain_fireworks/chat_models.py+++ b/libs/partners/fireworks/langchain_fireworks/chat_models.py@@ -85,12 +85,13 @@ from langchain_core.tools import BaseToolfrom langchain_core.utils import (get_pydantic_field_names,)+from langchain_core.utils._gateway import _apply_gateway_configfrom langchain_core.utils.function_calling import (convert_to_json_schema,convert_to_openai_tool,)from langchain_core.utils.pydantic import is_basemodel_subclass-from langchain_core.utils.utils import _build_model_kwargs, from_env, secret_from_env+from langchain_core.utils.utils import _build_model_kwargsfrom pydantic import (BaseModel,ConfigDict,@@ -814,27 +815,20 @@ class ChatFireworks(BaseChatModel):model_kwargs: dict[str, Any] = Field(default_factory=dict)"""Holds any model parameters valid for `create` call not explicitly specified."""- fireworks_api_key: SecretStr = Field(- alias="api_key",- default_factory=secret_from_env(- "FIREWORKS_API_KEY",- error_message=(- "You must specify an api key. "- "You can pass it an argument as `api_key=...` or "- "set the environment variable `FIREWORKS_API_KEY`."- ),- ),- )+ fireworks_api_key: SecretStr = Field(default=SecretStr(""), alias="api_key")"""Fireworks API key.Automatically read from env variable `FIREWORKS_API_KEY` if not provided.++ If `LANGSMITH_GATEWAY` is enabled and the base URL points at the gateway,+ `LANGSMITH_GATEWAY_API_KEY` is used instead."""- fireworks_api_base: str | None = Field(- alias="base_url", default_factory=from_env("FIREWORKS_API_BASE", default=None)- )+ fireworks_api_base: str | None = Field(default=None, alias="base_url")"""Base URL path for API requests, leave blank if not using a proxy or serviceemulator.++ If `LANGSMITH_GATEWAY` is set, it is used as a fallback after `FIREWORKS_API_BASE`."""request_timeout: float | tuple[float, float] | Any | None = Field(@@ -916,6 +910,36 @@ class ChatFireworks(BaseChatModel):all_required_field_names = get_pydantic_field_names(cls)return _build_model_kwargs(values, all_required_field_names)+ @model_validator(mode="before")+ @classmethod+ def _resolve_gateway(cls, values: Any) -> Any:+ """Resolve the base URL and API key, applying LangSmith gateway settings.++ An explicit ``base_url``/``api_key`` always wins. Otherwise the base URL+ falls back to ``FIREWORKS_API_BASE``, then the LangSmith gateway. The+ gateway key is preferred only when the base URL came from the gateway;+ for any other endpoint the provider key wins, and the gateway key is a+ candidate only when the gateway is enabled.+ """+ if isinstance(values, dict):+ config = _apply_gateway_config(+ values,+ cls,+ base_url_field="fireworks_api_base",+ api_key_field="fireworks_api_key",+ provider_path="fireworks",+ base_url_env="FIREWORKS_API_BASE",+ api_key_env="FIREWORKS_API_KEY",+ )+ if config.api_key is None:+ msg = (+ "You must specify an api key. "+ "You can pass it an argument as `api_key=...` or "+ "set the environment variable `FIREWORKS_API_KEY`."+ )+ raise ValueError(msg)+ return values+@model_validator(mode="after")def _set_fireworks_chat_version(self) -> Self:"""Set package version in metadata."""diff --git a/libs/partners/fireworks/tests/unit_tests/test_chat_models.py b/libs/partners/fireworks/tests/unit_tests/test_chat_models.pyindex 84906675ff..87088b5dcf 100644--- a/libs/partners/fireworks/tests/unit_tests/test_chat_models.py+++ b/libs/partners/fireworks/tests/unit_tests/test_chat_models.py@@ -1920,3 +1920,67 @@ def test_request_timeout_tuple_normalized_to_httpx_timeout(assert forwarded.connect == 5.0assert forwarded.read == 30.0assert async_mock.call_args.kwargs["timeout"] == forwarded+++def test_langsmith_gateway_true(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("LANGSMITH_GATEWAY", "true")+ llm = _make_model()+ assert llm.fireworks_api_base == "https://gateway.smith.langchain.com/fireworks"+++def test_langsmith_gateway_false(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("LANGSMITH_GATEWAY", "false")+ monkeypatch.delenv("FIREWORKS_API_BASE", raising=False)+ llm = _make_model()+ assert llm.fireworks_api_base is None+++def test_langsmith_gateway_unset(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv("LANGSMITH_GATEWAY", raising=False)+ monkeypatch.delenv("FIREWORKS_API_BASE", raising=False)+ llm = _make_model()+ assert llm.fireworks_api_base is None+++def test_langsmith_gateway_custom_url(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("LANGSMITH_GATEWAY", "https://my-gateway.example.com/")+ monkeypatch.delenv("FIREWORKS_API_BASE", raising=False)+ llm = _make_model()+ assert llm.fireworks_api_base == "https://my-gateway.example.com/fireworks"+++def test_langsmith_gateway_provider_env_overrides_gateway(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("LANGSMITH_GATEWAY", "true")+ monkeypatch.setenv("FIREWORKS_API_BASE", "https://api.fireworks.ai/inference/v1")+ llm = _make_model()+ assert llm.fireworks_api_base == "https://api.fireworks.ai/inference/v1"+++def test_langsmith_gateway_api_key(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("LANGSMITH_GATEWAY", "true")+ monkeypatch.setenv("LANGSMITH_GATEWAY_API_KEY", "gateway-key")+ monkeypatch.delenv("FIREWORKS_API_KEY", raising=False)+ llm = ChatFireworks(model=MODEL_NAME) # type: ignore[call-arg]+ assert llm.fireworks_api_key.get_secret_value() == "gateway-key"+++def test_langsmith_gateway_api_key_not_used_without_gateway(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.delenv("LANGSMITH_GATEWAY", raising=False)+ monkeypatch.setenv("LANGSMITH_GATEWAY_API_KEY", "gateway-key")+ monkeypatch.setenv("FIREWORKS_API_KEY", "provider-key")+ llm = ChatFireworks(model=MODEL_NAME) # type: ignore[call-arg]+ assert llm.fireworks_api_key.get_secret_value() == "provider-key"+++def test_langsmith_gateway_api_key_overrides_provider_key(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("LANGSMITH_GATEWAY", "true")+ monkeypatch.setenv("LANGSMITH_GATEWAY_API_KEY", "gateway-key")+ monkeypatch.setenv("FIREWORKS_API_KEY", "provider-key")+ llm = ChatFireworks(model=MODEL_NAME) # type: ignore[call-arg]+ assert llm.fireworks_api_key.get_secret_value() == "gateway-key"diff --git a/libs/partners/openai/langchain_openai/chat_models/base.py b/libs/partners/openai/langchain_openai/chat_models/base.pyindex cc68d18bf3..0702b6d55d 100644--- a/libs/partners/openai/langchain_openai/chat_models/base.py+++ b/libs/partners/openai/langchain_openai/chat_models/base.py@@ -108,6 +108,7 @@ from langchain_core.runnables.config import run_in_executorfrom langchain_core.tools import BaseToolfrom langchain_core.tools.base import _stringifyfrom langchain_core.utils import get_pydantic_field_names+from langchain_core.utils._gateway import _resolve_gateway_configfrom langchain_core.utils.function_calling import (convert_to_openai_function,convert_to_openai_tool,@@ -117,7 +118,7 @@ from langchain_core.utils.pydantic import (TypeBaseModel,is_basemodel_subclass,)-from langchain_core.utils.utils import _build_model_kwargs, from_env, secret_from_env+from langchain_core.utils.utils import _build_model_kwargs, from_envfrom pydantic import (BaseModel,ConfigDict,@@ -648,9 +649,7 @@ class BaseChatOpenAI(BaseChatModel):openai_api_key: (SecretStr | None | Callable[[], str] | Callable[[], Awaitable[str]]- ) = Field(- alias="api_key", default_factory=secret_from_env("OPENAI_API_KEY", default=None)- )+ ) = Field(alias="api_key", default=None)"""API key to use.Can be inferred from the `OPENAI_API_KEY` environment variable, or specified@@ -1212,26 +1211,36 @@ class BaseChatOpenAI(BaseChatModel):or os.getenv("OPENAI_ORG_ID")or os.getenv("OPENAI_ORGANIZATION"))- self.openai_api_base = self.openai_api_base or os.getenv("OPENAI_API_BASE")-- # Enable stream_usage by default if using default base URL and client- if (- all(- getattr(self, key, None) is None- for key in (- "stream_usage",- "openai_proxy",- "openai_api_base",- "base_url",- "client",- "root_client",- "async_client",- "root_async_client",- "http_client",- "http_async_client",- )+ # Resolve base URL and API key, applying LangSmith gateway settings.+ _gateway_config = _resolve_gateway_config(+ base_url=self.openai_api_base,+ api_key=self.openai_api_key,+ provider_path="openai/v1",+ base_url_env="OPENAI_API_BASE",+ api_key_env="OPENAI_API_KEY",+ )+ self.openai_api_base = _gateway_config.base_url+ self.openai_api_key = _gateway_config.api_key+ _base_url_from_gateway = _gateway_config.base_url_from_gateway++ # Enable stream_usage by default if using default base URL and client,+ # or when the base URL was set by the LangSmith gateway (which proxies+ # to OpenAI and supports streaming token usage).+ if all(+ getattr(self, key, None) is None+ for key in (+ "stream_usage",+ "openai_proxy",+ "client",+ "root_client",+ "async_client",+ "root_async_client",+ "http_client",+ "http_async_client",)- and "OPENAI_BASE_URL" not in os.environ+ ) and (+ _base_url_from_gateway+ or (self.openai_api_base is None and "OPENAI_BASE_URL" not in os.environ)):self.stream_usage = Truediff --git a/libs/partners/openai/tests/unit_tests/chat_models/test_base.py b/libs/partners/openai/tests/unit_tests/chat_models/test_base.pyindex f2a72620d0..4a4233d6da 100644--- a/libs/partners/openai/tests/unit_tests/chat_models/test_base.py+++ b/libs/partners/openai/tests/unit_tests/chat_models/test_base.py@@ -4690,3 +4690,84 @@ def test_defer_loading_in_responses_api_payload() -> None:assert weather_tool["defer_loading"] is Trueassert weather_tool["type"] == "function"assert {"type": "tool_search"} in result["tools"]+++def test_langsmith_gateway_true(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("LANGSMITH_GATEWAY", "true")+ llm = ChatOpenAI(model=OPENAI_TEST_MODEL, api_key=SecretStr("test"))+ assert llm.openai_api_base == "https://gateway.smith.langchain.com/openai/v1"+ assert llm.stream_usage is True+++def test_langsmith_gateway_false(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("LANGSMITH_GATEWAY", "false")+ llm = ChatOpenAI(model=OPENAI_TEST_MODEL, api_key=SecretStr("test"))+ assert llm.openai_api_base is None+++def test_langsmith_gateway_unset(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv("LANGSMITH_GATEWAY", raising=False)+ llm = ChatOpenAI(model=OPENAI_TEST_MODEL, api_key=SecretStr("test"))+ assert llm.openai_api_base is None+++def test_langsmith_gateway_custom_url(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("LANGSMITH_GATEWAY", "https://my-gateway.example.com/")+ llm = ChatOpenAI(model=OPENAI_TEST_MODEL, api_key=SecretStr("test"))+ assert llm.openai_api_base == "https://my-gateway.example.com/openai/v1"+++def test_langsmith_gateway_provider_env_overrides_gateway(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("LANGSMITH_GATEWAY", "true")+ monkeypatch.setenv("OPENAI_API_BASE", "https://api.openai.com/v1")+ llm = ChatOpenAI(model=OPENAI_TEST_MODEL, api_key=SecretStr("test"))+ assert llm.openai_api_base == "https://api.openai.com/v1"+++def test_langsmith_gateway_api_key(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("LANGSMITH_GATEWAY", "true")+ monkeypatch.setenv("LANGSMITH_GATEWAY_API_KEY", "gateway-key")+ monkeypatch.delenv("OPENAI_API_KEY", raising=False)+ llm = ChatOpenAI(model=OPENAI_TEST_MODEL)+ assert isinstance(llm.openai_api_key, SecretStr)+ assert llm.openai_api_key.get_secret_value() == "gateway-key"+++def test_langsmith_gateway_api_key_not_used_without_gateway(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.delenv("LANGSMITH_GATEWAY", raising=False)+ monkeypatch.setenv("LANGSMITH_GATEWAY_API_KEY", "gateway-key")+ monkeypatch.setenv("OPENAI_API_KEY", "provider-key")+ llm = ChatOpenAI(model=OPENAI_TEST_MODEL)+ assert isinstance(llm.openai_api_key, SecretStr)+ assert llm.openai_api_key.get_secret_value() == "provider-key"+++def test_langsmith_gateway_api_key_overrides_provider_key(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("LANGSMITH_GATEWAY", "true")+ monkeypatch.setenv("LANGSMITH_GATEWAY_API_KEY", "gateway-key")+ monkeypatch.setenv("OPENAI_API_KEY", "provider-key")+ llm = ChatOpenAI(model=OPENAI_TEST_MODEL)+ assert isinstance(llm.openai_api_key, SecretStr)+ assert llm.openai_api_key.get_secret_value() == "gateway-key"+++def test_langsmith_gateway_provider_base_url_uses_provider_key(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ # Provider-specific wiring check: base URL overridden away from the gateway+ # -> provider key wins over the gateway key. Full precedence matrix lives in+ # core's test_gateway.py.+ monkeypatch.setenv("LANGSMITH_GATEWAY", "true")+ monkeypatch.setenv("LANGSMITH_GATEWAY_API_KEY", "gateway-key")+ monkeypatch.setenv("OPENAI_API_BASE", "https://api.openai.com/v1")+ monkeypatch.setenv("OPENAI_API_KEY", "provider-key")+ llm = ChatOpenAI(model=OPENAI_TEST_MODEL)+ assert llm.openai_api_base == "https://api.openai.com/v1"+ assert isinstance(llm.openai_api_key, SecretStr)+ assert llm.openai_api_key.get_secret_value() == "provider-key"