【LangChain】概要(Summarization)

LangChain学习文档

  • 流行
    • 【LangChain】Retrieval QA
    • 【LangChain】对话式问答(Conversational Retrieval QA)
    • 【LangChain】SQL
    • 【LangChain】概要(Summarization)

概要

summarization chain可用于汇总多个文档。一种方法是输入多个较小的文档,将它们分为块后,并使用 MapReduceDocumentsChain 对它们进行操作。还可以选择将进行汇总的链改为 StuffDocumentsChainRefineDocumentsChain

准备数据

首先我们准备数据。在此示例中,我们从一个长文档创建多个文档,但可以以任何方式获取这些文档(本笔记本的重点是突出显示获取文档后要执行的操作)。

from langchain import OpenAI, PromptTemplate, LLMChain
from langchain.text_splitter import CharacterTextSplitter
from langchain.chains.mapreduce import MapReduceChain
from langchain.prompts import PromptTemplate
# 大模型
llm = OpenAI(temperature=0)
# 初始化拆分器
text_splitter = CharacterTextSplitter()
# 加载长文本
with open("../../state_of_the_union.txt") as f:state_of_the_union = f.read()
texts = text_splitter.split_text(state_of_the_union)from langchain.docstore.document import Document
# 将拆分后的文本转成文档
docs = [Document(page_content=t) for t in texts[:3]]

快速开始

如果您只是想尽快开始,建议采用以下方法:

from langchain.chains.summarize import load_summarize_chain
# 注意这里是load_summarize_chain
chain = load_summarize_chain(llm, chain_type="map_reduce")
chain.run(docs)

结果:

'问界M5是赛力斯与华为合力打造的高端品牌AITO的首款车,问界M5共推出两款车型,后驱标准版预售价格25万元,四驱性能版28万元。'

如果您想更好地控制和了解正在发生的事情,请参阅以下信息。

stuff Chain

本节展示使用 stuff Chain 进行汇总的结果。

chain = load_summarize_chain(llm, chain_type="stuff")
chain.run(docs)

结果:

    ' 问界M5是赛力斯与华为合力打造的高端品牌AITO的首款车,问界M5共推出两款车型,后驱标准版预售价格25万元,四驱性能版28万元。'

自定义提示(Custom Prompts

您还可以在该链上使用您自己的提示。在此示例中,我们将用意大利语回复。

prompt_template = """Write a concise summary of the following:{text}CONCISE SUMMARY IN ITALIAN:"""
# 上面的prompt是要用意大利语做摘要
PROMPT = PromptTemplate(template=prompt_template, input_variables=["text"])
# summarize_chain
chain = load_summarize_chain(llm, chain_type="stuff", prompt=PROMPT)
chain.run(docs)

结果:就不打印了。

map_reduce Chain

本节展示使用map_reduce Chain进行汇总的结果。

chain = load_summarize_chain(llm, chain_type="map_reduce")
chain.run(docs)
    ' 问界M5是赛力斯与华为合力打造的高端品牌AITO的首款车,问界M5共推出两款车型,后驱标准版预售价格25万元,四驱性能版28万元。'

中间步骤

如果我们想检查它们,我们还可以返回 map_reduce 链的中间步骤。这是通过 return_map_steps 变量完成的。

chain = load_summarize_chain(OpenAI(temperature=0), chain_type="map_reduce", return_intermediate_steps=True)chain({"input_documents": docs}, return_only_outputs=True)

结果:

    {'map_steps': [" In response to Russia's aggression in Ukraine, the United States has united with other freedom-loving nations to impose economic sanctions and hold Putin accountable. The U.S. Department of Justice is also assembling a task force to go after the crimes of Russian oligarchs and seize their ill-gotten gains.",' The United States and its European allies are taking action to punish Russia for its invasion of Ukraine, including seizing assets, closing off airspace, and providing economic and military assistance to Ukraine. The US is also mobilizing forces to protect NATO countries and has released 30 million barrels of oil from its Strategic Petroleum Reserve to help blunt gas prices. The world is uniting in support of Ukraine and democracy, and the US stands with its Ukrainian-American citizens.'," President Biden and Vice President Harris ran for office with a new economic vision for America, and have since passed the American Rescue Plan and the Bipartisan Infrastructure Law to help struggling families and rebuild America's infrastructure. This includes creating jobs, modernizing roads, airports, ports, and waterways, replacing lead pipes, providing affordable high-speed internet, and investing in American products to support American jobs."],'output_text': " In response to Russia's aggression in Ukraine, the United States and its allies have imposed economic sanctions and are taking other measures to hold Putin accountable. The US is also providing economic and military assistance to Ukraine, protecting NATO countries, and passing legislation to help struggling families and rebuild America's infrastructure. The world is uniting in support of Ukraine and democracy, and the US stands with its Ukrainian-American citizens."}

自定义提示

您还可以在该链上使用您自己的prompt。在此示例中,我们将用意大利语回复。

# 该prompt说:要用意大利语做摘要
prompt_template = """Write a concise summary of the following:{text}CONCISE SUMMARY IN ITALIAN:"""
# 创建prompt的模板
PROMPT = PromptTemplate(template=prompt_template, input_variables=["text"])
chain = load_summarize_chain(OpenAI(temperature=0), chain_type="map_reduce", return_intermediate_steps=True, map_prompt=PROMPT, combine_prompt=PROMPT)
chain({"input_documents": docs}, return_only_outputs=True)

自定义MapReduceChain

多输入提示

您还可以使用多输入提示。在此示例中,我们将使用 MapReduce 链来回答有关我们代码的特定问题。

from langchain.chains.combine_documents.map_reduce import MapReduceDocumentsChain
from langchain.chains.combine_documents.stuff import StuffDocumentsChain
# 第一个prompt
map_template_string = """Give the following python code information, generate a description that explains what the code does and also mention the time complexity.
Code:
{code}Return the the description in the following format:
name of the function: description of the function
"""# 第二个prompt
reduce_template_string = """Given the following python function names and descriptions, answer the following question
{code_description}
Question: {question}
Answer:
"""
# 第一个prompt模板
MAP_PROMPT = PromptTemplate(input_variables=["code"], template=map_template_string)
# 第二个prompt模板
REDUCE_PROMPT = PromptTemplate(input_variables=["code_description", "question"], template=reduce_template_string)
# 大模型
llm = OpenAI()
# map 链
map_llm_chain = LLMChain(llm=llm, prompt=MAP_PROMPT)
#reduce 链
reduce_llm_chain = LLMChain(llm=llm, prompt=REDUCE_PROMPT)generative_result_reduce_chain = StuffDocumentsChain(llm_chain=reduce_llm_chain,document_variable_name="code_description",
)combine_documents = MapReduceDocumentsChain(llm_chain=map_llm_chain,combine_document_chain=generative_result_reduce_chain,document_variable_name="code",
)map_reduce = MapReduceChain(combine_documents_chain=combine_documents,text_splitter=CharacterTextSplitter(separator="\n##\n", chunk_size=100, chunk_overlap=0),
)

代码片段为:

code = """
def bubblesort(list):for iter_num in range(len(list)-1,0,-1):for idx in range(iter_num):if list[idx]>list[idx+1]:temp = list[idx]list[idx] = list[idx+1]list[idx+1] = tempreturn list
##
def insertion_sort(InputList):for i in range(1, len(InputList)):j = i-1nxt_element = InputList[i]while (InputList[j] > nxt_element) and (j >= 0):InputList[j+1] = InputList[j]j=j-1InputList[j+1] = nxt_elementreturn InputList
##
def shellSort(input_list):gap = len(input_list) // 2while gap > 0:for i in range(gap, len(input_list)):temp = input_list[i]j = iwhile j >= gap and input_list[j - gap] > temp:input_list[j] = input_list[j - gap]j = j-gapinput_list[j] = tempgap = gap//2return input_list"""
# 哪个函数的时间复杂度更好
map_reduce.run(input_text=code, question="Which function has a better time complexity?")

结果:

    Created a chunk of size 247, which is longer than the specified 100Created a chunk of size 267, which is longer than the specified 100'shellSort has a better time complexity than both bubblesort and insertion_sort, as it has a time complexity of O(n^2), while the other two have a time complexity of O(n^2).'

refine(提炼) Chain

本节显示使用refine链进行汇总的结果。

chain = load_summarize_chain(llm, chain_type="refine")chain.run(docs)

结果:

问界M5是赛力斯与华为合力打造的高端品牌AITO的首款车,问界M5共推出两款车型,后驱标准版预售价格25万元,四驱性能版28万元。

中间步骤

如果我们想要检查它们,我们还可以返回refine链的中间步骤。这是通过 return_refine_steps 变量完成的。

# 注意这里指定参数
chain = load_summarize_chain(OpenAI(temperature=0), chain_type="refine", return_intermediate_steps=True)chain({"input_documents": docs}, return_only_outputs=True)
# 结果
'问界M5是赛力斯与华为合力打造的高端品牌AITO的首款车,问界M5共推出两款车型,后驱标准版预售价格25万元,四驱性能版28万元。'

自定义prompt

您还可以在该链上使用您自己的提示。在此示例中,我们将用意大利语回复。

prompt_template = """写出以下内容的简洁摘要:{text}意大利语简洁摘要:"""
PROMPT = PromptTemplate(template=prompt_template, input_variables=["text"])
refine_template = ("你的工作是编写最终摘要\n""我们已经提供了一定程度的现有摘要: {existing_answer}\n""我们有机会完善现有的摘要""(only if needed) 下面有更多背景信息.\n""------------\n""{text}\n""------------\n""鉴于新的背景,完善意大利语的原始摘要""如果上下文没有用,则返回原始摘要。"
)
refine_prompt = PromptTemplate(input_variables=["existing_answer", "text"],template=refine_template,
)
chain = load_summarize_chain(OpenAI(temperature=0), chain_type="refine", return_intermediate_steps=True, question_prompt=PROMPT, refine_prompt=refine_prompt)
chain({"input_documents": docs}, return_only_outputs=True)

结果:

    {'intermediate_steps': ["\n\nQuesta sera, ci incontriamo come democratici, repubblicani e indipendenti, ma soprattutto come americani. La Russia di Putin ha cercato di scuotere le fondamenta del mondo libero, ma ha sottovalutato la forza della gente ucraina. Insieme ai nostri alleati, stiamo imponendo sanzioni economiche, tagliando l'accesso della Russia alla tecnologia e bloccando i suoi più grandi istituti bancari dal sistema finanziario internazionale. Il Dipartimento di Giustizia degli Stati Uniti sta anche assemblando una task force dedicata per andare dopo i crimini degli oligarchi russi.","\n\nQuesta sera, ci incontriamo come democratici, repubblicani e indipendenti, ma soprattutto come americani. La Russia di Putin ha cercato di scuotere le fondamenta del mondo libero, ma ha sottovalutato la forza della gente ucraina. Insieme ai nostri alleati, stiamo imponendo sanzioni economiche, tagliando l'accesso della Russia alla tecnologia, bloccando i suoi più grandi istituti bancari dal sistema finanziario internazionale e chiudendo lo spazio aereo americano a tutti i voli russi. Il Dipartimento di Giustizia degli Stati Uniti sta anche assemblando una task force dedicata per andare dopo i crimini degli oligarchi russi. Stiamo fornendo più di un miliardo di dollari in assistenza diretta all'Ucraina e fornendo assistenza militare,","\n\nQuesta sera, ci incontriamo come democratici, repubblicani e indipendenti, ma soprattutto come americani. La Russia di Putin ha cercato di scuotere le fondamenta del mondo libero, ma ha sottovalutato la forza della gente ucraina. Insieme ai nostri alleati, stiamo imponendo sanzioni economiche, tagliando l'accesso della Russia alla tecnologia, bloccando i suoi più grandi istituti bancari dal sistema finanziario internazionale e chiudendo lo spazio aereo americano a tutti i voli russi. Il Dipartimento di Giustizia degli Stati Uniti sta anche assemblando una task force dedicata per andare dopo i crimini degli oligarchi russi. Stiamo fornendo più di un miliardo di dollari in assistenza diretta all'Ucraina e fornendo assistenza militare."],'output_text': "\n\nQuesta sera, ci incontriamo come democratici, repubblicani e indipendenti, ma soprattutto come americani. La Russia di Putin ha cercato di scuotere le fondamenta del mondo libero, ma ha sottovalutato la forza della gente ucraina. Insieme ai nostri alleati, stiamo imponendo sanzioni economiche, tagliando l'accesso della Russia alla tecnologia, bloccando i suoi più grandi istituti bancari dal sistema finanziario internazionale e chiudendo lo spazio aereo americano a tutti i voli russi. Il Dipartimento di Giustizia degli Stati Uniti sta anche assemblando una task force dedicata per andare dopo i crimini degli oligarchi russi. Stiamo fornendo più di un miliardo di dollari in assistenza diretta all'Ucraina e fornendo assistenza militare."}

参考地址:

https://python.langchain.com/docs/modules/chains/popular/summarize

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

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

相关文章

单例模式:懒汉式和饿汉式

目录 懒汉模式和饿汉模式 区别 示例 懒汉模式线程不安全 懒汉模式线程安全 懒汉模式内部静态变量线程安全 饿汉式线程安全 指的是在系统生命周期内,只产生一个实例。 懒汉模式和饿汉模式 分为懒汉式和饿汉式 区别 创建时机和线程安全 线程安全&#xff1…

高时空分辨率、高精度一体化预测技术的风、光、水自动化预测技术的应用

第一章 预测平台讲解及安装 一、高精度气象预测基础理论介绍 综合气象观测数值模拟模式; 全球预测模式、中尺度数值模式; 二、自动化预测平台介绍 Linux系统 Crontab定时任务执行机制 Bash脚本自动化编程 硬件需求简介 软件系统安装 …

分享一个加载按钮动画

先看效果&#xff1a; 再看代码&#xff1a; <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><title>加载动画按钮</title><script src"https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2…

flutter开发实战-卡片翻转动画效果Transform+IndexedStack+rotateAnimation

flutter开发实战-实现卡片翻转动画效果 之前开发中遇到了商品卡片翻转&#xff0c;商品正面是商品图片、商品名称&#xff1b;背面是商品价格&#xff0c;需要做卡片翻转动画。 动画实现即&#xff1a;在一段时间内&#xff0c;快速地多次改变UI外观&#xff1b;由于人眼会产生…

FL Studio是什么软件?FL Studio2023最新更新内容

FL Studio是什么软件 FL Studio是由比利时软件公司Image-Line开发的音乐制作软件&#xff0c;它拥有丰富的音效、合成器、采样器、鼓机等工具。FL Studio支持多种音频文件格式&#xff0c;包括MIDI、MP3、WAV、OGG等&#xff0c;可以帮助用户自由地进行音乐创作。 FL Studio界…

如何有效利用chatgpt?

如何有效地使用ChatGPT&#xff1f; 代码、诗歌、歌曲和短篇小说都可以由 ChatGPT 以特定的风格编写。您所需要的只是正确的问题和适当的提示。以下是有关如何有效使用ChatGPT的一些提示和想法&#xff1a; 头脑 风暴获取初稿解决编码问题尝试不同的提示格式查找标题寻求帮助…

Android 内存泄漏的常见原因及其对应的解决方案

Android 内存泄漏 Android应用程序中常见的内存泄漏原因有很多&#xff0c;以下是一些常见的原因及对应的解决方案&#xff1a; 1. 静态引用导致的内存泄漏&#xff1a; 静态变量持有对Activity或Fragment的引用&#xff0c;导致它们无法被垃圾回收机制释放。 解决方案&…

rk3588+视频采集(mpp硬编码H.265)

rk3588+视频采集(mpp硬编码H.265) mpp硬编码 mpp硬编码可以压缩500倍左右,详细代码见该专栏文章《MPP硬编码H265(500倍压缩)》; 视频采集 本案例是通过opencv+定时器(需按照FPS刷新)获取frame; 自定义一个counter计数,保存counter个帧; 当需要保存一个视频时: 可…

DASCTF密码第一题,bbcrypto

貌似叫这个名字。 # -*- coding:utf-8 -*- import A,SALT from itertools import *def encrypt(m, a, si):c""for i in range(len(m)):chex(((ord(m[i])) * a ord(next(si))) % 128)[2:].zfill(2)return c if __name__ "__main__":m flag{************…

随手笔记——实现去畸变部分的代码

随手笔记——实现去畸变部分的代码 说明关键代码 说明 本程序实现去畸变部分的代码。尽管我们可以调用OpenCV的去畸变&#xff0c;但自己实现一遍有助于理解。 关键代码 // 本程序实现去畸变部分的代码。尽管我们可以调用OpenCV的去畸变&#xff0c;但自己实现一遍有助于理解…

WordPress作为可扩展的企业级解决方案

网络商业世界就像一片汪洋大海&#xff0c;大型企业是大海中最大的鱼。然而&#xff0c;只因为你比其他人都大&#xff0c;并不意味着你不能逆流而上。相反&#xff0c;企业业务面临的挑战更大&#xff0c;对网站的技术要求更高。 多年来&#xff0c;大型公司通常依赖最昂贵的…

Centos终端显示-bash-4.2#的解决方法

登录linux系统过后&#xff0c;突然发现显示的是-bash-4.2# 而不是root主机名 路径的显示方式&#xff0c;发生这种情况的原因是根目录下缺失几个配置文件&#xff0c;从默认配置中拷贝过来就可以解决了。 cp /etc/skel/.bashrc /root/ cp /etc/skel/.bash_profile /root/如…

Linux总线设备驱动模型

1. 简介 驱动模型中的总线可以是真是存在的物理总线&#xff08;USB总线&#xff0c;I2C总线&#xff0c;PCI总线&#xff09;&#xff0c;也可以是为了驱动模型架构设计出的虚拟总线&#xff08;Platform总线&#xff09;。为此linux设备驱动模型都将围绕"总线–设备–驱…

科普一下Elasticsearch中BM25算法的使用

首先还是先了解几个概念&#xff0c;Elasticsearch是一个开源的分布式搜索和分析引擎&#xff0c;它使用一系列算法来计算文档的相关性分数&#xff08;relevance score&#xff09;。这些算法用于确定查询与文档的匹配程度&#xff0c;以便按相关性对搜索结果进行排序。以下是…

生命在于折腾——MacOS(Inter)渗透测试环境搭建

一、前景提要 之前使用的是2022款M2芯片的MacBook Air 13寸&#xff0c;不得不说&#xff0c;是真的续航好&#xff0c;轻薄&#xff0c;刚开始我了解到M芯片的底层是ARM架构&#xff0c;我觉得可以接受&#xff0c;虚拟机用的不多&#xff0c;但在后续的使用过程中&#xff0…

换零钱II:零钱面值动态变化,class方法自动兑换最少零钱(贪心算法)

银行现存零钱面值种类动态变化但数量无限&#xff0c;类方法change()完成指定金额的最少零钱个数兑换。 (本笔记适合学透python基本数据结构&#xff0c;熟悉class的基构造&#xff0c;对类内全局变量有一定认的 coder 翻阅) 【学习的细节是欢悦的历程】 Python 官网&#xff1…

RabbitMQ消息堆积问题及惰性队列

一&#xff0c;消息堆积 1&#xff0c;消费者堆积问题 当生产者生产消息的速度超过了消费者处理消息的速度&#xff0c;就会导致消息在队列中进行堆积&#xff0c;一定时间后会造成队列达到存储的上限&#xff0c;那么最开始进入队列的消息可能变成死信&#xff0c;会被丢弃&…

【软件测试】Git 详细实战-打标签,一篇通关...

目录&#xff1a;导读 前言一、Python编程入门到精通二、接口自动化项目实战三、Web自动化项目实战四、App自动化项目实战五、一线大厂简历六、测试开发DevOps体系七、常用自动化测试工具八、JMeter性能测试九、总结&#xff08;尾部小惊喜&#xff09; 前言 Git 打标签 一般会…

dede编辑器修改成纯文本编辑器的方法

我在做优秀啦网站大全的时候需要的正文内容都不需要设置什么文字样式&#xff0c;所以我需要把编辑器上的工具全部取消掉&#xff0c;包括会员投稿中的编辑器工具栏全部取消掉或者屏蔽隐藏掉&#xff0c;所以我需要把DEDE编辑器修改成纯文本编辑器的方法如下&#xff1a;如图&a…

防范 XSS 攻击的措施

防范 XSS 攻击的措施 XSS&#xff08;Cross-site scripting&#xff09;攻击是一种常见的网络安全漏洞&#xff0c;它可以通过注入恶意代码来攻击用户的计算机和浏览器&#xff0c;从而窃取用户的敏感信息或执行恶意操作。本篇文章将介绍防范 XSS 攻击的措施&#xff0c;并提供…