微信扫码
和创始人交个朋友
我要投稿
这是关于 LangChain 中 OutputParser 的绝佳实战指南,没有之一。 核心内容: 1. 输出解析器的定义与作用 2. OutputParser 的用途介绍 3. 以 JSON 格式返回的实例讲解
LangChain 的 OutputParser 是一种强大工具,用于将大模型的原始输出转换为结构化、可操作的数据格式,如 JSON 或 Python 对象。本文介绍了 OutputParser 的核心功能、应用场景及其在实际业务中的实现方法,包括使用 JsonOutputParser 和 Pydantic 定义数据结构,从而高效格式化输出内容以满足业务需求。
在大模型应用中,原始输出通常只是处理的开端,尽管这些输出能够提供很好的内容,但是根据下游使用场景,语言模型生成的原始文本很大概率需要被进一步处理才能使用。
输出解析器(OutputParser)是 LangChain 中的一种工具,用于帮助将语言模型的文本响应转化为实用的格式化输出。
输出解析器有两个主要用途:
get_format_instructions()
方法,该方法会返回用于提示格式化文本的指令。我们需要大模型生成一个小说,内容以json返回,在这个基础上,增加一些其他业务数据后,给客户端以json格式返回:
{
作者:"xx",
年龄:"80",
标题:"xxx",
摘要:"xxxx",
正文:"xxxxxx",
}
import os # 导入操作系统模块
import json # 导入json模块
os.environ['OpenAI_API_KEY'] = 'hk-iwtb91e427' # 设置OpenAI API密钥
from langchain_core.output_parsers import PydanticOutputParser, JsonOutputParser
from langchain_core.prompts import PromptTemplate
from langchain_openai import OpenAI, ChatOpenAI
from pydantic import BaseModel, Field, model_validator
model = ChatOpenAI( # 创建ChatOpenAI的实例
model="gpt-4o-mini", # 指定模型
temperature=0, # 设置温度
base_url="https://api.openai-hk.com/v1" # 设置基础URL
)
使用pydantic定义所需的数据结构,和基本的格式校验逻辑,并作为JsonOutputParser的参数
# 使用pydantic定义所需的数据结构
class Story(BaseModel):# 创建Story类,继承自BaseModel
title: str = Field(description="标题") # 科幻小说的标题
summary: str = Field(description="摘要") # 科幻小说的摘要
content: str = Field(description="正文") # 科幻小说的正文
# 可以轻松添加自定义验证逻辑
@model_validator(mode="before") # 在模型验证之前进行验证
@classmethod
def validate_story(cls, values: dict) -> dict:# 定义验证方法
# 这里可以添加对标题、摘要和正文的验证逻辑
return values # 返回验证后的值
# 设置解析器
parser = JsonOutputParser(pydantic_object=Story) # 创建JsonOutputParser实例
解析器通过 get_format_instructions()
方法,返回用于提示的格式化文本指令,然后向提示注入指令,指导语言模型如何格式化响应(见运行日志)。
# 创建提示模板
prompt = PromptTemplate( # 创建提示模板
template="请按用户要求返回文章,包括标题、摘要和正文。\n{format_instructions}\n{query}\n", # 模板内容
input_variables=["query"], # 输入变量
partial_variables={"format_instructions": parser.get_format_instructions()}, # 部分变量
)
# 定义查询
story_query = "请给我一个100字的科幻小说。"# 查询内容
# 打印最终模板结果
final_template = prompt.format(format_instructions=parser.get_format_instructions(), query=story_query) # 格式化最终模板
print("=================================提示词开始========================================")
print(final_template) # 打印最终模板结果
print("=================================提示词结束========================================")
这是生成的指导提示词:
The output should be formatted as a JSON instance that conforms to the JSON schema below.
As an example, for the schema {"properties": {"foo": {"title": "Foo", "description": "a list of strings", "type": "array", "items": {"type": "string"}}}, "required": ["foo"]}
the object {"foo": ["bar", "baz"]} is a well-formatted instance of the schema. The object {"properties": {"foo": ["bar", "baz"]}} is not well-formatted.
Here is the output schema:
```
{"properties": {"title": {"description": "标题", "title": "Title", "type": "string"}, "summary": {"description": "摘要", "title": "Summary", "type": "string"}, "content": {"description": "正文", "title": "Content", "type": "string"}}, "required": ["title", "summary", "content"]}
```
放到链的最后,用来格式化输出:output = prompt | model | parser
# 创建一个查询,旨在提示语言模型生成科幻小说
output = prompt | model | parser # 将提示和模型结合
story_output = output.invoke({"query": story_query}) # 调用模型并传入查询
print("模型输出结果 :")
print(story_output) # 打印输出
print()
# 拼接作者和年龄信息
final_json = {
"title": story_output['title'],
"summary": story_output['summary'],
"content": story_output['content'],
"author": "AI取经人", # 作者
"age": 18 # 年龄
}
# 打印最终的 JSON 结果
print("最终的 JSON 结果:")
print(json.dumps(final_json, ensure_ascii=False, indent=4)) # 格式化打印JSON结果
{
"title": "穿越时空的信号",
"summary": "在未来的某一天,科学家通过先进的量子技术接收到了来自20世纪的神秘信号。这一信号揭示了一段被遗忘的历史,改变了人类对时间的理解。",
"content": "当信号首次被接收时,整个实验室都陷入了震惊。信号中包含着关于平行宇宙的知识和未来人类的命运。科学家们决定通过量子隧道进行实验,试图与过去的自己交流。在这个过程中,他们不仅面对科技的诱惑,也直面人性的挣扎。最终,他们意识到,改变历史的代价是不可承受的,但真相仍旧摆在他们面前。",
"author": "AI取经人",
"age": 18
}
53AI,企业落地大模型首选服务商
产品:场景落地咨询+大模型应用平台+行业解决方案
承诺:免费场景POC验证,效果验证后签署服务协议。零风险落地应用大模型,已交付160+中大型企业
2024-10-10
2024-04-08
2024-06-03
2024-08-18
2024-09-04
2024-07-13
2024-04-08
2024-06-24
2024-07-10
2024-04-17
2025-02-05
2024-12-02
2024-11-25
2024-10-30
2024-10-11
2024-08-18
2024-08-16
2024-08-04