AI Agents for Beginners 如何用主备工具回退模式让智能体在工具失败时自我纠正

AI Agents for Beginners 如何用主备工具回退模式让智能体在工具失败时自我纠正 AI Agents for Beginners 如何用主备工具回退模式让智能体在工具失败时自我纠正【免费下载链接】ai-agents-for-beginners18 Lessons to Get Started Building AI Agents项目地址: https://gitcode.com/GitHub_Trending/ai/ai-agents-for-beginners这篇教程基于AI Agents for Beginners课程第 09 课Metacognition元认知的代码示例演示如何用一个「主备工具回退」模式让智能体在首选工具报错时自己识别失败、切换备用工具并把回退过程向用户透明说明。示例代码位于 09-python-agent-framework.ipynb基于 Microsoft Agent Framework 实现需要配置好 Azure OpenAI / Microsoft Foundry 部署并通过 Azure CLI 登录。前提条件环境变量与登录该 Notebook 的 Setup 部分列出了两个前置条件已通过环境变量配置好 Azure OpenAI 部署Microsoft Foundry 项目已用az login完成 Azure CLI 认证。按 00-course-setup 的说明Notebook 通过azure-identity包里的DefaultAzureCredential从你的az login会话读取凭据不需要在代码里写 API Key。如果还没有完成课程基础配置按以下步骤准备在 Microsoft Foundry 门户ai.azure.com创建项目并部署模型例如gpt-5-mini。复制.env.example为.env填入两个变量cp .env.example .envAZURE_AI_PROJECT_ENDPOINThttps://your-project.services.ai.azure.com/api/projects/your-project-id AZURE_AI_MODEL_DEPLOYMENT_NAMEgpt-5-miniAZURE_AI_PROJECT_ENDPOINT取自 Foundry 门户项目的Overview页AZURE_AI_MODEL_DEPLOYMENT_NAME取自Models Endpoints中你部署的模型名。登录 Azure CLI远程环境无浏览器使用--use-device-codeaz login az login --use-device-code在 Notebook 中安装依赖这是 Notebook 第一个代码单元的命令-q表示静默安装%pip install agent-framework azure-ai-projects azure-identity python-dotenv -q定义主、备两个工具示例用两个航班查询工具模拟「主系统不可用」的场景两者的城市覆盖范围互不重叠用来强制触发回退主工具get_flight_times— 覆盖 Paris、Tokyo、Barcelona查不到时抛出404: No flights found for {destination} in primary system备工具get_flight_times_backup— 覆盖 Berlin、Sydney、New York City查不到时不抛异常而是返回提示文本No flights found for {destination} in any system. Please try again later.。代码直接取自 Notebook可原样复制tool(approval_modenever_require) def get_flight_times( destination: Annotated[str, The destination city] ) - str: Get available flight times for a destination (primary source). flights { Paris: Departures: 08:00, 12:30, 17:45 — from $350, Tokyo: Departures: 11:00, 23:30 — from $890, Barcelona: Departures: 07:15, 14:00, 19:30 — from $280, } if destination in flights: return flights[destination] raise Exception(f404: No flights found for {destination} in primary system) tool(approval_modenever_require) def get_flight_times_backup( destination: Annotated[str, The destination city] ) - str: Get available flight times from backup system (used when primary fails). backup_flights { Berlin: Departures: 09:00, 16:00 — from $220, Sydney: Departures: 22:00 — from $1200, New York City: Departures: 06:00, 10:30, 15:00, 20:00 — from $450, } return backup_flights.get( destination, fNo flights found for {destination} in any system. Please try again later., )文件开头需要 Notebook 中的导入部分含Annotated工具签名会用到import os import asyncio import dotenv from typing import Annotated from agent_framework import tool from agent_framework.foundry import FoundryChatClient from azure.identity import DefaultAzureCredential dotenv.load_dotenv()注意两个工具的行为差异是回退模式的关键设计主工具用抛异常表达「本系统查不到」让智能体感知到明确的 404 错误备工具用返回兜底文本表达「两套系统都查不到」让智能体转而向用户道歉并建议其他方案。组装带回退指令的智能体用client.as_agent把两个工具装进智能体回退逻辑完全写在instructions里——这也是这个模式最核心的部分client FoundryChatClient( project_endpointendpoint, modeldeployment_name, credentialDefaultAzureCredential() ) agent client.as_agent( tools[get_flight_times, get_flight_times_backup], nameFlightBookingAgent, instructionsYou are a flight booking agent with self-reflection capabilities. When looking up flights: 1. Try the primary flight system first (get_flight_times) 2. If the primary system fails (404 error), acknowledge the error and try the backup system (get_flight_times_backup) 3. Always explain to the user what happened — be transparent about fallbacks 4. If both systems fail, apologize and suggest alternatives After each response, briefly evaluate whether your answer was complete and helpful., )其中endpoint与deployment_name来自前面.env中的AZURE_AI_PROJECT_ENDPOINT和AZURE_AI_MODEL_DEPLOYMENT_NAMENotebook 中通过os.getenv读取缺任一变量会直接抛出Missing required environment variables的ValueError。四条 instructions 分别对应回退链的四个环节先试主工具 → 主工具 404 时承认错误并试备工具 → 对回退保持透明 → 双双失败时道歉并给出替代建议。最后一条还要求智能体在每次回答后简短自评是否完整回答了用户问题这是 Notebook 对元认知metacognition的定义的一部分能自我反思、检测错误并优雅恢复而不是静默失败。运行两个测试并判断结果Notebook 用两个问题分别覆盖「主工具命中」和「主工具失败、备工具命中」两条路径# Test with a destination in primary system print( Test 1: Destination in primary system ) response await agent.run( What flights are available to Paris?, ) print(response) # Test with a destination only in backup system print(\n Test 2: Destination only in backup system ) response await agent.run( What flights are available to Berlin?, ) print(response)两个测试都直接print模型输出判断依据来自文档对两套数据源的行为定义Test 1Paris仅主系统覆盖get_flight_times命中字典返回Departures: 08:00, 12:30, 17:45 — from $350示例数据。正常输出不应提及 404因为主工具一次就成功了。Test 2Berlin仅备系统覆盖get_flight_times会抛出404: No flights found for Berlin in primary system智能体按 instructions 第 2、3 条应承认该错误、改调get_flight_times_backup并拿到Departures: 09:00, 16:00 — from $220示例数据。判断回退是否生效就看输出中是否同时出现对主系统 404 的说明和备用系统查到的航班。模型回复是自由文本措辞不会逐字固定但「是否提到主系统失败 是否给出 Berlin 的航班数据」这两点可以用来核对回退路径确实被触发。可选加一个自评估智能体Notebook 还演示了元认知的第二个面向——self-evaluation用第二个智能体按完整性、准确性、有用性三个维度各 1–5 分给上面的回答打分。这段是可选的不跑也不影响回退模式本身evaluation_agent client.as_agent( tools[get_flight_times, get_flight_times_backup], nameResponseEvaluator, instructionsYou are a quality evaluator for travel agent responses. Given a travel question and the agents response, evaluate: 1. Completeness: Did it answer all parts of the question? (1-5) 2. Accuracy: Is the information correct? (1-5) 3. Helpfulness: Would a traveler find this useful? (1-5) Provide a brief evaluation with scores and one suggestion for improvement., ) # Evaluate the agents response from Test 1 eval_prompt fQuestion: What flights are available to Paris? Agent Response: {response} Please evaluate the above response. evaluation await evaluation_agent.run(eval_prompt) print( Self-Evaluation ) print(evaluation)注意这里的response依赖上一个单元已经执行过eval_prompt会把它内联进评估提示词。小结这个示例的完整链路是主工具用异常标记本系统查询失败 → instructions 告诉智能体如何识别 404 并切换到备工具 → 对双失败给出兜底话术 → 每次回答后自评。Summary 部分把这种「primary backup tool pattern」列为错误恢复error recovery with fallbacks的代表并指出这些模式让智能体更稳健、透明、可信是生产部署所需的关键性质。更多元认知背景Corrective RAG、规划与自我反思示例可参考 09-metacognition 的 README。【免费下载链接】ai-agents-for-beginners18 Lessons to Get Started Building AI Agents项目地址: https://gitcode.com/GitHub_Trending/ai/ai-agents-for-beginners创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考