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

LangChain @tool Decorator - Defining Tools

LangChain @tool Decorator - Defining Tools

Tools (Tool) are an important bridge between LangChain Agents and external systems.

Through tools, an Agent can query databases, call APIs, perform calculations, read files, or complete other operations provided by the program.

LangChain provides the @tool decorator, which can quickly convert a Python function into a tool that an Agent can recognize and call.

This chapter introduces @tool basic usage, parameter definitions, Pydantic validation, tool registration, and methods for multiple tools working together.


1. @tool basic syntax

@tool is a tool-definition decorator provided by LangChain.

Simply add the decorator before a regular Python function @tool, and LangChain can create a tool based on the function name, parameter types, and description information.

Basic syntax:

from langchain.tools import tool



@tool

def tool_name(parameter: str) -> str:

    """工具的功能描述。"""

    return "工具执行结果"

Use @tool After that, the function is wrapped as a LangChain tool object.

It is no longer just the original ordinary Python function, but an object with a name, description, parameter Schema, and execution interface.

Example: The first tool

Example

from

langchain.

tools

import

tool

@

tool

def

hello_tool

(

name:

str

)

str

:

   

"""Greet a specified person.

    Args:
        name: the name of the person to greet.
    """

   

return

f

"Hello, {name}! Welcome to Runoob Tutorial RUNOOB."

Call the tool

result

=

hello_tool.

invoke

(

{

   

"name"

:

"Xiao Ming"

}

)

print

(

result

)

View tool information

print

(

"Tool name:"

,

hello_tool.

name

)

print

(

"Tool description:"

,

hello_tool.

description

)

print

(

"Tool arguments:"

,

hello_tool.

args

)

Main content in the execution result:

你好,小明!欢迎来到Runoob Tutorial RUNOOB。



工具名称: hello_tool

You can also use description and args to view the tool's description and parameter structure.

**Note:** regular tool input usually uses invoke():

hello_tool.invoke({"name": "小明"})

Do not call the decorated tool object directly as a raw Python function.

What changes after @tool conversion?

LangChain tools usually have the following attributes and methods:

Attribute or method Description
name Tool name, uses the function name by default
description Tool description, usually from the function docstring
args Schema information of tool parameters
args_schema Parameter validation Schema
invoke() Execute the tool synchronously
ainvoke() Call the tool interface asynchronously

Among these, the tool name, description, and parameter structure help the model understand the tool's purpose.

The execution interface is responsible for actually running the corresponding Python code.


2. Tool descriptions and docstrings

A tool's docstring is very important.

The model needs to determine through the tool description:

For example:

@tool

def get_weather(city: str) -> str:

    """查询指定城市的天气信息。"""

    ...

Although this description is brief, it already clarifies the tool's basic purpose.

If the tool is complex, you can also use Google-style docstrings to describe parameters.

Using parse_docstring

By default,@tool does not automatically parse the parameter information in Google-style docstrings Args into separate parameter descriptions.

If parsing is needed, you can set:

@tool(parse_docstring=True)

Example

Example

from

langchain.

tools

import

tool

@

tool

(

parse_docstring

=

True

)

def

get_course_info

(

    language:

str

,

    level:

str

=

"Beginner"

)

str

:

   

"""Query simulated course information for a specified programming language.

    Args:
        language: the programming language name, e.g., Python, Java.
        level: the difficulty level, defaults to beginner.
    """

   

return

f

"Query the {level} courses of {language}"

print

(

"Tool name:"

)

print

(

get_course_info.

name

)

print

(

"\nTool description:"

)

print

(

get_course_info.

description

)

print

(

"\nParameter Schema:"

)

print

(

get_course_info.

args

)

Here it uses parse_docstring=True, so that LangChain tries to extract parameter descriptions from the docstring.

**Note:** After enabling this option, the docstring should conform to the supported Google style format. If the format is incorrect, an error may be raised ValueError。

For simple tools, using a clear function description and type annotations is usually sufficient; for tools with many parameters, it is recommended to combine parse_docstring Google-style docstrings or Pydantic's Field model fields to provide description information.


3. Using different parameter types

@tool supports generating parameter Schema based on Python type annotations.

Common types include:

Example: Simulated course search

The following defines a course search tool that supports keywords, difficulty, maximum number of results, and whether to show only free courses.

To avoid confusion with real website data, the following course lists are all teaching simulation data.

Example

from

typing

import

Literal

from

langchain.

tools

import

tool

@

tool

(

parse_docstring

=

True

)

def

search_courses

(

   

keyword

:

str

,

    level: Literal

[

"Beginner"

,

"Intermediate"

,

"Advanced"

]

,

    max_results:

int

=

5

,

    free_only:

bool

=

True

)

str

:

   

"""Search the simulated course list.

    Args:
        keyword: search keyword, e.g., Python, HTML.
        level: the course difficulty level.
        max_results: the maximum number of results to return, ranging from 1 to 20.
        free_only: whether to return only free courses.
    """

    courses

=

[

       

{

           

"title"

:

"Python Basics"

,

           

"keyword"

:

"python"

,

           

"level"

:

"Beginner"

,

           

"free"

:

True

       

}

,

       

{

           

"title"

:

"Python beginner exercises"

,

           

"keyword"

:

"python"

,

           

"level"

:

"Beginner"

,

           

"free"

:

True

       

}

,

       

{

           

"title"

:

"Python Data Analysis"

,

           

"keyword"

:

"python"

,

           

"level"

:

"Intermediate"

,

           

"free"

:

True

       

}

,

       

{

           

"title"

:

"Python advanced practice"

,

           

"keyword"

:

"python"

,

           

"level"

:

"Advanced"

,

           

"free"

:

False

       

}

,

       

{

           

"title"

:

"HTML basics"

,

           

"keyword"

:

"html"

,

           

"level"

:

"Beginner"

,

           

"free"

:

True

       

}

   

]

   

if

not

1

<=

max_results

<=

20

:

       

return

"max_results must be between 1 and 20"

    results

=

[

]

   

for

course

in

courses:

       

if

keyword

.

lower

(

)

not

in

course

[

"keyword"

]

:

           

continue

       

if

course

[

"level"

]

!=

level:

           

continue

       

if

free_only

and

not

course

[

"free"

]

:

           

continue

        results.

append

(

course

[

"title"

]

)

    results

=

results

[

:max_results

]

   

if

not

results:

       

return

"No matching simulated courses found"

   

return

"Search results:"

"、"

.

join

(

results

)

Query beginner courses

print

(

search_courses.

invoke

(

{

   

"keyword"

:

"python"

,

   

"level"

:

"Beginner"

}

)

)

Query advanced courses, including paid items

print

(

search_courses.

invoke

(

{

   

"keyword"

:

"python"

,

   

"level"

:

"Advanced"

,

   

"free_only"

:

False

}

)

)

Execution result:

搜索结果:Python 基础、Python 入门练习

搜索结果:Python 高级实战

Where:

The above search is performed only on the Python list and does not connect to any real website or database.


4. Registering tools to an Agent

After a tool is defined, it can be registered to an Agent through the create_agent() 's tools tools parameter.

For example, a learning advisor Agent can have two tools:

Example: Creating a course recommendation Agent

Example

from

dotenv

import

load_dotenv

from

langchain.

tools

import

tool

from

langchain.

agents

import

create_agent

from

langchain.

chat_models

import

init_chat_model

load_dotenv

(

)

Simulated course database

COURSES

=

{

   

"Python3 Basic Tutorial"

:

{

       

"language"

:

"python"

,

       

"chapters"

:

30

,

       

"hours"

:

20

   

}

,

   

"Python Data Analysis"

:

{

       

"language"

:

"python"

,

       

"chapters"

:

18

,

       

"hours"

:

15

   

}

,

   

"HTML Basics Tutorial"

:

{

       

"language"

:

"html"

,

       

"chapters"

:

25

,

       

"hours"

:

12

   

}

}

@

tool

def

search_courses

(

keyword

:

str

)

str

:

   

"""Search simulated courses by programming language keyword."""

    results

=

[

        name

       

for

name

,

info

in

COURSES.

items

(

)

       

if

keyword

.

lower

(

)

in

info

[

"language"

]

   

]

   

if

not

results:

       

return

"No relevant simulated courses found"

   

return

"、"

.

join

(

results

)

@

tool

def

get_course_detail

(

course_name:

str

)

str

:

   

"""Get the number of chapters and estimated study time for a specified simulated course."""

    info

=

COURSES.

get

(

course_name

)

   

if

info

is

None

:

       

return

f

"Course not found: {course_name}"

   

return

(

        f

"Course: {course_name};"

        f

"Number of chapters: {info['chapters']};"

        f

"Estimated study time: {info['hours']} hours"

   

)

Initialize the model

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

)

Creating the Agent

agent

=

create_agent

(

    model

=

model

,

    tools

=

[

        search_courses

,

        get_course_detail

   

]

,

    system_prompt

=

(

       

"You are a programming learning advisor."

       

"The course data in the tools is teaching simulation data."

       

"Prefer using tools when querying courses."

       

"If no course is found, state it clearly,"

       

"do not fabricate course information."

   

)

)

Calling the Agent

def

ask

(

question:

str

)

:

    result

=

agent.

invoke

(

{

       

"messages"

:

[

           

{

               

"role"

:

"user"

,

               

"content"

: question

           

}

       

]

   

}

)

   

print

(

"Question:"

,

question

)

   

print

(

"Answer:"

,

result

[

"messages"

]

[

1

]

.

content

)

   

print

(

"-"

40

)

ask

(

"What Python mock courses are available?"

)

ask

(

"How long does it take to study the Python3 Basic Tutorial?"

)

At runtime, the Agent can select the appropriate tool based on the question.

For example, when querying a course list, the model may call:

search_courses(keyword="python")

when querying course details, it may call:

get_course_detail(

    course_name="Python3 基础教程"

)

After the tool returns a result, the Agent calls the model again to generate an answer.

**Note:** Tool selection is not fixed. The model may call one tool, multiple tools, or answer directly.

If a tool must be executed, it should be explicitly controlled through a program flow or workflow, rather than relying solely on prompts.


5. Multiple tools working together

An Agent can combine different tools to complete tasks.

For example, a user wants to know the simulated price of a stock and convert the amount into RMB.

This process may involve:

  1. Call a stock price query tool.
  2. Get the stock price.
  3. Call a currency conversion tool.
  4. Generate the final answer.

The following still uses simulated data to demonstrate how multiple tools work together.

Example: Simulated stock price and currency conversion

Example

from

langchain.

tools

import

tool

from

langchain.

agents

import

create_agent

from

langchain.

chat_models

import

init_chat_model

@

tool

def

get_stock_price

(

symbol

:

str

)

str

:

   

"""Query the simulated USD price of a specified stock.

    Args:
        symbol: the stock symbol, e.g., AAPL, GOOGL.
    """

    prices

=

{

       

"AAPL"

:

185.50

,

       

"GOOGL"

:

142.30

,

       

"TSLA"

:

245.80

   

}

    price

=

prices.

get

(

symbol

.

upper

(

)

)

   

if

price

is

None

:

       

return

"No simulated price found for this stock"

   

return

(

        f

"The simulated price of {symbol.upper()} is "

        f

"{price:.2f} USD"

   

)

@

tool

def

convert_currency

(

    amount:

float

,

    from_currency:

str

,

    to_currency:

str

)

str

:

   

"""Convert a currency amount based on a fixed simulated exchange rate."""

   

Simulated exchange rate for teaching

    rates

=

{

       

(

"USD"

,

"CNY"

)

:

7.25

   

}

    source

=

from_currency.

upper

(

)

    target

=

to_currency.

upper

(

)

   

if

source

==

target:

       

return

f

"{amount:.2f} {target}"

    rate

=

rates.

get

(

(

source

,

target

)

)

   

if

rate

is

None

:

       

return

"The specified simulated currency conversion is not supported"

    result

=

amount * rate

   

return

(

        f

"{amount:.2f} {source} "

        f

"= {result:.2f} {target}"

        f

"(simulated rate {rate})"

   

)

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

)

agent

=

create_agent

(

    model

=

model

,

    tools

=

[

        get_stock_price

,

        convert_currency

   

]

,

    system_prompt

=

(

       

"You are a financial data demonstration assistant."

       

"Stock prices and exchange rates are all simulated data,"

       

"and cannot be treated as real-time market quotes."

       

"If you need to calculate the conversion result, please call the tool."

   

)

)

result

=

agent.

invoke

(

{

   

"messages"

:

[

       

{

           

"role"

:

"user"

,

           

"content"

:

(

               

"Query the simulated price of AAPL,"

               

"and convert it into RMB based on the simulated exchange rate."

           

)

       

}

   

]

}

)

View tool execution result

for

message

in

result

[

"messages"

]

:

   

if

message.

type

==

"tool"

:

       

print

(

            f

"[Tool {message.name}] "

            f

"{message.content}"

       

)

print

(

"\nFinal answer:"

)

print

(

result

[

"messages"

]

[

1

]

.

content

)

If the Agent calls the two tools in sequence, the result may be:

[工具 get_stock_price] AAPL 的模拟价格为 185.50 USD

[工具 convert_currency] 185.50 USD = 1344.88 CNY(模拟汇率 7.25)

The prices and exchange rates here are fixed teaching data and do not represent real market conditions.

**Note:** The model may first get the price and then call the conversion tool based on the returned value, or it may take other paths. Do not treat the number and order of tool calls in the example as a fixed result.


6. Optional parameters and default values of tools

Python functions can set default values for parameters, and LangChain tools support this as well.

Parameters without default values are usually required; parameters with default values can usually be omitted.

Example

Example

from

langchain.

tools

import

tool

@

tool

def

recommend_tutorial

(

    language:

str

,

    level:

str

=

"Beginner"

,

    count:

int

=

3

)

str

:

   

"""Recommend learning content from the simulated tutorial list.

    Args:
        language: the programming language.
        level: the learning level.
        count: the maximum number of recommendations.
    """

    tutorials

=

{

       

"python"

:

[

           

"Python Basics"

,

           

"Python object-oriented"

,

           

"Python Data Analysis"

,

           

"Python automation"

       

]

,

       

"java"

:

[

           

"Java basics"

,

           

"Java Object-Oriented"

,

           

"Java collection framework"

,

           

"Java multithreading"

       

]

   

}

   

if

not

1

<=

count

<=

10

:

       

return

"count must be between 1 and 10"

    available

=

tutorials.

get

(

        language.

lower

(

)

,

       

[

]

   

)

   

if

not

available:

       

return

"No relevant tutorials"

    selected

=

available

[

:count

]

   

return

(

        f

"Recommendations for {language} ({level}):"

        +

"、"

.

join

(

selected

)

   

)

Provide only required parameters

print

(

recommend_tutorial.

invoke

(

{

   

"language"

:

"Python"

}

)

)

Override optional parameters

print

(

recommend_tutorial.

invoke

(

{

   

"language"

:

"Java"

,

   

"level"

:

"Intermediate"

,

   

"count"

:

2

}

)

)

Possible output:

Python(入门)推荐:Python 基础、Python 面向对象、Python 数据分析

Java(进阶)推荐:Java 基础、Java 面向对象

Here, level It is only used to mark the requested learning level and does not actually filter course difficulty.

In actual projects, if recommendations need to be made precisely by course difficulty, a corresponding difficulty field should be defined in the data and filtering performed.

Default parameters can reduce the fields that need to be passed during tool calls, but default values should not be set arbitrarily for key parameters such as user identity, permissions, or payment amounts.


7. args_schema: Using Pydantic to validate parameters

For tools with many parameters that require strict input validation, you can args_schema specify a Pydantic model.

For example, you can restrict:

Example: Custom search parameters

Example

from

pydantic

import

BaseModel

,

Field

from

typing

import

Literal

from

langchain.

tools

import

tool

class

CourseSearchInput

(

BaseModel

)

:

   

"""Course search parameters."""

   

keyword

:

str

=

Field

(

        min_length

=

1

,

        max_length

=

50

,

        description

=

"Search keyword"

   

)

    category: Literal

[

       

"all"

,

       

"frontend"

,

       

"backend"

,

       

"data"

   

]

=

Field

(

        default

=

"all"

,

        description

=

"Course category"

   

)

    page:

int

=

Field

(

        default

=

1

,

        ge

=

1

,

        le

=

100

,

        description

=

"Page number, starting from 1"

   

)

@

tool

(

args_schema

=

CourseSearchInput

)

def

search_course

(

   

keyword

:

str

,

    category:

str

=

"all"

,

    page:

int

=

1

)

str

:

   

"""Search simulated course data."""

   

return

(

        f

"Search keyword: {keyword};"

        f

"Category: {category};"

        f

"Page number: {page}"

   

)

Normal call

print

(

search_course.

invoke

(

{

   

"keyword"

:

"Python"

,

   

"category"

:

"backend"

,

   

"page"

:

1

}

)

)

Parameters do not conform to the Schema

try

:

    search_course.

invoke

(

{

       

"keyword"

:

"Python"

,

       

"category"

:

"invalid"

   

}

)

except

Exception

as

error:

   

print

(

       

"Parameter validation failed:"

,

       

type

(

error

)

.name

   

)

Normal call returns:

搜索关键词:Python;分类:backend;页码:1

In the second call,category="invalid" is not in the allowed list of values, triggering a parameter validation error.

This can intercept some inputs that do not meet the requirements before the tool function is executed.

**Note:** Even with Pydantic validation, it cannot replace security measures such as business permission checks, SQL parameterized queries, and file path restrictions.

View JSON Schema

You can learn what parameters a tool accepts through its parameter Schema.

print(search_course.args)

If you use a Pydantic model, you can also directly obtain its JSON Schema:

print(

    CourseSearchInput.model_json_schema()

)

This is very helpful for tool debugging, front-end parameter form generation, and API documentation writing.


8. Other common parameters of @tool

Besides args_schemaIn addition, LangChain's @tool @tool also supports multiple optional parameters.

Parameters Default value Description
description None Explicitly specify the tool description, with higher priority than the function docstring
args_schema None Specify the Schema of tool input parameters
infer_schema True Whether to infer the parameter Schema from the function signature
parse_docstring False Whether to parse Google-style parameter descriptions
return_direct False Configure whether the tool result can be directly used as the Agent's final output, depending on the execution framework
response_format content Specify that the tool returns regular content, or a combination of content and artifact

The behavior of these options should be understood in the context of the current LangChain version and the Agent execution framework being used.

Specify a custom name and description

You can directly specify the tool name and description through the decorator.

Example

from

langchain.

tools

import

tool

@

tool

(

   

"search_python_docs"

,

    description

=

"Query Python-related knowledge in local simulated documents"

)

def

search_docs

(

keyword

:

str

)

str

:

   

"""Find documents by keyword."""

   

return

f

"Simulated search: {keyword}"

print

(

search_docs.

name

)

print

(

search_docs.

description

)

The actual Python function name here is search_docs, but the tool name exposed to the model is search_python_docs。

The return_direct parameter

For some scenarios, the tool execution result does not need to be organized by the model and can be returned directly as the result.

You can set:

@tool(return_direct=True)

def get_help(topic: str) -> str:

    """获取帮助内容。"""

    return f"帮助主题:{topic}"

return_direct=True It is mainly used to tell the Agent execution framework that supports this mechanism: the result can be returned directly after the tool call is completed.

**Note:** If you only manually call tool.invoke(), this parameter does not change the return value of the Python function itself. Different Agent frameworks may also handle it differently.


9. Tool return content and artifact

Sometimes a tool needs to return two types of information:

You can use the response_format="content_and_artifact"。

Example

Example

from

langchain.

tools

import

tool

@

tool

(

response_format

=

"content_and_artifact"

)

def

search_documents

(

keyword

:

str

)

:

   

"""Query simulated documents and return a summary and complete records."""

    records

=

[

       

{

           

"id"

:

1

,

           

"title"

:

"Python Basics Tutorial"

       

}

,

       

{

           

"id"

:

2

,

           

"title"

:

"Python Data Analysis"

       

}

   

]

    content

=

(

        f

"Found records related to {keyword} "

        f

"{len(records)} simulated records"

   

)

    artifact

=

{

       

"keyword"

:

keyword

,

       

"records"

: records

   

}

   

return

content

,

artifact

Execute directly to view the tool's return value

result

=

search_documents.

invoke

(

{

   

"keyword"

:

"Python"

}

)

print

(

result

)

When a tool is executed as an Agent Tool Call and has a corresponding tool call ID, LangChain can place the content and artifact separately into ToolMessage.content and ToolMessage.artifact。

Wherecontent for the model to read;artifact can save the complete structured data.

**Note:** The encapsulation form of the return value may differ when a tool is called directly versus executed via a Tool Call with an ID. Do not assume that a direct call invoke() necessarily returns a ToolMessage with an artifact attribute.


10. Synchronous tools and asynchronous tools

LangChain tools also support asynchronous calls.

For example, when a tool needs to access a network API, you can use an asynchronous function to reduce thread occupancy during waiting.

Example: Asynchronous tool

Example

import

asyncio

from

langchain.

tools

import

tool

@

tool

async

def

async_search

(

keyword

:

str

)

str

:

   

"""Perform an asynchronous simulated search."""

   

Simulate asynchronous wait

    await asyncio.

sleep

(

0.1

)

   

return

f

"Asynchronous search result: {keyword}"

async

def

main

(

)

:

    result

=

await async_search.

ainvoke

(

{

       

"keyword"

:

"Python"

   

}

)

   

print

(

result

)

if

name

==

"main"

:

    asyncio.

run

(

main

(

)

)

Execution result:

异步搜索结果:Python

For I/O-intensive tasks such as network requests and database queries, asynchronous tools are usually more suitable for use with asynchronous Agents or web services.

Note that using async def does not automatically make blocking code non-blocking. Actual network requests still need to use the corresponding asynchronous client.


11. Error handling in tool calls

Exceptions may occur during tool execution, for example:

Recoverable business errors can be converted into tool return results as needed, making it easier for the Agent to continue processing.

Example

Example

from

langchain.

tools

import

tool

@

tool

def

get_course_detail

(

course_name:

str

)

str

:

   

"""Get detailed information about a specified simulated course."""

    courses

=

{

       

"Python Basics"

:

"Suitable for beginners"

,

       

"Java basics"

:

"Introduces basic Java syntax"

   

}

   

if

course_name

not

in

courses:

       

return

(

            f

"Course not found: {course_name}."

           

"Please check the name or search again."

       

)

   

return

courses

[

course_name

]

print

(

get_course_detail.

invoke

(

{

   

"course_name"

:

"Nonexistent course"

}

)

)

Execution result:

未找到课程:不存在的课程。请检查名称或重新搜索。

Here, a clear return message tells the Agent that the course does not exist.

For genuine program exceptions, you can also use LangChain's tool error-handling mechanisms, such as ToolException and the corresponding error-handling configurations.

In production environments, do not expose sensitive information such as database passwords, internal server paths, or complete exception stack traces to the model or users.


12. Comparison of tool definition methods

LangChain can declare tools to the model in multiple ways, but it is necessary to distinguish betweenexecutable toolsandtool Schemas used only to describe interfaces。

Definition Feature Applicable scenarios
@tool Generate an executable tool from a Python function Regular Agent tools
@tool(args_schema=...) Adds fine-grained parameter descriptions and validation Complex parameters, business tools
StructuredTool Explicitly create a tool object that supports multiple parameters Need more flexible control over synchronous or asynchronous execution logic
Pydantic model class Mainly used to define tool parameter structure With the model's bind_tools() together with
JSON Schema / dictionary Directly describes the tool name and parameter protocol Existing tool Schema, compatible interface

**Note:** Passing a Pydantic class or tool Schema to model.bind_tools()does not mean it contains actual execution logic.

If you want the Agent to automatically execute Python tools, it is usually recommended to use @tool to create a tool object, then pass it to create_agent()。


13. Complete example: Simulated course query assistant

The following combines tool definition, parameter validation, model initialization, and Agent invocation into a complete example.

Filename:langchain_tools_demo.py

First install the dependencies:

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

The file in the project directory .env needs to contain:

DEEPSEEK_API_KEY=your_deepseek_api_key

Complete example

from

typing

import

Literal

from

dotenv

import

load_dotenv

from

pydantic

import

BaseModel

,

Field

from

langchain.

tools

import

tool

from

langchain.

agents

import

create_agent

from

langchain.

chat_models

import

init_chat_model

load_dotenv

(

)

Mock Course Data

COURSES

=

[

   

{

       

"name"

:

"Python Basics"

,

       

"language"

:

"python"

,

       

"level"

:

"Beginner"

   

}

,

   

{

       

"name"

:

"Python Data Analysis"

,

       

"language"

:

"python"

,

       

"level"

:

"Intermediate"

   

}

,

   

{

       

"name"

:

"Java basics"

,

       

"language"

:

"java"

,

       

"level"

:

"Beginner"

   

}

]

class

SearchInput

(

BaseModel

)

:

   

"""Course search parameters."""

    language:

str

=

Field

(

        min_length

=

1

,

        description

=

"Programming language, e.g., python, java"

   

)

    level: Literal

[

"Beginner"

,

"Intermediate"

]

=

Field

(

        default

=

"Beginner"

,

        description

=

"Learning difficulty"

   

)

@

tool

(

args_schema

=

SearchInput

)

def

search_courses

(

    language:

str

,

    level:

str

=

"Beginner"

)

str

:

   

"""Search simulated courses by programming language and difficulty."""

    results

=

[

        course

[

"name"

]

       

for

course

in

COURSES

       

if

course

[

"language"

]

==

language.

lower

(

)

       

and

course

[

"level"

]

==

level

   

]

   

if

not

results:

       

return

"No matching simulated courses found"

   

return

"、"

.

join

(

results

)

@

tool

def

count_courses

(

language:

str

)

str

:

   

"""Count the number of simulated courses for a specified programming language."""

    total

=

sum

(

       

1

       

for

course

in

COURSES

       

if

course

[

"language"

]

==

language.

lower

(

)

   

)

   

return

f

"There are {total} simulated courses in {language}"

Initialize the model

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

)

Creating the Agent

agent

=

create_agent

(

    model

=

model

,

    tools

=

[

        search_courses

,

        count_courses

   

]

,

    system_prompt

=

(

       

"You are a programming learning advisor."

       

"All current tools use simulated course data."

       

"Prefer using tools when querying courses."

       

"State clearly when no data is found."

       

"Do not fabricate course names or statistical results."

   

)

)

def

ask

(

question:

str

)

:

    result

=

agent.

invoke

(

{

       

"messages"

:

[

           

{

               

"role"

:

"user"

,

               

"content"

: question

           

}

       

]

   

}

)

   

print

(

"\nQuestion:"

,

question

)

   

Output the tool call process

   

for

message

in

result

[

"messages"

]

:

       

if

message.

type

==

"ai"

and

message.

tool_calls

:

           

for

call

in

message.

tool_calls

:

               

print

(

                   

"[Tool request]"

,

                    call

[

"name"

]

,

                    call

[

"args"

]

               

)

       

elif

message.

type

==

"tool"

:

           

print

(

               

"[Tool result]"

,

                message.

name

,

                message.

content

           

)

   

print

(

       

"Final answer: "

,

        result

[

"messages"

]

[

1

]

.

content

   

)

if

name

==

"main"

:

    ask

(

"What Python beginner simulated courses are there?"

)

    ask

(

"How many simulated courses are there in Python in total?"

)

Run:

python langchain_tools_demo.py

The program displays the tool calls initiated by the model, the tool execution results, and the Agent's final answer.

Since the tool call path is determined by the model, the actual execution log may vary slightly.

But when the simulated tools are used correctly, you can query:

Python 入门模拟课程:Python 基础



Python 模拟课程总数:2

These results come from the simulated courses in the program COURSES list, not real-time website data.


14. Frequently Asked Questions

1. Does the @tool decorator execute the function immediately?

No.

@tool is responsible for creating the tool object; only when calling invoke()、ainvoke(), or when the Agent executes the corresponding tool call, is the underlying logic run.

2. Why was the tool not called by the Agent?

It may be because the model thinks the tool is unnecessary, or the tool description is not clear enough.

You should also confirm that the model supports Tool Calling and that the tool has been correctly passed to create_agent()。

If a business step must be executed, it should be explicitly orchestrated in the program and should not rely solely on the model's autonomous choice.

3. Why does @tool report a missing docstring?

By default, if no description is explicitly provided, the tool needs to obtain description information from the function docstring.

For example:

@tool

def hello(name: str) -> str:

    """向指定用户打招呼。"""

    return f"你好,{name}"

You can also use the decorator's description parameter to explicitly specify the description.

4. How to modify the tool name?

You can use:

@tool("custom_tool_name")

def my_function(value: str) -> str:

    """工具描述。"""

    return value

Then the tool name will use custom_tool_name。

5. Is args_schema mandatory?

No.

For functions with simple parameters, LangChain can usually automatically generate the Schema from type annotations.

If fine-grained validation such as field value ranges and string lengths is needed, you can use a Pydantic model.

6. Can a Pydantic class be passed directly to the Agent?

A Pydantic class that only describes parameters should not be treated as a tool containing execution logic.

In model tool-binding scenarios, a Pydantic class can describe the Tool Calling Schema; but in Agent automatic-execution scenarios, an executable tool object is usually required.

7. Is a tool safe after parameter validation?

No.

Pydantic can check data types and some value constraints, but it cannot replace permission control, network access restrictions, database parameterized queries, and confirmation of sensitive operations.

For tools with the ability to delete files, make payments, or write to databases, security controls also need to be added at the application layer.

8. How to view a tool's parameter definitions?

You can use:

print(my_tool.args)

You can also view:

print(my_tool.name)

print(my_tool.description)

For parameters defined using Pydantic, you can model_json_schema() view the complete JSON Schema.

9. Can multiple tools be called in parallel?

If the model generates multiple tool call requests in the same turn, the Agent's tool execution node may process independent tools concurrently.

But whether concurrency actually happens depends on the model, the tool implementation, and the execution framework.

If there are dependencies between tools, you should explicitly control the execution order.

10. Must tool return values be strings?

Not necessarily.

Tools can return other supported data types, and LangChain will convert or wrap them according to the execution mode.

In Agent scenarios, it is recommended to keep the results provided to the model concise and clear, and to avoid returning large amounts of unnecessary data.


Summary

@tool is a common way to define tools in LangChain.

It can convert a Python function into a tool object with a name, description, parameter Schema, and execution interface.

This chapter focuses on:

For most projects, you can start with the following basic approach:

from langchain.tools import tool



@tool

def search(keyword: str) -> str:

    """根据关键词执行搜索。"""

    return f"搜索结果:{keyword}"

Then use:

agent = create_agent(

    model=model,

    tools=[search]

)

to hand the tools to the Agent.

Remember:The model decides when to request a tool, LangChain handles scheduling, and the tool function actually performs the task.