code.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. #!/usr/bin/env python3
  2. """
  3. s11: 错误恢复 — 三条恢复路径 + 指数退避。
  4. 运行: python s11_error_recovery/code.py
  5. 需要: pip install anthropic python-dotenv + .env 中配置 ANTHROPIC_API_KEY
  6. 相对 s10 的变化:
  7. - LLM 调用包在 try/except 中,并提供三条恢复路径
  8. - 路径 1:max_tokens -> 从 8K 升级到 64K(第一次升级不追加截断输出),
  9. 然后发送续写提示(最多 3 次)
  10. - 路径 2:prompt_too_long -> reactive compact -> 重试(一次)
  11. - 路径 3:429/529 -> 带抖动的指数退避(最多 10 次),
  12. 连续 529 时切换备用模型
  13. - with_retry 包装器处理瞬时错误
  14. - RecoveryState 跟踪升级 / 压缩 / 529 / 模型
  15. ASCII 流程:
  16. messages -> 提示词组装 -> 压缩+加载 -> [try] LLM [except] -> tools -> 循环
  17. | |
  18. stop_reason 错误类型
  19. max_tokens? prompt_too_long? -> 压缩
  20. 升级 / 429/529? -> 退避
  21. 继续 其他? -> 记录 + 退出
  22. """
  23. import os, subprocess, time, random, json
  24. from pathlib import Path
  25. try:
  26. import readline
  27. readline.parse_and_bind('set bind-tty-special-chars off')
  28. except ImportError:
  29. pass
  30. from anthropic import Anthropic
  31. from dotenv import load_dotenv
  32. load_dotenv(override=True)
  33. if os.getenv("ANTHROPIC_BASE_URL"):
  34. os.environ.pop("ANTHROPIC_AUTH_TOKEN", None)
  35. WORKDIR = Path.cwd()
  36. MEMORY_DIR = WORKDIR / ".memory"
  37. MEMORY_INDEX = MEMORY_DIR / "MEMORY.md"
  38. client = Anthropic(base_url=os.getenv("ANTHROPIC_BASE_URL"))
  39. PRIMARY_MODEL = os.environ["MODEL_ID"]
  40. FALLBACK_MODEL = os.getenv("FALLBACK_MODEL_ID")
  41. # ── 常量 ──
  42. ESCALATED_MAX_TOKENS = 64000
  43. DEFAULT_MAX_TOKENS = 8000
  44. MAX_RECOVERY_RETRIES = 3
  45. MAX_RETRIES = 10
  46. BASE_DELAY_MS = 500
  47. MAX_CONSECUTIVE_529 = 3
  48. CONTINUATION_PROMPT = (
  49. "已触发输出 token 上限。请直接继续 — "
  50. "不要道歉,不要回顾,从中断处接着写。"
  51. )
  52. # ── 提示词组装 (来自 s10,已同步) ──
  53. PROMPT_SECTIONS = {
  54. "identity": "你是一个编码 Agent。直接行动,不要只解释。",
  55. "tools": "可用工具:bash, read_file, write_file.",
  56. "workspace": f"工作目录:{WORKDIR}",
  57. "memory": "有可用的相关记忆时,会在下方注入。",
  58. }
  59. def assemble_system_prompt(context: dict) -> str:
  60. sections = [PROMPT_SECTIONS["identity"],
  61. PROMPT_SECTIONS["tools"],
  62. PROMPT_SECTIONS["workspace"]]
  63. memories = context.get("memories", "")
  64. if memories:
  65. sections.append(f"相关记忆:\n{memories}")
  66. return "\n\n".join(sections)
  67. _last_context_key, _last_prompt = None, None
  68. def get_system_prompt(context: dict) -> str:
  69. global _last_context_key, _last_prompt
  70. key = json.dumps(context, sort_keys=True, ensure_ascii=False, default=str)
  71. if key == _last_context_key and _last_prompt:
  72. print(" \033[90m[缓存命中] 系统提示词未变化\033[0m")
  73. return _last_prompt
  74. _last_context_key = key
  75. _last_prompt = assemble_system_prompt(context)
  76. loaded = ["identity", "tools", "workspace"]
  77. if context.get("memories"):
  78. loaded.append("memory")
  79. print(f" \033[32m[已组装] 片段:{', '.join(loaded)}\033[0m")
  80. return _last_prompt
  81. # ── 工具 (未改动) ──
  82. def safe_path(p: str) -> Path:
  83. path = (WORKDIR / p).resolve()
  84. if not path.is_relative_to(WORKDIR):
  85. raise ValueError(f"路径逃逸出工作区:{p}")
  86. return path
  87. def run_bash(command: str) -> str:
  88. try:
  89. r = subprocess.run(command, shell=True, cwd=WORKDIR,
  90. capture_output=True, text=True, timeout=120)
  91. out = (r.stdout + r.stderr).strip()
  92. return out[:50000] if out else "(无输出)"
  93. except subprocess.TimeoutExpired:
  94. return "错误:执行超时(120 秒)"
  95. def run_read(path: str, limit: int | None = None) -> str:
  96. try:
  97. lines = safe_path(path).read_text().splitlines()
  98. if limit and limit < len(lines):
  99. lines = lines[:limit] + [f"... ({len(lines) - limit} 行更多内容)"]
  100. return "\n".join(lines)
  101. except Exception as e:
  102. return f"错误:{e}"
  103. def run_write(path: str, content: str) -> str:
  104. try:
  105. file_path = safe_path(path)
  106. file_path.parent.mkdir(parents=True, exist_ok=True)
  107. file_path.write_text(content)
  108. return f"已写入 {len(content)} 字节到 {path}"
  109. except Exception as e:
  110. return f"错误:{e}"
  111. TOOLS = [
  112. {"name": "bash", "description": "运行一条 shell 命令。",
  113. "input_schema": {"type": "object",
  114. "properties": {"command": {"type": "string"}},
  115. "required": ["command"]}},
  116. {"name": "read_file", "description": "读取文件内容。",
  117. "input_schema": {"type": "object",
  118. "properties": {"path": {"type": "string"},
  119. "limit": {"type": "integer"}},
  120. "required": ["path"]}},
  121. {"name": "write_file", "description": "向文件写入内容。",
  122. "input_schema": {"type": "object",
  123. "properties": {"path": {"type": "string"},
  124. "content": {"type": "string"}},
  125. "required": ["path", "content"]}},
  126. ]
  127. TOOL_HANDLERS = {"bash": run_bash, "read_file": run_read, "write_file": run_write}
  128. # ── 错误恢复 (s11 new) ──
  129. class RecoveryState:
  130. """在循环中跟踪恢复尝试。"""
  131. def __init__(self):
  132. self.has_escalated = False
  133. self.recovery_count = 0
  134. self.consecutive_529 = 0
  135. self.has_attempted_reactive_compact = False
  136. self.current_model = PRIMARY_MODEL
  137. def retry_delay(attempt, retry_after=None):
  138. """带抖动的指数退避。Retry-After 优先。"""
  139. if retry_after:
  140. return retry_after
  141. base = min(BASE_DELAY_MS * (2 ** attempt), 32000) / 1000
  142. jitter = random.uniform(0, base * 0.25)
  143. return base + jitter
  144. def with_retry(fn, state: RecoveryState):
  145. """针对瞬时错误(429/529)的指数退避。
  146. 非瞬时错误会重新抛给外层处理器。"""
  147. for attempt in range(MAX_RETRIES):
  148. try:
  149. result = fn()
  150. state.consecutive_529 = 0
  151. return result
  152. except Exception as e:
  153. name = type(e).__name__
  154. msg = str(e).lower()
  155. # 429 速率限制 -> 指数退避
  156. if "ratelimit" in name.lower() or "429" in msg:
  157. delay = retry_delay(attempt)
  158. print(f" \033[33m[429 速率限制] 重试 {attempt+1}/{MAX_RETRIES},"
  159. f" 等待 {delay:.1f}s\033[0m")
  160. time.sleep(delay)
  161. continue
  162. # 529 过载 -> 指数退避 + 备用模型
  163. if "过载" in name.lower() or "529" in msg or "过载" in msg:
  164. state.consecutive_529 += 1
  165. if state.consecutive_529 >= MAX_CONSECUTIVE_529:
  166. if FALLBACK_MODEL:
  167. state.current_model = FALLBACK_MODEL
  168. state.consecutive_529 = 0
  169. print(f" \033[31m[529 x{MAX_CONSECUTIVE_529}]"
  170. f" 切换到 {FALLBACK_MODEL}\033[0m")
  171. else:
  172. state.consecutive_529 = 0
  173. print(f" \033[31m[529 x{MAX_CONSECUTIVE_529}]"
  174. f" 未配置 FALLBACK_MODEL_ID,继续重试\033[0m")
  175. delay = retry_delay(attempt)
  176. print(f" \033[33m[529 过载] 重试 {attempt+1}/{MAX_RETRIES},"
  177. f" 等待 {delay:.1f}s\033[0m")
  178. time.sleep(delay)
  179. continue
  180. # 非瞬时错误 -> 重新抛给外层 try/except
  181. raise
  182. raise RuntimeError(f"最大重试次数({MAX_RETRIES})已超出")
  183. def is_prompt_too_long_error(e: Exception) -> bool:
  184. """检查 API 错误是否表示提示词/上下文过长。"""
  185. msg = str(e).lower()
  186. return (("prompt" in msg and "long" in msg)
  187. or "提示词过长" in msg
  188. or "context_length_exceeded" in msg
  189. or "max_context_window" in msg)
  190. def reactive_compact(messages: list) -> list:
  191. """应急压缩 — 教学版本保留最后 N 条消息。
  192. 真实 CC 会通过 LLM 生成压缩摘要,然后用压缩后的消息列表重试。
  193. 因为 s08/s09 已覆盖基于 LLM 的压缩,教学版本简化为保留尾部消息。"""
  194. print(" \033[31m[响应式压缩] 裁剪到最后 5 条消息\033[0m")
  195. tail = messages[-5:]
  196. return [{"role": "user",
  197. "content": "[响应式压缩] 早前对话已被裁剪。请从中断处继续。"}, *tail]
  198. # ── 上下文 ──
  199. def update_context(context: dict, messages: list) -> dict:
  200. """从真实状态推导上下文:有哪些工具、是否存在记忆文件。"""
  201. memories = ""
  202. if MEMORY_INDEX.exists():
  203. content = MEMORY_INDEX.read_text().strip()
  204. if content:
  205. memories = content
  206. return {
  207. "enabled_tools": list(TOOL_HANDLERS.keys()),
  208. "workspace": str(WORKDIR),
  209. "memories": memories,
  210. }
  211. # ── Agent 循环 ──
  212. def agent_loop(messages: list, context: dict):
  213. """主循环:为 LLM 调用包上错误恢复逻辑。"""
  214. system = get_system_prompt(context)
  215. state = RecoveryState()
  216. max_tokens = DEFAULT_MAX_TOKENS
  217. while True:
  218. # ── LLM 调用:with_retry 处理 429/529,外层处理其余错误 ──
  219. try:
  220. response = with_retry(
  221. lambda: client.messages.create(
  222. model=state.current_model, system=system,
  223. messages=messages, tools=TOOLS,
  224. max_tokens=max_tokens),
  225. state)
  226. except Exception as e:
  227. # 路径 2:prompt_too_long -> 响应式压缩(一次)
  228. if is_prompt_too_long_error(e):
  229. if not state.has_attempted_reactive_compact:
  230. messages[:] = reactive_compact(messages)
  231. state.has_attempted_reactive_compact = True
  232. continue
  233. print(" \033[31m[不可恢复] 压缩后仍然过长\033[0m")
  234. messages.append({"role": "assistant", "content": [
  235. {"type": "text",
  236. "text": "[错误] 上下文过大,无法继续。"}]})
  237. return
  238. # 不可恢复
  239. name = type(e).__name__
  240. print(f" \033[31m[不可恢复] {name}: {str(e)[:100]}\033[0m")
  241. messages.append({"role": "assistant", "content": [
  242. {"type": "text", "text": f"[错误] {name}: {str(e)[:200]}"}]})
  243. return
  244. # ── 路径 1:max_tokens -> 升级或继续 ──
  245. if response.stop_reason == "max_tokens":
  246. # 第一次升级:不追加截断输出,重试同一个请求
  247. if not state.has_escalated:
  248. max_tokens = ESCALATED_MAX_TOKENS
  249. state.has_escalated = True
  250. print(f" \033[33m[max_tokens] 升级"
  251. f" {DEFAULT_MAX_TOKENS} -> {ESCALATED_MAX_TOKENS}\033[0m")
  252. continue
  253. # 64K 仍被截断:保存截断输出 + 续写提示
  254. messages.append({"role": "assistant", "content": response.content})
  255. if state.recovery_count < MAX_RECOVERY_RETRIES:
  256. messages.append({"role": "user", "content": CONTINUATION_PROMPT})
  257. state.recovery_count += 1
  258. print(f" \033[33m[max_tokens] 续写"
  259. f" {state.recovery_count}/{MAX_RECOVERY_RETRIES}\033[0m")
  260. continue
  261. print(" \033[31m[max_tokens] 恢复次数已达上限\033[0m")
  262. return
  263. # 正常完成:追加 assistant 响应
  264. messages.append({"role": "assistant", "content": response.content})
  265. if response.stop_reason != "tool_use":
  266. return
  267. # ── 工具执行 ──
  268. results = []
  269. for block in response.content:
  270. if block.type != "tool_use":
  271. continue
  272. print(f"\033[36m> {block.name}\033[0m")
  273. handler = TOOL_HANDLERS.get(block.name)
  274. output = handler(**block.input) if handler else f"未知工具:{block.name}"
  275. print(str(output)[:200])
  276. results.append({"type": "tool_result",
  277. "tool_use_id": block.id, "content": output})
  278. messages.append({"role": "user", "content": results})
  279. context = update_context(context, messages)
  280. system = get_system_prompt(context)
  281. if __name__ == "__main__":
  282. print("s11: 错误恢复")
  283. print("输入问题后按回车发送。输入 q 退出。\n")
  284. history = []
  285. context = update_context({}, [])
  286. while True:
  287. try:
  288. query = input("\033[36ms11 >> \033[0m")
  289. except (EOFError, KeyboardInterrupt):
  290. break
  291. if query.strip().lower() in ("q", "exit", ""):
  292. break
  293. turn_start = len(history)
  294. history.append({"role": "user", "content": query})
  295. agent_loop(history, context)
  296. context = update_context(context, history)
  297. for msg in history[turn_start:]:
  298. if msg.get("role") != "assistant":
  299. continue
  300. for block in msg["content"]:
  301. if getattr(block, "type", None) == "text":
  302. print(block.text)
  303. print()