AI Agents · 课时

检测并恢复工具错误

当工具返回 500 错误时,将错误返回给模型,让它尝试其他方法,而不是直接崩溃。

第 4 / 4 课15 个步骤

检测并恢复工具错误 是 CoddyKit 上的免费 AI Agents 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Agents 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Agents 课程共包含 4 节课。

工具会失败,请做好准备

每个真实工具有时都会失败:

  • 网络超时
  • 速率限制
  • 模型提供了错误的参数
  • 外部服务停机
  • 身份验证无效

生产环境中的代理必须能够优雅地恢复。

始终返回,不要抛出异常

在代理循环中,捕获所有工具错误并将其作为内容返回。绝不要让异常终止循环:

def safe_dispatch(tool_call):
    try:
        args = json.loads(tool_call.function.arguments)
        return TOOLS[tool_call.function.name](**args)
    except json.JSONDecodeError:
        return {'error': 'Arguments are not valid JSON.'}
    except KeyError:
        return {'error': f'Unknown tool: {tool_call.function.name}'}
    except Exception as e:
        return {'error': f'{type(e).__name__}: {e}'}

结构化错误格式

使用一致的结构,让模型能够识别错误:

error = {'ok': False, 'error_type': 'TimeoutError', 'error_message': 'Tavily timed out after 10s', 'retryable': True}
print(error)

区分可重试错误与永久错误

有些错误值得重试(超时),有些则不值得(404)。请告诉模型:

if isinstance(e, requests.Timeout):
    return {'ok': False, 'retryable': True, 'error': str(e)}
if isinstance(e, ValueError):
    return {'ok': False, 'retryable': False, 'error': str(e)}

自动重试暂时性错误

对于网络调用,请使用指数退避策略进行重试:

from tenacity import retry, wait_exponential, stop_after_attempt, retry_if_exception_type

@retry(
    wait=wait_exponential(multiplier=1, max=10),
    stop=stop_after_attempt(3),
    retry=retry_if_exception_type((requests.Timeout, requests.ConnectionError))
)
def web_search(query):
    return requests.get('https://api.tavily.com/search', ...).json()

参数验证

调用工具之前,请使用 Pydantic 模型验证参数:

from pydantic import BaseModel, ValidationError

class SearchArgs(BaseModel):
    query: str
    k: int = 5

try:
    args = SearchArgs.model_validate_json(tool_call.function.arguments)
except ValidationError as e:
    return {'error': f'Bad arguments: {e}'}

向模型展示错误

将错误追加为工具结果,然后再次调用模型。模型通常会自行纠正:

messages.append({
    'role': 'tool',
    'tool_call_id': tc.id,
    'content': json.dumps({'error': 'Argument k must be an integer'})
})
# Next model call: 'Sorry, let me retry with k=5...'

避免无限错误循环

有些模型在看到错误后,会重试同一个有问题的调用。请限制循环次数并检测重复调用:

recent_calls = []
for tc in msg.tool_calls:
    key = (tc.function.name, tc.function.arguments)
    if recent_calls.count(key) >= 3:
        return 'Agent stuck in retry loop, aborting.'
    recent_calls.append(key)

针对工具的恢复策略

对于已知容易出现瞬时故障的工具,请将重试逻辑构建在工具内部,而不是循环中:

def search_with_fallback(query):
    try:
        return tavily_search(query)
    except Exception:
        return bing_search(query)   # secondary provider

为每次调用设置超时

每次外部调用都需要设置超时。否则,一个响应缓慢的服务会冻结整个代理:

import requests
response = requests.get(url, timeout=10)  # 10s

# For LLM calls:
from openai import OpenAI
client = OpenAI(timeout=30.0)

熔断器

当某个工具反复失败时,请“打开”熔断器,并在一段时间内跳过该工具:

import time

class CircuitOpen(Exception):
    pass

def circuit(failure_threshold=5, recovery_timeout=60):
    def decorator(func):
        state = {'failures': 0, 'open_until': 0}
        def wrapper(*args, **kwargs):
            if time.time() < state['open_until']:
                raise CircuitOpen('circuit is open')
            try:
                result = func(*args, **kwargs)
                state['failures'] = 0
                return result
            except Exception:
                state['failures'] += 1
                if state['failures'] >= failure_threshold:
                    state['open_until'] = time.time() + recovery_timeout
                raise
        return wrapper
    return decorator

@circuit(failure_threshold=3, recovery_timeout=1)
def fragile_tool(x):
    if x < 0:
        raise ValueError('bad input')
    return x * 2

for x in [1, -1, -1, -1, -1]:
    try:
        print('ok', fragile_tool(x))
    except CircuitOpen as e:
        print('blocked:', e)
    except ValueError as e:
        print('failed:', e)

记录带上下文的错误日志

记录足够的信息,以便事后进行调试:工具名称、参数、错误类型、堆栈跟踪、请求 ID、用户 ID、跟踪 ID。将这些信息发送到您的可观测性工具。

优雅降级

当关键工具不可用时,请诚实地告知用户,而不是假装代理已经成功:

if all_search_tools_failed:
    return 'I was unable to search the web right now. Please try again in a few minutes.'

工具错误处理模式

在代理循环内部处理工具异常的最安全方式是什么?

回顾

工具会失败。请捕获错误、分类错误、将错误结构化为内容,并让代理完成恢复。为了保证生产环境的可靠性,请添加超时、重试和熔断器。

免费开始

用 AI 导师学习 AI Agents — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
60
课程
239

常见问题解答

「检测并恢复工具错误」课时是免费的吗?

是的 — 「检测并恢复工具错误」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Agents 课程的其余内容,请升级到 CoddyKit PRO。 AI Agents 课程共包含 4 节课。

「检测并恢复工具错误」这节课中我会学到什么?

当工具返回 500 错误时,将错误返回给模型,让它尝试其他方法,而不是直接崩溃。 你通过在浏览器中直接运行的动手代码来练习 AI Agents,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 AI Agents 需要有经验吗?

无需任何先前经验。CoddyKit 上的 AI Agents 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「检测并恢复工具错误」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 AI Agents 课中编写并运行代码吗?

能。每节 AI Agents 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. ReAct:推理 + 行动模式
  2. 从零实现 ReAct
  3. 常用工具集(网页、计算器、RAG)
  4. 检测并恢复工具错误
← 返回 AI Agents