xinli/xinlidsj/AI意图识别修复说明.md
2026-02-26 18:18:03 +08:00

87 lines
2.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# AI意图识别JSON解析失败修复
## 问题现象
用户输入:"想看张三数据"
错误:`JSON解析失败: Unexpected end of JSON input`
## 根本原因
原代码使用的正则表达式有问题:
```javascript
const jsonMatch = jsonStr.match(/```(?:json)?\s*(\{[\s\S]*?\})\s*```/)
```
这个正则使用了**非贪婪匹配** `*?`,会在遇到第一个 `}` 时就停止导致嵌套的JSON对象被截断。
例如对于这样的JSON
```json
{"action":"analyzeProfile","params":{"keyword":"张三"},"confidence":0.95}
```
非贪婪匹配会在第一个 `}` (params后面的) 就停止,得到:
```json
{"action":"analyzeProfile","params":{"keyword":"张三"}
```
这是一个不完整的JSON导致解析失败。
## 解决方案
使用更简单可靠的方法:
```javascript
// 1. 移除markdown代码块标记
jsonStr = jsonStr.replace(/```(?:json)?/g, '').replace(/```/g, '').trim()
// 2. 找到第一个{和最后一个}
const firstBrace = jsonStr.indexOf('{')
const lastBrace = jsonStr.lastIndexOf('}')
// 3. 提取完整的JSON对象
if (firstBrace !== -1 && lastBrace !== -1 && lastBrace > firstBrace) {
jsonStr = jsonStr.substring(firstBrace, lastBrace + 1)
}
// 4. 使用try-catch保护解析
try {
intent = JSON.parse(jsonStr)
} catch(e) {
console.error('JSON解析失败:', e.message)
console.log('失败的JSON字符串:', jsonStr)
return null
}
```
## 已应用的修复
✅ 改进了JSON提取逻辑
✅ 添加了try-catch保护
✅ 添加了详细的调试日志
✅ 添加了空值检查
## 测试建议
现在再次测试时,控制台会显示:
1. AI意图识别原始响应
2. AI意图识别响应类型
3. AI意图识别提取的JSON
4. 如果失败JSON解析失败的具体错误和完整的JSON字符串
这样可以准确定位问题所在。
## 预期结果
用户输入:"想看张三数据"
AI识别
```json
{
"action": "analyzeProfile",
"params": {"keyword": "张三"},
"confidence": 0.95,
"reasoning": "用户想分析张三的个体画像数据"
}
```
系统执行:打开张三的个体画像页面