fix: 改進 LLM API JSON 解析錯誤處理
- 增加智能 JSON 提取:自動查找首尾大括號 - 更詳細的錯誤訊息:顯示原始響應前 200 字符 - 更新錯誤提示建議 - 防止亂碼導致的解析失敗 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
27
js/api.js
27
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();
|
||||
|
||||
// 嘗試提取 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 模型是否支援繁體中文'
|
||||
]
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user