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

LangChain Model Invocation — init_chat_model() Function

LangChain Model Invocation -- init_chat_model() Function

init_chat_model() is a unified chat model initialization function provided by LangChain, allowing connection to different model providers through the same interface.

For example, when using DeepSeek, OpenAI, Anthropic, Google Gemini, or Ollama, developers do not need to memorize the names of all model integration classes; they only need to specify the model provider and model name.

init_chat_model() It mainly provides two usage modes:

In addition, the initialized chat model can also support synchronous calls, asynchronous calls, streaming output, and other features through a unified interface.

This chapter uses DeepSeek as the main example, while also introducing how to connect other model providers.

**Note:** What LangChain unifies is the model initialization and invocation interface; it does not mean different models support exactly the same features, parameters, or context length.

I. Installing LangChain

First, install LangChain:

pip install -U langchain

init_chat_model() It does not automatically install integration packages for all model providers, so you still need to install the corresponding dependencies.

For example, using DeepSeek:

pip install -U langchain-deepseek

Using OpenAI:

pip install -U langchain-openai

Using Anthropic:

pip install -U langchain-anthropic

Using Ollama local models:

pip install -U langchain-ollama

If you need to load the API Key via a .env file, you can also install:

pip install -U python-dotenv

Configure API Key

Calling the DeepSeek API requires setting DEEPSEEK_API_KEY environment variable.

You can create a .env File:

DEEPSEEK_API_KEY=your_deepseek_api_key

in the project directory and load the file in a Python program:

from dotenv import load_dotenv



load_dotenv()

If you use other providers, you can configure the corresponding environment variables:

OPENAI_API_KEY=your_openai_api_key

ANTHROPIC_API_KEY=your_anthropic_api_key

**Note:** You only need to configure the key for the provider you actually use. Do not commit a .env file containing a real API Key to a public code repository.


II. init_chat_model() Function Syntax

The basic syntax of the function is as follows:

from langchain.chat_models import init_chat_model



model = init_chat_model(

    model=None,

    *,

    model_provider=None,

    configurable_fields=None,

    config_prefix=None,

    **kwargs

)

Parameter Description:

Parameters Type Description Default value
model str or None Model name; the provider:model format is recommended; when None, a configurable model is created None
model_provider str or None Specify the model provider separately None
configurable_fields "any", list, tuple, or None Specify the model fields allowed to be modified at runtime None
config_prefix str or None Prefix for runtime configuration keys None
**kwargs Keyword arguments Initialization parameters passed to the underlying model None

init_chat_model() There are usually two types of return results:

The following sections introduce how to use each parameter.


III. model Parameter in Detail

model Used to specify the model to call.

LangChain recommends using the provider:model format to explicitly specify the provider.

1. provider:model Format

The basic format is:

提供商名称:模型名称

For example:

Example

from

langchain.

chat_models

import

init_chat_model

DeepSeek Flash

deepseek_flash

=

init_chat_model

(

   

"deepseek:deepseek-flash"

)

DeepSeek V4 Pro

deepseek_pro

=

init_chat_model

(

   

"deepseek:deepseek-v4-pro"

)

OpenAI

openai_model

=

init_chat_model

(

   

"openai:gpt-4o-mini"

)

Anthropic

anthropic_model

=

init_chat_model

(

   

"anthropic:claude-sonnet-4-5"

)

Ollama local models

ollama_model

=

init_chat_model

(

   

"ollama:llama3.2"

)

The above code is used to demonstrate the initialization method; it does not automatically complete a chat request just by creating a model object.

In actual use, you need to install the corresponding LangChain integration package in advance and confirm that the specified model ID is currently available.

**Recommendation:** New projects should prefer the provider:model format to reduce errors in automatic provider inference.

2. Currently Recommended DeepSeek Models

According to the official DeepSeek API documentation, the following two model names are currently recommended:

API model name Model version LangChain call name
deepseek-flash DeepSeek-V4.1-Flash deepseek:deepseek-flash
deepseek-v4-pro DeepSeek-V4-Pro-0813 deepseek:deepseek-v4-pro

Wheredeepseek-flash is the currently officially recommended Flash model name.

The old deepseek-v4-flash and deepseek-v4-flash-vision-exp name still retains compatibility for calls, but the corresponding old model has been taken offline, and requests are actually served by DeepSeek-V4.1-Flash.

Therefore, new projects should prefer:

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

When you need to use the Pro model:

model = init_chat_model("deepseek:deepseek-v4-pro")

Model features, thinking mode, pricing, and context length may change with the service provider; it is recommended to refer to the official DeepSeek model documentation as the authoritative source.

3. Automatic Model Provider Inference

If the provider prefix is omitted, LangChain will try to infer it automatically from the model name.

Example

from

langchain.

chat_models

import

init_chat_model

Auto-infer DeepSeek

model

=

init_chat_model

(

"deepseek-flash"

)

Auto-infer OpenAI

model

=

init_chat_model

(

"gpt-4o-mini"

)

Auto-infer Anthropic

model

=

init_chat_model

(

"claude-sonnet-4-5"

)

Auto-infer xAI

model

=

init_chat_model

(

"grok-3"

)

Auto-infer Perplexity

model

=

init_chat_model

(

"sonar"

)

Common model name inference rules are as follows:

Model name prefix Auto-inferred provider
gpt-、o1、o3、chatgpt、text-davinci openai
claude anthropic
deepseek deepseek
gemini google_vertexai
command cohere
mistral、mixtral mistralai
grok xai
sonar perplexity
solar upstage
accounts/fireworks fireworks
amazon.、anthropic.、meta. bedrock

**Note:** Automatic inference is not a general model recognition service; it only determines the provider based on preset name rules.

For example,deepseek-flash will be inferred as deepseekrather than openai。

The default inference rules for Google Gemini may also change with LangChain versions; it is recommended to specify explicitly google_genai or google_vertexai。

4. model_provider Parameter

If you need to pass the model name and provider separately, you can use model_provider。

For example, the following two approaches are equivalent in terms of provider and model selection:

Example

from

langchain.

chat_models

import

init_chat_model

Method 1: specify the provider separately

model1

=

init_chat_model

(

   

"deepseek-flash"

,

    model_provider

=

"deepseek"

)

Method 2: provider:model format

model2

=

init_chat_model

(

   

"deepseek:deepseek-flash"

)

This approach can be used when the model configuration is read from a file, database, or environment variables:

provider = "deepseek"

model_name = "deepseek-flash"



model = init_chat_model(

    model_name,

    model_provider=provider

)

This approach is more suitable for applications that need to read configuration dynamically.


IV. Fixed Model Mode

A fixed model is the init_chat_model() most common way to use it.

Specify the name and parameters when creating the model, then use the invoke() invoked.

Example: calling DeepSeek Flash

Example

from

dotenv

import

load_dotenv

from

langchain.

chat_models

import

init_chat_model

Load the API Key from the current project's .env

load_dotenv

(

)

Initialize DeepSeek Flash

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

)

Call the model

response

=

model.

invoke

(

   

"Introduce Runoob Tutorial RUNOOB in one sentence."

)

Output result

print

(

response.

content

)

When called, LangChain sends requests to the API through the corresponding DeepSeek integration.

invoke() It usually returns a AIMessage object, in which content stores the response content.

Since the model generates content dynamically, the actual output of each call may differ.

Example: calling DeepSeek V4 Pro

If you need to use the Pro model, you only need to change the model name:

Example

from

dotenv

import

load_dotenv

from

langchain.

chat_models

import

init_chat_model

load_dotenv

(

)

model

=

init_chat_model

(

   

"deepseek:deepseek-v4-pro"

)

response

=

model.

invoke

(

   

"Explain how Python decorators work and give an example."

)

print

(

response.

content

)

This approach does not require manually creating different model integration classes; you only need to replace the model ID.

**Note:** The above examples require a real API Key and an available model service; actual calls will incur corresponding API fees.


V. Calling DeepSeek Through the OpenAI-Compatible Interface

In addition to its own API, DeepSeek officially provides interfaces compatible with OpenAI and Anthropic formats.

The official addresses are as follows:

Interface format base_url
OpenAI compatible https://api.deepseek.com
Anthropic compatible https://api.deepseek.com/anthropic

Therefore, in LangChain you can choose to use the native DeepSeek integration or the OpenAI-compatible integration.

Method 1: use the native DeepSeek integration

You need to install:

pip install -U langchain-deepseek

The code is as follows:

model = init_chat_model(

    "deepseek:deepseek-flash"

)

This is the recommended way to connect DeepSeek using LangChain.

Method 2: use the OpenAI-compatible interface

If you want to call langchain-openai DeepSeek through it, you can specify the model provider, API address, and key separately.

Example

import

os

from

dotenv

import

load_dotenv

from

langchain.

chat_models

import

init_chat_model

load_dotenv

(

)

model

=

init_chat_model

(

   

"deepseek-flash"

,

   

Use the OpenAI-compatible integration

    model_provider

=

"openai"

,

   

DeepSeek official API address

    base_url

=

"https://api.deepseek.com"

,

   

DeepSeek API Key

    api_key

=

os

.

environ

[

"DEEPSEEK_API_KEY"

]

)

response

=

model.

invoke

(

   

"Give a brief introduction to LangChain."

)

print

(

response.

content

)

The above code requires installing:

pip install -U langchain-openai

Although the provider used here is openai , the actual requests are sent to the DeepSeek API, not the OpenAI API.

This is achieved through a custom base_url implementation.

The two calling methods are compared below:

Method LangChain provider Install packages
Native DeepSeek integration deepseek langchain-deepseek
OpenAI-Compatible Interface openai langchain-openai

**Note:** Compatibility with the OpenAI API does not mean that all special response fields of third-party models will be fully handled by the generic integration. If you need DeepSeek-specific features, you should first check whether the corresponding LangChain DeepSeek integration supports them.

In addition, DeepSeek's Anthropic-compatible interface uses a different request format; you should not simply treat that address directly as an OpenAI-format base_url .


VI. Configurable Model Mode

If you want to switch models at runtime rather than creating a new model variable each time, you can use a configurable model.

This is common in model comparison, A/B testing, cost management, and multi-model applications.

1. Not Specifying model

If calling init_chat_model() When no model is specified, LangChain returns a configurable model.

In this case, by default you can configure at runtime model and model_provider。

Example

from

dotenv

import

load_dotenv

from

langchain.

chat_models

import

init_chat_model

load_dotenv

(

)

No default model specified

model

=

init_chat_model

(

)

Use DeepSeek Flash

response

=

model.

invoke

(

   

"Introduce Runoob Tutorial RUNOOB."

,

    config

=

{

       

"configurable"

:

{

           

"model"

:

"deepseek:deepseek-flash"

       

}

   

}

)

print

(

response.

content

)

Switch to DeepSeek Pro

response

=

model.

invoke

(

   

"Introduce Runoob Tutorial RUNOOB."

,

    config

=

{

       

"configurable"

:

{

           

"model"

:

"deepseek:deepseek-v4-pro"

       

}

   

}

)

print

(

response.

content

)

As you can see, the same configurable model object can, through config specify different models.

Switching models does not require recreating the application, but the calling process still needs to load the integration for the target model and access the corresponding service.

2. configurable_fields Parameter

configurable_fields Used to control which fields are allowed to be modified at runtime.

Common values are as follows:

Value Description
None When model is specified, no configurable fields are opened; when model is not specified, model and model_provider are opened by default
"any" Open all related configuration fields; note the security risks
["model", "temperature"] Only allow configuration of specified fields
("model", "model_provider") Specify configurable fields using a tuple

For example, to only allow modifying the model name:

Example

from

langchain.

chat_models

import

init_chat_model

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

,

    configurable_fields

=

[

"model"

]

)

Use the default Flash model

response

=

model.

invoke

(

"Introduce Python."

)

print

(

response.

content

)

Switch to the Pro model

response

=

model.

invoke

(

   

"Explain Python decorators."

,

    config

=

{

       

"configurable"

:

{

           

"model"

:

"deepseek:deepseek-v4-pro"

       

}

   

}

)

print

(

response.

content

)

Here, model The field is declared as configurable, so it can override the model name specified at initialization at runtime.

If you want to modify the provider and model name separately, you can also add model_provider to the list of configurable fields.


VII. config_prefix Parameter

config_prefix Used to add a prefix to configurable fields, avoiding multiple model objects using the same configuration keys.

For example, an application might have two models:

To avoid configuration conflicts between the two models, you can use chat and summary prefix.

Example

Example

from

langchain.

chat_models

import

init_chat_model

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

,

    configurable_fields

=

[

       

"model"

,

       

"temperature"

   

]

,

    config_prefix

=

"my"

,

    temperature

=

0.3

)

Use the default configuration

response

=

model.

invoke

(

   

"Introduce Runoob Tutorial."

)

print

(

response.

content

)

Modify the temperature at runtime

response

=

model.

invoke

(

   

"Introduce Runoob Tutorial RUNOOB."

,

    config

=

{

       

"configurable"

:

{

           

"my_temperature"

:

0.7

       

}

   

}

)

print

(

response.

content

)

Settings config_prefix="my" After that, the configuration fields need to use my_ prefix.

For example:

my_model

my_temperature

If no prefix is set, use directly:

model

temperature

Note that the above example of modifying temperature applies to model configurations that accept this parameter; whether the sampling temperature can actually be adjusted should be determined by the interface documentation of the called model.


VIII. configurable_fields="any"

If you want all fields that can be passed to the model initializer to be configurable at runtime, you can use:

configurable_fields="any"

For example:

Example

from

langchain.

chat_models

import

init_chat_model

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

,

    configurable_fields

=

"any"

,

    config_prefix

=

"my"

)

response

=

model.

invoke

(

   

"Introduce Python."

,

    config

=

{

       

"configurable"

:

{

           

"my_model"

:

"deepseek:deepseek-v4-pro"

       

}

   

}

)

print

(

response.

content

)

This approach is very flexible, but it also carries certain risks.

For example, if untrusted users are allowed to directly control all runtime configuration, it may lead to sensitive fields such as api_key、base_url being tampered with.

Malicious configuration could even send model requests containing sensitive information to unintended servers.

Therefore, in production it is recommended to explicitly list the fields allowed to be modified:

configurable_fields=[

    "model",

    "model_provider"

]

and perform whitelist validation of selectable models and providers at the application layer.


IX. Supported Model Providers

init_chat_model() It supports multiple mainstream model providers; the specific provider names and integration packages are determined by the LangChain version.

The following lists common providers supported by the official API:

provider Install packages Description
openai langchain-openai OpenAI models
anthropic langchain-anthropic Claude models
deepseek langchain-deepseek DeepSeek Model
google_genai langchain-google-genai Google Gemini API
google_vertexai langchain-google-vertexai Google Vertex AI
azure_openai langchain-openai Azure OpenAI
azure_ai langchain-azure-ai Azure AI
mistralai langchain-mistralai Mistral AI
groq langchain-groq Groq inference platform
ollama langchain-ollama Ollama local models
fireworks langchain-fireworks Fireworks AI
together langchain-together Together AI
xai langchain-xai xAI Grok
perplexity langchain-perplexity Perplexity Sonar
cohere langchain-cohere Cohere models
huggingface langchain-huggingface Hugging Face models
openrouter langchain-openrouter OpenRouter model gateway
bedrock langchain-aws Amazon Bedrock
upstage langchain-upstage Upstage models
nvidia langchain-nvidia-ai-endpoints NVIDIA AI Endpoints
ibm langchain-ibm IBM watsonx.ai

Different integration packages may have different features and version requirements; before actual use, you should check the official LangChain API Reference。

Special note:The existence of a LangChain integration package for a provider does not mean all of its models can be called by arbitrary names.

Model IDs, authentication methods, and calling permissions are still determined by the specific model platform.


X. Common kwargs Parameters

**kwargs Used to pass initialization parameters to the underlying model.

Common parameters include:

Parameters Purpose Notes
temperature Control the sampling randomness of model generation Value range and support are determined by the specific model
max_tokens Limit the maximum number of output Tokens Specific field mapping depends on the model integration
timeout Set the request timeout Common unit is seconds
max_retries Set the number of retries on failure Retry behavior depends on the model integration
base_url Configure a custom API address Usually used for compatible interfaces or gateways
rate_limiter Configure a rate limiter Requires a compatible BaseRateLimiter instance
top_p Control the nucleus sampling range Not supported by all models

For example:

Example

from

langchain.

chat_models

import

init_chat_model

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

,

   

Request timeout

    timeout

=

30

,

   

Retry on failure

    max_retries

=

2

)

response

=

model.

invoke

(

   

"Introduce the Python programming language."

)

print

(

response.

content

)

Note:temperature、top_p and max_tokens and other parameters cannot be guaranteed to apply to all models.

In particular, reasoning models from different vendors may have different requirements for sampling parameters, thinking mode, and output length.

If the model returns an error indicating unsupported parameters, you should first check that model's official API rather than assuming all parameters are universal.


XI. Common Model Calling Methods

After initializing the model, you can perform different types of calls through LangChain's unified interface.

1. invoke() Synchronous Call

invoke() Used to send input and wait for the model to return a complete response.

Example

from

langchain.

chat_models

import

init_chat_model

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

)

response

=

model.

invoke

(

"What is Python?"

)

print

(

response.

content

)

2. stream() Streaming Output

stream() Can receive model output progressively, suitable for chat interfaces and real-time content generation applications.

Example

from

langchain.

chat_models

import

init_chat_model

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

)

for

chunk

in

model.

stream

(

   

"Introduce three advantages of Python"

)

:

   

print

(

chunk

.

text

,

end

=

""

,

flush

=

True

)

The streaming interface returns message chunks, whose text attribute can be used to read the text.

Note that some models may also return thinking content, tool call information, or other non-plain-text content.

3. ainvoke() Asynchronous Call

If the program uses asyncio, you can use ainvoke() to call the model asynchronously.

Example

import

asyncio

from

langchain.

chat_models

import

init_chat_model

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

)

async

def

main

(

)

:

    response

=

await model.

ainvoke

(

       

"Give a brief introduction to Python."

   

)

   

print

(

response.

content

)

asyncio.

run

(

main

(

)

)

The asynchronous approach is suitable for web services, Agent applications, and scenarios that need to handle multiple requests simultaneously.

4. Using a Message List

In addition to passing a string directly, LangChain also supports using a message list to organize conversations.

Example

from

langchain.

chat_models

import

init_chat_model

from

langchain_core.

messages

import

(

    SystemMessage

,

    HumanMessage

)

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

)

messages

=

[

    SystemMessage

(

        content

=

"You are a Python programming tutorial author."

   

)

,

    HumanMessage

(

        content

=

"Explain in simple terms what a Python decorator is."

   

)

]

response

=

model.

invoke

(

messages

)

print

(

response.

content

)

This approach makes it easy to set system prompts and organize conversations that require messages from different roles.


XII. Practical Application: Switching Between Flash and Pro at Runtime

Suppose you are developing an AI tool that needs to choose different DeepSeek models based on task complexity.

For example:

You can use the configurable_fields Implement dynamic model selection.

Example

from

dotenv

import

load_dotenv

from

langchain.

chat_models

import

init_chat_model

load_dotenv

(

)

Model whitelist

ALLOWED_MODELS

=

{

   

"flash"

:

"deepseek:deepseek-flash"

,

   

"pro"

:

"deepseek:deepseek-v4-pro"

}

Use Flash by default

model

=

init_chat_model

(

    ALLOWED_MODELS

[

"flash"

]

,

    configurable_fields

=

[

"model"

]

)

def

ask

(

question

,

mode

=

"flash"

)

:

   

if

mode

not

in

ALLOWED_MODELS:

       

raise

ValueError

(

"Unsupported model type"

)

    selected_model

=

ALLOWED_MODELS

[

mode

]

    response

=

model.

invoke

(

        question

,

        config

=

{

           

"configurable"

:

{

               

"model"

: selected_model

           

}

       

}

   

)

   

return

response.

content

Use Flash

print

(

ask

(

"Introduce Python"

,

"flash"

)

)

Use Pro

print

(

ask

(

"Explain Python decorators in depth"

,

"pro"

)

)

This example uses the same LangChain configurable model wrapper object and selects different models based on parameters.

In practical applications, you can decide which model to use based on the user's plan, task type, or cost budget.

**Note:** The Flash and Pro in the example are just two selectable models; they do not mean LangChain will automatically judge question complexity or automatically optimize costs.

In production, it is recommended to maintain a model whitelist at the application layer and not allow users to directly submit arbitrary base_url、api_key or model initialization parameters.


XIII. Frequently Asked Questions

1. Why does it say the model provider cannot be recognized?

If the model name does not conform to LangChain's known automatic inference rules, an error like the following may occur:

ValueError: Unable to infer model provider

It is recommended to specify the provider explicitly:

model = init_chat_model(

    "deepseek:deepseek-flash"

)

or:

model = init_chat_model(

    "deepseek-flash",

    model_provider="deepseek"

)

2. Why does it say langchain-deepseek cannot be found?

You need to install the DeepSeek integration package first:

pip install -U langchain-deepseek

If it is already installed but the error persists, check whether you are using a different Python virtual environment.

3. Why can't deepseek-chat be called?

This is a model name commonly seen in older tutorials.

According to the current official DeepSeek API documentation, new projects should use:

deepseek-flash

deepseek-v4-pro

For example:

model = init_chat_model(

    "deepseek:deepseek-flash"

)

If you need to use Pro:

model = init_chat_model(

    "deepseek:deepseek-v4-pro"

)

Do not continue to use old model names as default examples in new tutorials.

4. Why can deepseek-v4-flash still be called?

DeepSeek officially retains some old names as compatibility aliases.

According to the official statement,deepseek-v4-flash and deepseek-v4-flash-vision-exp the corresponding old model has been taken offline, but requests using the old name can still be handled by DeepSeek-V4.1-Flash.

Therefore, new projects are recommended to use deepseek-flashand should not rely on old model names.

5. Why do API Key errors occur?

Common reasons include:

It is recommended to first check whether the environment variable exists, then verify the API Key status in the DeepSeek console.

6. Can the openai provider be used to call DeepSeek?

Yes, but you must correctly set base_url and the DeepSeek API Key.

For example:

model = init_chat_model(

    "deepseek-flash",

    model_provider="openai",

    base_url="https://api.deepseek.com",

    api_key="your_deepseek_api_key"

)

This example only demonstrates the parameter format. In real projects, you should read the key from environment variables rather than writing the real key into the code.

7. Does switching models require restarting the program?

If you use a configurable model, you can specify the model at runtime through config without needing to restart the application just to switch models.

However, the target model still requires the corresponding integration package, authentication information, and server-side calling permission.

8. Why does an error occur after setting temperature?

Different models have different levels of support for sampling parameters.

If the specific model does not accept temperature or restricts its value, you need to adjust the calling parameters according to that model's official documentation.

It is recommended to start with a minimal configuration, and after confirming the model can be called, add the necessary initialization parameters.

9. Is configurable_fields="any" safe?

If the configuration is entirely controlled by trusted server code, you can use it as needed.

But if the configuration comes from HTTP requests or other untrusted sources, it may allow sensitive parameters to be modified.

Therefore, in production it is more recommended to:

configurable_fields=[

    "model"

]

and control the actually selectable models through a model whitelist.


Summary

init_chat_model() is the unified chat model initialization entry point provided by LangChain, which simplifies switching between different model providers.

It mainly includes the following features:

For developers who are just starting with LangChain, it is recommended to first use the simplest approach:

from langchain.chat_models import init_chat_model



model = init_chat_model(

    "deepseek:deepseek-flash"

)



response = model.invoke("你好")



print(response.content)

When the project needs to switch between Flash, Pro, or other providers' models, then use the configurable model feature.

What you need to remember is:LangChain unifies the model calling entry point, but model names, feature support, parameter limits, and billing rules are still determined by the specific provider.