context.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. """Context builder — assembles system prompt and message lists."""
  2. from __future__ import annotations
  3. import platform
  4. import time
  5. from datetime import datetime
  6. from pathlib import Path
  7. from typing import Any
  8. _BOOTSTRAP_FILES = ("AGENTS.md", "SOUL.md", "USER.md", "IDENTITY.md")
  9. _RUNTIME_TAG = "[Runtime Context]"
  10. class ContextBuilder:
  11. """Builds system prompt + message lists for the LLM."""
  12. def __init__(self, workspace: Path):
  13. self.workspace = workspace
  14. # ------------------------------------------------------------------
  15. # Public API
  16. # ------------------------------------------------------------------
  17. def build_messages(
  18. self,
  19. history: list[dict[str, Any]],
  20. user_message: str,
  21. channel: str | None = None,
  22. chat_id: str | None = None,
  23. skills_summary: str = "",
  24. ) -> list[dict[str, Any]]:
  25. """Return the full message list: [system, ...history, user]."""
  26. system = self._build_system_prompt(skills_summary)
  27. runtime = self._runtime_context(channel, chat_id)
  28. merged_user = f"{runtime}\n\n{user_message}"
  29. return [
  30. {"role": "system", "content": system},
  31. *history,
  32. {"role": "user", "content": merged_user},
  33. ]
  34. @staticmethod
  35. def add_assistant_message(
  36. messages: list[dict[str, Any]],
  37. content: str | None,
  38. tool_calls: list[dict[str, Any]] | None = None,
  39. ) -> list[dict[str, Any]]:
  40. msg: dict[str, Any] = {"role": "assistant", "content": content}
  41. if tool_calls:
  42. msg["tool_calls"] = tool_calls
  43. messages.append(msg)
  44. return messages
  45. @staticmethod
  46. def add_tool_result(
  47. messages: list[dict[str, Any]],
  48. tool_call_id: str,
  49. tool_name: str,
  50. result: str,
  51. ) -> list[dict[str, Any]]:
  52. messages.append({
  53. "role": "tool",
  54. "tool_call_id": tool_call_id,
  55. "name": tool_name,
  56. "content": result,
  57. })
  58. return messages
  59. # ------------------------------------------------------------------
  60. # Internals
  61. # ------------------------------------------------------------------
  62. def _build_system_prompt(self, skills_summary: str) -> str:
  63. ws = str(self.workspace.expanduser().resolve())
  64. system = platform.system()
  65. runtime = f"{'macOS' if system == 'Darwin' else system} {platform.machine()}"
  66. parts: list[str] = [
  67. f"# ToyClaw 🐾\n\n"
  68. f"You are ToyClaw, a helpful AI assistant.\n\n"
  69. f"## Runtime\n{runtime}, Python {platform.python_version()}\n\n"
  70. f"## Workspace\n"
  71. f"Your workspace is at: {ws}\n"
  72. f"- Long-term memory: {ws}/memory/MEMORY.md\n"
  73. f"- History log: {ws}/memory/HISTORY.md\n\n"
  74. f"## Guidelines\n"
  75. f"- State intent before tool calls, but NEVER predict results.\n"
  76. f"- Before modifying a file, read it first.\n"
  77. f"- If a tool call fails, analyze the error before retrying.\n"
  78. f"- Ask for clarification when the request is ambiguous.",
  79. ]
  80. # Load workspace bootstrap files
  81. for fname in _BOOTSTRAP_FILES:
  82. fp = self.workspace / fname
  83. if fp.exists():
  84. parts.append(f"## {fname}\n\n{fp.read_text(encoding='utf-8')}")
  85. # Memory context
  86. mem_file = self.workspace / "memory" / "MEMORY.md"
  87. if mem_file.exists():
  88. mem = mem_file.read_text(encoding="utf-8").strip()
  89. if mem:
  90. parts.append(f"## Long-term Memory\n\n{mem}")
  91. if skills_summary:
  92. parts.append(f"## Skills\n\n"
  93. f"Read a skill's SKILL.md with read_file to use it.\n\n"
  94. f"{skills_summary}")
  95. return "\n\n---\n\n".join(parts)
  96. @staticmethod
  97. def _runtime_context(channel: str | None, chat_id: str | None) -> str:
  98. now = datetime.now().strftime("%Y-%m-%d %H:%M (%A)")
  99. tz = time.strftime("%Z") or "UTC"
  100. lines = [_RUNTIME_TAG, f"Time: {now} ({tz})"]
  101. if channel and chat_id:
  102. lines.append(f"Channel: {channel} Chat: {chat_id}")
  103. return "\n".join(lines)
  104. @staticmethod
  105. def strip_runtime_tag(content: str) -> str:
  106. """Strip the runtime context prefix from stored user messages."""
  107. if isinstance(content, str) and content.startswith(_RUNTIME_TAG):
  108. parts = content.split("\n\n", 1)
  109. return parts[1].strip() if len(parts) > 1 else ""
  110. return content