"""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()
本例需在 Windows x64、CPython 3.12.14、LangChain 本地离线隔离依赖。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、LangChain 本地离线隔离依赖。
入口文件:projects/langchain-error-handling-lab/explore-error-handling.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-error-handling.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、LangChain 本地离线隔离依赖。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联37章) · 含当前章节或实例 · mbskycom202612a509.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a517.zip