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')]}
相关推荐
居7然23 分钟前
京东开源王炸!JoyAgent-JDGenie如何重新定义智能体开发?
人工智能·开源·大模型·mcp
老兵发新帖27 分钟前
归一化分析3
人工智能
QYR_1139 分钟前
2025-2031年全球 MT 插芯市场全景分析报告:技术演进、供需格局与投资前景
人工智能·自然语言处理·机器翻译
mwq3012339 分钟前
从GPT-1到GPT-2的性能飞跃及其驱动因素分析
人工智能
程序员小远43 分钟前
常用的测试用例
自动化测试·软件测试·python·功能测试·测试工具·职场和发展·测试用例
IT学长编程1 小时前
计算机毕业设计 基于EChants的海洋气象数据可视化平台设计与实现 Python 大数据毕业设计 Hadoop毕业设计选题【附源码+文档报告+安装调试】
大数据·hadoop·python·毕业设计·课程设计·毕业论文·海洋气象数据可视化平台
mwq301231 小时前
GPT-2技术范式解析:无监督多任务学习的概率视角
人工智能
辣椒http_出海辣椒1 小时前
Python 数据抓取实战:从基础到反爬策略的完整指南
python
荼蘼1 小时前
使用 Flask 实现本机 PyTorch 模型部署:从服务端搭建到客户端调用
人工智能·pytorch·python
后端小肥肠1 小时前
【n8n 入门系列】10 分钟部署 n8n,手把手教你搭第一个自动化工作流,小白可学!
人工智能·aigc