function callDeepSeekAPI() { // API配置 const apiUrl = 'https://api./v1/chat/completions'; const apiKey = '你自己的key'; // 替換為你的API密鑰
// 獲取選中的文本 let str_question = Selection.Text; if (!str_question) { alert('請(qǐng)先選中一個(gè)問(wèn)題!'); return; }
// 請(qǐng)求參數(shù) const requestBody = JSON.stringify({ 'model': 'deepseek-ai/DeepSeek-R1', 'messages': [ {'role': 'user', 'content': str_question} ], 'stream': false });
// 創(chuàng)建HTTP請(qǐng)求 const xhr = new XMLHttpRequest(); xhr.open('POST', apiUrl, true); // 異步請(qǐng)求 xhr.setRequestHeader('Content-Type', 'application/json'); xhr.setRequestHeader('Authorization', 'Bearer ' + apiKey);
// 請(qǐng)求發(fā)送前提示 alert('正在獲取回答,請(qǐng)稍候...');
xhr.onreadystatechange = function() { if (xhr.readyState === 4) { // 請(qǐng)求完成 if (xhr.status === 200) { const response = JSON.parse(xhr.responseText); const answer = '\r\n【DeepSeek回答】\r\n' + response.choices[0].message.content;
// 在選中位置后插入回答 const sel = Application.Selection; sel.EndKey(wdLine, wdMove); sel.TypeText(answer); sel.Collapse(1); // 將光標(biāo)移動(dòng)到回答末尾
alert('回答已插入到文檔中!'); } else { alert('API調(diào)用失?。顟B(tài)碼:' + xhr.status + ' 響應(yīng)內(nèi)容:' + xhr.responseText); } } };
xhr.onerror = function() { alert('網(wǎng)絡(luò)錯(cuò)誤,請(qǐng)檢查網(wǎng)絡(luò)連接!'); };
xhr.send(requestBody); } 有較多人反映報(bào)錯(cuò),本文對(duì)代碼進(jìn)行了優(yōu)化,請(qǐng)求方式改為了異步請(qǐng)求,如果還報(bào)錯(cuò),說(shuō)明是硅基的API響應(yīng)慢,超時(shí)了,多點(diǎn)幾次調(diào)用按鈕。
|