Agent学习记录七:Authorization权限判断+Error Handling失败处理
Authorization权限判断在获得Tool工具后执行工具前进行权限判断即在 for item in tool_calls:中。for item in tool_calls: print(\n Tool Call ) print(工具:, item.name) print(参数:, item.arguments) arguments json.loads(item.arguments) # 从 Registry 获取 tool tool_registry.get(item.name) if tool is None: raise ValueError( f不存在的工具: {item.name} ) # 执行 # 执行前先检查权限 if tool.requires_confirmation: print(\n⚠️ 检测到需要授权的敏感操作) print(工具:, tool.name) print(参数:, arguments) confirm input(是否允许执行(y/n)).strip().lower() if confirm ! y: result 操作被拒绝未获得用户授权 print(❌ 用户拒绝执行) else: print(✅ 用户已确认执行) try: result tool.execute_with_retry(arguments,max_retries2) print(Tool Result:, result) except Exception as e: result f工具执行失败{type(e).__name__}: {e} print(Tool Error:, result) else: try: result tool.execute_with_retry(arguments,max_retries2) print(Tool Result:, result) except Exception as e: result f工具执行失败{type(e).__name__}: {e} print(Tool Error:, result) print(Tool Result:, result) # # 把 Tool Result 放回上下文 # input_items.append( { type: function_call_output, call_id: item.call_id, output: str(result) } ) else: print(❌ Agent 达到最大执行轮数停止运行。)定义工具的时候加入字段requires_confirmation表示是否需要进行权限判断。calculator_tool Tool( namecalculator, description计算两个数字的乘积, args_modelCalculatorArgs, functioncalculator, requires_confirmationFalse #权限 ) secret_tool Tool( nameget_secret, description获取内部系统中的敏感信息, args_modelSecretArgs, functionget_secret, requires_confirmationTrue )异常捕获在 Agent Loop 中找到真正执行工具的位置(就是tool.execute)try: result tool.execute(arguments) print(Tool Result:, result) except Exception as e: result f工具执行失败{type(e).__name__}: {e} print(Tool Error:, result)增加工具重试机制在你的.py中找到Tool类在execute()方法下面增加一个方法def execute_with_retry(self, arguments, max_retries2): for attempt in range(max_retries 1): try: return self.execute(arguments) except Exception as e: print( f[Tool Error] 第 {attempt 1} 次执行失败 f{type(e).__name__}: {e} ) if attempt max_retries: raise注意这个方法需要定义在class Tool:内部与execute()保持相同的缩进层级。这里的max_retries2表示第 1 次正常执行。第 2 次第一次重试。第 3 次第二次重试。仍然失败抛出异常由 Agent 外层捕获。接下来在 Agent Loop 中把原来的result tool.execute(arguments)替换成result tool.execute_with_retry( arguments, max_retries2 )保留外层的try/except这样最终失败时仍然可以将错误回传给 LLM。最终代码import json from openai import OpenAI from pydantic import BaseModel client OpenAI() # # 1. 参数模型 # class CalculatorArgs(BaseModel): a: float b: float class SecretArgs(BaseModel): reason: str # # 2. Python 工具函数 # def calculator(a, b): print(f[Python] calculator({a}, {b})) if b 0: raise ValueError(第二个参数不能为 0) return a * b def get_secret(reason): print(f[Python] get_secret(reason{reason})) # 模拟一个敏感资源 return 这是模拟的内部信息SECRET-123456 # # 3. Tool 类 # class Tool: def __init__(self, name, description, args_model, function,requires_confirmationFalse): self.name name self.description description self.args_model args_model self.function function self.requires_confirmation requires_confirmation def schema(self): return { type: function, name: self.name, description: self.description, parameters: self.args_model.model_json_schema() } def execute(self, arguments): args self.args_model(**arguments) return self.function(**args.model_dump()) def execute_with_retry(self, arguments, max_retries2): for attempt in range(max_retries 1): try: return self.execute(arguments) except Exception as e: print( f[Tool Error] 第 {attempt 1} 次执行失败 f{type(e).__name__}: {e} ) if attempt max_retries: raise # # 4. 创建 Tool # calculator_tool Tool( namecalculator, description计算两个数字的乘积, args_modelCalculatorArgs, functioncalculator, requires_confirmationFalse #权限 ) secret_tool Tool( nameget_secret, description获取内部系统中的敏感信息, args_modelSecretArgs, functionget_secret, requires_confirmationTrue ) # # 5. Tool Registry # tool_registry { calculator_tool.name: calculator_tool, secret_tool.name: secret_tool } # # 6. Tool Schema # tools [ tool.schema() for tool in tool_registry.values() ] # # 7. 模拟恶意用户 # user_input 计算 123 * 0。 print( User ) print(user_input) # # 8. Agent Loop # input_items [ { role: user, content: user_input } ] MAX_STEPS 5 for step in range(MAX_STEPS): print(\n Calling LLM ) response client.responses.create( modelgpt-6.1-sol, inputinput_items, toolstools, tool_choicerequired ) print(LLM 返回) # # 把 LLM 的输出加入上下文 # input_items.extend(response.output) # # 找出 Tool Call # tool_calls [ item for item in response.output if item.type function_call ] # # 没有 Tool Call → Agent 完成 # if not tool_calls: print(\n Final Answer ) print(response.output_text) break # # 执行所有 Tool # for item in tool_calls: print(\n Tool Call ) print(工具:, item.name) print(参数:, item.arguments) arguments json.loads(item.arguments) # 从 Registry 获取 tool tool_registry.get(item.name) if tool is None: raise ValueError( f不存在的工具: {item.name} ) # 执行 # 执行前先检查权限 if tool.requires_confirmation: print(\n⚠️ 检测到需要授权的敏感操作) print(工具:, tool.name) print(参数:, arguments) confirm input(是否允许执行(y/n)).strip().lower() if confirm ! y: result 操作被拒绝未获得用户授权 print(❌ 用户拒绝执行) else: print(✅ 用户已确认执行) try: result tool.execute_with_retry(arguments,max_retries2) print(Tool Result:, result) except Exception as e: result f工具执行失败{type(e).__name__}: {e} print(Tool Error:, result) else: try: result tool.execute_with_retry(arguments,max_retries2) print(Tool Result:, result) except Exception as e: result f工具执行失败{type(e).__name__}: {e} print(Tool Error:, result) print(Tool Result:, result) # # 把 Tool Result 放回上下文 # input_items.append( { type: function_call_output, call_id: item.call_id, output: str(result) } ) else: print(❌ Agent 达到最大执行轮数停止运行。)总结此时的Agent 架构已经开始成型┌─────────────────────────────┐│ Agent ││ ││ LLM ←──────────────┐ ││ ↓ │ ││ Tool Selection │ ││ ↓ │ ││ Authorization │ ││ ↓ │ ││ Pydantic Validation │ ││ ↓ │ ││ Tool Execution │ ││ ↓ │ ││ Error / Result ──────┘ ││ ││ MAX_STEPS │└─────────────────────────────┘Prompt 层LLM 应该怎么做Tool Calling 层LLM 想调用什么Pydantic 层参数是否合法Authorization 层有没有权限Error Handling 层工具失败怎么办Agent Loop 层失败之后能不能继续

相关新闻

智能体之间怎么“开会“?Agentic Design Patterns之A2A智能体通信模式详解

智能体之间怎么“开会“?Agentic Design Patterns之A2A智能体通信模式详解

文档教程AI Agent人工智能 【免费下载链接】Agentic-Design-Patterns Agentic Design Patterns 项目地址: https://gitcode.com/gh_mirrors/agen/Agentic-Design-Patterns 点击查看 免费下载 Agentic Design Patterns 是一本系统讲解 AI 智能体(AI Agen…

2026/10/11 18:48:03 阅读更多 →
OpenSSL EC_POINT_mul 详解:椭圆曲线点乘的核心 API

OpenSSL EC_POINT_mul 详解:椭圆曲线点乘的核心 API

1. 函数概述 EC_POINT_mul 是 OpenSSL 密码学库中椭圆曲线(Elliptic Curve, EC)算法体系里最核心的计算函数之一。它的主要作用是在椭圆曲线上进行点乘运算(标量乘法,Scalar Multiplication)。 2. 函数原型与定义 在 OpenSSL 的 <openssl/ec.h> 头文件中,定义如…

2026/10/11 18:48:03 阅读更多 →
200MW/400MWh储能电站并网后:有功功率接近零,电流测量还要关注什么

200MW/400MWh储能电站并网后:有功功率接近零,电流测量还要关注什么

梅州兴宁&#xff0c;一座200MW/400MWh的共享储能电站正式并网。按照公开报道&#xff0c;电站配置了80个5MWh储能电池舱&#xff0c;总投资约4.8亿元。对于这样一座电站&#xff0c;人们首先想到的往往是电池容量、充放电功率&#xff0c;以及多久能够完成一次充放电循环。图1…

2026/10/11 18:48:03 阅读更多 →

最新新闻

5G NR中TA与距离换算:协议原理、公式与避坑指南

5G NR中TA与距离换算:协议原理、公式与避坑指南

简介&#xff1a;这份资源聚焦5G(NR)网络优化中的时间对齐&#xff08;TA&#xff09;及其与实际物理距离的对应关系&#xff0c;适合无线网络优化工程师、运维人员及5G接入技术学习者。文档从TA offset取值受频段和制式影响的原理出发&#xff0c;梳理了初始接入时TA命令与实际…

2026/10/11 19:37:34 阅读更多 →
【OpenCode】源码架构分析:从 TaoToken 统一 Key 通道看 AI 编程工具的接入层设计

【OpenCode】源码架构分析:从 TaoToken 统一 Key 通道看 AI 编程工具的接入层设计

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

2026/10/11 19:37:34 阅读更多 →
37signals 远程公司档案全解析:从 frontmatter 到站点渲染的完整链路

37signals 远程公司档案全解析:从 frontmatter 到站点渲染的完整链路

数据集 【免费下载链接】remote-jobs Source for remoteintech.company — a community-maintained directory of remote-friendly tech companies 项目地址&#xff1a; https://gitcode.com/GitHub_Trending/re/remote-jobs 点击查看 免费下载 remoteintech.company&#xf…

2026/10/11 19:37:34 阅读更多 →
AI Agent数据库权限管控:动态鉴权与字段级访问控制实战

AI Agent数据库权限管控:动态鉴权与字段级访问控制实战

1. 项目概述&#xff1a;当AI Agent撞上数据库权限墙&#xff0c;我们到底在防什么&#xff1f;“没有权限&#xff0c;AI Agent也读不到数据”——这句话乍看像一句技术常识&#xff0c;但放在今天这个AI Agent遍地开花、企业数据资产加速智能化的背景下&#xff0c;它其实是一…

2026/10/11 19:37:34 阅读更多 →
Druid连接池爆满事故复盘:从线程Dump到生产级配置调优

Druid连接池爆满事故复盘:从线程Dump到生产级配置调优

1. 事故现场&#xff1a;连接池干涸&#xff0c;业务线程排队等连接那天下午两点多&#xff0c;服务群突然开始刷屏&#xff1a;订单接口超时率直接跳到百分之四十多&#xff0c;调用方一个接一个地来问情况。我第一反应是数据库出了问题&#xff0c;赶紧打开数据库监控&#x…

2026/10/11 19:37:34 阅读更多 →
图书馆管理系统数据流图:从0层到2层的系统分析实战指南

图书馆管理系统数据流图:从0层到2层的系统分析实战指南

简介&#xff1a;这是一份面向软件工程、信息系统分析与设计方向学习者及备考者的图书馆管理系统数据流图PDF资料&#xff0c;内容以“系统分析”为主线。全文围绕LMS的系统分析展开&#xff0c;完整覆盖业务流程分析、组织结构说明、0层至2层数据流图绘制&#xff0c;以及数据…

2026/10/11 19:36:33 阅读更多 →

日新闻

流感时间序列预测实战:ARIMA/LSTM全流程拆解与避坑指南

流感时间序列预测实战:ARIMA/LSTM全流程拆解与避坑指南

简介&#xff1a;基于 ARIMA、LSTM、Transformer 等模型的流感时间序列预测 Python 源码&#xff0c;面向计算机相关专业课程设计与期末大作业学生&#xff0c;以及项目实战学习者。内容覆盖预处理、平稳性检验、定阶、残差分析、多模型对比预测的完整时序建模流程&#xff0c;…

2026/10/11 0:00:27 阅读更多 →
影刀RPA新手教程:键盘模拟输入实战——输入文本与模拟按键的区别

影刀RPA新手教程:键盘模拟输入实战——输入文本与模拟按键的区别

影刀RPA新手教程&#xff1a;键盘模拟输入实战——输入文本与模拟按键的区别 做影刀RPA自动化&#xff0c;十个新手有八个栽在"往输入框里填东西"这件事上&#xff1a;要么填不进去&#xff0c;要么填了一半&#xff0c;要么直接把原来内容追加在后面。这背后的根因&…

2026/10/11 0:00:27 阅读更多 →
影刀RPA新手教程:阅文起点小说数据采集实战——书籍信息与章节内容

影刀RPA新手教程:阅文起点小说数据采集实战——书籍信息与章节内容

影刀RPA新手教程&#xff1a;阅文起点小说数据采集实战——书籍信息与章节内容 1. 认识影刀&#xff1a;什么场景该用RPA采小说数据 起点中文网的页面结构相对稳定——分类榜单、书籍详情、章节内容三块独立页面&#xff0c;跳转链路清晰。这种场景非常适合影刀自动化&#x…

2026/10/11 0:00:27 阅读更多 →

周新闻

流感时间序列预测实战:ARIMA/LSTM全流程拆解与避坑指南

流感时间序列预测实战:ARIMA/LSTM全流程拆解与避坑指南

简介&#xff1a;基于 ARIMA、LSTM、Transformer 等模型的流感时间序列预测 Python 源码&#xff0c;面向计算机相关专业课程设计与期末大作业学生&#xff0c;以及项目实战学习者。内容覆盖预处理、平稳性检验、定阶、残差分析、多模型对比预测的完整时序建模流程&#xff0c;…

2026/10/11 0:00:27 阅读更多 →
影刀RPA新手教程:键盘模拟输入实战——输入文本与模拟按键的区别

影刀RPA新手教程:键盘模拟输入实战——输入文本与模拟按键的区别

影刀RPA新手教程&#xff1a;键盘模拟输入实战——输入文本与模拟按键的区别 做影刀RPA自动化&#xff0c;十个新手有八个栽在"往输入框里填东西"这件事上&#xff1a;要么填不进去&#xff0c;要么填了一半&#xff0c;要么直接把原来内容追加在后面。这背后的根因&…

2026/10/11 0:00:27 阅读更多 →
影刀RPA新手教程:阅文起点小说数据采集实战——书籍信息与章节内容

影刀RPA新手教程:阅文起点小说数据采集实战——书籍信息与章节内容

影刀RPA新手教程&#xff1a;阅文起点小说数据采集实战——书籍信息与章节内容 1. 认识影刀&#xff1a;什么场景该用RPA采小说数据 起点中文网的页面结构相对稳定——分类榜单、书籍详情、章节内容三块独立页面&#xff0c;跳转链路清晰。这种场景非常适合影刀自动化&#x…

2026/10/11 0:00:27 阅读更多 →

月新闻

我发现了一个新思路:用 Remotion + Claude Code 像写代码一样自动化生成短视频

我发现了一个新思路:用 Remotion + Claude Code 像写代码一样自动化生成短视频

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

2026/10/11 10:45:37 阅读更多 →
Windows下 Codex 中 Chrome 和 Computer Use 插件不可用问题排查及解决参考方式:TaoToken 统一 Key 配置与验证

Windows下 Codex 中 Chrome 和 Computer Use 插件不可用问题排查及解决参考方式:TaoToken 统一 Key 配置与验证

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

2026/10/11 14:36:53 阅读更多 →
黑夜航拍船只数据集训练YOLOV5模型全流程解析

黑夜航拍船只数据集训练YOLOV5模型全流程解析

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

2026/10/11 14:36:54 阅读更多 →