56 lines
2.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// scripts/ai.js
import { COMMANDS } from './commands.js';
export async function translateToCommand(userInput) {
const availableKeys = COMMANDS.map(c => c.key).join(', ');
const systemPrompt = `你是一个工业自动化系统助手。
标准指令列表:[${availableKeys}]
任务规则:
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 结果,不要输出任何解释说明,保持简洁。`;
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();
console.log("📥 AI 原始响应:", content);
// 返回包含内容和语音开关状态的对象
resolve({
content: content === "UNKNOWN" ? null : content,
voiceEnabled: response.voiceEnabled // 从 background.js 透传回来的开关状态
});
} else {
resolve(null);
}
} catch (e) {
console.error("解析响应失败:", e);
resolve(null);
}
} else {
console.error("AI 请求失败:", response?.error);
resolve(null);
}
};
// 监听来自 content.js 的结果反馈
window.addEventListener("AI_RESULT", handler);
// 触发自定义事件,由 content.js 转发给 background.js
window.dispatchEvent(new CustomEvent("DO_AI_REQUEST", {
detail: { userInput, systemPrompt }
}));
});
}