2026-01-14 22:21:02 +08:00
|
|
|
|
// 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(', ');
|
2026-01-14 22:21:02 +08:00
|
|
|
|
|
|
|
|
|
|
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);
|
|
|
|
|
|
|
2026-01-14 22:21:02 +08:00
|
|
|
|
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 {
|
2026-01-14 22:21:02 +08:00
|
|
|
|
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-14 22:21:02 +08:00
|
|
|
|
|
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 }
|
|
|
|
|
|
}));
|
|
|
|
|
|
});
|
|
|
|
|
|
}
|