From a068ef9704446fb97b07ba8551be2bfd324de442 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?DonaldFang=20=E6=96=B9=E5=A3=AB=E7=A2=A9?= Date: Sat, 6 Dec 2025 01:29:44 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E6=94=B9=E9=80=B2=20LLM=20API=20JSON=20?= =?UTF-8?q?=E8=A7=A3=E6=9E=90=E9=8C=AF=E8=AA=A4=E8=99=95=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 增加智能 JSON 提取:自動查找首尾大括號 - 更詳細的錯誤訊息:顯示原始響應前 200 字符 - 更新錯誤提示建議 - 防止亂碼導致的解析失敗 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- js/api.js | 29 +++++++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/js/api.js b/js/api.js index b656630..c2ed846 100644 --- a/js/api.js +++ b/js/api.js @@ -56,10 +56,29 @@ export async function callClaudeAPI(prompt, api = 'ollama') { throw new Error(data.error || 'API 調用失敗'); } - // 清理 JSON 代碼塊標記 + // 清理 JSON 代碼塊標記和其他格式 let responseText = data.text; + + // 移除 Markdown 代碼塊標記 responseText = responseText.replace(/```json\n?/g, '').replace(/```\n?/g, '').trim(); - return JSON.parse(responseText); + + // 嘗試提取 JSON 內容(如果包含其他文字) + // 查找第一個 { 和最後一個 } + const firstBrace = responseText.indexOf('{'); + const lastBrace = responseText.lastIndexOf('}'); + + if (firstBrace !== -1 && lastBrace !== -1 && lastBrace > firstBrace) { + responseText = responseText.substring(firstBrace, lastBrace + 1); + } + + // 嘗試解析 JSON + try { + return JSON.parse(responseText); + } catch (parseError) { + // JSON 解析失敗,拋出更詳細的錯誤 + console.error('JSON 解析失敗,原始響應:', responseText); + throw new Error(`LLM 返回的內容不是有效的 JSON 格式。\n\n原始響應前 200 字符:\n${responseText.substring(0, 200)}...`); + } } catch (error) { console.error('Error calling LLM API:', error); @@ -78,10 +97,12 @@ export async function callClaudeAPI(prompt, api = 'ollama') { message: error.message, details: errorDetails, suggestions: [ - 'Flask 後端已啟動 (python start_server.py)', + 'Flask 後端已啟動 (python app.py)', '已在 .env 文件中配置有效的 LLM API Key', '網路連線正常', - '嘗試使用不同的 LLM API (DeepSeek 或 OpenAI)' + '確認 Prompt 要求返回純 JSON 格式', + '嘗試使用不同的 LLM API (切換到其他模型)', + '檢查 LLM 模型是否支援繁體中文' ] });