【AI】Langchain框架学习05

工具篇,三步走:

确定该大模型有调用工具的能力(deepseek-v3可以,qwen-plus可以) - @tool - StructedTool

  • @tool 绑定工具
import datetime
from langchain.tools import tool

# 定义工具 注意要添加注释
@tool
def get_current_date():
    ""获取今天日期""
    return datetime.datetime.today.strftime ("%Y-%m-%d")
# 大模型绑定工具
Ilm_with_tools = llm.bind_tools([get_current_date])
# 工具容器
all_tools = {"get_current_date": get_current_date}
# 把所有消息存到一起
query ="今天是几月几号"
messages = [query]
# 询问大模型。大模型会判断需要调用工具,并返回一个工具调用请求
ai_msg = llm_with_tools.invoke(messages)
print(ai_msg)
messages.append(ai_msg)
# 打印需要调用的工具
print(ai_msg.tool_calls)
if ai_msg.tool_calls:
    for tool_call in ai_msg.tool_calls:
        selected_tool = all_tools[tool_call ["name"].lower()]
        tool_msg = selected_tool.invoke(tool_call)
        messages.append(tool_msg)
        
llm_with_tools.invoke(messages).content
  • 为工具添加详细注解
# 定义工具 注意要添加注释
@tool(description="获取某个城市的天气")
def get_city_weather(city: str):
    """获取某个城市的天气
    Args: 
        city: 具体城市
    """
    return "城市" + city + ",今天天气不错"
  • 深度定制工具StructedTool
    使用StructedTool就可以免去@tool声明,并且该方法含有更多的内部参数可供调用
from langchain_core.tools import StructuredTool

def bad_weather_tool (city:str):
    """获取某个城市的天气
    Args:
        city:具体城市
    """
    return"城市"+ city +",今天天气不太好"

# 定义工具。这个方法中有更多参数可以定制
weatherTool = StructuredTooL.from_function(func=bad_weather_tool, description="获取某个城市的天气",name="bad_weather_tool")

all_tools = {"bad_weather_tool": weatherTool}

  • 一个小demo:和风天气API可以用来调用,展示真实天气,每日天气,实时天气
def get_weather(city, api_key):
# 和风天气API的URL
url = "https://devapi.qweather.com/v7/weather/now"
# 清求参数
params = {
    'location': city, # 城市名称或ID
    'key': api_key # 你的API密钥
}

# 发送GET请求
response = requests.get(url, params=params)

# 检查请求是否成功
if response.status_code == 200:
    # 解析JSON响应
    data = response.json()
    if data['code'] == '200':
        # 提取天气信息
        weather_info = data['now']
        print (f"城市: {city}")
        print (f"天气状况:{weather_info['text']}")
        print (f"温度: {weather_info['temp']}°C")
        print (f"体感温度: {weather_info['feelsLike']}°C")
        print (f"相对湿度:{weather_info['humidity']}%")
        print (f"降水量:{weather_info['precip']}mm")
        print (f"风向:{weather_info['windDir']}")
        print (f"风速: {weather_info['windSpeed']}km/h")
    else:
        print (f"错误: {data['code']} - {data['msg']}")
else:
    print (f"请求失败,状态码:{response.status_code}")
    
    
# 使用示例
api_key = 'xxx'
city = '101010100' # 北京的城市ID
get_weather(city, api_key)
# 申请的API密钥
posted @ 2026-07-21 16:49  leah-xx  阅读(5)  评论(0)    收藏  举报