LangGraph构建Ai智能体-3-智能体调用工具

前言

智能体必须能够与外界交互,我们此处介绍tool_calls(function_calling)的方式。

大模型本身是不能调用任何工具的,但是当我们给大模型增加一些工具的描述时,大模型会根据用户的问题来确认是不是需要外部工具,如果需要调用外部工具的话,就会把需要调用的工具名字和具体参数作为一个AIMessage的tool_calls参数返回给应用程序,应用程序收到后,需要自行执行相应的任务,并把任务结果告诉大模型,这个过程称之为tool_call。

具体流程如下

环境

见前文

查询天气的示例

我们给大模型配置了查询天气的工具,当我们询问某地区的天气时,看下大模型是怎么处理的

步骤

  1. 加载环境变量
  2. 定义工具和工具节点
  3. 创建大模型并绑定工具
  4. 定义工作流
    • 大模型调用节点,需要处理返回的AI消息中的tool_calls
    • tool_calls交给工具节点处理,然把结果返回
  5. 用户输入并询问大模型
  6. 输出结果
python 复制代码
# 调用工具
from dotenv import load_dotenv
import os
from langchain_openai import ChatOpenAI
from langgraph.graph import StateGraph, START, END, MessageGraph, MessagesState
from langchain_core.tools import tool
from langgraph.prebuilt import ToolNode

#1. 加载环境变量
load_dotenv()
base_url = os.getenv("BASE_URL")
openai_api_key = os.getenv("OPENAI_API_KEY")
model_name = "qwen-plus"

#2. 定义工具和工具节点
# Define a tool to get the weather for a city
@tool
def get_weather(location: str):
    """Fetch the current weather for a specific location."""
    weather_data = {
        "San Francisco": "Its 60 degrees and foggy.",
        "New York": "Its 90 degrees and sunny.",
        "London": "Its 70 degrees and cloudy.",
        "上海": "晴天 20摄氏度",
        "北京": "大雨 10摄氏度",
    }
    return weather_data.get(location, "无法获取当地天气状况")
# 错误传播出来
tool_node = ToolNode([get_weather], handle_tool_errors=False)

#3. 创建大模型并绑定工具
model = ChatOpenAI(
    base_url=base_url, api_key=openai_api_key, model=model_name
).bind_tools([get_weather])

# 4. 定义工作流
def call_llm(state: MessagesState):
    messages = state["messages"]
    response = model.invoke(messages[-1].content)
    # 是否 toolcall
    if response.tool_calls:
        tool_result = tool_node.invoke({"messages": [response]})
        tool_message = tool_result["messages"][-1].content
        response.content += f"\nTool Result:{tool_message}"
    return {"messages": [response]}

workflow = StateGraph(MessagesState)
workflow.add_node("call_llm", call_llm)
workflow.add_edge(START, "call_llm")
workflow.add_edge("call_llm", END)
app = workflow.compile()

# 持续对话
def interact_with_agent():
    while True:
        # 5. 用户输入并询问大模型
        user_input = input("You: ")
        if user_input.lower() in ["exit", "quit", "q"]:
            print("结束对话")
            break
        input_message = {"messages": [("human", user_input)]}
        for chunk in app.stream(input_message, stream_mode="values"):
            # 6. 输出结果
            chunk["messages"][-1].pretty_print()

interact_with_agent()

输出结果

bash 复制代码
You: London 天气如何
================================ Human Message =================================

London 天气如何
================================== Ai Message ==================================


Tool Result:Its 70 degrees and cloudy.
Tool Calls:
  get_weather (call_1b89d3f1afe94be3bfc020)
 Call ID: call_1b89d3f1afe94be3bfc020
  Args:
    location: London
You: 上海天气怎么样
================================ Human Message =================================

上海天气怎么样
================================== Ai Message ==================================


Tool Result:晴天 20摄氏度
Tool Calls:
  get_weather (call_f05384e466f84037b4cb81)
 Call ID: call_f05384e466f84037b4cb81
  Args:
    location: 上海
You: 北京天气呢
================================ Human Message =================================

北京天气呢
================================== Ai Message ==================================


Tool Result:大雨 10摄氏度
Tool Calls:
  get_weather (call_00cae603cea84dacb4cfaf)
 Call ID: call_00cae603cea84dacb4cfaf
  Args:
    location: 北京
You: exit
结束对话

ToolCall 的原理模拟示例

上面的示例是大模型直接返回的tool_calls参数,我们也可以直接模拟这一行为,用于演示原理或者测试我们自己 的工具。

下面我们将创建一个获取用户信息的工具,然后创建一个带tool_calls的AIMessage,来调用工具节点

步骤

  1. 加载环境
  2. 定义工具和工具节点
  3. 定义AiMessage
  4. 调用工具节点
  5. 输出结果
python 复制代码
# 调用工具
from dotenv import load_dotenv
import os
from langchain_openai import ChatOpenAI
from langgraph.graph import StateGraph, START, END, MessageGraph, MessagesState
from langchain_core.tools import tool
from langchain_core.messages import AIMessage
from langgraph.prebuilt import ToolNode
# 1. 加载环境
load_dotenv()
base_url = os.getenv("BASE_URL")
openai_api_key = os.getenv("OPENAI_API_KEY")
model_name = "qwen-plus"

# 2. 定义工具和工具节点
# Define a tool to get the weather for a city
@tool
def get_user_profile(user_id: str):
    """通过user_id获取用户信息"""
    weather_data = {
        "101": {"name": "爱丽丝", "年龄": 30, "location": "纽约"},
        "102": {"name": "Bob", "age": 25, "location": "旧金山"},
    }
    return weather_data.get(user_id, "没有此用户")
# 工具节点
# handle_tool_errors 错误传播出来
tool_node = ToolNode([get_user_profile], handle_tool_errors=False)

# 3. 定义AiMessage
message_with_tool_call = AIMessage(
    content="",
    tool_calls=[
        {
            "name": "get_user_profile",
            "args": {"user_id": "101"},
            "id": "tool_call_id",
            "type": "tool_call",
        }
    ],
)
#
state = {"messages": [message_with_tool_call]}

# 4. 调用工具节点
# 直接把消息交给工具节点调用
result = tool_node.invoke(state)

# 5. 输出结果
print(result)

输出结果

rust 复制代码
{'messages': [ToolMessage(content='{"name": "爱丽丝", "年龄": 30, "location": "纽约"}', name='get_user_profile', tool_call_id='tool_call_id')]}
相关推荐
tudficdew4 分钟前
实战:用Python分析某电商销售数据
jvm·数据库·python
风静如云10 分钟前
Claude Code:进入dash模式
人工智能
TM1Club16 分钟前
AI驱动的预测:新的竞争优势
大数据·人工智能·经验分享·金融·数据分析·自动化
陈天伟教授19 分钟前
人工智能应用-机器听觉:15. 声纹识别的应用
人工智能·神经网络·机器学习·语音识别
zhang1338308907520 分钟前
CG-09H 超声波风速风向传感器 加热型 ABS材质 重量轻 没有机械部件
大数据·运维·网络·人工智能·自动化
sjjhd65225 分钟前
Python日志记录(Logging)最佳实践
jvm·数据库·python
板面华仔43 分钟前
机器学习入门(三)——决策树(Decision Tree)
人工智能·决策树·机器学习
2301_821369611 小时前
用Python生成艺术:分形与算法绘图
jvm·数据库·python
GAOJ_K1 小时前
滚珠花键的无预压、间隙调整与过盈配合“场景适配型”
人工智能·科技·机器人·自动化·制造
ai_xiaogui1 小时前
【开源探索】Panelai:重新定义AI服务器管理面板,助力团队私有化算力部署与模型运维
人工智能·开源·私有化部署·docker容器化·panelai·ai服务器管理面板·comfyui集群管理