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_ENDPOINT=https://<your-project>.services.ai.azure.com/api/projects/<your-project-id> AZURE_AI_MODEL_DEPLOYMENT_NAME=gpt-5-miniAZURE_AI_PROJECT_ENDPOINT取自 Foundry 门户项目的Overview页;AZURE_AI_MODEL_DEPLOYMENT_NAME取自Models + Endpoints中你部署的模型名。
- 登录 Azure CLI,远程环境(无浏览器)使用
--use-device-code:
az 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_mode="never_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(f"404: No flights found for {destination} in primary system") @tool(approval_mode="never_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, f"No 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_endpoint=endpoint, model=deployment_name, credential=DefaultAzureCredential() ) agent = client.as_agent( tools=[get_flight_times, get_flight_times_backup], name="FlightBookingAgent", instructions="""You 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_NAME(Notebook 中通过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 1(Paris,仅主系统覆盖):
get_flight_times命中字典,返回"Departures: 08:00, 12:30, 17:45 — from $350"(示例数据)。正常输出不应提及 404,因为主工具一次就成功了。 - Test 2(Berlin,仅备系统覆盖):
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], name="ResponseEvaluator", instructions="""You are a quality evaluator for travel agent responses. Given a travel question and the agent's 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 agent's response from Test 1 eval_prompt = f"""Question: 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),仅供参考