【总结】LangChain中工具的使用

目录

1.通过装饰器定义工具

2.通过装饰器定义工具名称

3.通过装饰器定义工具描述

4.对参数进行约束

5.使用LangChain里的预定义的工具

[6. 优化预定义工具](#6. 优化预定义工具)


1.通过装饰器定义工具

python 复制代码
@tool
def get_wheather(location: str) -> str:
    """
    Get the weather in a given location.
    Args:
        location: city name or coordinates
    """
    return "the current weather in {} is sunny".format(location)

注释很重要,必须要,不然agent不知道这个工具是干什么的


2.通过装饰器定义工具名称

python 复制代码
@tool("square_root")
def square_root(x: float) -> float:
    """计算平方根"""
    if x < 0:
        raise ValueError("不能计算负数的平方根")
    x = float(x)
    return x ** 0.5

通过这种方式的话,函数的名字就可以随意了


3.通过装饰器定义工具描述

python 复制代码
@tool("square_root", description="Calculate the square root of a number")
def tool1(x: float) -> float:
    return x ** 0.5

定义描述之后,函数中的注释就可以不用写了


4.对参数进行约束

定义类:

python 复制代码
class wheather_input(BaseModel):
    location: str = Field(..., description="City name or coordinates")
    units: Literal["celsius", "fahrenheit"] = Field("celsius", description="Temperature units")
    include_forecast: bool = Field(False, description="Whether to include a 5-day forecast")

在工具的装饰器中通过args_schema约束

python 复制代码
@tool(args_schema=wheather_input)
def get_weather_info(location: str, units: str, include_forecast: bool) -> str:
    """
    Get weather information for a given location.
    """
    if units == "celsius":
        temp = 22
    else:
        temp = 72
    result = f"Current weather in {location}: {temp} degrees {units[0].upper()}"
    if include_forecast:
        result += "\n5-day forecast: Sunny, Sunny, Sunny, Sunny, Sunny"
    return result

这样就对进入函数的参数进行了约束


5.使用LangChain里的预定义的工具

=> TavilySearch

python 复制代码
# 初始化工具,并设置参数,具体参数设置参考官网
tool = TavilySearch(
    max_results=5,
    topic="general",
    # include_answer=False,
    # include_raw_content=False,
    # include_images=False,
    # include_image_descriptions=False,
    # search_depth="basic",
    # time_range="day",
    # include_domains=None,
    # exclude_domains=None
)
python 复制代码
agent = create_agent(
    model="deepseek-chat",
    tools=[tool],
    system_prompt="你是一个智能助手,你使用工具来解决用户问题。",
)
response = agent.stream({
    "messages": [
        HumanMessage(content="南京今天天气如何?")
    ]
}, stream_mode="messages")

for token, metadata in response:
    if token.content:
        print(token.content, end="", flush=True)

直接用就可以,但是通过这种方式返回的内容很多,会消耗很多token, 我们一般会对这个进行优化


6. 优化预定义工具

python 复制代码
# LangChain提供的TavilySearch工具描述非常复杂,参数也很多。会有额外的网络消耗。
# 如果我们仅仅是需要query参数,建议自定义工具。
python 复制代码
# 使用tavily作为web搜索工具
tavily = TavilySearch(
    max_results=5,
    topic="general"
)
python 复制代码
@tool
def web_search(query: str):
    """Search the web for information"""
    return tavily.invoke(query)
python 复制代码
# Agent回答内容引用的网页信息
class Reference(BaseModel):
    title: str = Field(description="The title of the web page cited in the answer")
    url: str = Field(description="The url of the web page cited in the answer")

# Agent的回答内容
class AnswerInfo (BaseModel):
    answer: str = Field(description="The final answer for user")
    reference: list[Reference] = Field(description="The web pages cited in the answer")

agent = create_agent(
    model="deepseek-chat",
    tools=[web_search],
    system_prompt="你是一个智能助手,你使用工具来解决用户问题。",
    response_format=AnswerInfo
)

response = agent.invoke(
    {"messages": [HumanMessage(content="我要验牌是什么梗?")]},
)

print(response['structured_response'])
相关推荐
vx-程序开发1 天前
基于机器学习的动漫可视化系统的设计与实现-计算机毕业设计源码08339
java·c++·spring boot·python·spring·django·php
爱睡懒觉的焦糖玛奇朵1 天前
【从视频到数据集:焦糖玛奇朵的魔法工具Video To YOLO Dataset】
人工智能·python·学习·yolo·音视频
明月_清风1 天前
从零到一构建生产级 AI Agent:架构拆解 × Python 高并发实战 × 技术选型方法论
后端·agent
石榴树下的七彩鱼1 天前
医疗票据 OCR 识别 API 多场景落地指南:医保结算 + 商保理赔 + 医疗信息化(附 Python/Java 完整示例)
java·python·ocr·石榴智能·医疗票据ocr·医保结算·ocrapi
打小就很皮...1 天前
基于 Python + LangChain + React 的 AI 流式对话与历史存储实战
人工智能·langchain·flask·react·sse
idingzhi1 天前
A股量化策略日报(2026年05月22日)
android·开发语言·python·kotlin
太华1 天前
学习AI Agent编程-第一天-MCP基础
agent
song5011 天前
多卡训练加速:HCCL 集合通信实战
分布式·python·flutter·ci/cd·分类
江上清风山间明月1 天前
如何将python开发的window应用打包成exe
开发语言·python·exe·打包
知识分享小能手1 天前
Flask入门学习教程,从入门到精通, Flask模板 — 完整知识点与案例代码 (2)
python·学习·flask