Implementation:Langchain ai Langgraph Init Chat Model
| Attribute | Value |
|---|---|
| API | init_chat_model and BaseChatModel.bind_tools
|
| Workflow | ReAct_Agent_Creation |
| Type | Wrapper Doc |
| Repository | Langchain_ai_Langgraph |
| Source File | External: langchain.chat_models; usage context at libs/prebuilt/langgraph/prebuilt/chat_agent_executor.py (L563-589)
|
Overview
init_chat_model is an external utility from the langchain package that converts a provider-prefixed model string (e.g., "openai:gpt-4" or "anthropic:claude-3-7-sonnet-latest") into a BaseChatModel instance. Within the create_react_agent function, this is used when the model parameter is a string, enabling a concise shorthand for model specification. After initialization, BaseChatModel.bind_tools attaches tool schemas to the model so it can generate structured tool calls during inference.
This page documents how these two external APIs are used within the LangGraph agent construction flow.
Description
When create_react_agent receives a string as the model parameter, it follows this sequence:
- Import check: The function attempts to import
init_chat_modelfromlangchain.chat_models. If not available, it raises anImportErrordirecting the user to installlangchain. - Model initialization:
init_chat_model(model)is called with the string identifier. The function parses the provider prefix (before the colon) and model name (after the colon) to instantiate the appropriate provider-specific chat model class. - Tool binding check: The
_should_bind_toolshelper determines whether tools need to be bound (they may already be bound if the user provided a pre-configured model). - Tool binding: If tools are needed,
model.bind_tools(tool_classes + llm_builtin_tools)is called, returning a new model instance with tool schemas attached. - Prompt composition: The bound model is composed with the prompt runnable:
_get_prompt_runnable(prompt) | model.
The relevant code from chat_agent_executor.py (lines 568-590):
if not is_dynamic_model:
if isinstance(model, str):
try:
from langchain.chat_models import init_chat_model
except ImportError:
raise ImportError(
"Please install langchain (`pip install langchain`) to "
"use '<provider>:<model>' string syntax for `model` parameter."
)
model = cast(BaseChatModel, init_chat_model(model))
if (
_should_bind_tools(model, tool_classes, num_builtin=len(llm_builtin_tools))
and len(tool_classes + llm_builtin_tools) > 0
):
model = cast(BaseChatModel, model).bind_tools(
tool_classes + llm_builtin_tools
)
static_model = _get_prompt_runnable(prompt) | model
For dynamic models (callables), this initialization is deferred to runtime. The callable receives (state, runtime) and must return a model with tools already bound via bind_tools.
Usage
# Usage via create_react_agent with string identifier
from langgraph.prebuilt import create_react_agent
agent = create_react_agent(
"openai:gpt-4", # String triggers init_chat_model
tools=[my_tool],
prompt="You are a helpful assistant.",
)
# Direct usage of init_chat_model (external API)
from langchain.chat_models import init_chat_model
model = init_chat_model("anthropic:claude-3-7-sonnet-latest")
# model is now a BaseChatModel instance
# Explicit tool binding
from langchain_core.tools import tool
@tool
def search(query: str) -> str:
"""Search the web."""
return f"Results for {query}"
bound_model = model.bind_tools([search])
# bound_model includes the search tool schema in every request
# Using bound model in create_react_agent
agent = create_react_agent(bound_model, tools=[search])
Code Reference
Source Location
| init_chat_model | External: langchain.chat_models.init_chat_model
|
| bind_tools | External: langchain_core.language_models.BaseChatModel.bind_tools
|
| Usage context | libs/prebuilt/langgraph/prebuilt/chat_agent_executor.py, lines 563-590
|
Signature
# External API (from langchain package)
def init_chat_model(
model: str,
*,
model_provider: str | None = None,
**kwargs: Any,
) -> BaseChatModel
# External API (from langchain_core)
class BaseChatModel:
def bind_tools(
self,
tools: Sequence[BaseTool | dict | type | Callable],
**kwargs: Any,
) -> Runnable[LanguageModelInput, BaseMessage]
Import
from langchain.chat_models import init_chat_model
from langchain_core.language_models import BaseChatModel
I/O Contract
init_chat_model
| Parameter | Type | Default | Description |
|---|---|---|---|
model |
str |
(required) | Model identifier in "provider:model_name" format (e.g., "openai:gpt-4", "anthropic:claude-3-7-sonnet-latest").
|
model_provider |
None | None |
Explicit provider override. If None, parsed from the model string prefix.
|
**kwargs |
Any |
Additional keyword arguments passed to the provider-specific model constructor (e.g., temperature, max_tokens).
|
Returns: A BaseChatModel instance configured for the specified provider and model.
BaseChatModel.bind_tools
| Parameter | Type | Default | Description |
|---|---|---|---|
tools |
dict | type | Callable] | (required) | Tools to bind. Accepts BaseTool instances, OpenAI-format dicts, Pydantic classes, or plain callables.
|
**kwargs |
Any |
Provider-specific binding options (e.g., tool_choice).
|
Returns: A Runnable[LanguageModelInput, BaseMessage] -- a new model instance that includes tool schemas in every request.
Usage Examples
String Shorthand in create_react_agent
from langgraph.prebuilt import create_react_agent
from langchain_core.tools import tool
@tool
def get_weather(city: str) -> str:
"""Get weather for a city."""
return f"Sunny in {city}"
# The string "openai:gpt-4" triggers init_chat_model internally,
# then bind_tools is called automatically with [get_weather]
agent = create_react_agent("openai:gpt-4", tools=[get_weather])
result = agent.invoke({"messages": [("user", "Weather in NYC?")]})
Dynamic Model with Manual Binding
from langchain_openai import ChatOpenAI
from langgraph.prebuilt import create_react_agent
from langgraph.runtime import Runtime
gpt4 = ChatOpenAI(model="gpt-4")
gpt35 = ChatOpenAI(model="gpt-3.5-turbo")
def select_model(state, runtime: Runtime):
"""Choose model based on runtime context."""
if runtime.context.get("premium_user"):
return gpt4.bind_tools(tools)
return gpt35.bind_tools(tools)
tools = [get_weather]
agent = create_react_agent(select_model, tools=tools)
Pre-bound Model
from langchain_openai import ChatOpenAI
from langgraph.prebuilt import create_react_agent
model = ChatOpenAI(model="gpt-4")
# Pre-bind tools with specific options
bound = model.bind_tools([get_weather], tool_choice="auto")
# create_react_agent detects tools are already bound and skips re-binding
agent = create_react_agent(bound, tools=[get_weather])