Skip to content

The agent engineering platform.

feat(langchain): enhance `init_chat_model` with improved validation (#34226)

Vishwajeet Kumar3dcafac79bb6
diff --git a/libs/langchain/langchain_classic/chat_models/base.py b/libs/langchain/langchain_classic/chat_models/base.py
index e637b866f0..e648d069ce 100644
--- a/libs/langchain/langchain_classic/chat_models/base.py
+++ b/libs/langchain/langchain_classic/chat_models/base.py
@@ -494,6 +494,11 @@ def _init_chat_model_helper(
from langchain_perplexity import ChatPerplexity
return ChatPerplexity(model=model, **kwargs)
+ if model_provider == "upstage":
+ _check_pkg("langchain_upstage")
+ from langchain_upstage import ChatUpstage
+
+ return ChatUpstage(model=model, **kwargs)
supported = ", ".join(_SUPPORTED_PROVIDERS)
msg = (
f"Unsupported {model_provider=}.\n\nSupported model providers are: {supported}"
@@ -522,34 +527,81 @@ _SUPPORTED_PROVIDERS = {
"ibm",
"xai",
"perplexity",
+ "upstage",
}
def _attempt_infer_model_provider(model_name: str) -> str | None:
- if any(model_name.startswith(pre) for pre in ("gpt-", "o1", "o3")):
+ """Attempt to infer model provider from model name.
+
+ Args:
+ model_name: The name of the model to infer provider for.
+
+ Returns:
+ The inferred provider name, or `None` if no provider could be inferred.
+ """
+ model_lower = model_name.lower()
+
+ # OpenAI models (including newer models and aliases)
+ if any(
+ model_lower.startswith(pre)
+ for pre in (
+ "gpt-",
+ "o1",
+ "o3",
+ "chatgpt",
+ "text-davinci",
+ )
+ ):
return "openai"
- if model_name.startswith("claude"):
+
+ # Anthropic models
+ if model_lower.startswith("claude"):
return "anthropic"
- if model_name.startswith("command"):
+
+ # Cohere models
+ if model_lower.startswith("command"):
return "cohere"
+
+ # Fireworks models
if model_name.startswith("accounts/fireworks"):
return "fireworks"
- if model_name.startswith("gemini"):
+
+ # Google models
+ if model_lower.startswith("gemini"):
return "google_vertexai"
- if model_name.startswith("amazon."):
+
+ # AWS Bedrock models
+ if model_name.startswith("amazon.") or model_lower.startswith(
+ ("anthropic.", "meta.")
+ ):
return "bedrock"
- if model_name.startswith("mistral"):
+
+ # Mistral models
+ if model_lower.startswith(("mistral", "mixtral")):
return "mistralai"
- if model_name.startswith("deepseek"):
+
+ # DeepSeek models
+ if model_lower.startswith("deepseek"):
return "deepseek"
- if model_name.startswith("grok"):
+
+ # xAI models
+ if model_lower.startswith("grok"):
return "xai"
- if model_name.startswith("sonar"):
+
+ # Perplexity models
+ if model_lower.startswith("sonar"):
return "perplexity"
+
+ # Upstage models
+ if model_lower.startswith("solar"):
+ return "upstage"
+
return None
def _parse_model(model: str, model_provider: str | None) -> tuple[str, str]:
+ """Parse model name and provider, inferring provider if necessary."""
if not model_provider and ":" in model:
prefix, suffix = model.split(":", 1)
if prefix in _SUPPORTED_PROVIDERS:
@@ -563,11 +615,17 @@ def _parse_model(model: str, model_provider: str | None) -> tuple[str, str]:
model_provider = model_provider or _attempt_infer_model_provider(model)
if not model_provider:
+ supported_list = ", ".join(sorted(_SUPPORTED_PROVIDERS))
msg = (
- f"Unable to infer model provider for {model=}, please specify "
- f"model_provider directly."
+ f"Unable to infer model provider for {model=}. "
+ f"Please specify 'model_provider' directly.\n\n"
+ f"Supported providers: {supported_list}\n\n"
+ f"For help with specific providers, see: "
+ f"https://docs.langchain.com/oss/python/integrations/providers"
)
raise ValueError(msg)
+
+ # Normalize provider name
model_provider = model_provider.replace("-", "_").lower()
return model, model_provider
diff --git a/libs/langchain/langchain_classic/embeddings/base.py b/libs/langchain/langchain_classic/embeddings/base.py
index e79aa0ff8b..0e64ed7013 100644
--- a/libs/langchain/langchain_classic/embeddings/base.py
+++ b/libs/langchain/langchain_classic/embeddings/base.py
@@ -159,7 +159,7 @@ def init_embeddings(
- `google_genai` -> [`langchain-google-genai`](https://docs.langchain.com/oss/python/integrations/providers/google)
- `google_vertexai` -> [`langchain-google-vertexai`](https://docs.langchain.com/oss/python/integrations/providers/google)
- `huggingface` -> [`langchain-huggingface`](https://docs.langchain.com/oss/python/integrations/providers/huggingface)
- - `mistraiai` -> [`langchain-mistralai`](https://docs.langchain.com/oss/python/integrations/providers/mistralai)
+ - `mistralai` -> [`langchain-mistralai`](https://docs.langchain.com/oss/python/integrations/providers/mistralai)
- `ollama` -> [`langchain-ollama`](https://docs.langchain.com/oss/python/integrations/providers/ollama)
**kwargs: Additional model-specific parameters passed to the embedding model.
diff --git a/libs/langchain/uv.lock b/libs/langchain/uv.lock
index 139c9fdf2d..57637f54f8 100644
--- a/libs/langchain/uv.lock
+++ b/libs/langchain/uv.lock
@@ -1,5 +1,5 @@
version = 1
-revision = 2
+revision = 3
requires-python = ">=3.10.0, <4.0.0"
resolution-markers = [
"python_full_version >= '3.14' and platform_python_implementation == 'PyPy'",
@@ -2458,7 +2458,7 @@ typing = [
[[package]]
name = "langchain-core"
-version = "1.2.3"
+version = "1.2.4"
source = { editable = "../core" }
dependencies = [
{ name = "jsonpatch" },
diff --git a/libs/langchain_v1/langchain/chat_models/base.py b/libs/langchain_v1/langchain/chat_models/base.py
index 8c5965cf0e..d67c8a619e 100644
--- a/libs/langchain_v1/langchain/chat_models/base.py
+++ b/libs/langchain_v1/langchain/chat_models/base.py
@@ -73,7 +73,7 @@ def init_chat_model(
runtime via `config`. Makes it easy to switch between models/providers without
changing your code
- !!! note
+ !!! note "Installation requirements"
Requires the integration package for the chosen model provider to be installed.
See the `model_provider` parameter below for specific package names
@@ -83,10 +83,7 @@ def init_chat_model(
for supported model parameters to use as `**kwargs`.
Args:
- model: The name or ID of the model, e.g. `'o3-mini'`, `'claude-sonnet-4-5-20250929'`.
-
- You can also specify model and model provider in a single argument using
- `'{model_provider}:{model}'` format, e.g. `'openai:o1'`.
+ model: The model name, optionally prefixed with provider (e.g., `'openai:gpt-4o'`).
Will attempt to infer `model_provider` from model if not specified.
@@ -487,45 +484,95 @@ _SUPPORTED_PROVIDERS = {
def _attempt_infer_model_provider(model_name: str) -> str | None:
- if any(model_name.startswith(pre) for pre in ("gpt-", "o1", "o3")):
+ """Attempt to infer model provider from model name.
+
+ Args:
+ model_name: The name of the model to infer provider for.
+
+ Returns:
+ The inferred provider name, or `None` if no provider could be inferred.
+ """
+ model_lower = model_name.lower()
+
+ # OpenAI models (including newer models and aliases)
+ if any(
+ model_lower.startswith(pre)
+ for pre in (
+ "gpt-",
+ "o1",
+ "o3",
+ "chatgpt",
+ "text-davinci",
+ )
+ ):
return "openai"
- if model_name.startswith("claude"):
+
+ # Anthropic models
+ if model_lower.startswith("claude"):
return "anthropic"
- if model_name.startswith("command"):
+
+ # Cohere models
+ if model_lower.startswith("command"):
return "cohere"
+
+ # Fireworks models
if model_name.startswith("accounts/fireworks"):
return "fireworks"
- if model_name.startswith("gemini"):
+
+ # Google models
+ if model_lower.startswith("gemini"):
return "google_vertexai"
- if model_name.startswith("amazon."):
+
+ # AWS Bedrock models
+ if model_name.startswith("amazon.") or model_lower.startswith(("anthropic.", "meta.")):
return "bedrock"
- if model_name.startswith("mistral"):
+
+ # Mistral models
+ if model_lower.startswith(("mistral", "mixtral")):
return "mistralai"
- if model_name.startswith("deepseek"):
+
+ # DeepSeek models
+ if model_lower.startswith("deepseek"):
return "deepseek"
- if model_name.startswith("grok"):
+
+ # xAI models
+ if model_lower.startswith("grok"):
return "xai"
- if model_name.startswith("sonar"):
+
+ # Perplexity models
+ if model_lower.startswith("sonar"):
return "perplexity"
- if model_name.startswith("solar"):
+
+ # Upstage models
+ if model_lower.startswith("solar"):
return "upstage"
+
return None
def _parse_model(model: str, model_provider: str | None) -> tuple[str, str]:
- if (
- not model_provider
- and ":" in model
- and model.split(":", maxsplit=1)[0] in _SUPPORTED_PROVIDERS
- ):
- model_provider = model.split(":", maxsplit=1)[0]
+ """Parse model name and provider, inferring provider if necessary."""
+ # Handle provider:model format
+ if not model_provider and ":" in model and model.split(":")[0] in _SUPPORTED_PROVIDERS:
+ model_provider = model.split(":")[0]
model = ":".join(model.split(":")[1:])
+
+ # Attempt to infer provider if not specified
model_provider = model_provider or _attempt_infer_model_provider(model)
+
if not model_provider:
+ # Enhanced error message with suggestions
+ supported_list = ", ".join(sorted(_SUPPORTED_PROVIDERS))
msg = (
- f"Unable to infer model provider for {model=}, please specify model_provider directly."
+ f"Unable to infer model provider for {model=}. "
+ f"Please specify 'model_provider' directly.\n\n"
+ f"Supported providers: {supported_list}\n\n"
+ f"For help with specific providers, see: "
+ f"https://docs.langchain.com/oss/python/integrations/providers"
)
raise ValueError(msg)
+
+ # Normalize provider name
model_provider = model_provider.replace("-", "_").lower()
return model, model_provider
@@ -555,7 +602,7 @@ class _ConfigurableModel(Runnable[LanguageModelInput, Any]):
) -> None:
self._default_config: dict = default_config or {}
self._configurable_fields: Literal["any"] | list[str] = (
- configurable_fields if configurable_fields == "any" else list(configurable_fields)
+ "any" if configurable_fields == "any" else list(configurable_fields)
)
self._config_prefix = (
config_prefix + "_"
@@ -621,6 +668,8 @@ class _ConfigurableModel(Runnable[LanguageModelInput, Any]):
) -> _ConfigurableModel:
"""Bind config to a `Runnable`, returning a new `Runnable`."""
config = RunnableConfig(**(config or {}), **cast("RunnableConfig", kwargs))
+ # Ensure config is not None after creation
+ config = ensure_config(config)
model_params = self._model_params(config)
remaining_config = {k: v for k, v in config.items() if k != "configurable"}
remaining_config["configurable"] = {
diff --git a/libs/langchain_v1/langchain/embeddings/base.py b/libs/langchain_v1/langchain/embeddings/base.py
index e7c9063f7a..87a7c9f7ad 100644
--- a/libs/langchain_v1/langchain/embeddings/base.py
+++ b/libs/langchain_v1/langchain/embeddings/base.py
@@ -155,7 +155,7 @@ def init_embeddings(
- `cohere` -> [`langchain-cohere`](https://docs.langchain.com/oss/python/integrations/providers/cohere)
- `google_vertexai` -> [`langchain-google-vertexai`](https://docs.langchain.com/oss/python/integrations/providers/google)
- `huggingface` -> [`langchain-huggingface`](https://docs.langchain.com/oss/python/integrations/providers/huggingface)
- - `mistraiai` -> [`langchain-mistralai`](https://docs.langchain.com/oss/python/integrations/providers/mistralai)
+ - `mistralai` -> [`langchain-mistralai`](https://docs.langchain.com/oss/python/integrations/providers/mistralai)
- `ollama` -> [`langchain-ollama`](https://docs.langchain.com/oss/python/integrations/providers/ollama)
**kwargs: Additional model-specific parameters passed to the embedding model.
diff --git a/libs/langchain_v1/tests/unit_tests/chat_models/test_chat_models.py b/libs/langchain_v1/tests/unit_tests/chat_models/test_chat_models.py
index 822503b6df..aa2ea0e96e 100644
--- a/libs/langchain_v1/tests/unit_tests/chat_models/test_chat_models.py
+++ b/libs/langchain_v1/tests/unit_tests/chat_models/test_chat_models.py
@@ -178,7 +178,13 @@ def test_configurable() -> None:
},
],
},
- "config": {"tags": ["foo"], "configurable": {}},
+ "config": {
+ "callbacks": None,
+ "configurable": {},
+ "metadata": {"model": "gpt-4o"},
+ "recursion_limit": 25,
+ "tags": ["foo"],
+ },
"config_factories": [],
"custom_input_type": None,
"custom_output_type": None,
@@ -277,7 +283,13 @@ def test_configurable_with_default() -> None:
"kwargs": {
"tools": [{"name": "foo", "description": "foo", "input_schema": {}}],
},
- "config": {"tags": ["foo"], "configurable": {}},
+ "config": {
+ "callbacks": None,
+ "configurable": {},
+ "metadata": {"bar_model": "claude-sonnet-4-5-20250929"},
+ "recursion_limit": 25,
+ "tags": ["foo"],
+ },
"config_factories": [],
"custom_input_type": None,
"custom_output_type": None,
diff --git a/libs/langchain_v1/uv.lock b/libs/langchain_v1/uv.lock
index 6251740873..354381129d 100644
--- a/libs/langchain_v1/uv.lock
+++ b/libs/langchain_v1/uv.lock
@@ -1,5 +1,5 @@
version = 1
-revision = 2
+revision = 3
requires-python = ">=3.10.0, <4.0.0"
resolution-markers = [
"python_full_version >= '3.14' and platform_python_implementation == 'PyPy'",
@@ -2102,7 +2102,7 @@ wheels = [
[[package]]
name = "langchain-core"
-version = "1.2.3"
+version = "1.2.4"
source = { editable = "../core" }
dependencies = [
{ name = "jsonpatch" },