Create

Sign in to ReadmeX

or

How we handle your data: Privacy Policy

ReadmeX

Your AI reading companion

What would you like to catch up on?

Pick a briefing, or ask your own question.

Your community and people briefings stay personal to you.

Story

A runnable tolerant JSON parser for LLM tool calls

AI summary

A Juejin author recommends adding tolerant parsing between LLM output and tool calls instead of immediately replacing the model. The roughly 60-line Python example first tries standard json.loads, then repairs common formatting issues such as Markdown fences, trailing commas, unquoted keys, Python literals, and surrounding explanatory text. The author reports that all six test cases parsed successfully locally, while noting that the simple parser does not address incorrect content and may need json5 or json-repair for complex cases.

In-depth insight

The approach centralizes handling of common formatting defects before tool arguments reach individual tools, potentially avoiding parsing failures without replacing the model. It does not validate whether the content is correct: schema or parameter checks and separate hallucination detection are still needed.

LLM 吐的 JSON 十次坏三次,别急着骂模型——60 行容错解析器先兜住

结论:让 Agent 去调工具,模型给的 JSON 经常是不规整的,这很正常,第一反应不该是换模型,该是加一层容错解析。

我一开始也踩过这坑。Agent 跑着跑着突然崩,看日志一查,json.loads 抛异常了。盯半天以为模型坏了,后来把原始输出打印出来才发现,模型给的「JSON」长这样:

```json
{"city": "北京", "temp": 25}
```

外面套了层 markdown 代码围栏。你说它错吧,里面的 JSON 是对的;你说它对吧,json.loads 直接给你一个 JSONDecodeError。这种「内容对、外层报错」的情况,占了我遇到坏 JSON 的绝大多数。

一、模型吐的坏 JSON,常见就这几种

我把踩过的坑归了类,基本就六种:

#AIHCC#Python#json5#json-repair

Original · 7 min readRead the original
Group chat

No comments yet. Start the conversation.