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

LangChain Chat Model Advanced Usage

LangChain Chat Model Advanced Usage

Earlier we learned how to use init_chat_model() to initialize a model, and how to use invoke() to call a model.

This chapter introduces two important features of LangChain Chat Model:

These two features are often used in Agents, data extraction, automation tasks, and AI application development.

Note thatbind_tools() The difference between with_structured_output() have different purposes, but their underlying implementations may both involve the model's tool calling capability.


I. Installation and Environment Preparation

This tutorial uses LangChain 1.x, and takes the deepseek-flash model officially recommended by DeepSeek as the main example.

First install the dependencies:

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

Create in the project directory .env File:

DEEPSEEK_API_KEY=your_deepseek_api_key

Then initialize the model:

Example

from

dotenv

import

load_dotenv

from

langchain.

chat_models

import

init_chat_model

load_dotenv

(

)

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

)

response

=

model.

invoke

(

"Hello, LangChain!"

)

print

(

response.

content

)

The following examples assume the above initialization has been completed, unless the example recreates the model.

Note that whether tool calling and structured output features are available, as well as the specific supported parameters, depends on the model, API, and LangChain integration version used.


II. bind_tools(): Binding Tools to the Model

bind_tools() is used to provide tool definitions to the chat model, letting it know which tools are currently available and what parameters each tool requires.

For example, a weather query tool can accept a city name:

get_weather(city="Hangzhou")

When a user asks about the weather, the model can generate a tool call request specifying the tool name and parameters.

Note:bind_tools() does not actually execute Python functions.

It only provides tool definitions to the model and allows the model to return in its response tool_calls。

bind_tools() Basic Syntax

model_with_tools = model.bind_tools(tools)

Wheretools is a list of tool definitions.

LangChain supports multiple ways of defining tools, including:

Example 1: Defining a Tool with a Dictionary

Below, an OpenAI Function Calling-style dictionary describes a weather query tool.

Example

from

dotenv

import

load_dotenv

from

langchain.

chat_models

import

init_chat_model

load_dotenv

(

)

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

)

Describe a weather query tool

tools

=

[

   

{

       

"type"

:

"function"

,

       

"function"

:

{

           

"name"

:

"get_weather"

,

           

"description"

:

"Query simulated weather for a specified city"

,

           

"parameters"

:

{

               

"type"

:

"object"

,

               

"properties"

:

{

                   

"city"

:

{

                       

"type"

:

"string"

,

                       

"description"

:

"City name, such as Hangzhou or Beijing"

                   

}

               

}

,

               

"required"

:

[

"city"

]

           

}

       

}

   

}

]

Bind the tool definition to the model

model_with_tools

=

model.

bind_tools

(

tools

)

Request the model to use the tool

response

=

model_with_tools.

invoke

(

   

"Please use get_weather to query the simulated weather for Hangzhou."

)

View the tool call

if

response.

tool_calls

:

   

for

tool_call

in

response.

tool_calls

:

       

print

(

"Tool name:"

,

tool_call

[

"name"

]

)

       

print

(

"Tool arguments:"

,

tool_call

[

"args"

]

)

       

print

(

"Call ID:"

,

tool_call

[

"id"

]

)

else

:

   

print

(

"Model answers directly:"

,

response.

content

)

If the model chooses to call the tool, it may output something like:

工具名称: get_weather

工具参数: {'city': '杭州'}

调用 ID: call_xxxxx

Here, the call ID is generated by the model service, and its value usually differs between requests.

Also note that even if tools are bound, the model does not guarantee it will call them every time. Whether to call depends on the model and related configuration.

tool_calls Return Structure

LangChain standardizes the tool call requests returned by the model into AIMessage.tool_calls it.

A typical structure is as follows:

[

    {

        "name": "get_weather",

        "args": {

            "city": "杭州"

        },

        "id": "call_xxxxx",

        "type": "tool_call"

    }

]

Field Description
name Tool name
args the dictionary of tool arguments generated by the model
id the tool call identifier, used to associate tool return results
type the type of call content

If the model returns a malformed tool call, there may also be invalid_tool_calls. Therefore, in real development you cannot assume every tool call is valid.


III. Defining Tools with @tool

If a tool needs to actually execute Python code, it is usually recommended to use @tool Define tools with decorators.

For example:

Example

from

langchain.

tools

import

tool

@

tool

def

get_weather

(

city:

str

)

str

:

   

"""Query simulated weather for a specified city.

    Args:
        city: city name, such as Hangzhou or Beijing.
    """

    weather_data

=

{

       

"Hangzhou"

:

"Sunny, 25°C"

,

       

"Beijing"

:

"Cloudy, 18°C"

,

       

"Shanghai"

:

"Light rain, 22°C"

,

   

}

   

return

weather_data.

get

(

        city

,

        f

"No simulated weather found for {city}"

   

)

Bind the tool

model_with_tools

=

model.

bind_tools

(

[

    get_weather

]

)

response

=

model_with_tools.

invoke

(

   

"Query Hangzhou's mock weather."

)

print

(

response.

tool_calls

)

Use @tool , LangChain uses the function name, parameter types, and docstring to build the tool definition.

In this example:

The model can generate a tool call request based on this information.

However, at this point the weather query function is still not automatically executed.


IV. Manually Executing Tools: The Complete Tool Calling Flow

Use only bind_tools(), the model tells the program which tool to call, but does not execute it automatically.

If you are not using an Agent, you need to write the tool dispatch code yourself.

The basic flow is as follows:

用户提问

   ↓

模型生成工具调用请求

   ↓

程序检查 tool_calls

   ↓

调用对应 Python 工具

   ↓

将结果封装为 ToolMessage

   ↓

再次调用模型

   ↓

生成最终回答

Complete example

The following shows how to manually complete a tool call loop.

Example

from

dotenv

import

load_dotenv

from

langchain.

chat_models

import

init_chat_model

from

langchain.

tools

import

tool

from

langchain.

messages

import

(

    HumanMessage

,

    ToolMessage

)

load_dotenv

(

)

1. Define the tool

@

tool

def

get_weather

(

city:

str

)

str

:

   

"""Query simulated weather for a specified city.

    Args:
        city: city name.
    """

    data

=

{

       

"Hangzhou"

:

"Sunny, 25°C"

,

       

"Beijing"

:

"Cloudy, 18°C"

   

}

   

return

data.

get

(

city

,

"No simulated data for this city"

)

2. Initialize the model and bind the tool

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

)

model_with_tools

=

model.

bind_tools

(

[

    get_weather

]

)

3. Create the message list

messages

=

[

    HumanMessage

(

        content

=

"Please call the tool to query the simulated weather for Hangzhou."

   

)

]

4. First model call

response

=

model_with_tools.

invoke

(

messages

)

Keep the model message, including the tool call request

messages.

append

(

response

)

5. Manually execute the tool requested by the model

tool_map

=

{

   

"get_weather"

: get_weather

}

for

tool_call

in

response.

tool_calls

:

    tool_name

=

tool_call

[

"name"

]

   

if

tool_name

not

in

tool_map:

        tool_result

=

f

"Unknown tool: {tool_name}"

   

else

:

       

try

:

           

Execute the corresponding tool

            tool_result

=

tool_map

[

tool_name

]

.

invoke

(

                tool_call

[

"args"

]

           

)

       

except

Exception

as

error:

            tool_result

=

(

                f

"Tool execution failed: {type(error).name}"

           

)

   

Associate the result with the call ID

    messages.

append

(

        ToolMessage

(

            content

=

str

(

tool_result

)

,

            tool_call_id

=

tool_call

[

"id"

]

       

)

   

)

6. Pass the tool result back to the model

if

response.

tool_calls

:

    final_response

=

model_with_tools.

invoke

(

        messages

   

)

   

print

(

"Final answer: "

)

   

print

(

final_response.

content

)

else

:

   

print

(

"Model answers directly:"

)

   

print

(

response.

content

)

If the first model call produced get_weather a tool call, the program executes the corresponding Python function.

After the tool returns the simulated weather, use ToolMessage to pass the result back to the model.

The model can then use this result to compose the final answer.

For example:

杭州的模拟天气为晴天,气温25°C。

**Note:** This example demonstrates one tool execution and one subsequent model call. If the second model response still contains a tool call request, you need to continue the loop.

If you need complete multi-round tool calling, state management, and execution control, it is recommended to use the create_agent()introduced in the previous section, rather than implementing complex dispatch logic yourself.

In addition, tool arguments are generated by the model, so before executing sensitive tools such as database modifications, file operations, or network requests, you should also perform argument validation and permission checks.


V. Using Pydantic Models to Describe Tool Arguments

For tools with many arguments, you can use Pydantic to define the argument structure.

Pydantic provides type declarations, field descriptions, and data validation, reducing the work of writing JSON Schema by hand.

Example

Example

from

pydantic

import

BaseModel

,

Field

from

langchain.

chat_models

import

init_chat_model

class

GetWeather

(

BaseModel

)

:

   

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

    city:

str

=

Field

(

        description

=

"City name, such as Hangzhou or Beijing"

   

)

    unit:

str

=

Field

(

        default

=

"celsius"

,

        description

=

"Temperature unit: celsius or fahrenheit"

   

)

class

Calculate

(

BaseModel

)

:

   

"""Compute a simple mathematical expression."""

    expression:

str

=

Field

(

        description

=

"A mathematical expression, such as 123 * 456"

   

)

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

)

model_with_tools

=

model.

bind_tools

(

[

    GetWeather

,

    Calculate

]

)

response

=

model_with_tools.

invoke

(

   

"Query the simulated weather for Beijing and compute 123 times 456."

)

for

tool_call

in

response.

tool_calls

:

   

print

(

"Tool:"

,

tool_call

[

"name"

]

)

   

print

(

"Arguments:"

,

tool_call

[

"args"

]

)

If the model chooses to call two tools, it may return:

工具: GetWeather

参数: {'city': '北京', 'unit': 'celsius'}



工具: Calculate

参数: {'expression': '123 * 456'}

There is an important difference here:The tool name comes from the Pydantic class name by default。

Therefore:

If you want the tool name to be get_weather or calculate, you can use the correspondingly named @tool function in Vue 3.

**Note:** The Pydantic classes here are used to describe the tool input structure and do not contain the specific execution logic for weather queries or mathematical calculations. After the model returns a tool call request, the application still needs to provide the corresponding tool implementation.

The field descriptions of Pydantic classes can help the model generate arguments that meet the requirements, but the arguments generated by the model are not always valid. Validation is still needed before actual execution.


VI. with_structured_output(): Structured Output

with_structured_output() is used to convert the output of a chat model into a specified data structure.

For example, a plain model may return the following text:

张三今年28岁,是一名全栈工程师,

掌握 Python、React 和 Docker。

If the program needs to extract name, age, occupation, and skills, structured output can produce:

{

    "name": "张三",

    "age": 28,

    "occupation": "全栈工程师",

    "skills": ["Python", "React", "Docker"]

}

This way you do not have to parse fields from natural language yourself.

Basic Syntax

structured_model = model.with_structured_output(

    schema

)



result = structured_model.invoke(text)

Whereschema is used to define the expected output structure.

Common ways to define structures include:

Note:with_structured_output() does not guarantee that the underlying implementation uses a separate native structured output API. Some model integrations use Tool Calling or JSON Mode.

Example: Extracting Person Information with Pydantic

Example

from

dotenv

import

load_dotenv

from

pydantic

import

BaseModel

,

Field

from

langchain.

chat_models

import

init_chat_model

load_dotenv

(

)

Define the structured output format

class

PersonInfo

(

BaseModel

)

:

   

"""Extract person information from text."""

    name:

str

=

Field

(

        description

=

"Person name"

   

)

    age:

int

=

Field

(

        description

=

"Age"

   

)

    occupation:

str

=

Field

(

        description

=

"Occupation"

   

)

    skills:

list

[

str

]

=

Field

(

        description

=

"List of skills"

   

)

Initialize the model

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

)

Use Pydantic Schema

structured_model

=

model.

with_structured_output

(

    PersonInfo

)

text

=

(

   

"Zhang San is 28 years old and is a full-stack engineer,"

   

"proficient in Python, React, and Docker."

)

result

=

structured_model.

invoke

(

   

"Please extract person information from the text, do not fabricate: \n"

)

print

(

"Name:"

,

result.

name

)

print

(

"Age:"

,

result.

age

)

print

(

"Occupation:"

,

result.

occupation

)

print

(

"Skills:"

,

result.

skills

)

print

(

"Return type:"

,

type

(

result

)

)

If the model extracts the information correctly, the output may be:

姓名: 张三

年龄: 28

职业: 全栈工程师

技能: ['Python', 'React', 'Docker']



返回类型: 

When using Pydantic Schema and parsing succeeds, the return value is usually the corresponding Pydantic model instance.

Therefore, you can use:

result.name

result.age

result.skills

to read fields directly.

You can also convert it to a dictionary:

data = result.model_dump()



print(data)

Pydantic checks whether the returned fields satisfy the corresponding types and validation rules.

But note thattype validation is not the same as factual validation. Even if the returned structure is valid, you need to check whether the information extracted by the model is accurate according to business needs.


VII. The Difference Between bind_tools() and with_structured_output()

Both methods can leverage the model's structured response capability, but they have different purposes.

Comparison item bind_tools() with_structured_output()
Main Use Let the model choose and request to call a tool Let the model output data that conforms to a specified structure
Typical return values AIMessage Pydantic instance or dict
Tool execution Requires execution by a program or Agent Mainly focuses on data generation and parsing, not responsible for executing external business tools
Typical scenario Agents, search, weather queries, database operations Information extraction, classification, JSON data generation
Underlying mechanism Depends on the model's tool calling support May use Tool Calling, JSON Mode, or native structured output

You can understand it this way:

For example:

用户:查询杭州天气



bind_tools()

    ↓

模型请求调用 get_weather

    ↓

程序执行工具

    ↓

获得天气数据

While structured output is more like:

输入:张三今年28岁,职业是程序员



with_structured_output()

    ↓

{

    "name": "张三",

    "age": 28,

    "occupation": "程序员"

}

These two capabilities can be combined in more complex Agent workflows, but they should not be simply understood as identical operations.


VIII. Nested Structured Output

with_structured_output() You can extract not only simple fields, but also nested objects and lists.

For example, you can extract from a recipe text:

Example: Extracting Recipe Information

Example

from

pydantic

import

BaseModel

,

Field

from

langchain.

chat_models

import

init_chat_model

class

Ingredient

(

BaseModel

)

:

   

"""Ingredient information."""

    name:

str

=

Field

(

        description

=

"Ingredient name"

   

)

    amount:

str

=

Field

(

        description

=

"Ingredient quantity"

   

)

class

CookingStep

(

BaseModel

)

:

   

"""Cooking step."""

    step_number:

int

=

Field

(

        description

=

"Step number"

   

)

    description:

str

=

Field

(

        description

=

"Step description"

   

)

    duration_minutes:

int

=

Field

(

        description

=

"Minutes required for the step"

   

)

class

Recipe

(

BaseModel

)

:

   

"""Recipe information."""

    dish_name:

str

=

Field

(

        description

=

"Dish name"

   

)

    difficulty:

str

=

Field

(

        description

=

"Difficulty"

   

)

    ingredients:

list

[

Ingredient

]

=

Field

(

        description

=

"List of ingredients"

   

)

    steps:

list

[

CookingStep

]

=

Field

(

        description

=

"Cooking steps"

   

)

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

)

structured_model

=

model.

with_structured_output

(

    Recipe

)

recipe_text

=

"""
Today we introduce tomato and egg stir-fry.

Ingredients:
2 tomatoes, 3 eggs, a little chopped scallion,
salt to taste, and a little sugar.

Preparation steps:

  1. Cut the tomatoes into pieces and beat the eggs, about 5 minutes.
  2. Scramble the eggs until cooked and set aside, about 3 minutes.
  3. Stir-fry the tomatoes until juicy, add salt and sugar, about 5 minutes.
  4. Add the eggs and stir-fry, sprinkle with chopped scallion, about 2 minutes.
    """

result

=

structured_model.

invoke

(

   

"Please organize the following recipe into structured data. \n"

   

"The difficulty can be reasonably judged from the description,"

   

"do not fabricate other fields. \n\n"

    + recipe_text

)

print

(

"Dish name:"

,

result.

dish_name

)

print

(

"Difficulty:"

,

result.

difficulty

)

print

(

"\nIngredients:"

)

for

ingredient

in

result.

ingredients

:

   

print

(

        ingredient.

name

,

        ingredient.

amount

   

)

print

(

"\nSteps:"

)

for

step

in

result.

steps

:

   

print

(

        step.

step_number

,

        step.

description

,

        step.

duration_minutes

   

)

If parsing succeeds, you can get a result like:

菜名: 番茄炒蛋

难度: 简单



食材:

番茄 2个

鸡蛋 3个

葱花 少许

盐 适量

糖 少许



步骤:

1 番茄切块,鸡蛋打散 5

2 将鸡蛋炒熟盛出 3

3 炒番茄至出汁,加盐和糖 5

4 加入鸡蛋翻炒,撒上葱花 2

Here, Recipe contains two lists of nested objects:

ingredients: list[Ingredient]



steps: list[CookingStep]

The model can build hierarchical data structures according to the Schema.

However, the more complex the nested structure, the more you need to pay attention to the model's structured output capability, field completeness, and parsing failures.


IX. JSON Schema Structured Output

If you do not want to use Pydantic classes, you can also describe the output structure directly with a JSON Schema dictionary.

This is very useful for projects that need to share data formats with other languages, front-end applications, or external interfaces.

Example: Sentiment Analysis

Example

from

langchain.

chat_models

import

init_chat_model

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

)

Define the JSON Schema

json_schema

=

{

   

"title"

:

"SentimentAnalysis"

,

   

"description"

:

"Text sentiment analysis result"

,

   

"type"

:

"object"

,

   

"properties"

:

{

       

"sentiment"

:

{

           

"type"

:

"string"

,

           

"enum"

:

[

               

"positive"

,

               

"negative"

,

               

"neutral"

           

]

,

           

"description"

:

"Sentiment tendency"

       

}

,

       

"confidence"

:

{

           

"type"

:

"number"

,

           

"minimum"

:

0

,

           

"maximum"

:

1

,

           

"description"

:

"The confidence estimate given by the model"

       

}

,

       

"keywords"

:

{

           

"type"

:

"array"

,

           

"items"

:

{

               

"type"

:

"string"

           

}

,

           

"description"

:

"Key sentiment words"

       

}

   

}

,

   

"required"

:

[

       

"sentiment"

,

       

"confidence"

,

       

"keywords"

   

]

}

structured_model

=

model.

with_structured_output

(

    json_schema

)

text

=

(

   

"Runoob Tutorial RUNOOB is really great,"

   

"highly recommended for programming beginners!"

)

result

=

structured_model.

invoke

(

   

"Please analyze the sentiment of the following text and return structured data: \n"

    + text

)

print

(

"Sentiment:"

,

result

[

"sentiment"

]

)

print

(

"Confidence:"

,

result

[

"confidence"

]

)

print

(

"Keywords:"

,

result

[

"keywords"

]

)

If the model outputs as required, you can get something like:

情感: positive

置信度: 0.95

关键词: ['太棒了', '强烈推荐']

The confidence here is only an estimate generated by the model, not a statistically calibrated true probability.

Unlike the Pydantic mode, when passing a JSON Schema dictionary, LangChain usually returns a plain dict。

For example:

result["sentiment"]

result["confidence"]

**Note:** Using JSON Schema does not automatically guarantee that the model output fully conforms to all rules, nor does it mean LangChain will necessarily perform complete JSON Schema validation.

If the business needs strict validation of data types, ranges, and required fields, it is recommended to use Pydantic or perform Schema validation separately.


X. include_raw: Keeping the Raw Response as Well

By default,with_structured_output() returns the parsed result directly.

If you also need to view the raw model response, Token usage, or parsing errors, you can set:

include_raw=True

Example

Example

from

pydantic

import

BaseModel

,

Field

from

langchain.

chat_models

import

init_chat_model

class

PersonInfo

(

BaseModel

)

:

   

"""Person information."""

    name:

str

=

Field

(

        description

=

"Name"

   

)

    age:

int

=

Field

(

        description

=

"Age"

   

)

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

)

structured_model

=

model.

with_structured_output

(

    PersonInfo

,

    include_raw

=

True

)

result

=

structured_model.

invoke

(

   

"Extract person information: Zhang San is 28 years old."

)

print

(

"Parsing result:"

,

result

[

"parsed"

]

)

print

(

"Parsing error:"

,

result

[

"parsing_error"

]

)

print

(

"Raw response:"

,

result

[

"raw"

]

)

Settings include_raw=True , the returned result usually contains the following three fields:

Field Meaning
raw the model's raw message response
parsed the parsed structured result
parsing_error the error that occurred during parsing, usually None when there is no error

If parsing succeeds,parsed will contain the corresponding Pydantic instance.

If parsing fails,parsing_error can help locate the problem.

Note:include_raw=True mainly helps observe the parsing process and does not mean it will capture all network errors, authentication errors, or model service exceptions.


XI. Implementation Methods of Structured Output

LangChain's with_structured_output() is a unified interface, and the actual underlying mechanism used is determined by the model integration.

Common methods include:

Method Description
function_calling Producing arguments that conform to a specified structure through tool or function calling mechanisms
json_mode Using the JSON output mode of the model service
json_schema Using model interfaces that support native JSON Schema constraints

Not every provider supports all three methods.

In addition, different LangChain integrations may have different method default values and implementations for the parameters.

DeepSeek's JSON Output Capability

DeepSeek officially provides a JSON Output feature, which can be set in the corresponding interface:

{

    "response_format": {

        "type": "json_object"

    }

}

According to DeepSeek's official documentation, when using JSON Output, you should also explicitly request JSON output in the prompt and provide an example of the expected structure.

For example:

请将下列人物信息转换为 JSON。



JSON 字段:

{

    "name": "姓名",

    "age": 0

}



输入:张三今年28岁。

Note:JSON Mode mainly guarantees that the output uses valid JSON format, and does not mean all fields strictly conform to the specified Schema.

If field type validation is needed, it is still recommended to use mechanisms such as Pydantic in the program for validation.

In addition, DeepSeek officially notes that JSON Mode may produce empty output or truncated content in some cases, so you should set output limits reasonably and handle exceptions well.


XII. How to Handle Structured Output Failures?

In actual calls, the model may return data with missing fields, type errors, or non-conforming formats.

For example, the program requires:

{

    "name": "张三",

    "age": 28

}

but the model actually returns:

{

    "name": "张三",

    "age": "未知"

}

At this point age does not satisfy the expected integer type.

If you use a Pydantic model, an error may occur during the parsing and validation stage.

Example: Catching Structured Output Errors

Example

from

pydantic

import

BaseModel

,

Field

from

langchain.

chat_models

import

init_chat_model

class

UserInfo

(

BaseModel

)

:

   

"""User information."""

    name:

str

=

Field

(

        description

=

"User name"

   

)

    age:

int

=

Field

(

        ge

=

0

,

        le

=

150

,

        description

=

"User age"

   

)

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

)

structured_model

=

model.

with_structured_output

(

    UserInfo

,

    include_raw

=

True

)

try

:

    result

=

structured_model.

invoke

(

       

"Extract user information: Zhang San is 28 years old."

   

)

   

if

result

[

"parsing_error"

]

:

       

print

(

           

"Parsing failed:"

,

            result

[

"parsing_error"

]

       

)

   

else

:

       

user

=

result

[

"parsed"

]

       

print

(

"Name:"

,

user

.

name

)

       

print

(

"Age:"

,

user

.

age

)

except

Exception

as

error:

   

print

(

       

"Model request failed:"

,

       

type

(

error

)

.name

,

       

str

(

error

)

   

)

This example includes two layers of checks:

For production environments, it is recommended to further add logging, a limited number of retries, and business validation of results.

**Note:** Do not trust all the data just because the JSON can be parsed. The model may still generate factually inaccurate content.


XIII. Using bind_tools() in ConfigurableModel

Besides fixed models, LangChain, through init_chat_model() creates configurable models that also support declarative operations such as tool binding.

This means you can configure the model and tools first, then choose which model to use at runtime.

Example: Dynamically Switching Between DeepSeek Flash and Pro

Example

from

langchain.

chat_models

import

init_chat_model

from

langchain.

tools

import

tool

@

tool

def

get_weather

(

city:

str

)

str

:

   

"""Query simulated weather for a specified city.

    Args:
        city: city name.
    """

    data

=

{

       

"Hangzhou"

:

"Sunny, 25°C"

,

       

"Beijing"

:

"Cloudy, 18°C"

   

}

   

return

data.

get

(

        city

,

       

"No simulated data for this city"

   

)

Create a configurable model

configurable_model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

,

    configurable_fields

=

[

       

"model"

   

]

)

Bind the tool

model_with_tools

=

configurable_model.

bind_tools

(

[

    get_weather

]

)

Use the default Flash

response

=

model_with_tools.

invoke

(

   

"Query Hangzhou's mock weather."

)

print

(

"Flash tool call:"

)

print

(

response.

tool_calls

)

Switch to Pro

response

=

model_with_tools.

invoke

(

   

"Query the simulated weather for Beijing."

,

    config

=

{

       

"configurable"

:

{

           

"model"

:

"deepseek:deepseek-v4-pro"

       

}

   

}

)

print

(

"Pro tool call:"

)

print

(

response.

tool_calls

)

In the above code,configurable_model can choose Flash or Pro at runtime.

After binding tools, you can still use config to specify the current model.

But note that the target model must support the corresponding tool calling capability.

At the same time,bind_tools() still only lets the model generate tool call requests and does not automatically execute tools.


XIV. Using Structured Output in ConfigurableModel

Configurable models can also use it on supported integrations with_structured_output()。

Note that different model providers may have different structured output capabilities. Therefore, when dynamically switching models, you must ensure the target model supports the output Schema and parsing method used.

Example

Example

from

pydantic

import

BaseModel

,

Field

from

langchain.

chat_models

import

init_chat_model

class

SummaryInfo

(

BaseModel

)

:

   

"""Text summary information."""

    title:

str

=

Field

(

        description

=

"Title"

   

)

    summary:

str

=

Field

(

        description

=

"Brief summary"

   

)

configurable_model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

,

    configurable_fields

=

[

"model"

]

)

structured_model

=

(

    configurable_model.

with_structured_output

(

        SummaryInfo

   

)

)

Use the default Flash

result

=

structured_model.

invoke

(

   

"Please extract the title and summary:"

   

"Python is a simple and easy-to-learn programming language,"

   

"widely used for Web development and data analysis."

)

print

(

result.

model_dump

(

)

)

Switch to Pro at runtime

result

=

structured_model.

invoke

(

   

"Please extract the title and summary:"

   

"LangChain can help developers build AI applications."

,

    config

=

{

       

"configurable"

:

{

           

"model"

:

"deepseek:deepseek-v4-pro"

       

}

   

}

)

print

(

result.

model_dump

(

)

)

Such declarative operations can be combined with configurable models, keeping model selection and output structure relatively independent.

However, when switching providers, you cannot assume all parameters and Schemas can be used as-is. For different models, you should test tool calling and structured output compatibility separately.


XV. Complete Example: Extracting Structured Article Information

Below we use with_structured_output() Create a simple article information extraction program.

Suppose the user inputs an article introducing Python, and the program needs to extract the title, summary, and keywords.

Filename:chat_model_advanced.py

Complete example

File: chat_model_advanced.py

from

dotenv

import

load_dotenv

from

pydantic

import

BaseModel

,

Field

from

langchain.

chat_models

import

init_chat_model

load_dotenv

(

)

Define the article output structure

class

ArticleInfo

(

BaseModel

)

:

   

"""Article information."""

    title:

str

=

Field

(

        description

=

"Article title"

   

)

    summary:

str

=

Field

(

        description

=

"Article summary within 100 characters"

   

)

    keywords:

list

[

str

]

=

Field

(

        description

=

"Article keywords"

   

)

Initialize the model

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

)

Configure structured output

structured_model

=

model.

with_structured_output

(

    ArticleInfo

,

    include_raw

=

True

)

Article to be analyzed

article

=

"""
Python is a general-purpose high-level programming language.

Python's syntax is concise, suitable for beginners to learn.

It is widely used in Web development, data analysis,
artificial intelligence, automation scripts, and other fields.

Python has rich third-party libraries and an active community.
"""

Call the model

try

:

    response

=

structured_model.

invoke

(

       

"Please extract the title, summary, and keywords from the following article."

       

"Do not fabricate facts that do not exist in the original text. \n\n"

        + article

   

)

   

Check whether parsing succeeded

   

if

response

[

"parsing_error"

]

:

       

print

(

           

"Parsing failed:"

,

            response

[

"parsing_error"

]

       

)

   

else

:

        result

=

response

[

"parsed"

]

       

print

(

"Title:"

,

result.

title

)

       

print

(

"Summary:"

,

result.

summary

)

       

print

(

"Keywords:"

,

result.

keywords

)

       

Convert to JSON

       

print

(

"\nJSON:"

)

       

print

(

            result.

model_dump_json

(

indent

=

2

)

       

)

except

Exception

as

error:

   

print

(

       

"Model call failed:"

,

       

type

(

error

)

.name

,

       

str

(

error

)

   

)

If the model parses successfully, the program can generate JSON data like:

{

  "title": "Python 编程语言简介",

  "summary": "Python 语法简洁,应用广泛,拥有丰富的第三方库和活跃的社区。",

  "keywords": [

    "Python",

    "Web开发",

    "数据分析",

    "人工智能",

    "自动化"

  ]

}

This example shows the use of structured output in practical applications.

For example, the extracted results can be used for:


16. Common Questions

1. Why didn't bind_tools() execute the Python function?

Because bind_tools() is only responsible for declaring tools to the model and does not execute them automatically.

The model usually through AIMessage.tool_calls returns a tool call request.

To actually execute the tool, you can write dispatch code yourself, or use LangChain's create_agent()。

2. Why is tool_calls empty?

Possible reasons include:

If you need to improve the accuracy of tool calls, you can refine the tool descriptions and prompts, and check whether the provider supports the relevant Tool Choice parameter.

Note that not all providers support the forced tool call parameter.

3. Why wasn't the Pydantic tool class executed automatically?

Pydantic classes are mainly used to define tool argument structures and do not contain actual execution logic.

If you use model.bind_tools([GetWeather]), the model can generate a tool call named GetWeather but the program still needs to provide the actual query logic.

4. Why does with_structured_output() throw an error?

It may be that the model does not support the current structured output method, or that the data returned by the model cannot be parsed or validated.

Note:

5. Which is better, JSON Schema or Pydantic?

If used mainly in Python, Pydantic is usually more convenient, allowing field access via attributes and providing type validation.

If you need to share data structures across different languages such as Python, JavaScript, and Java, JSON Schema integrates more easily with multiple languages and systems.

The specific choice depends on project requirements.

6. Does structured output guarantee correct content?

No.

Structured output mainly controls the form of the returned data and cannot guarantee that all facts extracted or generated by the model are correct.

For contracts, finance, healthcare, or other high-demand scenarios, necessary data validation and human review should be performed.

7. Why does structured output return a dict instead of a Pydantic object?

The return type depends on the Schema passed in.

In general:

8. Can tools and structured output be used at the same time?

They can be combined in models and Agent frameworks that support the relevant capabilities.

For example, an Agent can query a database first, then organize the results into structured data.

But different model integrations may support different combinations, and you should not assume you can chain arbitrarily bind_tools() and with_structured_output() and always work correctly.

For more complex applications, you can use create_agent() to provide tools, and handle the final output through the Agent's structured response configuration.


Summary

This chapter introduces two advanced features of LangChain Chat Model.

bind_tools() mainly used for tool calling:

model_with_tools = model.bind_tools([

    get_weather

])



response = model_with_tools.invoke(

    "查询杭州天气"

)



print(response.tool_calls)

with_structured_output() mainly used for structured data generation:

structured_model = model.with_structured_output(

    PersonInfo

)



result = structured_model.invoke(

    "张三今年28岁"

)



print(result.name)

Their main differences are:

Once you master these two methods, you will have the foundation to further study LangChain Agents, tool orchestration, data extraction, and AI workflows.