Agent学习记录三:完成 Agent Loop
发布时间:2026/9/11 20:05:43 锦皓数字建站

一、最基础的 Agent Loop。修改代码from openai import OpenAI import json client OpenAI() def calculator(a, b): return a * b tools [ { type: function, name: calculator, description: 计算两个数字的乘积, parameters: { type: object, properties: { a: { type: number, description: 第一个数字 }, b: { type: number, description: 第二个数字 } }, required: [a, b], additionalProperties: False } } ] response client.responses.create( modelgpt-5.6-sol, input请调用 calculator 工具计算 123 × 456, toolstools, tool_choicerequired ) # 找到 LLM 发出的工具调用 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函数 result calculator( arguments[a], arguments[b] ) print( Tool Result ) print(result) # 第二次请求把工具结果交给 LLM response2 client.responses.create( modelgpt-5.6-sol, input[ *response.output, { type: function_call_output, call_id: item.call_id, output: str(result) } ], toolstools ) print( Final Answer ) print(response2.output_text)告诉 LLM 这是工具执行完之后返回给你的结果。type: function_call_output这个结果对应你刚才发出的那一次 calculator 调用call_id: item.call_id【*response.output】把第一次 LLM 的输出上下文带过去。让LLM知道刚才我让你调用了 calculator现在这是那个调用的结果。运行输出已经亲手完成了一个最小 Agent Loop二、完整过程┌──────────────┐│ LLM │└──────┬───────┘│Function Call│↓┌──────────────┐│ Python │└──────┬───────┘│calculator(123,456)│↓56088│Tool Output│↓┌──────────────┐│ LLM │└──────┬───────┘│↓123 × 456 56,088【注意】把这个过程彻底搞懂而不是继续加代码。尤其是tools、function_call、function_call_output、call_id、两次responses.create()这几个东西弄明白
锦
锦皓数字建站
深耕本土企业品牌数字化升级,专注原创端正雅致商务官网,从视觉设计到稳定运维全程保驾护航。