-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
119 lines (95 loc) · 3.87 KB
/
Copy pathmain.py
File metadata and controls
119 lines (95 loc) · 3.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
"""Mini Agent CLI 入口:交互式对话循环。"""
import logging
import sys
from pathlib import Path
from uuid import uuid4
def _configure_logging() -> None:
root = Path(__file__).resolve().parent
log_dir = root / "logs"
log_dir.mkdir(parents=True, exist_ok=True)
log_path = log_dir / "mini_agent.log"
console_handler = logging.StreamHandler(sys.stderr)
console_handler.setLevel(logging.WARNING)
file_handler = logging.FileHandler(log_path, encoding="utf-8")
file_handler.setLevel(logging.INFO)
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
handlers=[console_handler, file_handler],
force=True,
)
_configure_logging()
WELCOME_BANNER = """
╔══════════════════════════════════════════════════╗
║ Mini Agent - 基于 LangGraph ║
║ 输入你的问题开始对话,输入 'exit' 退出 ║
║ 输入 'new' 开始新对话(清除历史) ║
║ 输入 'help' 查看帮助 ║
╚══════════════════════════════════════════════════╝
"""
HELP_TEXT = """
可用命令:
exit / quit / 退出 — 退出程序
new / 新对话 — 开始新的对话(新的 thread_id)
help / 帮助 — 显示此帮助
其他输入 — 发送消息给 Agent
运行时特性:
- 显式 user_id / thread_id
- OpenViking session 维护可恢复会话历史
- OpenViking user memories 维护长期记忆
"""
def _new_thread_id() -> str:
return str(uuid4())
def _get_last_ai_message(messages: list) -> str:
for msg in reversed(messages):
if getattr(msg, "type", None) == "ai":
content = getattr(msg, "content", "")
if isinstance(content, list):
parts = [part.get("text", "") for part in content if isinstance(part, dict)]
return "\n".join(parts)
return str(content)
return "(无回复)"
def main() -> None:
print(WELCOME_BANNER)
user_id = input("请输入 user_id(默认 local-user): ").strip() or "local-user"
print("正在初始化 Agent...")
try:
from backend.runtime import MiniAgentRuntime
runtime = MiniAgentRuntime()
except Exception as exc:
print(f"\n❌ 初始化失败:{exc}")
print("请检查 config.yaml 和环境变量配置是否正确")
sys.exit(1)
print("✅ Agent 已就绪\n")
thread_id = _new_thread_id()
print(f"当前用户: {user_id}")
print(f"当前会话 ID: {thread_id[:8]}...\n")
while True:
try:
user_input = input("你: ").strip()
except (EOFError, KeyboardInterrupt):
print("\n\n再见!")
break
if not user_input:
continue
if user_input.lower() in ("exit", "quit", "退出", "q"):
print("再见!")
break
if user_input.lower() in ("new", "新对话"):
thread_id = _new_thread_id()
print(f"✅ 已开始新对话,会话 ID: {thread_id[:8]}...\n")
continue
if user_input.lower() in ("help", "帮助", "?"):
print(HELP_TEXT)
continue
try:
response = runtime.invoke(user_input, user_id=user_id, thread_id=thread_id)
answer = _get_last_ai_message(response.get("messages", []))
print(f"\n助手: {answer}\n")
except KeyboardInterrupt:
print("\n(已中断)\n")
except Exception as exc:
print(f"\n❌ 出错了:{exc}\n")
logging.getLogger(__name__).exception("Agent 调用失败")
if __name__ == "__main__":
main()