56 lines
2.7 KiB
JavaScript
Raw Normal View History

// scripts/ai.js
2026-01-11 12:22:49 +08:00
import { COMMANDS } from './commands.js';
export async function translateToCommand(userInput) {
const availableKeys = COMMANDS.map(c => c.key).join(', ');
const systemPrompt = `你是一个工业自动化系统助手。
标准指令列表[${availableKeys}]
任务规则
2026-01-15 22:49:48 +08:00
1. **必须包含对话**无论是否执行指令你都必须在 <communication>XXXX</communication>
2. **意图识别**如果用户意图匹配指令列表输出 <cmd>标准指令</cmd> <arg></arg>
3. **示例**
- 用户打开监控中心 -> <communication>好的正在为您进入监控中心</communication><cmd></cmd>
- 用户你是谁 -> <communication>我是您的自动化 AI 助手可以帮您操作平台</communication>
- 用户添加设备 888 -> <communication>没问题正在为您添加编号为 888 的设备</communication><cmd></cmd><arg>888</arg>
4. 只输出 XML 结果不要输出任何解释说明保持简洁`;
2026-01-11 12:22:49 +08:00
return new Promise((resolve) => {
const handler = (event) => {
const response = event.detail;
window.removeEventListener("AI_RESULT", handler);
if (response && response.success && response.data) {
try {
if (response.data.choices && response.data.choices.length > 0) {
const content = response.data.choices[0].message.content.trim();
2026-01-15 21:35:04 +08:00
console.log("📥 AI 原始响应:", content);
2026-01-17 20:24:08 +08:00
// 返回包含内容和语音开关状态的对象
resolve({
content: content === "UNKNOWN" ? null : content,
voiceEnabled: response.voiceEnabled // 从 background.js 透传回来的开关状态
});
2026-01-15 21:35:04 +08:00
} else {
resolve(null);
}
} catch (e) {
console.error("解析响应失败:", e);
resolve(null);
}
2026-01-11 12:22:49 +08:00
} else {
2026-01-17 20:24:08 +08:00
console.error("AI 请求失败:", response?.error);
2026-01-11 12:22:49 +08:00
resolve(null);
}
};
2026-01-17 20:24:08 +08:00
// 监听来自 content.js 的结果反馈
2026-01-11 12:22:49 +08:00
window.addEventListener("AI_RESULT", handler);
2026-01-17 20:24:08 +08:00
// 触发自定义事件,由 content.js 转发给 background.js
2026-01-11 12:22:49 +08:00
window.dispatchEvent(new CustomEvent("DO_AI_REQUEST", {
detail: { userInput, systemPrompt }
}));
});
}