使用 Vertex AI PaLM API 產生文字摘要方法

1. 簡介

「文字摘要」是指建立較短的文字文件版本,同時保留重要資訊。這個程序可以快速瀏覽長篇文件、取得文章重點,或是與使用者分享摘要。雖然總結簡短的段落並不容易,但如果想總結大型文件內容,可能需克服一些挑戰。例如包含多個頁面的 PDF 檔案。

在本程式碼研究室中,您將瞭解如何使用生成式模型產生大型文件的摘要。

建構項目

本教學課程將透過下列方法,使用生成式模型從文字中歸納資訊:

  • 填充
  • MapReduce
  • 利用重疊區塊繪製地圖
  • 根據滾動式摘要進行 MapReduce

2. 需求條件

  • 瀏覽器,例如 ChromeFirefox
  • 已啟用計費功能的 Google Cloud 專案

3. 費用

本教學課程使用 Vertex AI Generative AI Studio 做為 Google Cloud 的計費元件。

瞭解 Vertex AI 定價Generative AI 定價,並透過 Pricing Calculator 根據預測用量估算費用。

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. 填充方法

如要將資料傳遞至語言模型,最簡單的做法是「stuff」依據情境將字詞加入提示這包括所有相關資訊,按照您希望模型處理的順序和順序。

  1. 將只有第 2 頁的文字擷取至 PDF 檔案中。
# 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 使用大型語言模型,為擷取的文字產生摘要。請注意,大型語言模型目前有輸入文字限制,如果輸入大量文字,我們可能不會接受。如要進一步瞭解配額和限制,請參閱配額與限制

下列程式碼會導致例外狀況。

# 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 is 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 種方法,以及這類文件的優缺點。有幾個方法可產生大型文件的摘要。留意其他 2 種方法:MapReduce 包含重疊的區塊,以及有滾動式摘要的 MapReduce。

總結長篇文件並非易事。不過,您需要找出文件的重點、統整資訊,並以簡潔連貫的方式呈現。如果文件內容複雜或技術過於複雜,可能會難以辨識。此外,摘錄長篇文件往往相當耗時,因為您必須仔細閱讀及分析文字,才能確保摘要正確且完整。

雖然這些方法可讓您靈活地與 LLM 互動,為長篇文件產生摘要,但有時您可能會想使用啟動或預先建構的方法來加快處理速度。這正是 LangChain 等程式庫派上用場的地方。進一步瞭解 Vertex AI 的 LangChain 支援