LangChain入门----工具
2026/9/11 11:13:01 网站建设 项目流程


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

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

1自定义工具

1.1基于tool描述工具(不推荐)

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

fromlangchain.toolsimporttool@tool("square",description="计算一个数字的平方")deftool1(x:float)->float:returnx**2

1.2使用函数名和文档注释描述工具

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

  • 工具名:默认就是函数名
  • 工具所需的参数:默认就是函数的参数列表
  • 工具作用的描述:默认就是函数的文档注释
fromlangchain.toolsimporttool@tooldefsquare(x:float)->float:""" 计算一个数字的平方 """returnx**2

1.3定义Pydantic model 描述参数

当函数的参数比较复杂时,我们可以使用Pydantic model来描述参数。

frompydanticimportBaseModel,FieldfromtypingimportLiteral# 定义的参数classWeatherInput(BaseModel):""" 天气查询输入参数 """location:str=Field(description="city name")unit:Literal["celsius","fahrenheit"]=Field(default="celsius",description="温度单位")include_forecast:bool=Field(default=False,description="Include 5-day forecast")#unit计量单位,celsius摄氏度,degrees度@tool(args_schema=WeatherInput)defget_weather(location:str,unit:str="celsius",include_forecast:bool=False)->str:temp=22ifunit=="celsius"else72result=f"查询{location}:{temp}degrees{unit[0].upper()}"ifinclude_forecast:result+=",5天天气预报为:"returnresult
square.invoke({"x":4})get_weather.invoke({"location":"海南","include_forecast":False})

测试

fromlangchain.agentsimportcreate_agentfromlangchain.messagesimportHumanMessage agent=create_agent(model="deepseek-chat",tools=[square,get_weather],)
fortoken,metadatainagent.stream({"messages":[HumanMessage(content="海南的天气如何")]},stream_mode="messages"):print(token.content,end="",flush=True)
response=agent.invoke({"messages":[HumanMessage(content="88和100的平方是多少")]})formessageinresponse["messages"]:print(message.pretty_print())

2 预定义工具

#需要在.env文件中配置TAVILY_API_KEYfromlangchain_tavilyimportTavilySearchfromdotenvimportload_dotenv load_dotenv()search_tool=TavilySearch(max_results=5,topic="general",)search_tool.invoke("agent有几种输出方式")agent=create_agent(model="deepseek-chat",tools=[search_tool],system_prompt="你是一个智能助手,使用工具来解决用户的问题",)response=agent.invoke({"messages":[HumanMessage(content="真香是什么梗")]})formessageinresponse["messages"]:message.pretty_print()

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询