使用 Vertex AI PaLM API 创建文本摘要方法

1. 简介

文本摘要是创建较短版文本文档的过程,同时仍会保留重要信息。借助此流程,您可以快速浏览长文档、获取文章的要点或与用户分享摘要。虽然总结一个简短的段落是一项艰巨的任务,但如果您要总结一个大型文档,则有一些挑战需要克服。例如,包含多个页面的 PDF 文件。

在此 Codelab 中,您将学习如何使用生成模型总结大型文档。

构建内容

在本教程中,您将通过以下方法,学习如何使用生成模型从文本中总结信息:

  • 填充
  • MapReduce
  • 具有重叠块的 MapReduce
  • 使用滚动摘要的 MapReduce

2. 要求

  • 一个浏览器,例如 ChromeFirefox
  • 启用了结算功能的 Google Cloud 项目

3. 费用

本教程使用 Vertex AI Generative AI Studio 作为 Google Cloud 的收费组件。

了解 Vertex AI 价格生成式 AI 价格,并使用价格计算器根据您的预计使用情况来估算费用。

4. 使用入门

  1. 使用以下命令安装 Vertex AI SDK、其他软件包及其依赖项:
!pip install google-cloud-aiplatform PyPDF2 ratelimit backoff --upgrade --quiet --user
  • 对于 Colab,取消注释以下单元以重启内核。
# # Automatically restart kernel after installs so that your environment can access the new packages
 import IPython

 app = IPython.Application.instance()
 app.kernel.do_shutdown(True)
  • 对于 Vertex AI Workbench,您可以使用顶部的按钮重启终端。
  1. 通过以下任一方式对笔记本环境进行身份验证:
  • 对于 Colab,取消注释以下单元。
from google.colab import auth
auth.authenticate_user()
  1. 导入库以初始化 Vertex AI SDK。
  • 对于 Colab,通过取消注释以下单元来导入库。
import vertexai

 PROJECT_ID = "[your-project-id]"  # @param {type:"string"}
 vertexai.init(project=PROJECT_ID, location="us-central1")
import re
import urllib
import warnings
from pathlib import Path

import backoff
import pandas as pd
import PyPDF2
import ratelimit
from google.api_core import exceptions
from tqdm import tqdm
from vertexai.language_models import TextGenerationModel

warnings.filterwarnings("ignore")
  1. 导入需要加载名为 text-bison@001 的预训练文本生成模型的模型。
generation_model = TextGenerationModel.from_pretrained("text-bison@001")
  1. 准备要下载 PDF 文件的数据文件,以用于汇总任务。
# Define a folder to store the files
data_folder = "data"
Path(data_folder).mkdir(parents=True, exist_ok=True)

# Define a pdf link to download and place to store the download file
pdf_url = "https://services.google.com/fh/files/misc/practitioners_guide_to_mlops_whitepaper.pdf"
pdf_file = Path(data_folder, pdf_url.split("/")[-1])

# Download the file using `urllib` library
urllib.request.urlretrieve(pdf_url, pdf_file)

下面介绍了如何查看下载的 PDF 文件中的几页内容。

# Read the PDF file and create a list of pages
reader = PyPDF2.PdfReader(pdf_file)
pages = reader.pages

# Print three pages from the pdf
for i in range(3):
    text = pages[i].extract_text().strip()

print(f"Page {i}: {text} \n\n")

#text contains only the text from page 2

5. 填充方法

将数据传递给语言模型的最简单方法是“填充”作为上下文添加到提示中。这包括提示中的所有相关信息,以及按照您希望模型处理它的顺序。

  1. 仅提取 PDF 文件中第 2 页的文本。
# Entry string that contains the extacted text from page 2
print(f"There are {len(text)} characters in the second page of the pdf")
  1. 创建一个随后可在笔记本中使用的提示模板。
prompt_template = """
    Write a concise summary of the following text.
    Return your response in bullet points which covers the key points of the text.

    ```{text}```

    BULLET POINT SUMMARY:
"""
  1. 通过 API 使用 LLM 来汇总提取的文本。请注意,LLM 目前存在输入文本限制,可能不接受填充大量输入文本。如需详细了解配额和限制,请参阅配额和限制

以下代码会导致异常。

# Define the prompt using the prompt template
prompt = prompt_template.format(text=text)

# Use the model to summarize the text using the prompt
summary = generation_model.predict(prompt=prompt, max_output_tokens=1024).text

print(summary)
  1. 模型返回错误消息:400 Request contain an invalid arguments,因为提取的文本过长,生成模型无法处理。

为避免此问题,您需要输入所提取文本的一部分,例如前 30,000 个字词。

# Define the prompt using the prompt template
prompt = prompt_template.format(text=text[:30000])

# Use the model to summarize the text using the prompt
summary = generation_model.predict(prompt=prompt, max_output_tokens=1024)

summary

您应该会在屏幕截图中看到以下结果:

710efedd9f6dbc6d.png

摘要

虽然对于模型来说全文过大,但您已经成功地使用该模型从 PDF 的一部分中创建了一个简短的项目符号列表,其中包含最重要的信息。

优势

  • 此方法仅对模型进行一次调用。
  • 总结文本时,模型可以一次性访问所有数据。这会改善结果。

缺点

  • 大多数模型都有上下文长度。对于大型文档(或许多文档),此方法不起作用,因为它会导致提示大于上下文长度。
  • 此方法仅适用于较小的数据,不适用于大型文档。

6. MapReduce 方法

为解决大型文档这一问题,我们将研究 MapReduce 方法。这种方法首先将大数据拆分为较小的数据片段,然后在每个数据块上运行提示。对于摘要任务,第一个提示的输出是对这一部分的摘要。生成所有初始输出后,将运行另一个提示来将它们合并。

如需了解此方法的实现详情,请参阅此 GitHub 链接

7. 恭喜

恭喜!您已成功总结了一个长文档的摘要。您学习了对长文档进行总结的 2 种方法,以及它们的优缺点。汇总大型文档有几种方法。在另一个 Codelab 中,请注意另外 2 种方法:带有重叠分块的 MapReduce 和带有滚动摘要的 MapReduce。

总结篇幅较长的文档并非易事。您需要确定文档的要点,对信息进行整合,并以简洁连贯的方式进行呈现。如果文档比较复杂或技术性较强,则很难做到这一点。此外,总结篇幅较长的文档可能非常耗时,因为您需要仔细阅读和分析文本,以确保摘要准确而完整。

虽然这些方法可让您与 LLM 交互并灵活地总结长文档,但有时您可能想要使用引导方法或预构建方法来加快此过程。这正是 LangChain 等库的用武之地。详细了解 Vertex AI 上的 LangChain 支持