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}")
相关推荐
杀生丸学AI1 小时前
【三维重建】ArtiFixer:自回归扩散增强与扩展3DGS(NVIDIA)
人工智能·3d·数据挖掘·aigc·三维重建·扩散模型·视觉大模型
爱勇宝1 小时前
DeepSeek实习生日薪5500:真正恐怖的不是工资
人工智能·深度学习·面试
Feisy1 小时前
出口锂电池-无人机等危险品的拍摄多张外包装申报照片的落地方案
深度学习·手机自动拍照·照片采集·电池外观拍摄·出口电池
蓝星空20003 小时前
GPT-image-2 模型国内免费使用教程:零门槛直出商业级 AI 大片
人工智能·gpt·aigc·image2·imagen
直接冲冲冲3 小时前
两层神经网络与三层神经网络的区别
人工智能·深度学习·神经网络
QiZhang | UESTC4 小时前
学习agent开发
深度学习
yingyuecom5 小时前
映悦AI复刻爆款更新深度评测:资产锁定如何治好AI短剧的‘变脸症’
人工智能·gpt·chatgpt·prompt·aigc
Sirius Wu6 小时前
OpenClaw Observability 并发安全(Per-Request Hook)完整详解
服务器·网络·人工智能·安全·ai·架构·aigc
宅小年6 小时前
AI 记忆是怎么实现的?下篇:向量检索、知识图谱和长期记忆系统
aigc·openai·ai编程
TrisighT8 小时前
Claude Code 的 8 大机制我全踩了一遍:哪些真香,哪些是坑
aigc·agent·workflow