-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinteractive.py
More file actions
180 lines (154 loc) · 5.97 KB
/
interactive.py
File metadata and controls
180 lines (154 loc) · 5.97 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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
#!/usr/bin/env python3
"""
text_adventure 交互式 Shell
使用方法:
python interactive.py --model /to/model.litertlm --skill-dir /to/skills
环境变量:
LITEAGENT_MODEL_PATH 默认模型路径
LITEAGENT_SKILL_DIR 默认技能目录
"""
import sys
import os
import ast
import argparse
from text_adventure import text_adventure
def create_interactive_shell(agent):
"""创建交互式对话 Shell"""
print("=" * 60)
print("text_adventure Interactive Shell")
print("=" * 60)
print(f"模型:{agent.model_path}")
if agent._skill_manager:
print(f"可用技能:{', '.join(agent.get_available_skills())}")
else:
print("可用技能:无")
print("提示符:输入 'quit' 或 'exit' 退出,'history' 查看历史")
print("=" * 60)
history = [] # 存储对话历史
BLUE = '\033[94m'
YELLOW = '\033[93m'
END = '\033[0m'
while True:
try:
# 获取用户输入
user_input = input(f"\n{BLUE}您:{END}").strip()
if not user_input:
continue
if user_input.lower() in ('quit', 'exit', 'q'):
print("再见!")
break
if user_input.lower() == 'history':
if not history:
print("暂无历史记录")
else:
print("\n--- 对话历史 ---")
for i, (inp, out) in enumerate(history, 1):
print(f"\n{i}. {BLUE}您:{inp}{END}")
# 显示原始响应或解析后的内容
cleaned = out.strip().rstrip(',')
try:
if cleaned.startswith('[') and cleaned.endswith(']'):
json_data = ast.literal_eval(cleaned)
if isinstance(json_data, list) and len(json_data) > 0:
if isinstance(json_data[0], dict):
answer = json_data[0].get('text', out)
print(f" {YELLOW}助手:{answer}{END}")
continue
except (ValueError, SyntaxError):
pass
# 显示原始响应
print(f" {YELLOW}助手:{out}{END}")
continue
if user_input.lower() == 'clear':
history = []
print("对话历史已清")
continue
# 发送消息
if user_input.startswith('/skill '):
# 查询技能信息
skill_name = user_input[7:].strip()
info = agent.get_skill_info(skill_name)
if info:
print(f"\n技能:{info['name']}")
print(f"描述:{info['description']}")
print(f"指令:\n{info['instructions']}")
else:
print(f"未找到技能:{skill_name}")
continue
if user_input.startswith('/list'):
agent.list_skills()
continue
# 发送消息获取响应
response = agent.chat(user_input)
# 显示响应 - 检查返回格式
if isinstance(response, str):
# 尝试解析可能的 JSON 格式响应
cleaned = response.strip().rstrip(',')
if cleaned.startswith('[') and cleaned.endswith(']'):
# 可能是列表格式的 JSON,尝试解析
try:
json_data = ast.literal_eval(cleaned)
if isinstance(json_data, list) and len(json_data) > 0:
# 提取第一个元素的 text 字段
if isinstance(json_data[0], dict):
answer = json_data[0].get('text', str(response))
else:
answer = str(response)
else:
answer = str(response)
except (ValueError, SyntaxError):
# 不是有效 JSON,直接显示
answer = str(response)
else:
# 不是列表,直接显示
answer = str(response)
else:
answer = str(response)
print(f"助手:{YELLOW}{answer}{END}")
# 保存到历史
history.append((user_input, response))
except EOFError:
print("\n再见!")
break
except KeyboardInterrupt:
print("\n再见!")
break
except Exception as e:
print(f"错误:{e}")
def main():
parser = argparse.ArgumentParser(description="text_adventure 交互式 Shell")
parser.add_argument(
"--model",
type=str,
default=os.environ.get('LITEAGENT_MODEL_PATH', None),
help="LiteRT-LM 模型文件路径 (默认:LITEAGENT_MODEL_PATH 环境变量)"
)
parser.add_argument(
"--skill-dir",
type=str,
default=os.environ.get('LITEAGENT_SKILL_DIR', ''),
help="SKILL.md 目录路径 (默认:LITEAGENT_SKILL_DIR 环境变量)"
)
parser.add_argument(
"--temperature",
type=float,
default=0.7,
help="采样温度 (0.0 最确定,1.0 最随机)"
)
args = parser.parse_args()
# 验证模型路径
if not args.model:
print("❌ 错误:未指定模型路径")
print("请使用 --model 参数或设置 LITEAGENT_MODEL_PATH 环境变量")
sys.exit(1)
# 创建 Agent
agent = text_adventure(
model_path=args.model,
skill_dir=args.skill_dir,
temperature=args.temperature,
max_tokens=32678
)
# 启动交互式 Shell
create_interactive_shell(agent)
if __name__ == "__main__":
main()