Skip to content

fix(emotion): decode first JSON object instead of greedy span - #508

Open
jack12178 wants to merge 2 commits into
Tencent-Hunyuan:mainfrom
jack12178:fix/emotion-parse-json-trailing
Open

jack12178 wants to merge 2 commits into
Tencent-Hunyuan:mainfrom
jack12178:fix/emotion-parse-json-trailing

Conversation

@jack12178

Copy link
Copy Markdown
Contributor

变更

EmotionAnalyzer._parse_json() 在 json.loads() 失败后用 re.search(r'\{[\s\S]*\}', text) 兜底提取 JSON。这个正则是贪婪的:它从第一个 { 一直匹配到文本里最后一个 }。

Reproduced on main d8138b501a755f662a024f7e8eb879613eabf1d3:

input:  Analysis {"valence": 0.5} trailing note {"other": 1}
match:  {"valence": 0.5} trailing note {"other": 1}   # invalid JSON
result: {}                                             # whole analysis dropped

LLM 偶尔会在结果 JSON 后面再附一段带花括号的说明、示例或第二个对象;此时兜底提取拼出一个非法 JSON,_parse_json() 直接返回 {}。调用方拿不到 valence/arousal,整条情绪分析静默降级为默认值,且没有任何错误信号。单纯的后缀散文(不含 })不受影响,所以这个问题在常规测试里不显眼。

修复:改用 json.JSONDecoder().raw_decode() 从第一个 { 开始解析,只取第一个完整对象,忽略其后所有文本;顺带移除不再使用的 import re。plain JSON、```json 代码块、完全非法输入的原有行为不变。无 API、schema 或依赖变更。两个逻辑 commit 分别承载生产修复和回归测试。

用户影响

LLM 在情绪结果后附加说明文字时,不会再让整条分析静默丢失;valence/arousal 正常落库。此前已能正确解析的输出保持原样。

验证

  • Failing-test-first: tests/test_emotion_parse_json_trailing.py — baseline 1 failed, 3 passed(第二个对象场景返回 {});修复后 4 passed。
  • 相关回归:连同 fix(emotion): clamp NaN scores to neutral instead of the upper bound #507 的 NaN 修复测试一起跑 tests/test_emotion_parse_json_trailing.py tests/test_emotion_clamp_nan.py tests/test_tag_point_id_delimiter.py tests/test_keyword_ties_all_equal.py tests/test_retrieval.py -q → 50 passed。
  • 测试固定了 plain JSON、fenced JSON、完全非法文本的行为不变。
  • 完整 uv run pytest tests/ 未在本地通过:隔离环境缺少 chromadb 等可选依赖,与本次改动无关。
  • 改动仅限 1 个生产文件 + 1 个测试文件;与 fix(emotion): clamp NaN scores to neutral instead of the upper bound #507 同文件但不同函数,两个 PR 的 diff 互不重叠。

查重

No issue claimed. 已检查当前全部 open PR:#507 修复的是同文件 _clamp() 的 NaN 处理,与本 PR 的 _parse_json() 是不同函数、不同动因;#116 处理的是 extractor 的语言检测路由。tests/ 下此前无 emotion 相关测试文件。

AI assistance: the change was located, implemented and tested by an AI agent; the author reviewed the diff and test output. No human maintainer review is claimed.

The greedy regex matched from the first '{' to the last '}', so a trailing prose segment containing another object made the blob invalid and silently dropped the whole analysis.
Fails on the unmodified source when a second object follows the answer; pins plain JSON, fenced JSON and invalid text.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant