| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243 |
- """
- agent67.core.assistant โ lambda ็ๅคง่ ๐
- Lambda ่กจ่พพๅผ:
- lambda = Memory(Loop(Brain >> parse_action >> route_execute))
- assistant = ฮป user_msg.
- let history = Memory.recall()
- let response = Loop(Brain(history + user_msg + observations))
- Memory.store(user_msg, response)
- response
- """
- from __future__ import annotations
- import json
- import re
- import sys
- import os
- from pathlib import Path
- from typing import Any
- # ่ทฏๅพ่ฎพ็ฝฎ
- PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent.parent
- sys.path.insert(0, str(PROJECT_ROOT))
- from lambdagent import Lam, Tool, Loop, Context
- from lambdagent.extensions import Memory, Guard
- from .claude_lam import ClaudeLam
- from .ollama_lam import OllamaLam
- from .config import BACKEND_OLLAMA, BACKEND_CLAUDE_CODE, BACKEND_API
- from .prompt import SYSTEM_PROMPT
- from ..tools.shell_executor import execute_shell
- from ..tools.file_manager import manage_file
- from ..tools.browser_controller import control_browser
- from ..tools.app_controller import control_app
- from ..tools.system_info import query_system
- from ..tools.screenshot import take_screenshot
- # โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
- # ๅทฅๅ
ทๆณจๅ่กจ
- # โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
- TOOL_REGISTRY = {
- "shell": execute_shell,
- "file": manage_file,
- "browser": control_browser,
- "app": control_app,
- "system": query_system,
- "screenshot": take_screenshot,
- }
- # โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
- # ่งฃๆ & ๆง่กๅผๆ
- # โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
- def parse_and_execute(llm_output: str) -> tuple[str, bool]:
- """
- ่งฃๆ LLM ่พๅบ๏ผๆๅๅทฅๅ
ท่ฐ็จๅนถๆง่กใ
- ่ฟๅ: (result_text, is_done)
- """
- # ๅฐ่ฏไป ```json ... ``` ไปฃ็ ๅๆๅ
- matches = re.findall(r'```json\s*\n?(.*?)\n?```', llm_output, re.DOTALL)
- if not matches:
- # ๅฐ่ฏ็ดๆฅๆพ JSON ๅฏน่ฑก
- matches = re.findall(r'\{[^{}]*"tool"\s*:.*?\}', llm_output, re.DOTALL)
- if not matches:
- # ๆฒกๆๅทฅๅ
ท่ฐ็จ๏ผ็บฏๆๆฌๅๅค
- return llm_output, False
- # ๅๆๅไธไธช JSON
- json_str = matches[-1].strip()
- try:
- data = json.loads(json_str)
- except json.JSONDecodeError:
- return f"(ๆ ๆณ่งฃๆ JSON: {json_str[:100]})\n{llm_output}", False
- tool_name = data.get("tool", "")
- # ไปปๅกๅฎๆไฟกๅท
- if tool_name == "done":
- summary = data.get("summary", "ไปปๅกๅฎๆ")
- return summary, True
- # ่ทฏ็ฑๅฐๅทฅๅ
ท
- tool_fn = TOOL_REGISTRY.get(tool_name)
- if not tool_fn:
- return f"โ ๆช็ฅๅทฅๅ
ท: {tool_name}", False
- # ๅๅค่พๅ
ฅ๏ผๅปๆ tool ๅญๆฎต๏ผ
- tool_input = {k: v for k, v in data.items() if k != "tool"}
- tool_input_str = json.dumps(tool_input, ensure_ascii=False)
- # ๆง่ก
- result = tool_fn(tool_input_str)
- return result, False
- # โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
- # PersonalAssistant โ ไธป็ฑป
- # โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
- class PersonalAssistant:
- """
- lambda ไธชไบบๅฉ็ = Memory(ReAct(Brain))
- ฮป ๆผ็ฎ:
- lambda = Memory(Loop(Lam("brain", SYSTEM_PROMPT)))
- """
- def __init__(self, model: str = "sonnet", use_api: bool = False,
- backend: str = ""):
- if backend == BACKEND_OLLAMA:
- # Ollama ๆฌๅฐๆจกๅ๏ผQwen2.5ใGLM-4ใLlama3 ็ญ๏ผ
- self.brain = OllamaLam(
- "lambda_assistant",
- prompt=SYSTEM_PROMPT,
- model=model,
- temperature=0.3,
- max_tokens=4096,
- )
- elif use_api or backend == BACKEND_API:
- # API ๆจกๅผ๏ผ็ดๆฅ่ฐ API๏ผ้่ฆ API Key๏ผ
- self.brain = Lam(
- "lambda_assistant",
- prompt=SYSTEM_PROMPT,
- model=model,
- temperature=0.3,
- max_tokens=2048,
- )
- else:
- # Claude Code ๆจกๅผ๏ผ้่ฟ CLI ่ฐ็จ๏ผMax Plan๏ผๆ ้ API Key๏ผ
- self.brain = ClaudeLam(
- "lambda_assistant",
- prompt=SYSTEM_PROMPT,
- model=model,
- max_tokens=4096,
- )
- self.ctx = Context()
- self.conversation_history: list[dict] = []
- self.max_history = 20
- def _build_input(self, user_msg: str, observations: list[str] | None = None) -> str:
- """ๆๅปบๅฎๆด่พๅ
ฅ๏ผๅๅฒ + ๆถๆฏ + ๅทฅๅ
ท็ปๆ๏ผ"""
- parts = []
- # ๅฏน่ฏๅๅฒ
- if self.conversation_history:
- parts.append("=== ๅฏน่ฏๅๅฒ ===")
- for entry in self.conversation_history[-self.max_history:]:
- content = entry["content"]
- if len(content) > 300:
- content = content[:300] + "..."
- parts.append(f"[{entry['role']}] {content}")
- parts.append("=== ๅๅฒ็ปๆ ===\n")
- # ๅทฅๅ
ท่งๅฏ
- if observations:
- parts.append("=== ๅทฅๅ
ทๆง่ก็ปๆ ===")
- for obs in observations:
- parts.append(obs)
- parts.append("=== ็ปๆ็ปๆ ===\n")
- parts.append("่ฏทๅบไบไปฅไธๅทฅๅ
ทๆง่ก็ปๆ๏ผๅณๅฎไธไธๆญฅ่กๅจๆ็ปๅบๆ็ปๅๅคใ")
- else:
- parts.append(f"[็จๆท] {user_msg}")
- return "\n".join(parts)
- def chat(self, user_msg: str) -> str:
- """
- ไธ lambda ๅฏน่ฏใๅฎๆด ReAct ๅพช็ฏใ
- ReAct:
- 1. Brain ๆ่ โ ๅๅค or ๅทฅๅ
ท่ฐ็จ
- 2. ๅทฅๅ
ท่ฐ็จ โ ๆง่ก โ ็ปๆๅ้ฆ็ป Brain
- 3. ้ๅค็ดๅฐๅฎๆๆ่พพๅฐๆๅคงๆญฅๆฐ
- """
- self.conversation_history.append({"role": "็จๆท", "content": user_msg})
- observations = []
- max_steps = 10
- final_response = ""
- for step in range(max_steps):
- # ๆๅปบ่พๅ
ฅ
- if step == 0:
- llm_input = self._build_input(user_msg)
- else:
- llm_input = self._build_input(user_msg, observations)
- # Brain ๆ่ (ฮฒ-่ง็บฆ)
- llm_output = self.brain.apply(llm_input, self.ctx)
- # ่งฃๆๅนถๆง่ก
- result, is_done = parse_and_execute(llm_output)
- if is_done:
- text_part = re.sub(r'```json.*?```', '', llm_output, flags=re.DOTALL).strip()
- final_response = text_part + ("\n" + result if result else "")
- break
- if result != llm_output:
- # ๅทฅๅ
ท่ขซๆง่ก๏ผๆพ็คบไธญ้ด่ฟ็จ
- text_part = re.sub(r'```json.*?```', '', llm_output, flags=re.DOTALL).strip()
- json_matches = re.findall(r'\{[^{}]*"tool"\s*:.*?\}', llm_output)
- tool_call = json_matches[-1] if json_matches else ""
- if text_part:
- print(f" ๐ญ {text_part[:150]}")
- print(f" ๐ง ๆง่ก: {tool_call[:100]}")
- print(f" ๐ ็ปๆ: {result[:200]}")
- print()
- observations.append(f"[ๅทฅๅ
ท่ฐ็จ] {tool_call}\n[ๆง่ก็ปๆ] {result}")
- else:
- # ็บฏๆๆฌๅๅค
- final_response = llm_output
- break
- else:
- final_response = f"(่พพๅฐๆๅคงๆญฅๆฐ {max_steps})\nๆๅ็่งๅฏ:\n" + (
- observations[-1] if observations else "ๆ "
- )
- # ่ฎฐๅฝๅๅค
- self.conversation_history.append({
- "role": "lambda",
- "content": final_response[:500],
- })
- return final_response
- def print_trace(self):
- """ๆๅฐ ฮฒ-่ง็บฆ่ฟฝ่ธช"""
- print(f"\n{'=' * 50}")
- print(f"ฮฒ-่ง็บฆ่ฟฝ่ธช ({len(self.ctx.trace)} ๆญฅ):")
- print(f"{'=' * 50}")
- self.ctx.print_trace()
|