![](https://s5-media.51cto.com/aigc/pc/static/noavatar.gif)
回复
在我们日常处理大模型的输出时,经常希望输出的结果为结构化的(例如输出json格式),这样有助于我们进行结果的后处理。但是在模型输出超过限制和流式输出时就会遇到问题了,由于答案没完全输出,转json就存在问题。
大型语言模型(LLMs)产生结构化输出的原因包括:
工具功能介绍:
效果展示
text = '''{"name":"张三", "age":'''
print(parse_json_markdown(text))
# {'name': '张三'}
markdown格式
text = '''```json\n{"name":"张三", "age":27'''
print(parse_json_markdown(text))
# {'name': '张三', 'age': 27}
多维嵌套
text = '''```json\n{"name":"张三", "age": 27, "爱好": ["羽毛球'''
print(parse_json_markdown(text))
# {'name': '张三', 'age': 27, '爱好': ['羽毛球']}
核心代码介绍
核心处理代码如下:
new_chars = []
stack = []
is_inside_string = False
escaped = False
# Process each character in the string one at a time.
for char in s:
if is_inside_string:
if char == '"' and not escaped:
is_inside_string = False
elif char == "\n" and not escaped:
char = "\\n" # Replace the newline character with the escape sequence.
elif char == "\\":
escaped = not escaped
else:
escaped = False
else:
if char == '"':
is_inside_string = True
escaped = False
elif char == "{":
stack.append("}")
elif char == "[":
stack.append("]")
elif char == "}" or char == "]":
if stack and stack[-1] == char:
stack.pop()
else:
# Mismatched closing character; the input is malformed.
return None
本文转载自公众号哎呀AIYA
原文链接:https://mp.weixin.qq.com/s/-I3wXkRGgyEuRYUQa84AEQ