Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

LangChain Chat Model API

LangChain Chat Model API Reference

LangChain provides a unified Chat Model interface that lets developers call different models such as OpenAI, Anthropic, DeepSeek, Google Gemini, and Ollama with similar code.

Among them, init_chat_model() is used to initialize chat models, while BaseChatModel defines common interfaces such as model invocation, streaming output, batch execution, tool binding, and structured output.

This chapter is based on LangChain 1.x and systematically covers model initialization parameters, common BaseChatModel methods, model providers, dynamic switching, the AIMessage data structure, and common questions.


1. What is init_chat_model()?

init_chat_model() is a unified chat model initialization function provided by LangChain.

For example, using DeepSeek:

from langchain.chat_models import init_chat_model



model = init_chat_model("deepseek:deepseek-chat")

response = model.invoke("你好")

print(response.content)

If you switch to another provider, you usually only need to change the model identifier and install the corresponding integration package.

The model name is recommended to use:

provider:model_name

For example:

deepseek:deepseek-chat

openai:gpt-4o

anthropic:claude-sonnet-4-5-20250929

google_genai:gemini-2.5-flash

ollama:llama3.2

The above are examples of model identifier formats; whether a specific model is still callable should be determined by the corresponding provider's model list and account permissions.

If you do not provide a provider, LangChain will try to infer the provider from the model name, but this inference does not apply to all models.

**Recommendation:** Explicitly specify the provider in real projects to avoid misidentification when model names are similar.


2. init_chat_model() Function Signature

The core function signature of the current API is as follows:

init_chat_model(

    model: str | None = None,

    *,

    model_provider: str | None = None,

    configurable_fields: Literal["any"] | list[str] | tuple[str, ...] | None = None,

    config_prefix: str | None = None,

    **kwargs

)

It mainly contains four explicit parameters, plus a **kwargs。

Parameters Type Default value Description
model str | None None Model name, provider:model_name format recommended
model_provider str | None None Specify the model provider separately
configurable_fields "any" / list / tuple / None None Specify which model parameters can be modified at runtime
config_prefix str | None None Add a prefix to dynamic configuration keys
**kwargs Any Varies by model Other arguments passed to the specific model constructor

The function usually returns a BaseChatModel instance; if dynamic configuration is enabled, it returns a wrapper object that supports selecting model parameters at runtime.


3. Common Model Configuration Parameters

Besides the core parameters, init_chat_model() can also **kwargs pass model configuration through it.

Note: these are not fixed parameters uniformly supported by all providers.

Parameters Common Types Description
temperature float Controls sampling randomness; the valid range varies by model
max_tokens int | None Limits the maximum number of output tokens the model generates
timeout float | None Model request timeout setting, usually in seconds
max_retries int Failure retry configuration for the model client
base_url str | None Custom model API service address
api_key Varies by integration Provider API credentials
rate_limiter BaseRateLimiter Limits the rate of model requests
top_p float | None Nucleus sampling parameter; support depends on the model
stop list[str] | None Stop sequences, usually provided as a call-time argument

For example:

Example: Configuring a Model

from

dotenv

import

load_dotenv

from

langchain.

chat_models

import

init_chat_model

load_dotenv

(

)

model

=

init_chat_model

(

   

"deepseek:deepseek-chat"

,

    temperature

=

0.3

,

    max_tokens

=

1024

,

    timeout

=

30

,

    max_retries

=

2

)

response

=

model.

invoke

(

"Introduce Python in 100 words."

)

print

(

response.

content

)

This example sets parameters such as output length, timeout, and retries.

Note:temperature=0 It does not guarantee that every generated result is exactly the same. Some reasoning models may also limit or ignore sampling parameters such as temperature.


4. Fixed Models and Dynamic Models

init_chat_model() supports two common modes:

Method 1: Fixed model

Example

from

langchain.

chat_models

import

init_chat_model

model

=

init_chat_model

(

   

"deepseek:deepseek-chat"

,

    temperature

=

0

)

response

=

model.

invoke

(

"What is Python?"

)

print

(

response.

content

)

When configurable_fields is not configured, an explicitly specified model is a fixed model by default.

Method 2: Dynamically adjusting parameters

If you want different requests to use different temperatures, you can configure explicitly:

Example

model

=

init_chat_model

(

   

"deepseek:deepseek-chat"

,

    temperature

=

0

,

    configurable_fields

=

(

"temperature"

,

)

)

response

=

model.

invoke

(

   

"Write some Python learning advice."

,

    config

=

{

       

"configurable"

:

{

           

"temperature"

:

0.7

       

}

   

}

)

print

(

response.

content

)

Here each call is allowed to modify temperature via config, while other model configurations still use default values.

Method 3: Dynamically switching models

You can allow the model name to change at runtime:

Example

model

=

init_chat_model

(

   

"deepseek:deepseek-chat"

,

    configurable_fields

=

(

"model"

,

)

)

response

=

model.

invoke

(

   

"Hello" (Chinese)

,

    config

=

{

       

"configurable"

:

{

           

"model"

:

"deepseek:deepseek-chat"

       

}

   

}

)

print

(

response.

content

)

If you want to switch between different providers, you need to install the corresponding integration package and configure the required API key.

For example, when switching to OpenAI, you also need langchain-openai and a valid OpenAI API key.


5. Special Behavior of model=None

If no model is specified when creating the model:

model = init_chat_model()

LangChain creates a configuration object that allows specifying the model at runtime.

By default, this allows configuration of:

model

model_provider

Example: Determining the Model at Runtime

Example

from

langchain.

chat_models

import

init_chat_model

model

=

init_chat_model

(

)

response

=

model.

invoke

(

   

"Hello, please introduce yourself."

,

    config

=

{

       

"configurable"

:

{

           

"model"

:

"deepseek:deepseek-chat"

       

}

   

}

)

print

(

response.

content

)

**Note:** If no default model was set at creation and no model is specified in config at call time, a configuration error usually occurs.


6. config_prefix: Dynamic Configuration Prefix

When the same application contains multiple configurable models, you can use config_prefix to distinguish them.

For example:

chat_model

summary_model

This applies to scenarios where one model handles ordinary conversations and another handles summarization.

Example: Using a Configuration Prefix

Example

model

=

init_chat_model

(

   

"deepseek:deepseek-chat"

,

    temperature

=

0

,

    configurable_fields

=

(

"temperature"

,

)

,

    config_prefix

=

"chat"

)

response

=

model.

invoke

(

   

"Introduce Python."

,

    config

=

{

       

"configurable"

:

{

           

"chat_temperature"

:

0.5

       

}

   

}

)

print

(

response.

content

)

Here the dynamic configuration keys become:

chat_temperature

Without config_prefix, they are directly:

temperature

**Security reminder:** Do not arbitrarily set config_prefix configurable_fields="any"in a service that accepts user input, because it may allow sensitive configurations such as api_key and base_url to be modified at runtime, creating risks of request redirection or credential leakage.


7. What is BaseChatModel?

BaseChatModel is the core abstract class for LangChain chat models.

Although models from different providers differ in API addresses, parameters, and return formats, BaseChatModel provides a unified way to call them.

For example:

model.invoke()

model.ainvoke()

model.stream()

model.astream()

model.batch()

model.bind_tools()

model.with_structured_output()

Therefore, a large amount of application code can be reused across different models.


8. Quick Reference of Common BaseChatModel Methods

Method Purpose Typical return values
invoke(input, config=None, **kwargs) Synchronously call the model AIMessage
ainvoke(input, config=None, **kwargs) Asynchronous call AIMessage
stream(input, config=None, **kwargs) Synchronous streaming call Iterator[AIMessageChunk]
astream(input, config=None, **kwargs) Asynchronous streaming call AsyncIterator[AIMessageChunk]
batch(inputs, config=None, **kwargs) Batch process multiple inputs list[AIMessage]
abatch(inputs, config=None, **kwargs) Asynchronous batch processing list[AIMessage]
batch_as_completed() Get batch results in completion order Result iterator with index
bind_tools(tools, **kwargs) Bind tool schema Model Runnable that supports tool calls
with_structured_output(schema, **kwargs) Structured output Runnable
bind(**kwargs) Pre-bind model call arguments Runnable
with_retry(**kwargs) Wrap calls with retry logic Runnable
with_fallbacks(...) Try a fallback Runnable on failure Runnable

The return values here are common types. After using wrapper methods such as bind_tools and with_structured_output, the specific return structure depends on the model and configuration.


9. invoke(): Synchronously Calling the Model

invoke() is the most common model invocation method.

It supports plain strings as well as message lists.

Example: String Input

Example

model

=

init_chat_model

(

"deepseek:deepseek-chat"

)

response

=

model.

invoke

(

"What is Python?"

)

print

(

response.

content

)

print

(

type

(

response

)

.name

)

The typical returned object is AIMessage。

Example: Message List

Example

from

langchain.

messages

import

SystemMessage

,

HumanMessage

messages

=

[

    SystemMessage

(

content

=

"You are a Python programming teacher; keep answers concise."

)

,

    HumanMessage

(

content

=

"Explain Python lists."

)

]

response

=

model.

invoke

(

messages

)

print

(

response.

content

)

Compared with a single string, a message list can clearly distinguish system instructions from user input.


10. ainvoke(): Asynchronous Call

If the application is based on an asynchronous framework such as asyncio or FastAPI, you can use ainvoke()。

Example

Example

import

asyncio

from

langchain.

chat_models

import

init_chat_model

async

def

main

(

)

:

    model

=

init_chat_model

(

"deepseek:deepseek-chat"

)

    response

=

await model.

ainvoke

(

"Introduce Python."

)

   

print

(

response.

content

)

asyncio.

run

(

main

(

)

)

ainvoke() In asynchronous applications it is usually easier to coordinate with other network I/O tasks.

However, whether native asynchronous HTTP requests are used, as well as the specific performance, depends on the model integration implementation.


11. stream(): Streaming Output

When the model generates long content, you can use stream() to obtain results step by step.

What is returned is usually a AIMessageChunk。

Example: Printing the Answer Step by Step

Example

model

=

init_chat_model

(

"deepseek:deepseek-chat"

)

for

chunk

in

model.

stream

(

"Introduce the main features of Python."

)

:

   

if

isinstance

(

chunk

.

content

,

str

)

:

       

print

(

chunk

.

content

,

end

=

""

,

flush

=

True

)

print

(

)

Note that streaming output does not necessarily return one Chinese character at a time, nor does it guarantee that only one token is returned each time.

Different models may combine multiple characters into one chunk.

If the provider does not support a real streaming interface, some model implementations may degrade to returning the complete content all at once.


12. astream(): Asynchronous Streaming Output

Example

import

asyncio

from

langchain.

chat_models

import

init_chat_model

async

def

main

(

)

:

    model

=

init_chat_model

(

"deepseek:deepseek-chat"

)

    async

for

chunk

in

model.

astream

(

"Introduce Python functions."

)

:

       

if

isinstance

(

chunk

.

content

,

str

)

:

           

print

(

chunk

.

content

,

end

=

""

,

flush

=

True

)

   

print

(

)

asyncio.

run

(

main

(

)

)

Asynchronous streaming output is suitable for web services, chat interfaces, and programs that support asynchronous processing.

For complex multi-model and tool execution events, you can further explore LangChain's Stream Events interface.


13. batch(): Batch Calling the Model

If you need to handle multiple independent questions, you can use batch()。

Example: Batch Processing Questions

Example

model

=

init_chat_model

(

"deepseek:deepseek-chat"

)

questions

=

[

   

"What is Python?"

,

   

"What is Java?"

,

   

"What are the features of the Go language?"

]

results

=

model.

batch

(

    questions

,

    config

=

{

"max_concurrency"

:

2

}

)

for

question

,

response

in

zip

(

questions

,

results

)

:

   

print

(

"Question:"

,

question

)

   

print

(

"Answer:"

,

response.

content

)

batch() returns results in the input order.

max_concurrency You can limit the level of concurrency.

Note that batch calling does not necessarily use the provider's dedicated batch API. The default implementation may be done by calling invoke() in parallel.


14. AIMessage: The Model Return Object

After calling the Chat Model directly, you usually get AIMessagerather than just a plain string.

It can contain the body text, tool calls, token usage, and model response information.

Common Fields

Field Description
content Model message content, which may be a string or content blocks
text A method interface for extracting text content
tool_calls The list of parsed tool calls
invalid_tool_calls Tool calls that could not be parsed correctly
usage_metadata Input, output, and total token usage
response_metadata Model or provider response metadata
id Message identifier, which may be empty

Example: Viewing Response Details

Example

response

=

model.

invoke

(

"Hello" (Chinese)

)

print

(

"Content:"

,

response.

content

)

print

(

"Type:"

,

response.

type

)

print

(

"Message ID:"

,

response.

id

)

print

(

"Tool calls:"

,

response.

tool_calls

)

print

(

"Token usage:"

,

response.

usage_metadata

)

print

(

"Response metadata:"

,

response.

response_metadata

)

For example, usage_metadata may contain:

{

    "input_tokens": 15,

    "output_tokens": 28,

    "total_tokens": 43

}

The numbers above are only format examples.

Actual token usage depends on whether the provider returns relevant statistics, and some fields may be empty.


15. bind_tools(): Binding Tools

bind_tools() You can provide tool definitions to the chat model so that it can return structured tool call requests.

For example:

Example: Tool Binding

from

langchain.

chat_models

import

init_chat_model

from

langchain.

tools

import

tool

@

tool

def

get_weather

(

city:

str

)

str

:

   

"""Query mock weather for a given city."""

   

return

f

"{city}: Simulated sunny, 25°C"

model

=

init_chat_model

(

"deepseek:deepseek-chat"

)

model_with_tools

=

model.

bind_tools

(

[

get_weather

]

)

response

=

model_with_tools.

invoke

(

"Please call a tool to check the weather in Hangzhou."

)

print

(

"Model answer:"

,

response.

content

)

print

(

"Tool calls:"

,

response.

tool_calls

)

If the model chooses to call a tool, tool_calls may look like:

[

    {

        "name": "get_weather",

        "args": {"city": "杭州"},

        "id": "call_xxx",

        "type": "tool_call"

    }

]

Important:bind_tools() It does not automatically execute Python tool functions.

It is mainly responsible for passing tool definitions to the model and having the model generate tool call requests.

Actual tool execution, ToolMessage return, and subsequent model calls need to be done by application code or the Agent.

If you want to automate the entire tool call loop, it is more recommended to use create_agent()。


16. with_structured_output(): Structured Output

Ordinary models return natural-language text.

If you want to directly obtain data conforming to a specified structure, you can use with_structured_output()。

Common schemas include:

Example: Using Pydantic

Example

from

pydantic

import

BaseModel

,

Field

from

langchain.

chat_models

import

init_chat_model

class

CourseInfo

(

BaseModel

)

:

    name:

str

=

Field

(

description

=

"Course name"

)

    level:

str

=

Field

(

description

=

"Course difficulty"

)

    language:

str

=

Field

(

description

=

"Programming Language"

)

model

=

init_chat_model

(

"deepseek:deepseek-chat"

)

structured_model

=

model.

with_structured_output

(

CourseInfo

)

result

=

structured_model.

invoke

(

   

"Extract course information: Python3 Basic Tutorial, beginner level, Python language."

)

print

(

result

)

print

(

"Course name:"

,

result.

name

)

When using a Pydantic schema and the model successfully generates and validates a result, it usually returns the corresponding Pydantic object.

If you use JSON Schema or TypedDict, the returned result may be a dictionary.

**Note:** Different models support structured output in different ways; some implement it through tool calls, while others use the provider's native structured output interface. If the corresponding integration does not support it, an error may occur at binding or call time.

The include_raw Parameter

Some model integrations support:

with_structured_output(

    CourseInfo,

    include_raw=True

)

In this case, a dictionary containing fields such as the raw message, parsed result, and parsing errors is usually returned, which is convenient for debugging.

During development, you can check:

raw

parsed

parsing_error

The specific structure of these fields is subject to the documentation of the corresponding model integration.


17. bind(): Pre-binding Model Arguments

bind() is a general method provided by Runnable.

You can preset arguments for subsequent calls, such as stop sequences.

Example

Example

model

=

init_chat_model

(

"deepseek:deepseek-chat"

)

limited_model

=

model.

bind

(

stop

=

[

"END"

]

)

response

=

limited_model.

invoke

(

   

"List three Python keywords and output END at the end."

)

print

(

response.

content

)

Note that whether stop sequences take effect as expected depends on the model provider's support.

bind() The difference between configurable_fields The difference between them is:


18. Model Provider Quick Reference

LangChain provides integrations for multiple model providers. The table below lists common Provider names and their corresponding installation packages.

The model names in the table are examples; actual availability should be determined by the provider's model catalog and account permissions.

Provider Install packages Model identifier examples
openai langchain-openai openai:gpt-4o
anthropic langchain-anthropic anthropic:claude-sonnet-4-5-20250929
deepseek langchain-deepseek deepseek:deepseek-chat
google_genai langchain-google-genai google_genai:gemini-2.5-flash
google_vertexai langchain-google-vertexai google_vertexai:gemini-2.5-flash
ollama langchain-ollama ollama:llama3.2
groq langchain-groq groq:llama-3.3-70b-versatile
xai langchain-xai xai:grok-3
mistralai langchain-mistralai mistralai:mistral-large-latest
openrouter langchain-openrouter openrouter:openai/gpt-4o
perplexity langchain-perplexity perplexity:sonar-pro
bedrock_converse langchain-aws Specified via model_provider and the provider's model ID
cohere langchain-cohere Specified via model_provider and the provider's model ID
together langchain-together Specified via model_provider and the provider's model ID

For example, to install the DeepSeek integration:

pip install -U langchain-deepseek

Using Ollama:

pip install -U langchain-ollama

Note that Ollama also requires the local Ollama service to be running properly and the corresponding model to be downloaded.

For Google Gemini, it is recommended to explicitly use google_genai or google_vertexaibecause the default behavior of inferring the Provider solely from the gemini model name may change across LangChain versions.


19. Rate Limiter: Model Call Rate Limiting

If a program needs to handle a large number of requests concurrently, it may trigger the model provider's rate limits.

LangChain supports passing a Rate Limiter to the model.

Example: InMemoryRateLimiter

Example

from

langchain.

chat_models

import

init_chat_model

from

langchain_core.

rate_limiters

import

InMemoryRateLimiter

limiter

=

InMemoryRateLimiter

(

    requests_per_second

=

1

,

    check_every_n_seconds

=

0.1

,

    max_bucket_size

=

2

)

model

=

init_chat_model

(

   

"deepseek:deepseek-chat"

,

    rate_limiter

=

limiter

)

response

=

model.

invoke

(

"Hello" (Chinese)

)

print

(

response.

content

)

This example limits the rate at which requests are issued to a specified range.

**Note:** InMemoryRateLimiter is only suitable for rate management within a single process and cannot automatically coordinate global rate limiting across multiple server instances.

If you use a distributed deployment, control is usually needed through Redis, an API gateway, or another centralized rate-limiting mechanism.


20. The Difference Between Chat Model and Agent

Beginners often confuse the Chat Model with the Agent.

In fact, the two are responsible for different work.

Capability Chat Model Agent
Call the model to generate text Supported Supported
Bind tool schema Supported Supported through tool configuration
Automatically execute tools Not responsible Supported
Multiple model-and-tool loops Need to be orchestrated manually Built-in execution flow
Checkpointer memory Requires extra orchestration Can be configured directly
Middleware Not the main entry point Directly supported

For example, an ordinary model call:

model.invoke("查询 Python 课程")

is just a single chat model request.

Whereas an Agent:

agent.invoke({

    "messages": [{"role": "user", "content": "查询 Python 课程"}]

})

can execute tools based on tool call requests produced by the model and continue generating the final answer.


21. Complete Comprehensive API Example

Finally, a concise program demonstrates fixed models, streaming output, batch calls, tool binding, and structured output.

Filename:chat_model_api_demo.py

Install dependencies:

pip install -U langchain langchain-deepseek pydantic python-dotenv

Configure .env:

DEEPSEEK_API_KEY=your_deepseek_api_key

Complete example

from

dotenv

import

load_dotenv

from

pydantic

import

BaseModel

,

Field

from

langchain.

chat_models

import

init_chat_model

from

langchain.

tools

import

tool

load_dotenv

(

)

model

=

init_chat_model

(

   

"deepseek:deepseek-chat"

,

    temperature

=

0

,

    timeout

=

30

)

========== 1. Synchronous Call ==========

response

=

model.

invoke

(

"Introduce Python in one sentence."

)

print

(

"Synchronous answer:"

,

response.

content

)

========== 2. Streaming Output ==========

print

(

"\nStreaming answer:"

,

end

=

""

,

flush

=

True

)

for

chunk

in

model.

stream

(

"Introduce three advantages of Python."

)

:

   

if

isinstance

(

chunk

.

content

,

str

)

:

       

print

(

chunk

.

content

,

end

=

""

,

flush

=

True

)

print

(

)

========== 3. Batch Calls ==========

results

=

model.

batch

(

   

[

"What is Python?"

,

"What is Java?"

]

,

    config

=

{

"max_concurrency"

:

2

}

)

for

i

,

result

in

enumerate

(

results

,

1

)

:

   

print

(

f

"Batch result {i}:"

,

result.

content

)

========== 4. Tool Binding ==========

@

tool

def

get_weather

(

city:

str

)

str

:

   

"""Query simulated weather."""

   

return

f

"{city}: Simulated sunny, 25°C"

tool_model

=

model.

bind_tools

(

[

get_weather

]

)

response

=

tool_model.

invoke

(

"Please call a tool to check the weather in Hangzhou."

)

print

(

"\nTool calls:"

,

response.

tool_calls

)

========== 5. Structured Output ==========

class

CourseInfo

(

BaseModel

)

:

    name:

str

=

Field

(

description

=

"Course name"

)

    level:

str

=

Field

(

description

=

"Course difficulty"

)

structured_model

=

model.

with_structured_output

(

CourseInfo

)

result

=

structured_model.

invoke

(

   

"Extract course information: Python3 Basic Tutorial, beginner level."

)

print

(

"\nStructured result:"

,

result

)

========== 6. View Token Usage ==========

response

=

model.

invoke

(

"Hello" (Chinese)

)

print

(

"\nToken Usage:"

,

response.

usage_metadata

)

Tool binding and structured output depend on the support provided by the current model provider.

Tool binding does not automatically execute tools; if structured output does not conform to the Schema, parsing or validation errors may also occur.


22. Frequently Asked Questions

1. What is the difference between init_chat_model() and ChatDeepSeek?

init_chat_model() is the unified initialization entry point; ChatDeepSeek is the dedicated model class for the DeepSeek provider. Both can be used to create a DeepSeek Chat Model.

2. Why does init_chat_model() require installing additional provider packages?

Because LangChain splits the integration implementations of different models into separate Python packages.

3. Can model_provider be omitted?

Yes. When using the provider:model_name format, you usually do not need to specify it separately.

4. Why might deepseek-chat work even without a prefix?

Because LangChain can try to infer the provider from the model name. However, it is recommended to explicitly use deepseek:deepseek-chat.

5. Does temperature=0 mean complete determinism?

Not necessarily. The model service, sampling implementation, and inference environment may affect the result.

6. Is max_tokens the model context window size?

No. max_tokens is typically used to limit the number of output tokens, while the context window limits the overall context size the model can process.

7. What is the difference between invoke() and stream()?

invoke() usually returns the complete message; stream() is used to obtain message fragments step by step.

8. Is batch() always faster than looping over invoke()?

Not necessarily. batch() can provide concurrent processing, but the actual speed is affected by the model service, rate limits, and concurrency configuration.

9. Does bind_tools() automatically run tools?

No. It only provides the tool definitions to the model. Automatic tool execution is usually handled by the Agent.

10. Does with_structured_output() always return Pydantic?

Not necessarily. The return type depends on the Schema type and related configuration.

11. How do I check how many tokens the model consumed?

You can check AIMessage.usage_metadata, but you must rely on the statistics actually returned by the provider.

12. How do I switch models dynamically?

Configure configurable_fields when creating the model, then pass the fields allowed to be modified at runtime via config["configurable"].

13. Is configurable_fields="any" safe?

For services that accept untrusted user configuration, it is not recommended to use any directly. You should explicitly restrict the modifiable fields to avoid exposing sensitive configuration such as the API Key or base_url.

14. How do I limit the API request rate?

You can use rate_limiter. Multi-instance deployments should also use a shared rate-limiting service.

15. Do all models support images, tools, and structured output?

No. You must check the features currently supported by the model provider and the corresponding LangChain integration capabilities.


Summary

The LangChain Chat Model API provides a unified way to call models.

This chapter mainly introduced:

The most commonly used initialization method:

from langchain.chat_models import init_chat_model



model = init_chat_model(

    "deepseek:deepseek-chat",

    temperature=0,

    timeout=30

)



response = model.invoke("你好")

print(response.content)

**Core principle:** init_chat_model() solves the problem of initializing different models, while BaseChatModel solves the problem of unifying the model call interface. For complex tool collaboration, execution loops, and conversation state management, you can use LangChain Agent on top of the Chat Model.

Reference Documentation