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

1. 简介

文本摘要是指创建文本文件的简短版本,同时保留重要信息的过程。此过程可用于快速浏览长文档、了解文章要点或与用户分享摘要。虽然总结短段落并非易事,但如果您想总结大型文档,则需要克服一些挑战。例如,多页 PDF 文件。

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

构建内容

在本教程中,您将学习如何使用生成模型来总结文本中的信息,具体方法如下:

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

2. 要求

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

3. 费用

本教程使用 Vertex AI 生成式 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 来总结提取的文本。请注意,大语言模型目前有输入文本限制,因此可能无法接受填充大量输入文本。如需详细了解配额和限制,请参阅 配额和限制。

以下代码会导致异常。

# 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 contains an invalid argument ,因为提取的文本太长,生成模型无法处理。

为避免此问题,您需要输入一部分提取的文本,例如前 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 支持。