一起学大模型 - LangChain 的 OutputParser

文章目录

  • 前言
  • 一、 OutputParser 的概述
  • 二、 JSON OutputParser
  • 三、自定义格式解析器
    • 1. 假设的自定义格式
    • 2. 实现 CustomFormatOutputParser
    • 3. 更复杂的自定义格式
  • 四、 正则表达式解析器
    • 1. 示例:正则表达式解析器
    • 2. 假设的语言模型输出
    • 3. 实现 RegexOutputParser
    • 4. 更复杂的示例
    • 5. 说明
  • 五、表格解析器
    • 1. 假设的表格数据
    • 2. 实现 TableOutputParser
    • 3. 输出
    • 4. 处理 CSV 格式的表格数据
    • 5. 实现 CSVOutputParser
    • 6. 输出
  • 总结


前言

LangChain 是一个用于构建语言模型应用的框架,它提供了许多工具和类来简化与语言模型交互的过程。OutputParser 是其中一个关键组件,用于解析语言模型生成的输出,并将其转换为更易处理的结构化数据。

一、 OutputParser 的概述

OutputParser 是一个抽象基类,定义了从语言模型输出解析数据的接口。在使用语言模型生成文本时,输出通常是非结构化的纯文本数据。OutputParser 提供了一种机制,将这些非结构化的文本数据转换为结构化的格式(如字典、列表、对象等),以便于后续处理。

一个典型的 OutputParser 类需要实现以下关键方法:

  • parse 方法
    该方法接受模型生成的输出文本,并返回解析后的结构化数据。

  • get_format_instructions 方法
    (可选)该方法返回一个字符串,包含如何格式化模型输出的指令。这对于提示设计(prompt design)非常有用。

二、 JSON OutputParser

下面是一个简单的示例,展示了如何实现一个 OutputParser,将语言模型的输出解析为 JSON 格式的数据。

from typing import Any, Dict
import json
from abc import ABC, abstractmethodclass OutputParser(ABC):@abstractmethoddef parse(self, text: str) -> Any:pass@abstractmethoddef get_format_instructions(self) -> str:passclass JsonOutputParser(OutputParser):def parse(self, text: str) -> Dict:try:# 尝试将文本解析为 JSONreturn json.loads(text)except json.JSONDecodeError:# 处理 JSON 解析错误raise ValueError("Failed to parse JSON")def get_format_instructions(self) -> str:return "Please provide the output in JSON format."# 示例使用
if __name__ == "__main__":parser = JsonOutputParser()# 模拟的语言模型输出model_output = '{"name": "Alice", "age": 30}'try:result = parser.parse(model_output)print("Parsed output:", result)except ValueError as e:print("Error:", e)format_instructions = parser.get_format_instructions()print("Format instructions:", format_instructions)

输出

Parsed output: {'name': 'Alice', 'age': 30}
Format instructions: Please provide the output in JSON format.

函数说明

  • parse 方法

    • 接受一个字符串(模型输出),尝试将其解析为 JSON 格式。
    • 如果解析成功,返回一个字典。
    • 如果解析失败,抛出一个 ValueError
  • get_format_instructions 方法

    • 返回一个字符串,说明模型应该如何格式化输出。在这个例子中,要求模型输出 JSON 格式的数据。

三、自定义格式解析器

下面是一个自定义格式解析器的示例,该解析器将语言模型的输出解析为自定义格式的数据。假设我们有一个自定义的输出格式,包含一些预定义的标签和对应的值。我们将实现一个 CustomFormatOutputParser 来解析这种格式的输出。

1. 假设的自定义格式

我们的自定义格式如下所示,每一行包含一个标签和值,以冒号分隔:

name: Alice
age: 30
location: Wonderland

2. 实现 CustomFormatOutputParser

我们将创建一个 CustomFormatOutputParser,它会解析上述格式的输出,将其转换为一个字典。

from typing import Any, Dict
from abc import ABC, abstractmethodclass OutputParser(ABC):@abstractmethoddef parse(self, text: str) -> Any:pass@abstractmethoddef get_format_instructions(self) -> str:passclass CustomFormatOutputParser(OutputParser):def parse(self, text: str) -> Dict[str, Any]:result = {}lines = text.strip().split('\n')for line in lines:key, value = line.split(':', 1)result[key.strip()] = value.strip()return resultdef get_format_instructions(self) -> str:return "Please provide the output in the following format:\nname: <name>\nage: <age>\nlocation: <location>"# 示例使用
if __name__ == "__main__":parser = CustomFormatOutputParser()# 模拟的语言模型输出model_output = """name: Aliceage: 30location: Wonderland"""try:result = parser.parse(model_output)print("Parsed output:", result)except ValueError as e:print("Error:", e)format_instructions = parser.get_format_instructions()print("Format instructions:", format_instructions)

输出

Parsed output: {'name': 'Alice', 'age': '30', 'location': 'Wonderland'}
Format instructions: Please provide the output in the following format:
name: <name>
age: <age>
location: <location>

3. 更复杂的自定义格式

假设我们有一个更复杂的自定义格式,其中标签和值可能包含多个单词,并且每个条目之间有一个空行:

Name: Alice SmithAge: 30Location: Wonderland

我们可以对 CustomFormatOutputParser 进行修改,以处理这种更复杂的格式:

class ComplexCustomFormatOutputParser(OutputParser):def parse(self, text: str) -> Dict[str, Any]:result = {}lines = text.strip().split('\n\n')  # 使用双换行分割条目for line in lines:key, value = line.split(':', 1)result[key.strip()] = value.strip()return resultdef get_format_instructions(self) -> str:return "Please provide the output in the following format with each entry separated by a blank line:\nName: <full name>\n\nAge: <age>\n\nLocation: <location>"# 示例使用
if __name__ == "__main__":parser = ComplexCustomFormatOutputParser()# 模拟的语言模型输出model_output = """Name: Alice SmithAge: 30Location: Wonderland"""try:result = parser.parse(model_output)print("Parsed output:", result)except ValueError as e:print("Error:", e)format_instructions = parser.get_format_instructions()print("Format instructions:", format_instructions)

输出

Parsed output: {'Name': 'Alice Smith', 'Age': '30', 'Location': 'Wonderland'}
Format instructions: Please provide the output in the following format with each entry separated by a blank line:
Name: <full name>Age: <age>Location: <location>

在这个版本中,我们修改了 parse 方法,以处理更复杂的格式,其中每个条目之间有一个空行。我们通过双换行符分割条目,并去掉每个条目的空白字符。这种方式可以更好地处理复杂的输出格式。

这个示例展示了如何根据特定的业务需求定制 OutputParser,以解析自定义格式的语言模型输出。


四、 正则表达式解析器

正则表达式解析器 (RegexOutputParser) 是一种用于从非结构化文本中提取特定模式的数据的工具。正则表达式强大且灵活,适用于各种复杂的解析任务。

1. 示例:正则表达式解析器

假设我们有一个语言模型输出包含一些结构化信息,但这些信息混杂在自然语言文本中。我们的目标是提取这些信息。以下是一个简单的例子,展示如何实现一个 RegexOutputParser 来解析特定的输出格式。

2. 假设的语言模型输出

Name: Alice
Age: 30
Location: Wonderland

3. 实现 RegexOutputParser

我们将创建一个 RegexOutputParser,它使用正则表达式来解析上述格式的输出,并将其转换为一个字典。

import re
from typing import Any, Dict
from abc import ABC, abstractmethodclass OutputParser(ABC):@abstractmethoddef parse(self, text: str) -> Any:pass@abstractmethoddef get_format_instructions(self) -> str:passclass RegexOutputParser(OutputParser):def parse(self, text: str) -> Dict[str, Any]:result = {}# 定义正则表达式模式patterns = {'name': re.compile(r'Name:\s*(.*)'),'age': re.compile(r'Age:\s*(\d+)'),'location': re.compile(r'Location:\s*(.*)')}for key, pattern in patterns.items():match = pattern.search(text)if match:result[key] = match.group(1).strip()return resultdef get_format_instructions(self) -> str:return "Please provide the output in the following format:\nName: <name>\nAge: <age>\nLocation: <location>"# 示例使用
if __name__ == "__main__":parser = RegexOutputParser()# 模拟的语言模型输出model_output = """Name: AliceAge: 30Location: Wonderland"""try:result = parser.parse(model_output)print("Parsed output:", result)except ValueError as e:print("Error:", e)format_instructions = parser.get_format_instructions()print("Format instructions:", format_instructions)

输出

Parsed output: {'name': 'Alice', 'age': '30', 'location': 'Wonderland'}
Format instructions: Please provide the output in the following format:
Name: <name>
Age: <age>
Location: <location>

4. 更复杂的示例

假设我们有更复杂的输出,包括额外的信息,如电子邮件和电话号码:

Name: Alice Smith
Age: 30
Location: Wonderland
Email: alice@example.com
Phone: +1234567890

我们可以扩展 RegexOutputParser 来处理这种更复杂的格式:

class ComplexRegexOutputParser(OutputParser):def parse(self, text: str) -> Dict[str, Any]:result = {}# 定义正则表达式模式patterns = {'name': re.compile(r'Name:\s*(.*)'),'age': re.compile(r'Age:\s*(\d+)'),'location': re.compile(r'Location:\s*(.*)'),'email': re.compile(r'Email:\s*([\w\.-]+@[\w\.-]+)'),'phone': re.compile(r'Phone:\s*(\+\d+.*)')}for key, pattern in patterns.items():match = pattern.search(text)if match:result[key] = match.group(1).strip()return resultdef get_format_instructions(self) -> str:return ("Please provide the output in the following format:\n""Name: <name>\n""Age: <age>\n""Location: <location>\n""Email: <email>\n""Phone: <phone>")# 示例使用
if __name__ == "__main__":parser = ComplexRegexOutputParser()# 模拟的语言模型输出model_output = """Name: Alice SmithAge: 30Location: WonderlandEmail: alice@example.comPhone: +1234567890"""try:result = parser.parse(model_output)print("Parsed output:", result)except ValueError as e:print("Error:", e)format_instructions = parser.get_format_instructions()print("Format instructions:", format_instructions)

输出

Parsed output: {'name': 'Alice Smith', 'age': '30', 'location': 'Wonderland', 'email': 'alice@example.com', 'phone': '+1234567890'}
Format instructions: Please provide the output in the following format:
Name: <name>
Age: <age>
Location: <location>
Email: <email>
Phone: <phone>

5. 说明

在这个扩展的示例中,正则表达式解析器被更新以处理更多类型的信息,包括电子邮件和电话号码。每个字段都有其对应的正则表达式模式,用于匹配并提取信息。这种方式可以灵活地适应多种复杂的输出格式。

五、表格解析器

表格解析器用于解析结构化的表格数据,例如 CSV 或 Markdown 表格格式。下面我们将创建一个 TableOutputParser 类,该类可以解析简单的表格数据,并将其转换为列表或字典格式。

1. 假设的表格数据

假设我们有一个 Markdown 格式的表格数据:

| Name  | Age | Location   |
|-------|-----|------------|
| Alice | 30  | Wonderland |
| Bob   | 25  | Neverland  |

2. 实现 TableOutputParser

我们将实现一个 TableOutputParser 类来解析这种表格数据。

from typing import Any, Dict, List
from abc import ABC, abstractmethod
import reclass OutputParser(ABC):@abstractmethoddef parse(self, text: str) -> Any:pass@abstractmethoddef get_format_instructions(self) -> str:passclass TableOutputParser(OutputParser):def parse(self, text: str) -> List[Dict[str, Any]]:lines = text.strip().split('\n')# 提取表头headers = [header.strip() for header in lines[0].strip('|').split('|')]# 提取数据行rows = []for line in lines[2:]:  # 跳过表头和分隔符行values = [value.strip() for value in line.strip('|').split('|')]row = dict(zip(headers, values))rows.append(row)return rowsdef get_format_instructions(self) -> str:return ("Please provide the output in the following Markdown table format:\n""| Name  | Age | Location   |\n""|-------|-----|------------|\n""| Alice | 30  | Wonderland |\n""| Bob   | 25  | Neverland  |")# 示例使用
if __name__ == "__main__":parser = TableOutputParser()# 模拟的语言模型输出model_output = """| Name  | Age | Location   ||-------|-----|------------|| Alice | 30  | Wonderland || Bob   | 25  | Neverland  |"""try:result = parser.parse(model_output)print("Parsed output:", result)except ValueError as e:print("Error:", e)format_instructions = parser.get_format_instructions()print("Format instructions:", format_instructions)

3. 输出

Parsed output: [{'Name': 'Alice', 'Age': '30', 'Location': 'Wonderland'}, {'Name': 'Bob', 'Age': '25', 'Location': 'Neverland'}]
Format instructions: Please provide the output in the following Markdown table format:
| Name  | Age | Location   |
|-------|-----|------------|
| Alice | 30  | Wonderland |
| Bob   | 25  | Neverland  |

4. 处理 CSV 格式的表格数据

我们还可以实现一个解析 CSV 格式表格数据的 CSVOutputParser。CSV 格式的表格数据如下:

Name,Age,Location
Alice,30,Wonderland
Bob,25,Neverland

5. 实现 CSVOutputParser

import csv
from io import StringIOclass CSVOutputParser(OutputParser):def parse(self, text: str) -> List[Dict[str, Any]]:f = StringIO(text)reader = csv.DictReader(f)return list(reader)def get_format_instructions(self) -> str:return ("Please provide the output in the following CSV format:\n""Name,Age,Location\n""Alice,30,Wonderland\n""Bob,25,Neverland")# 示例使用
if __name__ == "__main__":parser = CSVOutputParser()# 模拟的语言模型输出model_output = """Name,Age,LocationAlice,30,WonderlandBob,25,Neverland"""try:result = parser.parse(model_output)print("Parsed output:", result)except ValueError as e:print("Error:", e)format_instructions = parser.get_format_instructions()print("Format instructions:", format_instructions)

6. 输出

Parsed output: [{'Name': 'Alice', 'Age': '30', 'Location': 'Wonderland'}, {'Name': 'Bob', 'Age': '25', 'Location': 'Neverland'}]
Format instructions: Please provide the output in the following CSV format:
Name,Age,Location
Alice,30,Wonderland
Bob,25,Neverland

总结

OutputParser 是 LangChain 中一个重要的组件,用于将语言模型生成的非结构化文本数据转换为结构化数据。通过实现各种类型的自定义的 OutputParser,开发者可以根据具体需求灵活地解析模型输出,从而更好地利用语言模型生成的数据。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/21930.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

phpstudy配置的站点不能访问了

无法打开站点 打开网站的时候出现如下 没有人为主动去更改配置项&#xff0c;今天就不能正常访问了 检查了一遍配置&#xff0c;发现并无大碍&#xff0c;那就重新配置一遍看看 配置phpstudy 1、新建网站 2、选择项目入口文件夹 3、配置伪静态 4. 确认保存 在我的电脑 C:\…

C# using的几个用途

using 关键字有三个主要用途&#xff1a; 1.using 语句定义一个范围&#xff0c;在此范围的末尾将释放对象&#xff1a; string filePath "example.txt"; string textToWrite "Hello, this is a test message!"; // Use the using statement to ensure …

JVM优化之垃圾收集底层算法实现

JVM优化之垃圾收集底层算法实现 三色标记多标-浮动垃圾多标多标过程 浮动垃圾处理浮动垃圾总结 漏标-读写屏障漏标读写屏障读屏障写屏障应用实例总结 记忆集与卡表记忆集记忆集的作用记忆集的实现 卡表卡表的作用卡表的实现 应用实例总结 在并发标记过程中&#xff0c;用户线程…

Hive的常规操作

Hive常规操作 hive常用交互命令 -e执行sql语句 [rootmaster ~]# hive -e "show databases";-f执行sql脚本 [rootmaster ~]# hive -f /usr/local/demo.sql查看hive中输入的所有命令 [rootmaster ~]# cat ~/.hivehistory操作库 创建库 语法&#xff1a; create…

用贪心算法计算十进制数转二进制数(整数部分)

十进制整数转二进制数用什么方法&#xff1f;网上一搜&#xff0c;大部分答案都是用短除法&#xff0c;也就是除2反向取余法。这种方法是最基本最常用的&#xff0c;但是计算步骤多&#xff0c;还容易出错&#xff0c;那么还有没有其他更好的方法吗&#xff1f; 一、短除反向取…

Stage #3 选择列表中的XSS注入:技巧与实操

在Web安全的学习旅程中&#xff0c;理解跨站脚本&#xff08;XSS&#xff09;攻击的多种形态至关重要。"XSS Challenges"闯关游戏的Stage #3专注于教授如何在选择列表中执行XSS注入。本文将详细介绍这一阶段的实操技巧和学习重点。 1. 挑战页面概览 学习者首先访问…

FreeRTOS学习笔记-基于stm32(8)消息队列

一、什么是消息队列 队列是不同任务、中断中数据传递的一种机制&#xff0c;又称消息队列。就类似于全局变量&#xff0c;将数据传输到不同的任务中。但全局变量没有写保护&#xff0c;容易造成数据受损。而消息队列中加入了进入临界区的写保护。 队列类似于数组&#xff0c;可…

关于WIN环境下pip DeepSpeed安装报错问题

问题描述 安装resemble-enhance项目时遇到的问题: >>> ERROR 1error: subprocess-exited-with-errorpython setup.py egg_info did not run successfully.exit code: 1[15 lines of output]test.cLINK : fatal error LNK1181: cannot open input file aio.libTraceb…

一维时间序列信号的基于小波集的时频超分辨率分析方法(Python)

由于小波变换只能反映信号的零维奇异性&#xff0c;即只能表达奇异点的位置和特性。事实上具有线奇异的函数在高维空间中非常普遍&#xff0c;例如&#xff0c;自然物体光滑边界使得自然图像的不连续性往往体现为光滑曲线上的奇异性&#xff0c;而并不仅仅是点奇异。对于一个二…

如何科学识别solidworks价格是否合理

Solidworks作为一款在很多领域中都非常重要的设计管理软件而备受人们的关注&#xff0c;该类软件在国内相关渠道中持续得到很多技术单位及行业内人士的喜爱和信任&#xff0c;在人们购买该软件的时候关于各类线上及线下渠道的solidworks都有很大的兴趣。接下来主要分析下如何科…

人工智能专业现代学徒制人才培养质量评价体系构建

一、 引 言 随着信息时代的发展&#xff0c;人工智能&#xff08;AI&#xff09;技术的飞跃进步对各行各业产生了深远影响&#xff0c;对专业人才的培养提出了更高要求。现代学徒制作为一种创新人才培养模式&#xff0c;通过校企合作&#xff0c;强调理论与实践的深度结合&…

性能测试学习-基本使用-元件组件介绍(二)

jmeter优点是&#xff1a;开源免费&#xff0c;小巧&#xff0c;丰富的学习资料和扩展组件 缺点是&#xff1a;1.不支持IP欺骗&#xff0c;分析和报表能力相对于LR欠缺精确度&#xff08;以分钟为单位&#xff09; 工具用户量分析报表IP欺骗费用体积扩展性Loadrunner多(万)精…

Lumière:开创性的视频生成模型及其应用

视频内容创造领域迎来了突破性进展&#xff0c;但视频生成模型由于运动引入的复杂性而面临更多挑战。这些挑战主要源自运动的引入所带来的复杂性。时间连贯性是视频生成中的关键要素&#xff0c;模型必须确保视频中的运动在时间上是连贯和平滑的&#xff0c;避免出现不自然的跳…

LVS精益价值管理系统 LVS.Web.ashx SQL注入漏洞复现

0x01 产品简介 LVS精益价值管理系统是杭州吉拉科技有限公司研发的一款专注于企业精益化管理和价值流优化的解决方案。该系统通过集成先进的数据分析工具、可视化的价值流映射技术和灵活的流程改善机制,帮助企业实现高效、低耗、高质量的生产和服务。 0x02 漏洞概述 LVS精益…

记录岁月云明细账excel导出的性能优化

财务软件报表还是非常麻烦&#xff0c;因为使用excel最好的就是财务&#xff0c;但是通过java导出excel&#xff0c;使用easyexcel不用报表工具&#xff0c;不是这么容易。采用jprofile对一个导出操作进行监控&#xff0c;其中一家零售企业导出当月全部明细账&#xff0c;检测到…

PostgreSQL的视图pg_namespace

PostgreSQL的视图pg_namespace 基础信息 OS版本&#xff1a;Red Hat Enterprise Linux Server release 7.9 (Maipo) DB版本&#xff1a;16.2 pg软件目录&#xff1a;/home/pg16/soft pg数据目录&#xff1a;/home/pg16/data 端口&#xff1a;5777在 PostgreSQL 中&#xff0c;…

鬼刀画风扁平化粒子炫动引导页美化版

源码介绍 分享一款引导页,响应式布局&#xff0c;支持移动PC 添加背景图片&#xff0c;美化高斯模糊 &#xff0c;删除蒙版人物部分&#xff0c;更图片人物画风更美好 删除雪花特效 替换字体颜色 添加底备案号 预留友情连接 效果预览 源码下载 https://www.qqmu.com/3381.h…

‘yarn’不是内部或外部命令,也不是可运行的程序或批处理文件。

目录 问题点 解决方式 # 安装 # 版本 # 本地发生变化&#xff08;了解&#xff09; # 安装项目依赖 新问题 解决方式 问题点 在vscode中&#xff0c;点击dev运行&#xff0c;项目报错【Q1】 * 正在执行任务: yarn run dev yarn : 无法将“yarn”项识别为 cmdlet、函数…

AI生成PPT:一键式演示文稿制作的秘诀

工欲善其事&#xff0c;必先利其器。 随着AI技术与各个行业或细分场景的深度融合&#xff0c;日常工作可使用的AI工具呈现出井喷式发展的趋势&#xff0c;AI工具的类别也从最初的AI文本生成、AI绘画工具&#xff0c;逐渐扩展到AI思维导图工具、AI流程图工具、AI生成PPT工具、AI…

OrangePi Kunpeng Pro套装测评:开箱与基本功能测试

前言 大家好&#xff0c;我是起个网名真难。非常荣幸受到香橙派的邀请&#xff0c;同时也是第一次做这个事情&#xff0c;很荣幸对香橙派与华为鲲鹏在2024年5月12日联合发布的新品——香橙派Kunpeng Pro开发板进行深入的评测。这款开发板是香橙派与华为鲲鹏合作推出的高性能平…