0Pricing
AI Engineering Academy · 课时

处理智能体故障与循环

添加超时限制、最大迭代次数上限和错误恢复提示,防止智能体无限循环或反复调用失效工具。

处理智能体故障与循环 是 CoddyKit 上的免费 AI Engineering Academy 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Engineering Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Engineering Academy 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Why Agents Fail and Loop

Agents can get stuck in failure loops for several reasons: a broken tool returns an error the agent doesn't know how to escape, the model generates malformed action syntax repeatedly, a task is impossible given the available tools, or the agent keeps calling the same tool with slight variations hoping for a different result. Without safeguards, this burns API budget and never resolves.

Maximum Iteration Limits

The simplest protection is a hard cap on the number of Thought/Action/Observation cycles. LangChain's AgentExecutor accepts a max_iterations parameter. When the limit is hit, the executor stops the loop and returns a message indicating the agent could not complete the task.

from langchain.agents import AgentExecutor

agent_executor = AgentExecutor(
    agent=agent,
    tools=tools,
    max_iterations=10,             # Hard stop after 10 steps
    max_execution_time=30.0,       # Also stop after 30 wall-clock seconds
    early_stopping_method='generate',  # Ask the model for a partial answer at the limit
    verbose=True
)

Early Stopping: Force a Final Answer

When the agent hits its iteration limit, early_stopping_method='generate' prompts the model one final time with: 'You have reached your step limit. Based on what you know so far, give your best final answer.' This is better than returning a blank response or crashing, as it gives the user something useful.

# The 'generate' early_stopping_method adds this system instruction
# when max_iterations is reached:
#
# 'You have {N} steps remaining but the task is not complete.
#  Give your best final answer based on the information gathered so far.'
#
# Contrast with 'force' which abruptly terminates without generating an answer.

agent_executor = AgentExecutor(
    agent=agent,
    tools=tools,
    max_iterations=7,
    early_stopping_method='generate'
)

Handling Parse Errors Gracefully

When the model produces output that doesn't match the Thought/Action format — missing the action keyword, using the wrong tool name, or outputting free text — the agent raises a OutputParserException. Set handle_parsing_errors=True to feed the error back as an observation so the model can self-correct.

agent_executor = AgentExecutor(
    agent=agent,
    tools=tools,
    handle_parsing_errors=True,
    # Custom error message fed back to the model:
    # handle_parsing_errors='Please format your response as Thought/Action/Action Input.'
)

# When a parse error occurs, the executor automatically adds:
# Observation: Could not parse LLM output. Please follow the format:
#   Thought: ...
#   Action: tool_name
#   Action Input: ...

Detecting and Breaking Repetitive Loops

A common loop pattern: the agent calls search('same query') three times in a row, each time getting the same useless result. Implement loop detection by tracking recent (tool, input) pairs. If the same combination repeats more than twice, inject an observation that suggests a different approach.

from collections import Counter

class LoopDetector:
    def __init__(self, max_repeats: int = 2):
        self.max_repeats = max_repeats
        self.call_counts = Counter()

    def check(self, tool_name: str, tool_input: str) -> bool:
        key = f'{tool_name}:{tool_input}'
        self.call_counts[key] += 1
        if self.call_counts[key] > self.max_repeats:
            return True  # Loop detected
        return False

    def get_warning(self) -> str:
        return ('You have called this tool with the same input multiple times. '
                'Try a different approach, different search terms, or a different tool.')

Tool-Level Error Handling

Robust agents require robust tools. Every tool should catch its own exceptions and return structured error messages rather than raising Python exceptions. Include the error type and a suggestion for the agent so it knows whether to retry, change its approach, or escalate.

from langchain_core.tools import tool
import requests

@tool
def get_company_data(company_name: str) -> str:
    '''Retrieve company information from the business database.
    Input: company name as a string.
    '''
    try:
        resp = requests.get(
            f'https://api.example.com/companies/{company_name}',
            timeout=5
        )
        if resp.status_code == 404:
            return f'No company found with name "{company_name}". Try the exact legal name or ticker symbol.'
        if resp.status_code == 429:
            return 'Rate limit exceeded. Wait 60 seconds before trying again.'
        resp.raise_for_status()
        return resp.json().get('summary', 'No summary available.')
    except requests.Timeout:
        return 'The database is not responding. Try searching the web instead.'

Exponential Backoff on API Failures

When tools call external APIs, transient failures are common. Add retry logic with exponential backoff inside the tool function — retry up to 3 times with increasing waits between attempts. This handles rate limits and brief outages transparently without the agent needing to know about retries.

import time
import requests
from langchain_core.tools import tool

@tool
def reliable_search(query: str) -> str:
    '''Search with automatic retry on failure. Input: search query string.'''
    max_retries = 3
    for attempt in range(max_retries):
        try:
            resp = requests.get(
                'https://api.duckduckgo.com/',
                params={'q': query, 'format': 'json'},
                timeout=10
            )
            resp.raise_for_status()
            data = resp.json()
            return data.get('AbstractText', 'No results found.')
        except requests.RequestException as e:
            if attempt < max_retries - 1:
                wait = 2 ** attempt  # 1s, 2s, 4s
                time.sleep(wait)
            else:
                return f'Search failed after {max_retries} attempts: {str(e)}'

Timeout Budgets at the Agent Level

Individual tool retries are great, but you also need a total wall-clock timeout for the entire agent run. If the task takes longer than your SLA allows (say, 30 seconds), stop the loop and return a graceful degradation response. LangChain's max_execution_time parameter handles this at the executor level.

import asyncio

async def run_with_timeout(user_input: str, timeout_seconds: float = 30.0) -> str:
    try:
        result = await asyncio.wait_for(
            agent_executor.ainvoke({'input': user_input}),
            timeout=timeout_seconds
        )
        return result['output']
    except asyncio.TimeoutError:
        return ('I am taking longer than expected to answer this question. '
                'Please try again with a simpler question, or check back later.')

Logging Failures for Analysis

Every agent failure is data. Log the full trace — user input, all intermediate steps, the failure reason, and the number of iterations used — to a database or observability platform. Analysing failure patterns reveals which tools are unreliable, which question types the agent cannot handle, and which loops occur most often.

import logging
import json

logger = logging.getLogger('agent')

def run_and_log(user_input: str) -> str:
    try:
        result = agent_executor.invoke(
            {'input': user_input},
            return_intermediate_steps=True
        )
        if not result.get('output'):
            logger.warning('Agent returned empty output', extra={
                'input': user_input,
                'steps': len(result.get('intermediate_steps', []))
            })
        return result['output']
    except Exception as e:
        logger.error('Agent failed with exception', extra={
            'input': user_input,
            'error': str(e),
            'error_type': type(e).__name__
        })
        return 'I encountered an error. Please try rephrasing your question.'

Injecting Recovery Hints Into the Prompt

When you detect a failure pattern, you can dynamically inject recovery instructions into the agent's next prompt. For example, if the search tool has been failing, add a hint like: 'The web search tool is currently unreliable. Prefer the knowledge base tool for this query.' This steers the agent toward a working solution without hard-coded fallback logic.

Testing Failure Scenarios

Build an explicit test suite for failure scenarios. Test what happens when: all tools return errors, the model hits max_iterations, the input contains no answerable question, and the model calls a non-existent tool. Your agent should always return a sensible message and never crash the application, no matter how adversarial the situation.

Quick Check

Test your understanding of handling agent failures and preventing loops.

Lesson Recap

In this lesson you learned: max_iterations and max_execution_time set hard limits on agent runtime, handle_parsing_errors feeds format mistakes back to the model for self-correction, and tools should catch exceptions and return descriptive error strings rather than raising. Next up we explore OpenAI's native function calling feature for structured tool integration.

常见问题解答

「处理智能体故障与循环」课时是免费的吗?

是的 — 「处理智能体故障与循环」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Engineering Academy 课程的其余内容,请升级到 CoddyKit PRO。 AI Engineering Academy 课程共包含 4 节课。

「处理智能体故障与循环」这节课中我会学到什么?

添加超时限制、最大迭代次数上限和错误恢复提示,防止智能体无限循环或反复调用失效工具。 你通过在浏览器中直接运行的动手代码来练习 AI Engineering Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 AI Engineering Academy 需要有经验吗?

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

「处理智能体故障与循环」课时需要多长时间?

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

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

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

此课程中的所有课时

  1. ReAct 框架:思考、行动、观察
  2. 为您的 Agent 定义工具
  3. 使用 LangChain 构建 ReAct Agent
  4. 处理智能体故障与循环
← 返回 AI Engineering Academy