LangChain 入门 Tools 工具

目录

模型(Model)是Agent的大脑,负责推理分析。而工具(Tools)则是Agent的手脚,负责执行任务,与外界交互。

一个完整的 Agent 至少要包含两个关键的部分:

  • 模型: 是 Agent 的大脑,负责推理、分析、规划任务步骤
  • 工具: 是 Agent 的手脚,负责执行任务,与外界交互

因此,定义带有工具的 Agent 的基本流程如下:

  • 定义工具
  • 初始化模型
  • 初始化 Agent,绑定模型和工具

LangChain 入门 Agent 的基本运行机制

定义工具

所谓的工具(Tools),本质就是一个可调用的函数,但是这个函数不是我们自己去调用,而是给模型调用。因此除了定义函数外,我们还需要清晰描述这个工具,让模型知道这个工具如何使用。包括下列信息:

  • 工具名
  • 工具的作用
  • 工具需要的参数

基于 Tool 描述工具【不推荐】

在 LangChain 中定义工具需要用到 @tool 装饰器,我们可以通过装饰器来定义工具名、工具的作用:

python 复制代码
from langchain_core.tools import tool

@tool("square_root",descritpin="计算值平方根")
def square(x: float) -> float:
    return x ** 0.5

使用函数名和文档注释描述工具【推荐】

如果不@tool装饰器,没有定义工具名和作用描述,此时:

  • 工具名:默认就是函数名
  • 工具所需参数:默认就是函数的参数列表
  • 工具作用的描述:默认就是函数的文档注释
python 复制代码
from langchain_core.tools import tool

@tool
def square_root(x: float) -> float:
    """计算值平方根"""
    return x ** 0.5

多参数

python 复制代码
from langchain_core.tools import tool

@tool
def get_weather(location:str, units: str = "celsius", include_forecast: bool = False) -> str:
    """
    Get current weather and optional forecast.
    Args:
        location: city name or coordinates
        units: unit of degress
        include_forecast:dose it include the weather forecast
    """
    temp = 22 if units == "celsius" else 72
    result = f"Current weather in {location}:{temp} degrees {units[0].upper{}}"
    if include_forecast:
        result += "\Next 5 days: Sunny"
    return result

定义 Pydantic Model 描述参数

如果参数多了以后,上面的描述不太方便

如果函数的参数比较多,而且比较复杂,此时建议通过 pydantic model 来描述参数列表。

python 复制代码
# 通过自定义 model 来约束入参
from pydantic import BaseModel, Field
from typing import Literal

# 例如一个查询天气的 tool
class WeatherInput(BaseModel):
    """查询天气的输入参数"""
    location: str = Field(description="City name or coordinates")
    units: Literal["celsius","fahrenheit"] = Field(
        default="celsius",
        description="Temperature unit preference"
    )
    include_forecast: bool = Field(
        default=False,
        description="Include 5-day forecast"
    )

@tool(args_schema=WeatherInput)
def get_weather(location:str, units: str = "celsius", include_forecast: bool = False) -> str:
    """
    Get current weather and optional forecast
    """
    temp = 22 if units == "celsius" else 72
    result = f"Current weather in {location}:{temp} degrees {units[0].upper()}"
    if include_forecast:
        result += "\nNext 5 days: Sunny"
    return result

工具调用方法

python 复制代码
square_root.invoke({"x":467})

get_weather.invoke({"location":"杭州","include_forecast":False})

完整代码

python 复制代码
from langchain.agents import create_agent
from langchain.chat_models import init_chat_model
from langchain.tools import tool
from dotenv import load_dotenv
import os
from pydantic import BaseModel, Field
from typing import Literal
from langchain_core.messages import SystemMessage, HumanMessage, AIMessage

# 加载环境变更值
load_dotenv()



# 例如一个查询天气的 tool
class WeatherInput(BaseModel):
    """查询天气的输入参数"""
    location: str = Field(description="City name or coordinates")
    units: Literal["celsius","fahrenheit"] = Field(
        default="celsius",
        description="Temperature unit preference"
    )
    include_forecast: bool = Field(
        default=False,
        description="Include 5-day forecast"
    )

@tool(args_schema=WeatherInput)
def get_weather(location:str, units: str = "celsius", include_forecast: bool = False) -> str:
    """
    Get current weather and optional forecast
    """
    temp = 22 if units == "celsius" else 72
    result = f"Current weather in {location}:{temp} degrees {units[0].upper()}"
    if include_forecast:
        result += "\nNext 5 days: Sunny"
    return result

@tool
def square_root(x: float) -> float:
    """计算值平方根"""
    return x ** 0.5

# 获取环境变更值
base_url = os.getenv("DASHSCOPE_BASE_URL")
api_key = os.getenv("DASHSCOPE_API_KEY")

print("初始化模型")
# 初始化模型
model = init_chat_model(
    model = "qwen3.6-plus",
    model_provider="openai", # 指定模型提供者(阿里兼容 openai)
    base_url = base_url,
    api_key = api_key,
    temperature = 1.5,
    top_p = 0.9,
)


# 创建 agent
agent = create_agent(
    model=model,  # 不需要加 "openai:" 前缀
    tools=[get_weather,square_root],
)

# 测试 get_weather 工具
messages = agent.stream(
    {"messages": [HumanMessage(content="苏州接下来几天的天气如何?")]}, # 模型会根据用户的输入进行智能选择工具
    stream_mode="messages"
)

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

# 测试 square_root 工具
response = agent.invoke(
    {"messages": [HumanMessage(content="467和529的平方根是多少?")]} # 模型会根据用户的输入进行智能选择工具
)

for message in response['messages']:
    print(message.pretty_print())

返回内容

复制代码
D:\OpenSource\Python\VipLangChain\.venv\Scripts\python.exe D:\OpenSource\Python\VipLangChain\tools.py 
初始化模型
Current weather in 苏州:22 degrees C
Next 5 days: SunnyCurrent weather in 苏州:22 degrees C
Next 5 days: Sunny根据最新天气预报,苏州目前的气温是 **22°C**。接下来的5天天气预报均为**晴天**。================================ Human Message =================================

467和529的平方根是多少?
None
================================== Ai Message ==================================
Tool Calls:
  square_root (call_c92492e390ef49f382c2f270)
 Call ID: call_c92492e390ef49f382c2f270
  Args:
    x: 467
  square_root (call_6cb8193b9bc9400ba9c5f239)
 Call ID: call_6cb8193b9bc9400ba9c5f239
  Args:
    x: 529
None
================================= Tool Message =================================
Name: square_root

21.61018278497431
None
================================= Tool Message =================================
Name: square_root

23.0
None
================================== Ai Message ==================================

467的平方根约为 **21.61**(精确值约 21.61018)
529的平方根正好是 **23**
None

Process finished with exit code 0
相关推荐
wuhen_n2 小时前
RAG 第一步:多格式文档加载与文本预处理实战
前端·langchain·ai编程
Irissgwe5 小时前
十、LangGraph能力详解:工作流的常见模式
python·langchain·ai编程·工作流·langgraph
雪碧聊技术6 小时前
LangChain实战:AI私厨管家—需求分析、代码实现
langchain
Irissgwe7 小时前
十、LangGraph能力详解:LangGraph 的其他特性
python·ai·langchain·langgraph
兆。18 小时前
Agent_RAG_智能食谱推荐系统
langchain·智能体
小刘|1 天前
揭秘RAG:检索增强生成技术解析
langchain·rag
菜到离谱但坚持1 天前
【小白零基础】RAG+LangChain 搭建私有知识库问答系统(完整可运行代码+超详细教程+避坑指南)
python·langchain·rag
YsyaaabB1 天前
LangChain作业二---多语言翻译Prompt
开发语言·python·langchain
兆。1 天前
简历高光_Agent_RAG项目描述
人工智能·langchain