-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
330 lines (263 loc) · 11.3 KB
/
main.py
File metadata and controls
330 lines (263 loc) · 11.3 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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
#!/usr/bin/env python3
"""
AIOS 主入口 - 原型 v0.2
手机 AI 操作系统 (本地Ollama版)
设计理念:
- 手机 = 传感器 + 执行器
- 外脑 = 云端大模型
- 底层 AI 驱动
"""
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from aios.scheduler.router import Scheduler, Task, TaskPriority, ExecutionLocation
from aios.intent.classifier import IntentClassifier, IntentLogger
from aios.dal.devices import DeviceAbstractionLayer, DeviceType
from aios.memory.user_profile import UserMemory
from aios.model.registry import ModelRegistry, ModelSelector
# 导入服务层
from aios.services import WeatherService, MapService, SmartHomeService
class AIOS:
"""AIOS 核心类"""
def __init__(self, config_path: str = "config.yaml"):
self.config_path = config_path
print("🚀 初始化 AIOS...")
self.dal = DeviceAbstractionLayer()
print(f" ✓ 设备抽象层: {len(self.dal.get_capabilities()['input'])} 输入, {len(self.dal.get_capabilities())} 输出")
self.scheduler = Scheduler(config_path)
print(" ✓ 任务调度器就绪")
self.intent_classifier = IntentClassifier(config_path)
self.intent_logger = IntentLogger()
print(" ✓ 意图识别系统就绪")
self.memory = UserMemory("default_user")
print(" ✓ 记忆系统就绪")
self.model_selector = ModelSelector()
print(" ✓ 模型选择器就绪")
# 服务层
self.weather = WeatherService()
self.map_svc = MapService()
self.smarthome = SmartHomeService()
print(" ✓ 服务层: 天气/地图/智能家居")
# Ollama 本地模型
try:
from aios.model.api_client import OllamaClient
self.ollama = OllamaClient()
models = self.ollama.list_models()
print(f" 📱 Ollama: {len(models)}个模型")
self.ollama_available = True
except Exception as e:
print(f" ⚠️ Ollama: 不可用 ({e})")
self.ollama_available = False
self.ollama = None
print(f"✅ AIOS 启动完成!\n")
def run(self):
"""主循环"""
print("=" * 50)
print("🎯 AIOS 运行中 (输入 'quit' 退出)")
print("=" * 50)
while True:
try:
query = input("\n👤 你: ").strip()
if query.lower() in ['quit', 'exit', 'q']:
print("👋 再见!")
break
if not query:
continue
self.process(query)
except KeyboardInterrupt:
print("\n👋 再见!")
break
def process(self, query: str):
"""处理用户请求"""
# 1. 意图识别
print(f"\n🔍 意图识别...")
intent = self.intent_classifier.classify(query)
print(f" → {intent.category.value}: {intent.action}")
# 2. 任务调度
print(f"📡 任务调度...")
task = Task(
intent=intent.action,
query=query,
context=self._get_current_context(),
latency_requirement_ms=2000
)
plan = self.scheduler.route_task(task)
print(f" → 执行位置: {plan['location']}")
# 3. 获取设备数据 + 调用服务
print(f"📱 服务调用...")
service_result = None
# 天气查询
if "天气" in query:
location = self.dal.sense_location()
loc_data = location.data
city = intent.entities.get("city") if intent.entities else None
city = city or loc_data.get("city", "上海")
print(f" 🌤️ 调用天气服务: {city}")
service_result = self._call_service("weather", city=city)
# 智能家居控制
elif any(kw in query for kw in ["灯", "空调", "打开", "关闭", "调", "温度"]):
device_name = self._extract_device_name(query)
action = "on" if "开" in query else ("off" if "关" in query else "status")
print(f" 🏠 调用智能家居: {device_name} -> {action}")
service_result = self._call_service("smarthome", device=device_name, action=action)
# 地图/位置
elif any(kw in query for kw in ["在哪里", "地址", "附近", "找"]):
keyword = query.replace("附近", "").replace("找", "").replace("在哪里", "").strip()
location = self.dal.sense_location()
loc_data = location.data
print(f" 🗺️ 调用地图服务: 搜索 {keyword}")
service_result = self._call_service("map", keyword=keyword, lat=loc_data.get("lat"), lon=loc_data.get("lon"))
# 4. AI 生成响应
print(f"🤖 AI 生成响应...")
response = self._generate_response(query, intent, plan, service_result)
print(f" → {response}")
# 5. 记忆学习
print(f"🧠 记忆学习...")
self.memory.remember_interaction({
"intent": intent.action,
"query": query,
"result": response,
"emotion": "neutral"
})
self.intent_logger.log(intent, self._get_current_context(), {"success": True})
# 6. 输出
self.dal.speak(response)
def _extract_device_name(self, query: str) -> str:
"""从query中提取设备名称"""
# 简化实现
if "客厅" in query and "灯" in query:
return "客厅灯"
elif "卧室" in query and "灯" in query:
return "卧室灯"
elif "空调" in query:
return "空调"
elif "灯" in query:
return "灯"
return "default"
def _call_service(self, service_type: str, **kwargs):
"""统一服务调用"""
import asyncio
try:
loop = asyncio.get_event_loop()
except:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
if service_type == "weather":
city = kwargs.get("city", "上海")
return loop.run_until_complete(self.weather.get_weather(city))
elif service_type == "smarthome":
device = kwargs.get("device", "灯")
action = kwargs.get("action", "status")
# 先找设备
result = loop.run_until_complete(self.smarthome.find_device(device))
if result.get("success"):
device_id = result["device"]["id"]
return loop.run_until_complete(self.smarthome.control_device(device_id, action))
return result
elif service_type == "map":
keyword = kwargs.get("keyword", "")
lat = kwargs.get("lat")
lon = kwargs.get("lon")
return loop.run_until_complete(self.map_svc.search_poi(keyword, lat=lat, lon=lon))
return {"success": False}
def _get_current_context(self) -> dict:
"""获取当前上下文"""
from datetime import datetime
return {
"time": datetime.now().strftime("%H:%M"),
"location": self.dal.sense_location().data,
"device_state": "idle"
}
def _generate_response(self, query: str, intent, plan, service_result=None):
"""生成响应 - Ollama本地模型"""
# 如果有服务结果,优先使用
if service_result and service_result.get("success"):
return self._format_service_response(query, service_result)
# 如果有实体,加入上下文
context = ""
if intent.entities:
for k, v in intent.entities.items():
context += f"{k}: {v}\n"
# 构建 prompt
system_prompt = f"""你是AIOS手机助手。用户刚才说: "{query}"
意图类型: {intent.category.value}
具体动作: {intent.action}
实体信息: {context}
请用一句话简洁回答。"""
# 优先使用Ollama
if self.ollama_available and self.ollama:
try:
from aios.model.api_client import ChatMessage
messages = [
ChatMessage(role="system", content=system_prompt),
ChatMessage(role="user", content=query)
]
# 根据意图选择模型
model = "llama3.2" # 默认用llama3.2,加载快
result = self.ollama.chat(model, messages, max_tokens=200)
return result["content"].strip()
except Exception as e:
print(f" ⚠️ Ollama调用失败: {e}")
# Fallback: Mock响应
fallback = {
"查天气": "今天天气晴朗,温度22度",
"查时间": "现在是北京时间",
"订餐": "好的,已为您下单",
"导航": "正在为您规划路线",
"智能家居": "收到,已执行",
"听音乐": "为您播放喜欢的音乐",
"创作": "好的,我来帮您完成",
"闲聊": "你好!有什么可以帮你的?",
}
return fallback.get(intent.action, "收到!")
def _format_service_response(self, query: str, result: dict) -> str:
"""格式化服务响应"""
data = result
# 天气服务
if "temp" in data:
return f"当前{data.get('location', '本地')}天气{data.get('condition')},温度{data.get('temp')}度,湿度{data.get('humidity')}%。"
# 智能家居
if "message" in data:
return data["message"]
if "device_id" in data:
return f"已执行: {data.get('message', '操作成功')}"
# 地图POI
if "pois" in data:
pois = data.get("pois", [])
if pois:
names = [p.get("name", "") for p in pois[:3]]
return f"为您找到附近的{data.get('keyword', '')}: {', '.join(names)}"
return "执行完成"
def demo():
"""演示模式"""
aios = AIOS()
test_queries = [
"明天上海天气怎么样",
"帮我点一杯咖啡",
"打开客厅的灯",
"写一篇关于AI的文章",
"今天星期几?",
]
print("=" * 50)
print("🎬 演示模式")
print("=" * 50 + "\n")
for q in test_queries:
print(f"👤 用户: {q}")
aios.process(q)
print()
print("=" * 50)
print("📊 用户画像")
print("=" * 50)
import json
print(json.dumps(aios.memory.get_profile(), ensure_ascii=False, indent=2))
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="AIOS - AI Phone OS")
parser.add_argument("--demo", action="store_true", help="运行演示")
parser.add_argument("--config", default="config.yaml", help="配置文件")
args = parser.parse_args()
if args.demo:
demo()
else:
aios = AIOS(args.config)
aios.run()