function callDeepSeekAPI() { // API配置 const apiUrl = 'https://api./v1/chat/completions'; const apiKey = '你自己的key'; // 替換為你的API密鑰
// 獲取選中的文本 let str_question = Selection.Text; if (!str_question) { alert('請先選中一個問題!'); return; }
// 請求參數(shù) const requestBody = JSON.stringify({ 'model': 'deepseek-ai/DeepSeek-R1', 'messages': [ {'role': 'user', 'content': str_question} ], 'stream': false });
// 創(chuàng)建HTTP請求 const xhr = new XMLHttpRequest(); xhr.open('POST', apiUrl, true); // 異步請求 xhr.setRequestHeader('Content-Type', 'application/json'); xhr.setRequestHeader('Authorization', 'Bearer ' + apiKey);
// 請求發(fā)送前提示 alert('正在獲取回答,請稍候...');
xhr.onreadystatechange = function() { if (xhr.readyState === 4) { // 請求完成 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); // 將光標移動到回答末尾
alert('回答已插入到文檔中!'); } else { alert('API調用失敗!狀態(tài)碼:' + xhr.status + ' 響應內容:' + xhr.responseText); } } };
xhr.onerror = function() { alert('網絡錯誤,請檢查網絡連接!'); };
xhr.send(requestBody); } 有較多人反映報錯,本文對代碼進行了優(yōu)化,請求方式改為了異步請求,如果還報錯,說明是硅基的API響應慢,超時了,多點幾次調用按鈕。
|