Agent学习记录四:多工具时如何处理

因为不会只问Agent一个问题,所以也不会只有一个tool,这一节处理多个tool的情况。

一、定义多个Tool

先定义你的函数,例如实现天气查询

python 复制代码
def get_weather(city):
    return f"{city} 今天晴天,25℃"

前面章节已经展示过tools的组成,根据json的格式可知,tools是可以放入多个函数说明的。

tools = [

{

函数1说明

},{

函数2说明

}

]

函数说明的格式如下:

{

"type": "function",

"name": "函数名 ",

"description": "函数描述 ",

"parameters": {

"type": "object",

"properties": {

"参数1 ": {

"type": "参数类型 ",

"description": "参数说明 "

},

"参数1 ": {

"type": "参数类型 ",

"description": "参数说明 "

}

},

"required": "**参数1** ", "**参数2** ",

"additionalProperties": False

}

}

参数类型:number、string。。。

二、调用Tools

按照之前的方式的话,调用可以这么写

python 复制代码
for item in response.output:

    if item.type == "function_call":
        # JSON字符串 → Python字典 加载参数
        arguments = json.loads(item.arguments)

        if item.name == "calculator":
            result = calculator(
                arguments["a"],
                arguments["b"]
            )
        elif item.name == "get_weather":
            result = get_weather(
                arguments["city"]
            )

        print("========== Tool Result ==========")
        print(result)

但是这么写的弊端也明显:麻烦。每增加一个函数就要补一个,所以可以替换为

python 复制代码
tool_map = {
    "calculator": calculator,
    "get_weather": get_weather
}

for item in response.output:

    if item.type == "function_call":
        # JSON字符串 → Python字典 加载参数
        arguments = json.loads(item.arguments)

        # 找到对应的 Python 函数
        function = tool_map[item.name]

        # 执行 Python 函数
        result = function(**arguments)
        
        print("========== Tool Result ==========")
        print(result)

function(**arguments)解释

例如:arguments = { "city": "上海"}

那么function(**arguments)就是get_weather(city="上海")

例如:arguments = { "a": 123, "b": 456 }

那么function(**arguments)就是calculator(a=123, b=456)

三、测试结果

可以随意遂改你的input,例如提问"上海今天的天气"、"23*123=?"。

python 复制代码
from openai import OpenAI
import json

client = OpenAI()
def calculator(a, b):
    return a * b

def get_weather(city):
    return f"{city} 今天晴天,25℃"

tools = [
    {
        "type": "function",
        "name": "calculator",
        "description": "计算两个数字的乘积",
        "parameters": {
            "type": "object",
            "properties": {
                "a": {
                    "type": "number",
                    "description": "第一个数字"
                },
                "b": {
                    "type": "number",
                    "description": "第二个数字"
                }
            },
            "required": ["a", "b"],
            "additionalProperties": False
        }
    },{
        "type": "function",
        "name": "get_weather",
        "description": "查询指定城市的天气",
        "parameters": {
            "type": "object",
            "properties": {
                "city": {
                    "type": "string",
                    "description": "城市名称"
                }
            },
            "required": ["city"],
            "additionalProperties": False
        }
    }
]

# =========================
# 3. 工具名称 -> Python 函数
# =========================

tool_map = {
    "calculator": calculator,
    "get_weather": get_weather
}

# =========================
# 4. 第一次请求 LLM
# =========================
response = client.responses.create(
    model="gpt-5.6-sol",
    input="上海今天的天气",
    tools=tools,
    tool_choice="required"
)

# =========================
# 5. 处理 LLM 返回的 Tool Call
# =========================
for item in response.output:

    if item.type == "function_call":
        print("========== Tool Call ==========")
        print("工具名称:", item.name)
        print("参数:", item.arguments)
        print("Call ID:", item.call_id)

        # JSON字符串 → Python字典 加载参数
        arguments = json.loads(item.arguments)

        # 找到对应的 Python 函数
        function = tool_map[item.name]

        # 执行 Python 函数
        result = function(**arguments)
        
        print("========== Tool Result ==========")
        print(result)

        # =========================
        # 6. 把工具结果交还给 LLM
        # =========================
        response2 = client.responses.create(
            model="gpt-5.6-sol",
            input=[
                *response.output,
                {
                    "type": "function_call_output",
                    "call_id": item.call_id,
                    "output": str(result)
                }
            ],
            tools=tools
        )

        print("========== Final Answer ==========")
        print(response2.output_text)
相关推荐
ViperL13 分钟前
[高光谱]DADnet-基于对抗生成的单源域泛化分类
人工智能·分类·数据挖掘
AI创界者5 分钟前
Python 进阶实战:AsyncIO 异步环境下的熔断器、限流器与代理模式深度融合
人工智能·aigc
水如烟7 分钟前
孤能子视角:SEP《人工智能的认识论》EIS读法·信任与证言——外包信:载体跑在生产前面,物已通约,信未自生
人工智能
落雪snowflake8 分钟前
论文精讲:A Language-Informed Loss for Visual Generation中文题目:一种面向视觉生成的语言信息引导损失函数
人工智能·深度学习·计算机视觉
承渊政道8 分钟前
Linux网络学习【传输层协议UDP】
linux·网络·网络协议·学习·ubuntu·udp
andrsted9 分钟前
练题簿免费刷题小程序:和学习搭子共用一份题库,一起刷题复习
学习·面试·微信小程序·小程序·学习方法·刷题
jerrywus11 分钟前
给 Pi 装上生图插件:从登录报错到画出一只 200×200 的猫
前端·agent·claude
一线数智14 分钟前
Gartner发布2027年十大战略技术趋势
大数据·人工智能
美团技术团队27 分钟前
从 LOOP 到图探索 —— 算法模型的 AutoResearch 自进化系统架构演进之路
人工智能
云和数据.ChenGuang37 分钟前
光哥说Python 循环导入(Circular Import)深度解析:成因、排查与解决方案
开发语言·前端·人工智能·python·langchain