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}")
相关推荐
山间小僧3 小时前
「AI学习笔记」Agent Memory(二)跨会话记忆:从聊天记录到可演化的长期记忆
aigc·agent·vibecoding
LaughingZhu5 小时前
Product Hunt 每日热榜 | 2026-09-12
人工智能·深度学习·神经网络·搜索引擎·百度
Zguigo5 小时前
【CUDA1】GPUvsCPU,CUDA Kernel
人工智能·pytorch·深度学习
thesky1234565 小时前
用 ONNX Runtime 把 PyTorch 模型变成跨平台极速推理引擎:导出、优化、量化完整实
人工智能·深度学习·模型部署
Goboy5 小时前
多模态大模型已经能识别和描述视频,为什么仍然缺乏可靠的时序感知能力?
aigc·ai编程
开心就多写,一点就开心5 小时前
导演视听语言与分镜系统笔记(一):景别系统、机位视点与时空连贯性设计
笔记·aigc·镜头·电影
猎头南楼9 小时前
大模型后训练与 Agent 自迭代:两类工程能力的观察
人工智能·深度学习·机器学习
Zzj_tju10 小时前
CLIP 图文对齐:先核对正样本,再相信检索分数
人工智能·深度学习·语言模型·自然语言处理
千里码aicood10 小时前
基于深度学习的驾驶员分心驾驶行为识别研究
人工智能·深度学习
Zzj_tju12 小时前
VLM 读图评测:先审计评分器,再判断读错还是算错
人工智能·深度学习·机器学习·语言模型