LangChain 错误处理与调试
核对错误分类、模型与工具重试退避边界、幂等保护、ToolErrorMiddleware 组合、调用上限与 GraphRecursionError、流式调试、结构化纠错及长对话摘要并完成全套离线实测。
学完这一章,你能够
- 核对错误分类、模型与工具重试退避边界、幂等保护、ToolErrorMiddleware 组合、调用上限与 GraphRecursionError、流式调试、结构化纠错及长对话摘要并完成全套离线实测。
错误分类原则、依赖排查与凭据校验
可靠的 Agent 不仅要能完成正常任务,更要对各类异常做精准分流:网络超时与短暂限流可按条件有限重试;API Key 认证失败应立即修复凭据;工具参数不合法应校验并反馈模型;而创建订单、支付、发邮件等具外部副作用的调用失败后,必须先核实远端业务状态而绝不能盲目重发。核心原则是先判断“错误能否靠重试解决”以及“重复执行是否安全”。
LangChain 1.x 按功能拆分独立包,在当前虚拟环境内缺少集成包(如未装 langchain-deepseek)会抛出 ModuleNotFoundError,升级大版本后亦应核对新版官方导入路径(弃用旧版 AgentExecutor 与旧 Chain 路径)并可用 importlib.metadata.version() 核查实际版本。排查身份认证错误时依次核对 .env 加载、密钥拼写、有效期、模型授权与 API 地址;自检代码仅打印 bool(key),严禁向终端或日志输出完整 API Key,且不对认证错误配置大量重试。
ModelRetryMiddleware、指数退避与工具重试/错误处理组合
针对模型超时与瞬时故障,ModelRetryMiddleware 通过 max_retries、initial_delay、backoff_factor、max_delay、jitter、retry_on 与 on_failure 控制有限退避重试。务必明晰两项语义:(1)max_retries=2 表示首次调用失败后最多额外重试 2 次,即总计最多 3 次尝试;(2)将底层模型客户端自身的 max_retries 设为 0 可避免 SDK 与中间件双重重试叠加失控。当 jitter=False、initial_delay=1.0、backoff_factor=2.0、max_delay=10.0 时退避序列为 [1.0, 2.0, 4.0, 8.0, 10.0](开启 jitter=True 加入随机扰动防惊群)。本站离线实测真实 ModelRetryMiddleware:两次 TimeoutError 后第 3 次成功(attempts=3);不在 retry_on 内的 PermissionError 第 1 次立即抛出;重试耗尽时 on_failure='error' 抛异常,而 on_failure='continue' 将异常包装为 AIMessage 返回,故应用层绝不能仅凭“未抛异常”就假定业务成功。
对于搜索、只读查询等可安全重复的工具,可用 ToolRetryMiddleware(tools=[...], retry_on=(ConnectionError, TimeoutError)) 仅针对临时故障重试(教学示例里的全局计数器不适用于多并发服务)。相反,发邮件、建订单、扣款、删文件与改库等有外部副作用的工具切忌直接自动重试——若服务端已落单仅响应在网络中丢失,盲目重试将产生重复订单;真实业务必须引入幂等请求 ID、唯一流水号、状态反查与人工审批。本站实验验证了相同 req_id 重复提交仅创建 1 条订单。
业务参数非法等无需重试的错误可用 ToolErrorMiddleware(on_error=handle_tool_error) 转为模型可理解的错误 ToolMessage,未明确接管的异常返回 None 继续向外抛出以免掩盖基础设施故障。同时处理临时网络抖动与业务错误时,将 ToolErrorMiddleware 置外层、ToolRetryMiddleware 置内层(on_failure='error')。本站组合实测验证三条独立路径:search_course 首次 ConnectionError 由内层自动重试并在第 2 次成功;get_course(-5) 抛出的 ValueError 不触发重试并由外层转为 status='error' 的提示 ToolMessage;未处理的 RuntimeError 直接穿透向外抛出。
调试模式、防循环限流、Schema 纠错与长对话摘要
排错观测有三种梯度工具:create_agent(debug=True) 在本地输出详尽图执行日志(输出格式随版本变动,不可写死解析,且含消息与参数敏感内容,生产忌开);agent.stream(..., stream_mode='updates') 结构化查看节点更新(本站实测准确产出 ['model', 'tools', 'model']);stream_mode='debug' 产出包含 type、timestamp、step、payload 字段的细粒度图事件(数据量大,宜用于本地排错而非直推终端前端)。
当工具返回语义不清、Prompt 冲突或路由异常导致工具无限循环时,应三管齐下设防并根治工具输出:ToolCallLimitMiddleware 限制单次运行工具调用数(注意不同 exit_behavior 语义,切勿把触发上限视作成功),ModelCallLimitMiddleware 限制模型调用数,并在 invoke config 中设定 recursion_limit 捕获 GraphRecursionError(需明确 recursion_limit 限制的是底层图节点步数而非模型次数,遇错应排查循环根因而非盲目调大上限)。本站对死循环离线模型实测:ToolCallLimitMiddleware(run_limit=2) 精确在 2 次工具调用后止停,ModelCallLimitMiddleware(run_limit=2) 精确在 2 次模型调用后止停,无限制中间件时设 recursion_limit=5 稳定触发并捕获 GraphRecursionError。
工具入参可用 Pydantic args_schema(如 course_id: int = Field(gt=0))在执行前拦截非法类型与范围(本站实测 'abc' 与 0 均抛出 ValidationError,但须知 Pydantic 仅验格式而不验业务对象归属权限);结构化输出可用 ToolStrategy(CourseInfo, handle_errors=True) 把校验反馈交回模型修正(本站实测首轮输出非法枚举 'super_hard' 后第 2 轮自动修正为合法 'beginner',但不涵盖超时或网络故障)。长对话防上下文超限可用 SummarizationMiddleware(trigger=..., keep=...) 压缩早期历史(消息数不等价于 Token 数,且不能用 return {'messages': messages[-6:]} 覆盖 add_messages reducer,否则会破坏消息序列与工具配对);对话记忆失灵时应通过 agent.get_state(config) 核查 checkpointer、thread_id 与连接存活(InMemorySaver 重启即失)。本站实测四轮对话在 trigger=('messages', 6)、keep=('messages', 2) 下自动触发摘要并使最终历史长度收敛至 8 条以内且 state.next == ()。
结构化日志、完整故障控制、最佳实践与常见问题
生产调试应结合 Python 标准库 logging(记录请求 ID、工具名、耗时、错误类别、重试次数与终态,严禁泄露 API Key 与隐私)与 LangSmith 追踪(配好脱敏与权限)。完整容错 Agent 将模型超时、ModelRetryMiddleware、ToolRetryMiddleware、ToolErrorMiddleware、调用次数限制及顶层 try/except(分流 GraphRecursionError、TimeoutError 与兜底异常)整合为一体,并在返回后显式核对业务终态而非只看是否抛错。本站验证自定义 logging 处理器完整采集两项结构化日志且零密钥泄露。
生产十项最佳实践与高频问答核心在于:按错误类型分流重试策略;对有副作用操作强加幂等保护;拉通 SDK、中间件、HTTP 与网关的整体超时/重试预算;用调用上限与递归上限防止死循环;靠请求 ID 串联多端日志并脱敏敏感信息;区分“订单不存在”类正常业务失败与数据库断开类技术异常;工具失败后禁止模型声称成功;将线上故障沉淀为回归测试;把业务校验、事务、授权与异常恢复交给可信代码而非寄望 System Prompt。总而言之,构建可靠 Agent 的核心不是无条件自动重试,而是精准决策“何者可重试、何者须速停、如何保幂等”。
LangChain Agent 常见错误类型与处置矩阵
| 错误类型 | 典型原因 | 处理建议 |
| ImportError | 拆分依赖包缺失、版本不兼容或沿用旧版导入路径 | 核查虚拟环境与 importlib.metadata 版本并按新版 API 导入 |
| AuthenticationError | API Key 缺失、拼写错误、失效或无模型访问权限 | 立即检查凭据与端点配置,不做大量自动重试 |
| RateLimitError | 请求频率超限或账号额度不足 | 结合限流、指数退避加抖动重试并检查配额 |
| TimeoutError | 网络抖动或上游模型响应超时 | 设定合理超时预算并针对幂等调用有限重试 |
| Context Length Error | 多轮消息或工具返回超出模型上下文窗口 | 使用 SummarizationMiddleware 总结历史并限制输出长度 |
| ValidationError | 工具参数或结构化输出不符合 Pydantic Schema | 用 args_schema 拦截入参并用 ToolStrategy(handle_errors=True) 纠偏 |
| Tool Execution Error | 工具内部业务逻辑异常或外部依赖短暂不可用 | 组合 ToolRetryMiddleware(临时故障)与 ToolErrorMiddleware(业务错误) |
| GraphRecursionError | 工具死循环或路由异常导致超出图执行步数上限 | 排查工具输出与停止条件,并加装工具/模型调用上限中间件 |
| Checkpoint Error | thread_id 错配、连接失效或检查点状态恢复异常 | 通过 get_state() 核查检查点实例、线程标识与持久化连接 |
RetryMiddleware 常用重试与退避参数
| 参数 | 作用 |
| max_retries | 首次调用失败后最多额外重试次数(如 max_retries=2 总计最多 3 次尝试) |
| initial_delay | 第一次重试前的初始基础等待秒数 |
| backoff_factor | 指数退避乘数因子(逐次按幂次放大延迟) |
| max_delay | 单次退避等待时间的封顶上限秒数 |
| jitter | 是否在等待时长中加入随机抖动以避免并发重试惊群 |
| retry_on | 指定允许触发重试的异常类型元组或判断函数 |
| on_failure | 重试全部耗尽后的策略:'error' 抛出异常,'continue' 转为消息返回 |
运行模型/工具重试退避、错误中间件组合、防循环上限、结构化纠偏与历史摘要实验
展开查看收起
"""Offline runtime verification lab for LangChain Ch 37: Error Handling & Debugging."""
import json
import logging
import os
import platform
import warnings
from typing import Any, Literal
os.environ["LANGSMITH_TRACING"] = "false"
warnings.filterwarnings("ignore", category=DeprecationWarning)
from langchain.agents import create_agent
from langchain.agents.middleware import (
ModelCallLimitMiddleware,
ModelRetryMiddleware,
SummarizationMiddleware,
ToolCallLimitMiddleware,
ToolErrorMiddleware,
ToolRetryMiddleware,
)
from langchain.agents.structured_output import ToolStrategy
from langchain.tools import tool
from langchain_core.language_models.chat_models import BaseChatModel
from langchain_core.messages import AIMessage, BaseMessage
from langchain_core.outputs import ChatGeneration, ChatResult
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.errors import GraphRecursionError
from pydantic import BaseModel, Field, ValidationError
class FlakyChatModel(BaseChatModel):
"""Offline model raising scripted failures before returning a valid AIMessage."""
failures: list[str] = []
attempts: int = 0
reply: str = "模型调用成功。"
@property
def _llm_type(self) -> str:
return "offline-flaky-model"
def bind_tools(self, tools: Any, **kwargs: Any) -> "FlakyChatModel":
return self
def _generate(self, messages: list[BaseMessage], stop: Any = None, **kwargs: Any) -> ChatResult:
self.attempts += 1
if self.attempts <= len(self.failures):
kind = self.failures[self.attempts - 1]
if kind == "timeout":
raise TimeoutError("模拟:模型请求超时")
if kind == "auth":
raise PermissionError("模拟:API Key 认证失败")
return ChatResult(generations=[ChatGeneration(message=AIMessage(content=self.reply))])
class ScriptedToolAgentModel(BaseChatModel):
"""Offline model invoking scripted tool calls (single, looping, or structured recovery)."""
mode: str = "single"
tool_name: str = "search_course"
tool_args: dict[str, Any] = {}
calls: int = 0
@property
def _llm_type(self) -> str:
return "offline-scripted-agent-model"
def bind_tools(self, tools: Any, **kwargs: Any) -> "ScriptedToolAgentModel":
return self
def _generate(self, messages: list[BaseMessage], stop: Any = None, **kwargs: Any) -> ChatResult:
self.calls += 1
last = messages[-1]
if self.mode == "loop":
ai = AIMessage(
content="",
tool_calls=[
{
"name": self.tool_name,
"args": dict(self.tool_args),
"id": f"call_loop_{self.calls}",
"type": "tool_call",
}
],
)
return ChatResult(generations=[ChatGeneration(message=ai)])
if self.mode == "structured_recover":
diff = "super_hard" if self.calls == 1 else "beginner"
ai = AIMessage(
content="",
tool_calls=[
{
"name": "CourseInfo",
"args": {"course_name": "Python 基础", "difficulty": diff},
"id": f"call_struct_{self.calls}",
"type": "tool_call",
}
],
)
return ChatResult(generations=[ChatGeneration(message=ai)])
if self.mode == "echo_memory":
text = str(last.content)
if "叫什么" in text:
name = "未知"
for m in messages:
if m.type == "human" and "我叫" in str(m.content):
name = str(m.content).split("我叫", 1)[1].strip("。!? ")
return ChatResult(generations=[ChatGeneration(message=AIMessage(content=f"您叫{name}。"))])
return ChatResult(generations=[ChatGeneration(message=AIMessage(content=f"已收到:{text}"))])
if last.type == "tool":
return ChatResult(
generations=[ChatGeneration(message=AIMessage(content=f"处理完成:{last.content}"))]
)
ai = AIMessage(
content="",
tool_calls=[
{
"name": self.tool_name,
"args": dict(self.tool_args),
"id": f"call_once_{self.calls}",
"type": "tool_call",
}
],
)
return ChatResult(generations=[ChatGeneration(message=ai)])
def case_model_retry_and_backoff_semantics() -> dict:
# 1) Succeeds on attempt 3 with max_retries=2 (1 initial + 2 retries)
m_recover = FlakyChatModel(failures=["timeout", "timeout"], reply="第三次尝试成功")
agent_recover = create_agent(
model=m_recover,
tools=[],
middleware=[
ModelRetryMiddleware(
max_retries=2,
initial_delay=0.005,
backoff_factor=2.0,
max_delay=0.05,
jitter=False,
retry_on=(TimeoutError,),
on_failure="error",
)
],
)
res_ok = agent_recover.invoke({"messages": [{"role": "user", "content": "介绍一下 Python"}]})
# 2) Auth error not in retry_on fails immediately on attempt 1
m_auth = FlakyChatModel(failures=["auth", "auth"])
agent_auth = create_agent(
model=m_auth,
tools=[],
middleware=[
ModelRetryMiddleware(
max_retries=2,
initial_delay=0.005,
jitter=False,
retry_on=(TimeoutError,),
on_failure="error",
)
],
)
try:
agent_auth.invoke({"messages": [{"role": "user", "content": "测试认证错误"}]})
auth_raised = False
except PermissionError:
auth_raised = True
# 3) Exhausted retries: on_failure="error" raises, on_failure="continue" returns AIMessage
m_exhaust_err = FlakyChatModel(failures=["timeout"] * 5)
agent_err = create_agent(
model=m_exhaust_err,
tools=[],
middleware=[
ModelRetryMiddleware(
max_retries=2,
initial_delay=0.005,
jitter=False,
retry_on=(TimeoutError,),
on_failure="error",
)
],
)
try:
agent_err.invoke({"messages": [{"role": "user", "content": "测试耗尽抛错"}]})
exhaust_raised = False
except TimeoutError:
exhaust_raised = True
m_exhaust_cont = FlakyChatModel(failures=["timeout"] * 5)
agent_cont = create_agent(
model=m_exhaust_cont,
tools=[],
middleware=[
ModelRetryMiddleware(
max_retries=2,
initial_delay=0.005,
jitter=False,
retry_on=(TimeoutError,),
on_failure="continue",
)
],
)
res_cont = agent_cont.invoke({"messages": [{"role": "user", "content": "测试耗尽继续"}]})
# 4) Exponential backoff schedule formula verification
delays = [min(1.0 * (2.0**i), 10.0) for i in range(5)]
actual = {
"recover_attempts": m_recover.attempts,
"recover_reply": str(res_ok["messages"][-1].content),
"auth_raised_immediately": auth_raised and m_auth.attempts == 1,
"exhaust_error_raised_after_3": exhaust_raised and m_exhaust_err.attempts == 3,
"exhaust_continue_returned_ai": (
m_exhaust_cont.attempts == 3
and res_cont["messages"][-1].type == "ai"
and "TimeoutError" in str(res_cont["messages"][-1].content)
),
"backoff_schedule_capped": delays,
}
expected = {
"recover_attempts": 3,
"recover_reply": "第三次尝试成功",
"auth_raised_immediately": True,
"exhaust_error_raised_after_3": True,
"exhaust_continue_returned_ai": True,
"backoff_schedule_capped": [1.0, 2.0, 4.0, 8.0, 10.0],
}
return {
"name": "model_retry_and_backoff_semantics",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_tool_retry_error_schema_and_idempotency() -> dict:
transient_attempts = 0
biz_attempts = 0
@tool
def search_course(keyword: str) -> str:
"""查询模拟课程,首次模拟 ConnectionError。"""
nonlocal transient_attempts
transient_attempts += 1
if transient_attempts == 1:
raise ConnectionError("模拟:课程服务暂时不可用")
return f"找到 {keyword} 模拟课程"
@tool
def get_course(course_id: int) -> str:
"""根据正整数课程 ID 查询模拟课程。"""
nonlocal biz_attempts
biz_attempts += 1
if course_id <= 0:
raise ValueError("课程 ID 必须大于 0")
if course_id == 999:
raise RuntimeError("模拟:未处理内部故障")
return f"模拟课程 {course_id}:Python 基础"
def handle_tool_error(exc: Exception, request: Any):
if isinstance(exc, ValueError):
return "课程 ID 不合法,请使用大于 0 的整数。"
return None
mw = [
ToolErrorMiddleware(on_error=handle_tool_error),
ToolRetryMiddleware(
tools=["search_course", "get_course"],
max_retries=2,
retry_on=(ConnectionError, TimeoutError),
initial_delay=0.005,
backoff_factor=2.0,
jitter=False,
on_failure="error",
),
]
# Transient ConnectionError retried and recovered on attempt 2
a1 = create_agent(
model=ScriptedToolAgentModel(mode="single", tool_name="search_course", tool_args={"keyword": "Python"}),
tools=[search_course, get_course],
middleware=mw,
)
r1 = a1.invoke({"messages": [{"role": "user", "content": "查 Python"}]})
# Business ValueError NOT retried, converted to error ToolMessage by outer ToolErrorMiddleware
a2 = create_agent(
model=ScriptedToolAgentModel(mode="single", tool_name="get_course", tool_args={"course_id": -5}),
tools=[search_course, get_course],
middleware=mw,
)
r2 = a2.invoke({"messages": [{"role": "user", "content": "查 -5"}]})
r2_tool = next(m for m in r2["messages"] if m.type == "tool")
# Unhandled RuntimeError propagates out
a3 = create_agent(
model=ScriptedToolAgentModel(mode="single", tool_name="get_course", tool_args={"course_id": 999}),
tools=[search_course, get_course],
middleware=mw,
)
try:
a3.invoke({"messages": [{"role": "user", "content": "查 999"}]})
unhandled_propagated = False
except RuntimeError:
unhandled_propagated = True
# Pydantic args_schema validation before tool body runs
class CourseInput(BaseModel):
course_id: int = Field(gt=0, description="正整数课程 ID")
@tool(args_schema=CourseInput)
def validated_course(course_id: int) -> str:
"""带 Pydantic 校验的课程查询工具。"""
return f"课程 {course_id}:Python 基础"
ok_valid = validated_course.invoke({"course_id": 100})
try:
validated_course.invoke({"course_id": "abc"})
bad_str_rejected = False
except ValidationError:
bad_str_rejected = True
try:
validated_course.invoke({"course_id": 0})
zero_rejected = False
except ValidationError:
zero_rejected = True
# Idempotency guard for side-effect order creation
created_orders: dict[str, str] = {}
def create_order_idempotent(req_id: str, item: str) -> str:
if req_id not in created_orders:
created_orders[req_id] = f"ORDER-{len(created_orders) + 1}:{item}"
return created_orders[req_id]
o1 = create_order_idempotent("req-2026-01", "Python课")
o2 = create_order_idempotent("req-2026-01", "Python课")
actual = {
"transient_retried_to_2": transient_attempts == 2
and "找到 Python 模拟课程" in str(r1["messages"][-1].content),
"value_error_not_retried": biz_attempts == 2, # 1 for -5, 1 for 999
"value_error_converted_tool_msg": (
r2_tool.status == "error" and "课程 ID 不合法" in str(r2_tool.content)
),
"unhandled_runtime_propagated": unhandled_propagated,
"schema_valid_result": ok_valid,
"schema_rejects_bad_inputs": bad_str_rejected and zero_rejected,
"idempotent_single_order": o1 == o2 and len(created_orders) == 1,
}
expected = {
"transient_retried_to_2": True,
"value_error_not_retried": True,
"value_error_converted_tool_msg": True,
"unhandled_runtime_propagated": True,
"schema_valid_result": "课程 100:Python 基础",
"schema_rejects_bad_inputs": True,
"idempotent_single_order": True,
}
return {
"name": "tool_retry_error_schema_and_idempotency",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_loop_guards_limits_and_recursion_error() -> dict:
tool_hits = 0
@tool
def search_course(keyword: str) -> str:
"""搜索模拟编程课程。"""
nonlocal tool_hits
tool_hits += 1
return f"找到 {keyword} 入门课程"
# 1) ToolCallLimitMiddleware stops runaway tool loop
a_tool_limit = create_agent(
model=ScriptedToolAgentModel(mode="loop", tool_name="search_course", tool_args={"keyword": "Python"}),
tools=[search_course],
middleware=[
ToolCallLimitMiddleware(
tool_name="search_course",
run_limit=2,
exit_behavior="end",
)
],
)
a_tool_limit.invoke({"messages": [{"role": "user", "content": "查课程"}]})
hits_under_tool_limit = tool_hits
# 2) ModelCallLimitMiddleware stops runaway model calls
m_limit = ScriptedToolAgentModel(mode="loop", tool_name="search_course", tool_args={"keyword": "Python"})
a_model_limit = create_agent(
model=m_limit,
tools=[search_course],
middleware=[ModelCallLimitMiddleware(run_limit=2, exit_behavior="end")],
)
a_model_limit.invoke({"messages": [{"role": "user", "content": "查课程"}]})
# 3) GraphRecursionError triggered when recursion_limit is exceeded
a_rec = create_agent(
model=ScriptedToolAgentModel(mode="loop", tool_name="search_course", tool_args={"keyword": "Python"}),
tools=[search_course],
)
try:
a_rec.invoke(
{"messages": [{"role": "user", "content": "查课程"}]},
config={"recursion_limit": 5},
)
recursion_caught = False
except GraphRecursionError:
recursion_caught = True
actual = {
"tool_limit_capped_at_2": hits_under_tool_limit == 2,
"model_limit_capped_at_2": m_limit.calls == 2,
"graph_recursion_error_caught": recursion_caught,
}
expected = {
"tool_limit_capped_at_2": True,
"model_limit_capped_at_2": True,
"graph_recursion_error_caught": True,
}
return {
"name": "loop_guards_limits_and_recursion_error",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_debug_stream_structured_recovery_summarization_and_logging() -> dict:
@tool
def search_course(keyword: str) -> str:
"""搜索模拟编程课程。"""
return f"找到 {keyword} 入门课程"
# 1) stream_mode="updates" and stream_mode="debug"
a_stream = create_agent(
model=ScriptedToolAgentModel(mode="single", tool_name="search_course", tool_args={"keyword": "Python"}),
tools=[search_course],
)
update_nodes = [
node
for ev in a_stream.stream(
{"messages": [{"role": "user", "content": "请搜索 Python 课程"}]},
stream_mode="updates",
)
for node in ev.keys()
]
debug_events = list(
a_stream.stream(
{"messages": [{"role": "user", "content": "请搜索 Python 课程"}]},
stream_mode="debug",
)
)
debug_has_fields = all(
{"type", "timestamp", "step", "payload"} <= set(e.keys()) for e in debug_events
)
# 2) ToolStrategy(CourseInfo, handle_errors=True) auto-recovery from invalid literal
class CourseInfo(BaseModel):
course_name: str = Field(description="课程名称")
difficulty: Literal["beginner", "intermediate", "advanced"]
m_struct = ScriptedToolAgentModel(mode="structured_recover")
a_struct = create_agent(
model=m_struct,
tools=[],
response_format=ToolStrategy(CourseInfo, handle_errors=True),
)
res_struct = a_struct.invoke({"messages": [{"role": "user", "content": "返回 Python 基础信息"}]})
parsed = res_struct["structured_response"]
# 3) Checkpointer get_state + SummarizationMiddleware compressing long history
summary_llm = FlakyChatModel(failures=[], reply="历史摘要:用户名为小明,进行过多轮对话。")
a_mem = create_agent(
model=ScriptedToolAgentModel(mode="echo_memory"),
tools=[],
checkpointer=InMemorySaver(),
middleware=[
SummarizationMiddleware(
model=summary_llm,
trigger=("messages", 6),
keep=("messages", 2),
)
],
)
cfg = {"configurable": {"thread_id": "debug-memory-001"}}
for turn in ("我叫小明。", "介绍变量。", "介绍列表。", "介绍函数。"):
a_mem.invoke({"messages": [{"role": "user", "content": turn}]}, config=cfg)
state = a_mem.get_state(cfg)
msgs_after_summary = state.values.get("messages", [])
# 4) Python logging capturing business events without exposing secret key
records: list[str] = []
class ListHandler(logging.Handler):
def emit(self, record):
records.append(f"{record.levelname}:{record.getMessage()}")
logger = logging.getLogger("mbsky.agent.debug")
logger.setLevel(logging.INFO)
logger.propagate = False
logger.handlers = [ListHandler()]
fake_secret = "sk-live-secret-98765"
logger.info("API Key configured=%s", bool(fake_secret))
logger.info("tool=search_course status=ok")
actual = {
"updates_nodes": update_nodes,
"debug_events_gt_0_and_structured": len(debug_events) > 0 and debug_has_fields,
"structured_recovered_on_attempt_2": (
m_struct.calls == 2
and isinstance(parsed, CourseInfo)
and parsed.difficulty == "beginner"
),
"summarization_triggered_and_bounded": (
summary_llm.attempts >= 1 and len(msgs_after_summary) < 8 and state.next == ()
),
"logging_no_secret_leak": (
len(records) == 2 and all(fake_secret not in r for r in records)
),
}
expected = {
"updates_nodes": ["model", "tools", "model"],
"debug_events_gt_0_and_structured": True,
"structured_recovered_on_attempt_2": True,
"summarization_triggered_and_bounded": True,
"logging_no_secret_leak": True,
}
return {
"name": "debug_stream_structured_recovery_summarization_and_logging",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_model_retry_and_backoff_semantics(),
case_tool_retry_error_schema_and_idempotency(),
case_loop_guards_limits_and_recursion_error(),
case_debug_stream_structured_recovery_summarization_and_logging(),
]
print(
json.dumps(
{
"version": platform.python_version(),
"system": platform.system(),
"cases": cases,
},
ensure_ascii=False,
)
)
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
因为 on_failure='continue' 在重试耗尽时会捕获底层异常并包装成一条错误文本 AIMessage 返回,调用方收到的仍然是普通字典结果;因此业务代码必须显式检查返回状态、工具执行结果或错误标记,防止将故障提示误作正常完成。