AI Agent的主流设计模式之工具调用模式

为什么需要工具调用?

LLM本质上是"静态"的,它的知识截止于训练数据,且无法直接与外部世界交互。工具调用就是为了解决LLM的三大核心局限:

  1. 信息滞后性:无法获取实时信息(如今天天气、最新新闻、股票价格)。

  2. 能力边界:无法执行具体操作(如发送邮件、控制智能家居、预订餐厅)。

  3. 计算与精确性:不擅长精确计算或逻辑推理(如数学计算、代码执行)。

通过工具调用,Agent获得了"手"和"眼睛",可以像人一样使用计算器、浏览器、API来完成任务。

python 复制代码
from openai import OpenAI
import json
import random
import os

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"  # 阿里云兼容模式地址
)

# 1. 定义工具列表
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "查询指定城市的天气",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {"type": "string", "description": "城市名称"}
                },
                "required": ["location"]
            }
        }
    }
]

# 2. 模拟工具函数
def get_current_weather(arguments):
    location = json.loads(arguments)["location"] if isinstance(arguments, str) else arguments["location"]
    weather = random.choice(["晴天", "多云", "小雨"])
    return f"今天{location}的天气是{weather}。"

# 3. 对话流程
messages = [{"role": "user", "content": "南京天气怎么样?"}]
response = client.chat.completions.create(
    model="qwen-plus",  # 也可用 qwen-max, qwen-turbo 等
    messages=messages,
    tools=tools
)

assistant_msg = response.choices[0].message
messages.append(assistant_msg)

# 4. 如果模型要求调用工具
if assistant_msg.tool_calls:
    tool_call = assistant_msg.tool_calls[0]
    func_name = tool_call.function.name
    func_args = json.loads(tool_call.function.arguments)
    print(f"调用工具:{func_name},参数:{func_args}")
    # 执行本地工具函数
    tool_result = get_current_weather(func_args)
    # 将工具结果返回给模型
    messages.append({
        "role": "tool",
        "tool_call_id": tool_call.id,
        "content": tool_result
    })
    # 第二次调用模型生成最终回答
    final_response = client.chat.completions.create(
        model="qwen-plus",
        messages=messages,
        tools=tools
    )
    print(f"最终回答:{final_response.choices[0].message.content}")
相关推荐
RWKV元始智能2 小时前
RWKV超并发项目教程,RWKV-LM训练提速40%
人工智能·rnn·深度学习·自然语言处理·开源
Hommy882 小时前
【开源剪映小助手】API 接口文档
开源·github·aigc·视频剪辑自动化·剪映api
GISer_Jing2 小时前
AI前端(From豆包)
前端·aigc·ai编程
AI技术增长4 小时前
Pytorch图像去噪实战(六):CBDNet真实噪声去噪实战,解决合成噪声模型落地效果差的问题
pytorch·深度学习·机器学习
小糖学代码5 小时前
LLM系列:2.pytorch入门:8.神经网络的损失函数(criterion)
人工智能·深度学习·神经网络
Jmayday5 小时前
Pytorch:RNN理论基础
pytorch·rnn·深度学习
AI周红伟7 小时前
周红伟:GPT-Image-2深度解析:从技术原理到实战教程,为什么它能让整个AI圈炸锅?
人工智能·gpt·深度学习·机器学习·语言模型·openclaw
龙虾闯荡江湖7 小时前
2026年了,聊聊AI Agent工程化落地的几个关键问题
aigc
西索斯8 小时前
MiniMax M2.7 实测:和 Claude Sonnet 4.6、GPT-5.5 放一起跑,结果有点意外
aigc·claude
端平入洛8 小时前
梯度是什么:PyTorch 自动求导详解
人工智能·深度学习