code.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. #!/usr/bin/env python3
  2. """
  3. s10: 系统提示词 — 运行时组装提示词并缓存。
  4. 运行: python s10_system_prompt/code.py
  5. 需要: pip install anthropic python-dotenv + .env 中配置 ANTHROPIC_API_KEY
  6. 相对 s09 的变化:
  7. - PROMPT_SECTIONS:按主题作为 key 的提示词片段字典
  8. - assemble_system_prompt(context):根据真实状态选择并拼接片段
  9. - get_system_prompt(context):通过 json.dumps 实现确定性的缓存
  10. - agent_loop 使用 get_system_prompt(context),不再使用硬编码 SYSTEM
  11. 当 .memory/MEMORY.md 存在时加载记忆片段(基于真实状态,不靠关键词)。
  12. """
  13. import os, subprocess, json
  14. from pathlib import Path
  15. try:
  16. import readline
  17. readline.parse_and_bind('set bind-tty-special-chars off')
  18. except ImportError:
  19. pass
  20. from anthropic import Anthropic
  21. from dotenv import load_dotenv
  22. load_dotenv(override=True)
  23. if os.getenv("ANTHROPIC_BASE_URL"):
  24. os.environ.pop("ANTHROPIC_AUTH_TOKEN", None)
  25. WORKDIR = Path.cwd()
  26. MEMORY_DIR = WORKDIR / ".memory"
  27. MEMORY_INDEX = MEMORY_DIR / "MEMORY.md"
  28. client = Anthropic(base_url=os.getenv("ANTHROPIC_BASE_URL"))
  29. MODEL = os.environ["MODEL_ID"]
  30. # ── 提示词片段 ──
  31. PROMPT_SECTIONS = {
  32. "identity": "你是一个编码 Agent。直接行动,不要只解释。",
  33. }
  34. def assemble_system_prompt(context: dict) -> str:
  35. """Select and join prompt sections based on current context."""
  36. sections = []
  37. # 始终加载 — 身份
  38. sections.append(PROMPT_SECTIONS["identity"])
  39. # 动态加载 — 来自上下文的工具和工作区
  40. tools = ", ".join(context.get("enabled_tools", []))
  41. if tools:
  42. sections.append(f"可用工具:{tools}.")
  43. sections.append(f"工作目录:{context.get('workspace', WORKDIR)}")
  44. # 条件加载 — MEMORY.md 存在且有内容时加载记忆
  45. memories = context.get("memories", "")
  46. if memories:
  47. sections.append(f"Relevant memories:\n{memories}")
  48. return "\n\n".join(sections)
  49. _last_context_key = None
  50. _last_prompt = None
  51. def get_system_prompt(context: dict) -> str:
  52. """Cache wrapper — reassemble only when context changes.
  53. Uses json.dumps for deterministic serialization, not Python's hash()
  54. which has process randomization and fails on nested dicts/lists.
  55. This cache only avoids redundant string assembly within a process.
  56. Real Claude Code additionally protects API-level prompt cache via
  57. stable section ordering and SYSTEM_PROMPT_DYNAMIC_BOUNDARY.
  58. """
  59. global _last_context_key, _last_prompt
  60. key = json.dumps(context, sort_keys=True, ensure_ascii=False, default=str)
  61. if key == _last_context_key and _last_prompt:
  62. print(" \033[90m[缓存命中] 系统提示词未变化\033[0m")
  63. return _last_prompt
  64. _last_context_key = key
  65. _last_prompt = assemble_system_prompt(context)
  66. loaded = ["identity", "tools", "workspace"]
  67. if context.get("memories"):
  68. loaded.append("memory")
  69. print(f" \033[32m[已组装] 片段:{', '.join(loaded)}\033[0m")
  70. return _last_prompt
  71. # ── 工具 ──
  72. def safe_path(p: str) -> Path:
  73. path = (WORKDIR / p).resolve()
  74. if not path.is_relative_to(WORKDIR):
  75. raise ValueError(f"路径逃逸出工作区:{p}")
  76. return path
  77. def run_bash(command: str) -> str:
  78. try:
  79. r = subprocess.run(command, shell=True, cwd=WORKDIR,
  80. capture_output=True, text=True, timeout=120)
  81. out = (r.stdout + r.stderr).strip()
  82. return out[:50000] if out else "(无输出)"
  83. except subprocess.TimeoutExpired:
  84. return "错误:执行超时(120 秒)"
  85. def run_read(path: str, limit: int | None = None) -> str:
  86. try:
  87. lines = safe_path(path).read_text().splitlines()
  88. if limit and limit < len(lines):
  89. lines = lines[:limit] + [f"... ({len(lines) - limit} 行更多内容)"]
  90. return "\n".join(lines)
  91. except Exception as e:
  92. return f"错误:{e}"
  93. def run_write(path: str, content: str) -> str:
  94. try:
  95. file_path = safe_path(path)
  96. file_path.parent.mkdir(parents=True, exist_ok=True)
  97. file_path.write_text(content)
  98. return f"已写入 {len(content)} 字节到 {path}"
  99. except Exception as e:
  100. return f"错误:{e}"
  101. TOOLS = [
  102. {"name": "bash", "description": "运行一条 shell 命令。",
  103. "input_schema": {"type": "object",
  104. "properties": {"command": {"type": "string"}},
  105. "required": ["command"]}},
  106. {"name": "read_file", "description": "读取文件内容。",
  107. "input_schema": {"type": "object",
  108. "properties": {"path": {"type": "string"},
  109. "limit": {"type": "integer"}},
  110. "required": ["path"]}},
  111. {"name": "write_file", "description": "向文件写入内容。",
  112. "input_schema": {"type": "object",
  113. "properties": {"path": {"type": "string"},
  114. "content": {"type": "string"}},
  115. "required": ["path", "content"]}},
  116. ]
  117. TOOL_HANDLERS = {"bash": run_bash, "read_file": run_read, "write_file": run_write}
  118. # ── 上下文 ──
  119. def update_context(context: dict, messages: list) -> dict:
  120. """从真实状态推导上下文:有哪些工具、是否存在记忆文件。"""
  121. memories = ""
  122. if MEMORY_INDEX.exists():
  123. content = MEMORY_INDEX.read_text().strip()
  124. if content:
  125. memories = content
  126. return {
  127. "enabled_tools": list(TOOL_HANDLERS.keys()),
  128. "workspace": str(WORKDIR),
  129. "memories": memories,
  130. }
  131. # ── Agent 循环 ──
  132. def agent_loop(messages: list, context: dict):
  133. """Main loop — uses assembled system prompt instead of hardcoded SYSTEM."""
  134. system = get_system_prompt(context)
  135. while True:
  136. response = client.messages.create(
  137. model=MODEL, system=system, messages=messages,
  138. tools=TOOLS, max_tokens=8000)
  139. messages.append({"role": "assistant", "content": response.content})
  140. if response.stop_reason != "tool_use":
  141. return
  142. results = []
  143. for block in response.content:
  144. if block.type != "tool_use":
  145. continue
  146. print(f"\033[36m> {block.name}\033[0m")
  147. handler = TOOL_HANDLERS.get(block.name)
  148. output = handler(**block.input) if handler else f"未知工具:{block.name}"
  149. print(str(output)[:200])
  150. results.append({"type": "tool_result",
  151. "tool_use_id": block.id, "content": output})
  152. messages.append({"role": "user", "content": results})
  153. # 每轮工具调用后重新评估上下文和提示词
  154. context = update_context(context, messages)
  155. system = get_system_prompt(context)
  156. if __name__ == "__main__":
  157. print("s10: 系统提示词 — 运行时组装")
  158. print("输入问题后按回车发送。输入 q 退出。\n")
  159. history = []
  160. context = update_context({}, [])
  161. while True:
  162. try:
  163. query = input("\033[36ms10 >> \033[0m")
  164. except (EOFError, KeyboardInterrupt):
  165. break
  166. if query.strip().lower() in ("q", "exit", ""):
  167. break
  168. history.append({"role": "user", "content": query})
  169. agent_loop(history, context)
  170. context = update_context(context, history)
  171. for block in history[-1]["content"]:
  172. if getattr(block, "type", None) == "text":
  173. print(block.text)
  174. print()