LangChain Tools 工具使用
·
未完待续
关于大模型工具使用有关前置知识和原理,已经在下面文章提到
本文介绍基于langchain开发具有工具使用(Function calling)功能的智能体Agent
langchain开发Agent,需要安装包
pip install langchain==1.3.13
pip install langchain-openai
pip install langchain-classic
1.Tools
实现工具方法供大模型调用,并通过函数装饰器@tools修饰工具方法,默认使用函数名称作为工具名称,可通过name_or_callable覆盖。
@tools常用属性:
| 属性 | 类型 | 描述 |
|---|---|---|
| name_or_callable | str | Callable | 名称 |
| description | str | 描述工具的功能,会作为上下文发送给大模型 |
| args_schema | ArgsSchema | 可选择性地指定参数格式 |
| return_direct | bool | 是否直接从工具返回 |
from typing import Annotated
from langchain.tools import tool
from pydantic import Field
@tool(
description='根据城市名称获取温度',
name_or_callable='my_tool'
)
def tp_tool(
city: Annotated[str, Field(description='待查城市')]
) -> int:
print('=======tp_tool=======')
if city == '北京':
return 12
elif city == '武汉':
return 23
elif city == '沈阳':
return -10
elif city == '泉州':
return 27
else:
return None
if __name__ == '__main__':
print( tp_tool.name )
print( tp_tool.args )
print( tp_tool.description )
print( tp_tool.return_direct )
tp_tool.invoke({'city':'武汉'})
根据城市名称获取温度的方法
{'city': {'description': '待查城市', 'title': 'City', 'type': 'string'}}
根据城市名称获取温度
False
=======tp_tool=======
2.Agent
langchain1.x使用create_agent()实现function calling,绑定模型和工具,然后调用invoke()执行
from typing import Annotated
from langchain.tools import tool
from pydantic import Field
import os
from langchain.agents import create_agent
from langchain.chat_models import init_chat_model
from dotenv import load_dotenv
load_dotenv(encoding='utf-8')
@tool(
description='根据城市名称获取温度',
name_or_callable='my_tool'
)
def tp_tool(
city: Annotated[str, Field(description='待查城市')]
) -> int:
print('=======tp_tool=======')
if city == '北京':
return 12
elif city == '武汉':
return 23
elif city == '沈阳':
return -10
elif city == '泉州':
return 27
else:
return None
llm = init_chat_model(
model = 'deepseek-chat',
model_provider = 'openai',
api_key = os.getenv('DSKEY'),
base_url = 'https://api.deepseek.com'
)
# 创建 Agent,绑定tp_tool工具
agent = create_agent(
llm,
tools=[tp_tool],
system_prompt="""你是一个天气查询助手"""
)
# 执行
result = agent.invoke({
"messages": [{"role": "user", "content": "泉州温度多少"}]
})
for msg in result['messages']:
if hasattr(msg, 'content'):
print(f"{msg.__class__.__name__}: {msg.content}")
输出结果
=======tp_tool=======
HumanMessage: 泉州温度多少
AIMessage: 我来帮您查询泉州的温度。
ToolMessage: 27
AIMessage: 根据查询结果,泉州的当前温度是**27°C**。
更多推荐



所有评论(0)