assistant.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. """
  2. agent67.core.assistant โ€” lambda ็š„ๅคง่„‘ ๐Ÿ‘
  3. Lambda ่กจ่พพๅผ:
  4. lambda = Memory(Loop(Brain >> parse_action >> route_execute))
  5. assistant = ฮป user_msg.
  6. let history = Memory.recall()
  7. let response = Loop(Brain(history + user_msg + observations))
  8. Memory.store(user_msg, response)
  9. response
  10. """
  11. from __future__ import annotations
  12. import json
  13. import re
  14. import sys
  15. import os
  16. from pathlib import Path
  17. from typing import Any
  18. # ่ทฏๅพ„่ฎพ็ฝฎ
  19. PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent.parent
  20. sys.path.insert(0, str(PROJECT_ROOT))
  21. from lambdagent import Lam, Tool, Loop, Context
  22. from lambdagent.extensions import Memory, Guard
  23. from .claude_lam import ClaudeLam
  24. from .ollama_lam import OllamaLam
  25. from .config import BACKEND_OLLAMA, BACKEND_CLAUDE_CODE, BACKEND_API
  26. from .prompt import SYSTEM_PROMPT
  27. from ..tools.shell_executor import execute_shell
  28. from ..tools.file_manager import manage_file
  29. from ..tools.browser_controller import control_browser
  30. from ..tools.app_controller import control_app
  31. from ..tools.system_info import query_system
  32. from ..tools.screenshot import take_screenshot
  33. # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
  34. # ๅทฅๅ…ทๆณจๅ†Œ่กจ
  35. # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
  36. TOOL_REGISTRY = {
  37. "shell": execute_shell,
  38. "file": manage_file,
  39. "browser": control_browser,
  40. "app": control_app,
  41. "system": query_system,
  42. "screenshot": take_screenshot,
  43. }
  44. # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
  45. # ่งฃๆž & ๆ‰ง่กŒๅผ•ๆ“Ž
  46. # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
  47. def parse_and_execute(llm_output: str) -> tuple[str, bool]:
  48. """
  49. ่งฃๆž LLM ่พ“ๅ‡บ๏ผŒๆๅ–ๅทฅๅ…ท่ฐƒ็”จๅนถๆ‰ง่กŒใ€‚
  50. ่ฟ”ๅ›ž: (result_text, is_done)
  51. """
  52. # ๅฐ่ฏ•ไปŽ ```json ... ``` ไปฃ็ ๅ—ๆๅ–
  53. matches = re.findall(r'```json\s*\n?(.*?)\n?```', llm_output, re.DOTALL)
  54. if not matches:
  55. # ๅฐ่ฏ•็›ดๆŽฅๆ‰พ JSON ๅฏน่ฑก
  56. matches = re.findall(r'\{[^{}]*"tool"\s*:.*?\}', llm_output, re.DOTALL)
  57. if not matches:
  58. # ๆฒกๆœ‰ๅทฅๅ…ท่ฐƒ็”จ๏ผŒ็บฏๆ–‡ๆœฌๅ›žๅค
  59. return llm_output, False
  60. # ๅ–ๆœ€ๅŽไธ€ไธช JSON
  61. json_str = matches[-1].strip()
  62. try:
  63. data = json.loads(json_str)
  64. except json.JSONDecodeError:
  65. return f"(ๆ— ๆณ•่งฃๆž JSON: {json_str[:100]})\n{llm_output}", False
  66. tool_name = data.get("tool", "")
  67. # ไปปๅŠกๅฎŒๆˆไฟกๅท
  68. if tool_name == "done":
  69. summary = data.get("summary", "ไปปๅŠกๅฎŒๆˆ")
  70. return summary, True
  71. # ่ทฏ็”ฑๅˆฐๅทฅๅ…ท
  72. tool_fn = TOOL_REGISTRY.get(tool_name)
  73. if not tool_fn:
  74. return f"โŒ ๆœช็Ÿฅๅทฅๅ…ท: {tool_name}", False
  75. # ๅ‡†ๅค‡่พ“ๅ…ฅ๏ผˆๅŽปๆމ tool ๅญ—ๆฎต๏ผ‰
  76. tool_input = {k: v for k, v in data.items() if k != "tool"}
  77. tool_input_str = json.dumps(tool_input, ensure_ascii=False)
  78. # ๆ‰ง่กŒ
  79. result = tool_fn(tool_input_str)
  80. return result, False
  81. # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
  82. # PersonalAssistant โ€” ไธป็ฑป
  83. # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
  84. class PersonalAssistant:
  85. """
  86. lambda ไธชไบบๅŠฉ็† = Memory(ReAct(Brain))
  87. ฮป ๆผ”็ฎ—:
  88. lambda = Memory(Loop(Lam("brain", SYSTEM_PROMPT)))
  89. """
  90. def __init__(self, model: str = "sonnet", use_api: bool = False,
  91. backend: str = ""):
  92. if backend == BACKEND_OLLAMA:
  93. # Ollama ๆœฌๅœฐๆจกๅž‹๏ผˆQwen2.5ใ€GLM-4ใ€Llama3 ็ญ‰๏ผ‰
  94. self.brain = OllamaLam(
  95. "lambda_assistant",
  96. prompt=SYSTEM_PROMPT,
  97. model=model,
  98. temperature=0.3,
  99. max_tokens=4096,
  100. )
  101. elif use_api or backend == BACKEND_API:
  102. # API ๆจกๅผ๏ผš็›ดๆŽฅ่ฐƒ API๏ผˆ้œ€่ฆ API Key๏ผ‰
  103. self.brain = Lam(
  104. "lambda_assistant",
  105. prompt=SYSTEM_PROMPT,
  106. model=model,
  107. temperature=0.3,
  108. max_tokens=2048,
  109. )
  110. else:
  111. # Claude Code ๆจกๅผ๏ผš้€š่ฟ‡ CLI ่ฐƒ็”จ๏ผˆMax Plan๏ผŒๆ— ้œ€ API Key๏ผ‰
  112. self.brain = ClaudeLam(
  113. "lambda_assistant",
  114. prompt=SYSTEM_PROMPT,
  115. model=model,
  116. max_tokens=4096,
  117. )
  118. self.ctx = Context()
  119. self.conversation_history: list[dict] = []
  120. self.max_history = 20
  121. def _build_input(self, user_msg: str, observations: list[str] | None = None) -> str:
  122. """ๆž„ๅปบๅฎŒๆ•ด่พ“ๅ…ฅ๏ผˆๅކๅฒ + ๆถˆๆฏ + ๅทฅๅ…ท็ป“ๆžœ๏ผ‰"""
  123. parts = []
  124. # ๅฏน่ฏๅކๅฒ
  125. if self.conversation_history:
  126. parts.append("=== ๅฏน่ฏๅކๅฒ ===")
  127. for entry in self.conversation_history[-self.max_history:]:
  128. content = entry["content"]
  129. if len(content) > 300:
  130. content = content[:300] + "..."
  131. parts.append(f"[{entry['role']}] {content}")
  132. parts.append("=== ๅކๅฒ็ป“ๆŸ ===\n")
  133. # ๅทฅๅ…ท่ง‚ๅฏŸ
  134. if observations:
  135. parts.append("=== ๅทฅๅ…ทๆ‰ง่กŒ็ป“ๆžœ ===")
  136. for obs in observations:
  137. parts.append(obs)
  138. parts.append("=== ็ป“ๆžœ็ป“ๆŸ ===\n")
  139. parts.append("่ฏทๅŸบไบŽไปฅไธŠๅทฅๅ…ทๆ‰ง่กŒ็ป“ๆžœ๏ผŒๅ†ณๅฎšไธ‹ไธ€ๆญฅ่กŒๅŠจๆˆ–็ป™ๅ‡บๆœ€็ปˆๅ›žๅคใ€‚")
  140. else:
  141. parts.append(f"[็”จๆˆท] {user_msg}")
  142. return "\n".join(parts)
  143. def chat(self, user_msg: str) -> str:
  144. """
  145. ไธŽ lambda ๅฏน่ฏใ€‚ๅฎŒๆ•ด ReAct ๅพช็Žฏใ€‚
  146. ReAct:
  147. 1. Brain ๆ€่€ƒ โ†’ ๅ›žๅค or ๅทฅๅ…ท่ฐƒ็”จ
  148. 2. ๅทฅๅ…ท่ฐƒ็”จ โ†’ ๆ‰ง่กŒ โ†’ ็ป“ๆžœๅ้ฆˆ็ป™ Brain
  149. 3. ้‡ๅค็›ดๅˆฐๅฎŒๆˆๆˆ–่พพๅˆฐๆœ€ๅคงๆญฅๆ•ฐ
  150. """
  151. self.conversation_history.append({"role": "็”จๆˆท", "content": user_msg})
  152. observations = []
  153. max_steps = 10
  154. final_response = ""
  155. for step in range(max_steps):
  156. # ๆž„ๅปบ่พ“ๅ…ฅ
  157. if step == 0:
  158. llm_input = self._build_input(user_msg)
  159. else:
  160. llm_input = self._build_input(user_msg, observations)
  161. # Brain ๆ€่€ƒ (ฮฒ-่ง„็บฆ)
  162. llm_output = self.brain.apply(llm_input, self.ctx)
  163. # ่งฃๆžๅนถๆ‰ง่กŒ
  164. result, is_done = parse_and_execute(llm_output)
  165. if is_done:
  166. text_part = re.sub(r'```json.*?```', '', llm_output, flags=re.DOTALL).strip()
  167. final_response = text_part + ("\n" + result if result else "")
  168. break
  169. if result != llm_output:
  170. # ๅทฅๅ…ท่ขซๆ‰ง่กŒ๏ผŒๆ˜พ็คบไธญ้—ด่ฟ‡็จ‹
  171. text_part = re.sub(r'```json.*?```', '', llm_output, flags=re.DOTALL).strip()
  172. json_matches = re.findall(r'\{[^{}]*"tool"\s*:.*?\}', llm_output)
  173. tool_call = json_matches[-1] if json_matches else ""
  174. if text_part:
  175. print(f" ๐Ÿ’ญ {text_part[:150]}")
  176. print(f" ๐Ÿ”ง ๆ‰ง่กŒ: {tool_call[:100]}")
  177. print(f" ๐Ÿ“‹ ็ป“ๆžœ: {result[:200]}")
  178. print()
  179. observations.append(f"[ๅทฅๅ…ท่ฐƒ็”จ] {tool_call}\n[ๆ‰ง่กŒ็ป“ๆžœ] {result}")
  180. else:
  181. # ็บฏๆ–‡ๆœฌๅ›žๅค
  182. final_response = llm_output
  183. break
  184. else:
  185. final_response = f"(่พพๅˆฐๆœ€ๅคงๆญฅๆ•ฐ {max_steps})\nๆœ€ๅŽ็š„่ง‚ๅฏŸ:\n" + (
  186. observations[-1] if observations else "ๆ— "
  187. )
  188. # ่ฎฐๅฝ•ๅ›žๅค
  189. self.conversation_history.append({
  190. "role": "lambda",
  191. "content": final_response[:500],
  192. })
  193. return final_response
  194. def print_trace(self):
  195. """ๆ‰“ๅฐ ฮฒ-่ง„็บฆ่ฟฝ่ธช"""
  196. print(f"\n{'=' * 50}")
  197. print(f"ฮฒ-่ง„็บฆ่ฟฝ่ธช ({len(self.ctx.trace)} ๆญฅ):")
  198. print(f"{'=' * 50}")
  199. self.ctx.print_trace()