45 lines
1.4 KiB
JavaScript
45 lines
1.4 KiB
JavaScript
|
|
// background.js
|
|||
|
|
|
|||
|
|
// 监听来自 main.js 的消息
|
|||
|
|
chrome.runtime.onMessageExternal.addListener((message, sender, sendResponse) => {
|
|||
|
|
// 这种方式需要知道 Extension ID,更简单的方法是统一由 content.js 转发
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
// 通用监听(推荐)
|
|||
|
|
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
|
|||
|
|
if (request.type === "AI_TRANSLATE") {
|
|||
|
|
// 1. 先从 storage 获取配置
|
|||
|
|
chrome.storage.sync.get(['aiConfig'], async (result) => {
|
|||
|
|
const config = result.aiConfig;
|
|||
|
|
if (!config || !config.apiKey) {
|
|||
|
|
sendResponse({ success: false, error: "未配置 API Key" });
|
|||
|
|
return;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
try {
|
|||
|
|
// 2. 发起请求
|
|||
|
|
const response = await fetch(`${config.apiUrl}/chat/completions`, {
|
|||
|
|
method: 'POST',
|
|||
|
|
headers: {
|
|||
|
|
'Content-Type': 'application/json',
|
|||
|
|
'Authorization': `Bearer ${config.apiKey}`
|
|||
|
|
},
|
|||
|
|
body: JSON.stringify({
|
|||
|
|
model: config.modelName,
|
|||
|
|
messages: [
|
|||
|
|
{ role: "system", content: request.systemPrompt },
|
|||
|
|
{ role: "user", content: request.userInput }
|
|||
|
|
],
|
|||
|
|
temperature: 0.1
|
|||
|
|
})
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
const data = await response.json();
|
|||
|
|
sendResponse({ success: true, data: data });
|
|||
|
|
} catch (err) {
|
|||
|
|
sendResponse({ success: false, error: err.message });
|
|||
|
|
}
|
|||
|
|
});
|
|||
|
|
return true; // 保持异步
|
|||
|
|
}
|
|||
|
|
});
|