78 lines
2.1 KiB
Plaintext
78 lines
2.1 KiB
Plaintext
修复AI意图识别的JSON解析问题
|
||
|
||
找到这段代码(大约在1330-1355行):
|
||
|
||
console.log('AI意图识别:原始响应:', content)
|
||
|
||
// 提取JSON(可能被markdown代码块包裹)
|
||
let jsonStr = content.trim()
|
||
const jsonMatch = jsonStr.match(/```(?:json)?\s*(\{[\s\S]*?\})\s*```/)
|
||
if (jsonMatch) {
|
||
jsonStr = jsonMatch[1]
|
||
}
|
||
|
||
const intent = JSON.parse(jsonStr)
|
||
console.log('AI意图识别:解析结果:', intent)
|
||
|
||
// 验证置信度
|
||
if (intent.confidence < 0.6) {
|
||
console.log('AI意图识别:置信度过低,忽略结果')
|
||
return null
|
||
}
|
||
|
||
替换为:
|
||
|
||
console.log('AI意图识别:原始响应:', content)
|
||
|
||
// 检查是否有内容
|
||
if (!content || !content.trim()) {
|
||
console.log('AI意图识别:响应为空')
|
||
return null
|
||
}
|
||
|
||
// 提取JSON
|
||
let jsonStr = content.trim()
|
||
|
||
// 移除markdown代码块
|
||
jsonStr = jsonStr.replace(/```(?:json)?\s*/g, '').replace(/```\s*/g, '')
|
||
|
||
// 提取第一个完整的JSON对象
|
||
const jsonMatch2 = jsonStr.match(/\{[\s\S]*?\}/)
|
||
if (jsonMatch2) {
|
||
jsonStr = jsonMatch2[0]
|
||
}
|
||
|
||
console.log('AI意图识别:提取的JSON字符串:', jsonStr.substring(0, 200))
|
||
|
||
// 解析JSON
|
||
let intent = null
|
||
try {
|
||
intent = JSON.parse(jsonStr)
|
||
} catch (parseError) {
|
||
console.error('AI意图识别:JSON解析失败', parseError.message)
|
||
return null
|
||
}
|
||
|
||
console.log('AI意图识别:解析结果:', intent)
|
||
|
||
// 验证intent结构
|
||
if (!intent || typeof intent !== 'object') {
|
||
console.log('AI意图识别:intent不是对象')
|
||
return null
|
||
}
|
||
|
||
// 验证置信度
|
||
const confidence = parseFloat(intent.confidence)
|
||
if (isNaN(confidence) || confidence < 0.6) {
|
||
console.log('AI意图识别:置信度过低或无效', confidence)
|
||
return null
|
||
}
|
||
|
||
主要改进:
|
||
1. 添加了空内容检查
|
||
2. 改进了JSON提取逻辑,使用replace而不是match
|
||
3. 添加了try-catch包裹JSON.parse
|
||
4. 添加了更详细的错误日志
|
||
5. 验证intent对象结构
|
||
6. 改进了置信度验证逻辑
|