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

LangChain Chat Model Common Parameters

LangChain Chat Model Common Parameters

In the previous section, we learned about init_chat_model() the basic usage of the function.

When using LangChain to call a large language model, besides specifying the model name, you can also configure parameters such as output randomness, maximum Token count, request timeout, failure retries, and API address.

Using these parameters reasonably allows better control over model behavior, interface response time, and call cost.

This chapter introduces the common parameters of LangChain Chat Model and demonstrates them with the DeepSeek model.

**Note:** LangChain provides a unified model calling interface, but different providers, model versions, and thinking modes may support different parameters. The fact that a parameter can be passed successfully does not mean it will necessarily affect the model output.


I. Installation and Preparation

This tutorial uses LangChain 1.x and the official DeepSeek model interface.

First install the dependencies:

pip install -U langchain langchain-deepseek python-dotenv

Create in the project directory .env File:

DEEPSEEK_API_KEY=your_deepseek_api_key

Then use load_dotenv() to load environment variables:

Example

from

dotenv

import

load_dotenv

from

langchain.

chat_models

import

init_chat_model

load_dotenv

(

)

Use DeepSeek Flash

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

)

response

=

model.

invoke

(

"Hello, LangChain!"

)

print

(

response.

content

)

According to DeepSeek's current official API documentation, the commonly used model names are as follows:

Model API Model ID LangChain Initialization Name
DeepSeek Flash deepseek-flash deepseek:deepseek-flash
DeepSeek Pro deepseek-v4-pro deepseek:deepseek-v4-pro

Old Name deepseek-v4-flash etc. may still exist as compatibility aliases; new code is recommended to use deepseek-flash。


II. temperature: Controlling Generation Randomness

temperature is a common sampling parameter in chat models, used to adjust the degree of randomness when the model generates content.

In general:

For the DeepSeek Chat Completions interface that supports this parameter,temperature the range of values is 0 to 2.

For example:

temperature=0.0

temperature=0.7

temperature=1.5

Note that this range is not a range uniformly specified by LangChain for all models.

Example: Comparing Different temperature Values

Below, the same question is used to compare model output under different temperature settings.

This example only applies to non-thinking models or modes that actually support temperature adjustment.

Example

from

dotenv

import

load_dotenv

from

langchain.

chat_models

import

init_chat_model

load_dotenv

(

)

question

=

"Introduce Runoob Tutorial RUNOOB in one sentence"

Lower temperature

model_low

=

init_chat_model

(

   

"deepseek:deepseek-flash"

,

    temperature

=

0.2

)

Higher temperature

model_high

=

init_chat_model

(

   

"deepseek:deepseek-flash"

,

    temperature

=

1.2

)

print

(

"=== Lower temperature ==="

)

for

i

in

range

(

2

)

:

    response

=

model_low.

invoke

(

question

)

   

print

(

f

"Attempt {i + 1}: {response.content}"

)

print

(

"\n=== Higher temperature ==="

)

for

i

in

range

(

2

)

:

    response

=

model_high.

invoke

(

question

)

   

print

(

f

"Attempt {i + 1}: {response.content}"

)

If the current model is in non-thinking mode and actually supports temperature adjustment, you can observe its effect on the output.

But the model's output is not fixed each time, and a lower temperature cannot guarantee complete consistency.

temperature Usage Recommendations

Reference Range Typical Generation Characteristics Applicable scenarios
0~0.3 More biased toward high-probability output Classification, information extraction, formatting tasks
0.4~0.7 Relatively balanced General Q&A, content organization
0.8~1.2 More emphasis on diversity Creative writing, solution exploration
1.3~2.0 Randomness may increase significantly Experimental generation, creative exploration

This table only provides general sampling ideas and is not a recommended configuration for all models.

Special Rules for DeepSeek Thinking Mode

According to DeepSeek's current official documentation,thinking mode does not support adjusting sampling behavior through temperature。

For compatibility with existing software, even if the request contains temperature, the interface may not report an error, but the parameter will not take effect.

Therefore:

**Recommendation:** First confirm the current model mode and parameter support before conducting temperature experiments. If you want to compare the effect of sampling parameters, keep the model version and other request settings fixed.


III. max_tokens: Limiting the Number of Output Tokens

max_tokens is used to set the maximum number of Tokens the model is allowed to generate in a single request.

A Token is the basic unit used by the model to process text, but it is not equivalent to a character or a word.

For example, the following texts may have different Token counts:

Hello, world!



你好,世界!



print("Hello, world!")

The Token count depends on the tokenizer used by the specific model; you cannot simply assume that one Chinese character equals two Tokens, or that one Token corresponds to a fixed number of English words.

Example: Setting the Maximum Output Length

It is recommended to set max_tokens。

Example

from

dotenv

import

load_dotenv

from

langchain.

chat_models

import

init_chat_model

load_dotenv

(

)

question

=

"Introduce the main features of the Python programming language."

Shorter output limit

model_short

=

init_chat_model

(

   

"deepseek:deepseek-flash"

,

    max_tokens

=

100

)

Longer output limit

model_long

=

init_chat_model

(

   

"deepseek:deepseek-flash"

,

    max_tokens

=

500

)

response_short

=

model_short.

invoke

(

question

)

response_long

=

model_long.

invoke

(

question

)

print

(

"=== max_tokens=100 ==="

)

print

(

response_short.

content

)

print

(

"\n=== max_tokens=500 ==="

)

print

(

response_long.

content

)

If the model and interface support this parameter, a lower limit usually restricts the length of the content that can be generated.

but max_tokens=500 It does not mean the model will necessarily generate 500 tokens. It sets an upper limit, not a target output quantity.

Notes on max_tokens

Therefore,max_tokens It can help control the budget for a single output, but cannot by itself guarantee the final API cost.

Using bind() to create different configurations

If a model has already been created, you can use LangChain's bind() method to generate a model wrapper object with additional invocation parameters.

Example

from

langchain.

chat_models

import

init_chat_model

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

)

Binding an output limit for an invocation

short_model

=

model.

bind

(

max_tokens

=

100

)

long_model

=

model.

bind

(

max_tokens

=

500

)

question

=

"Introduce the main features of Python."

print

(

short_model.

invoke

(

question

)

.

content

)

print

(

long_model.

invoke

(

question

)

.

content

)

bind() This does not modify the original model's initialization configuration; instead, it returns a new Runnable with the bound parameters.

This approach is suitable for reusing the same model configuration across different tasks.

For example, a classification task can use a smaller output budget, while a tutorial generation task can use a larger one.


4. Viewing actual token usage

Rather than simply counting the characters of the output text, a more reliable approach is to read the token usage statistics returned by the model.

LangChain's AIMessage Usually through usage_metadata standardized token statistics are exposed.

Example

Example

from

langchain.

chat_models

import

init_chat_model

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

)

response

=

model.

invoke

(

   

"Introduce Python in about 100 words."

)

print

(

"Model answer:"

)

print

(

response.

content

)

print

(

"\nToken usage statistics:"

)

print

(

response.

usage_metadata

)

if

response.

usage_metadata

:

    usage

=

response.

usage_metadata

   

print

(

"Input Tokens:"

,

usage.

get

(

"input_tokens"

)

)

   

print

(

"Output Tokens:"

,

usage.

get

(

"output_tokens"

)

)

   

print

(

"Total Tokens:"

,

usage.

get

(

"total_tokens"

)

)

For models that provide usage statistics, the return may look like:

{

    'input_tokens': 20,

    'output_tokens': 85,

    'total_tokens': 105

}

The above is only a structural example and does not represent a fixed number of tokens produced by an actual call.

Different models may also provide additional token details, such as cache hits or thinking tokens.

If both the usage_metadata is None, indicating that the response did not provide standardized usage data; it cannot be directly assumed that the actual consumption was zero.


5. timeout: Setting the request timeout

timeout It is used to control the waiting time for model requests, preventing network requests from remaining unresolved for a long time.

For example:

timeout=30

Typically, it means setting a 30-second request timeout as defined by the underlying model integration.

Example

Example

from

langchain.

chat_models

import

init_chat_model

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

,

    timeout

=

30

)

try

:

    response

=

model.

invoke

(

       

"Introduce the Python programming language."

   

)

   

print

(

response.

content

)

except

Exception

as

error:

   

print

(

       

"Model call failed:"

,

       

type

(

error

)

.name

,

       

str

(

error

)

   

)

Setting a timeout can prevent some network requests from waiting indefinitely, but the specific timeout behavior may involve connections, reads, and the SDK's internal implementation.

For long-running model tasks, it is not advisable to use too short a timeout, as it may cause normal requests to be interrupted prematurely.

timeout reference settings

Scenario Reference timeout Description
Short Q&A 15-30 seconds Suitable for interactions that require high response speed
General text generation 30-60 seconds Adjust according to output length and service speed
Long text or complex reasoning 60 seconds or longer Need to account for model inference time and streaming responses

The above are only engineering configuration reference values, not mandatory rules of LangChain or DeepSeek.


6. max_retries: Retrying failed requests

max_retries Used to set the maximum number of retries after a model request fails.

For example:

max_retries=2

When the integration supports the corresponding retry strategy, a request can be reissued when a qualifying transient error occurs.

Example

Example

from

langchain.

chat_models

import

init_chat_model

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

,

   

Request timeout

    timeout

=

30

,

   

Number of retries on failure

    max_retries

=

2

)

try

:

    response

=

model.

invoke

(

       

"What is Runoob Tutorial RUNOOB?"

   

)

   

print

(

"Call succeeded:"

)

   

print

(

response.

content

)

except

Exception

as

error:

   

print

(

"Call failed:"

,

error

)

max_retries Mainly used to improve the success rate of requests under transient network failures or some server-side errors.

But it cannot fix all errors.

For example:

These errors generally require fixing the configuration, not solving them by increasing the number of retries.

The relationship between timeout and max_retries

Suppose the settings are:

timeout=30

max_retries=3

If the current model integration allows 3 retries in addition to the initial request, then when all requests fail, there may be up to 4 attempts.

But it cannot simply be assumed that the whole process takes at most:

4 × 30 = 120 秒

because the actual total time may also include:

If the business has a strict overall request time budget, a total timeout control should be added at the application layer rather than relying only on model initialization parameters.


7. base_url: Custom API address

base_url Used to specify the API address to which model requests are sent.

Common uses include:

Note thatbase_url It only changes the request destination address; it does not automatically change the underlying protocol.

The provider determines which LangChain integration to use, and base_url determines where requests are sent.

Example 1: Through the native DeepSeek integration

When using the native DeepSeek integration, you usually do not need to configure base_url。

Example

from

langchain.

chat_models

import

init_chat_model

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

)

response

=

model.

invoke

(

"Hello" (Chinese)

)

print

(

response.

content

)

the integration package uses the corresponding default DeepSeek API address.

Example 2: Calling DeepSeek through an OpenAI-compatible interface

DeepSeek officially provides an OpenAI-compatible interface, whose API address is:

https://api.deepseek.com

If you want to call langchain-openai To access it, you can use the following approach:

First install:

pip install -U langchain-openai

Example

import

os

from

dotenv

import

load_dotenv

from

langchain.

chat_models

import

init_chat_model

load_dotenv

(

)

model

=

init_chat_model

(

   

"deepseek-flash"

,

   

Using the OpenAI integration

    model_provider

=

"openai"

,

   

DeepSeek's official compatible interface

    base_url

=

"https://api.deepseek.com"

,

    api_key

=

os

.

environ

[

"DEEPSEEK_API_KEY"

]

)

response

=

model.

invoke

(

"Hello" (Chinese)

)

print

(

response.

content

)

Here, the openai provider, but the server actually accessed is DeepSeek's.

Note that interface compatibility does not mean all advanced features are fully consistent, and response data specific to third-party models may not be fully retrievable through the general integration.

Example 3: Calling a local vLLM service

If a local vLLM has started an OpenAI-compatible API service, you can connect in the same way.

Example

from

langchain.

chat_models

import

init_chat_model

model

=

init_chat_model

(

   

"Qwen/Qwen2.5-7B-Instruct"

,

    model_provider

=

"openai"

,

   

The OpenAI-compatible interface of local vLLM

    base_url

=

"http://127.0.0.1:8000/v1"

,

   

Only as a local example

    api_key

=

"not-needed"

)

response

=

model.

invoke

(

   

"Introduce Python."

)

print

(

response.

content

)

**Note:** Here it is assumed that the local vLLM service has been started and the actually exposed model ID is Qwen/Qwen2.5-7B-Instruct。

If a different model name was specified when starting the service, replace it with the ID actually provided by the server.

api_key="not-needed" Only applicable to local testing services that do not enable authentication but whose compatible clients require a key value; it should not be used as a security configuration for public interfaces.

base_url security considerations

Do not directly use untrusted user input as base_url。

If clients are allowed to modify the API address arbitrarily, it may lead to:

In real projects, the usable API service addresses should be restricted through a server-side whitelist.


8. top_p: The nucleus sampling parameter

top_p is another parameter that controls the range of token sampling, also known as nucleus sampling.

For example:

top_p=0.9

Generally, nucleus sampling selects a set of candidate tokens whose cumulative probability reaches a specified threshold, and then samples from this set.

Note thattop_p=0.1 It does not select from "the top 10% of words by probability," but uses a cumulative probability threshold.

General parameter example

For models that support this parameter, you can set it like this:

model = init_chat_model(

    "openai:gpt-4o-mini",

    top_p=0.9

)

Whether it is specifically supported and the allowed value range should follow the corresponding model API.

DeepSeek's special rules

DeepSeek's current official API has top_p special restrictions on its handling:

Operation mode top_p behavior
non-thinking mode Fixed at 1.0; any passed top_p value is ignored
thinking mode Effective range is 0.95-1.0; values below 0.95 are treated as 0.95

Therefore, it is not recommended to continue using the following from older tutorials:

top_p=0.1

as an example of DeepSeek randomness control.

Even if the request succeeds, it does not mean the value takes effect according to normal nucleus sampling rules.

For models that support both temperature and nucleus sampling, it is usually recommended to adjust only one of them first in order to observe the effect.


9. stop: Setting stop sequences

stop Used to specify one or more stop sequences.

When supported by the model and interface, generation ends when the generated content encounters a stop sequence.

For example:

stop=["END"]

It means terminating output when the model generates the specified stop string.

Example

Example

from

langchain.

chat_models

import

init_chat_model

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

)

Binding a stop sequence

model_with_stop

=

model.

bind

(

    stop

=

[

"END"

]

)

response

=

model_with_stop.

invoke

(

   

"Write three sentences introducing Python, and output END at the end."

)

print

(

response.

content

)

If the interface correctly applies the stop sequence rule, the returned content usually does not contain the stop marker END。

But note thatstop support, whether the stop string appears in the output, and the specific truncation behavior depend on the model and interface used.

In addition, stop sequences can only be used for text generation control and should not be regarded as a means of strict output structure validation.

If structured output such as JSON is needed, prefer the structured output feature supported by the model.


10. seed: Controlling reproducibility

Some model providers offer a seed parameter to maximize the reproducibility of identical requests.

For example, for models that support seed , you can use a similar form:

model = init_chat_model(

    "openai:gpt-4o-mini",

    seed=42

)

But note:

Currently, it is not recommended to use the following directly in DeepSeek's introductory examples:

seed=42

and claim that two outputs will definitely be the same. You should first confirm whether the target DeepSeek model interface explicitly supports this parameter.

If the business requires strictly reproducible results, you usually also need to fix the model version, inputs, and parameters, and combine them with mechanisms such as caching and output validation.


11. rate_limiter: Limiting the request rate

For applications that need to call the model continuously, you can use rate_limiter to configure a client-side request rate limit.

For example, in batch text processing or automated tasks, it can prevent the program from issuing a large number of requests in an instant.

LangChain provides InMemoryRateLimiterfor simple in-process rate limiting.

Example

Example

from

langchain.

chat_models

import

init_chat_model

from

langchain_core.

rate_limiters

import

InMemoryRateLimiter

Allows 1 request per second on average

rate_limiter

=

InMemoryRateLimiter

(

    requests_per_second

=

1

,

    check_every_n_seconds

=

0.1

,

    max_bucket_size

=

1

)

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

,

    rate_limiter

=

rate_limiter

)

questions

=

[

   

"What is Python?"

,

   

"What is Java?"

,

   

"What is JavaScript?"

]

for

question

in

questions:

    response

=

model.

invoke

(

question

)

   

print

(

response.

content

)

InMemoryRateLimiter Uses in-process state, so it is suitable for simple single-process applications or development and testing.

It is not a distributed rate limiter shared across multiple servers.

Also, client-side rate limiting is not the same as the provider's server-side quota limit; the server may still return rate-limiting errors.


12. The difference between initialization parameters and invocation parameters

LangChain's model parameters can be set at different stages.

Method 1: Specifying at initialization

model = init_chat_model(

    "deepseek:deepseek-flash",

    max_tokens=200,

    timeout=30,

    max_retries=2

)

This approach is suitable for setting a default configuration for a model object.

Method 2: Binding via bind()

short_model = model.bind(max_tokens=100)



response = short_model.invoke("介绍 Python")

This approach is suitable for binding additional invocation parameters when reusing the original model object.

Method 3: Using a configurable model

If you need to modify initialization fields at runtime through config a configurable field, you can combine configurable_fields。

Example

from

langchain.

chat_models

import

init_chat_model

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

,

    max_tokens

=

200

,

    configurable_fields

=

[

       

"model"

,

       

"max_tokens"

   

]

)

the default configuration with

response

=

model.

invoke

(

   

"Introduce Python."

)

print

(

response.

content

)

a runtime override of the maximum output tokens.

response

=

model.

invoke

(

   

"Introduce Python."

,

    config

=

{

       

"configurable"

:

{

           

"max_tokens"

:

500

       

}

   

}

)

print

(

response.

content

)

Here, config It is not equivalent to a native request parameter of the model API, but rather a runtime configuration mechanism of a LangChain Runnable.

Only configurable fields declared in advance can be passed through according to the corresponding rules via configurable afterwards.

Therefore,bind() and configurable_fields Although all of them can achieve parameter reuse or override, their purposes are not entirely the same.


13. Complete example: Common parameter combinations

Below, common parameters are combined into a runnable program.

This example uses DeepSeek Flash as the model, sets an output limit, request timeout, and retry count, and displays token usage statistics.

Example

File: chat_model_params.py

from

dotenv

import

load_dotenv

from

langchain.

chat_models

import

init_chat_model

load_dotenv

(

)

Initialize the model

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

,

   

Maximum output tokens

    max_tokens

=

300

,

   

Request timeout

    timeout

=

30

,

   

Retry on failure

    max_retries

=

2

)

def

ask

(

question:

str

)

:

   

"""Call the model and display the result and token statistics."""

   

try

:

        response

=

model.

invoke

(

question

)

       

print

(

"Question:"

,

question

)

       

print

(

"Answer:"

,

response.

content

)

       

Token usage statistics

        usage

=

response.

usage_metadata

       

if

usage:

           

print

(

"Input Tokens:"

,

usage.

get

(

"input_tokens"

)

)

           

print

(

"Output Tokens:"

,

usage.

get

(

"output_tokens"

)

)

           

print

(

"Total Tokens:"

,

usage.

get

(

"total_tokens"

)

)

       

else

:

           

print

(

"The model did not return standardized token statistics"

)

       

print

(

"-"

40

)

   

except

Exception

as

error:

       

print

(

"Call failed:"

)

       

print

(

type

(

error

)

.name

)

       

print

(

str

(

error

)

)

if

name

==

"main"

:

    ask

(

"Introduce Runoob Tutorial RUNOOB in one sentence."

)

    ask

(

"List three advantages of Python."

)

Run the code:

python chat_model_params.py

The program will output:

Since model output and token statistics can vary, no fixed run result is provided here.

**Note:** This example does not actively set temperature or top_p, but instead uses the default behavior of the corresponding model mode, avoiding passing potentially invalid configurations when the current sampling parameter support is unclear.


14. Parameter quick reference table

Parameters Common Types Purpose Notes
temperature float Adjust generation randomness Not effective in DeepSeek's thinking mode
max_tokens int Limit the number of output tokens May cause the answer to be truncated
timeout int / float Control the request timeout The specific timeout mechanism is determined by the integration implementation
max_retries int Control the number of retries on failure Does not guarantee that all errors will be retried
base_url str Specify the API address Must be compatible with the protocol of the provider used
top_p float Control the nucleus sampling threshold DeepSeek currently has mode-related restrictions
stop list[str] Set stop sequences Specific support is determined by the model
seed int Improve the reproducibility of some models Not a universal parameter; does not guarantee identical results
rate_limiter BaseRateLimiter Limit the client request rate Cannot replace server-side rate limiting

The parameter types and uses in the above table are common practices. Specific default values, acceptable ranges, and behaviors require consulting the documentation of the corresponding model integration.


XV. FAQ

1. Why are the two outputs still different when temperature=0?

A lower temperature does not equal strict determinism.

In addition, some model modes ignore temperature, or there are other server-side factors that affect the output.

Therefore, you cannot treat temperature=0 as a method that absolutely guarantees identical output.

2. Why is the answer truncated after setting max_tokens?

Because the model's actual output may have reached the maximum token limit.

You can appropriately raise the output limit or request a more concise answer in the prompt.

If the model provides a finish reason, you can further judge using the response.response_metadata relevant fields in it.

3. Why does setting top_p have no effect?

First check whether the specific model supports adjusting this parameter.

For the current DeepSeek API:

Therefore, a successful parameter setting does not mean the actual sampling strategy has changed.

4. Does timeout=30 mean the whole program runs for at most 30 seconds?

Not necessarily.

Request retries, exponential backoff, connection handling, and other program logic can all increase the total time.

If the maximum running time of the entire task must be limited, a total timeout mechanism should be implemented separately at the application layer.

5. Is a larger max_retries always better?

No.

Increasing the number of retries may improve the success rate under transient errors, but it also increases waiting time, the number of requests, and cost.

For unrecoverable problems such as authentication errors and illegal parameters, increasing retries is usually meaningless.

6. Can base_url be set to any model service address?

No.

You must ensure that the API protocol provided by that address is compatible with the LangChain integration used.

For example, when using model_provider="openai" , the target service usually needs to be compatible with the corresponding OpenAI API format.

7. Why do different models behave differently with max_tokens?

Different providers may have different definitions of output length, thinking tokens, and response formats.

LangChain maps parameters through the corresponding integrations, but cannot guarantee that all models have exactly the same behavior.

8. Can different parameters be used for each invocation?

Depending on the support of the model integration, you can use bind()to pass parameters, or through configurable_fields to create a configurable model.

For example:

model = init_chat_model(

    "deepseek:deepseek-flash"

)



short_model = model.bind(max_tokens=100)



response = short_model.invoke("介绍 Python")

If initialization parameters need to be modified dynamically based on the user or business scenario, it is recommended to use a configurable model combined with a configuration whitelist.


Summary

The common parameters of LangChain Chat Model can be divided into the following categories:

For beginners, it is recommended to first master max_tokens、timeout and max_retries, then adjust the sampling parameters according to the specific model's API support.

In particular, remember:What LangChain unifies is the invocation interface; whether specific parameters take effect is determined by the model provider and the model's operating mode.

In real projects, it is recommended to start with a minimal runnable configuration, add parameters gradually, and record actual responses, token consumption, and request duration.