使用json_repair修复大模型的json输出错误

该文章已生成可运行项目,

json_repair

有些 LLM 在返回格式正确的 JSON 数据时会有些问题,有时会漏掉括号,有时会在数据中添加一些单词。不至于这种错误每次都要丢弃,再次生成太浪费时间了,因此能修复错误时还是要尽量修复。这就是 json_repair 的主要目的:修复 LLM 在生成 json 数据时的错误。

  • 修复 JSON 中的语法错误
    • 缺少引号、逗号位置错误、未转义的字符以及不完整的键值对。
    • 缺少引号、格式不正确的值(true、false、null)以及修复损坏的键值结构。
  • 修复格式错误的 JSON 数组和对象
    • 通过添加必要的元素(例如逗号、括号)或默认值(null、“”)来修复不完整或损坏的数组/对象。
    • 该库可以处理包含额外非 JSON 字符(例如注释或位置不正确的字符)的 JSON,并在保持有效结构的同时进行清理。
  • JSON 缺失值自动补全
    • 使用合理的默认值(例如空字符串或 null)自动补全 JSON 字段中的缺失值,确保有效性。

安装

!pip install json-repair
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple/, https://mirrors.aliyun.com/pypi/simple/, https://pypi.mirrors.ustc.edu.cn/simple/
Requirement already satisfied: json-repair in /home/guest/anaconda3/envs/xprepo/lib/python3.11/site-packages (0.41.1)

使用

以常见的字段内部的多余""为例

import json
import json_repair
from json_repair import repair_json

bad_json_string = """```json
{
  "title": "Daily Thoughts",
  "mood": ""relaxed"",
  "content": "Today I felt really "productive" and relaxed."
}

“”"

a_str = bad_json_string
try:
obj = json.loads(a_str)
except json.JSONDecodeError as e:
print(“Attempting to fix the JSON string…”)
# solution 1. fix the json string
a_str = repair_json(a_str)
obj = json.loads(a_str)
# solution 1. fix the json string and load as json
# obj = json_repair.loads(a_str)

finally:
print(json.dumps(obj, indent=2))


    Attempting to fix the JSON string...
    {
      "title": "Daily Thoughts",
      "mood": "relaxed",
      "content": "Today I felt really \"productive\" and relaxed."
    }


本文章已经生成可运行项目
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值