跳到主要內容
Open In ColabOpen on GitHub

如何透過單次 LLM 呼叫總結文字

LLM 可以總結並以其他方式提煉文字中的所需資訊,包括大量文字。在許多情況下,特別是對於具有較大上下文視窗的模型,這可以透過單次 LLM 呼叫充分實現。

LangChain 實作了一個簡單的預建鏈,可將提示與用於總結和其他目的的所需上下文「填充」。在本指南中,我們示範如何使用此鏈。

載入聊天模型

首先,讓我們載入一個聊天模型

pip install -qU "langchain[openai]"
import getpass
import os

if not os.environ.get("OPENAI_API_KEY"):
os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter API key for OpenAI: ")

from langchain.chat_models import init_chat_model

llm = init_chat_model("gpt-4o-mini", model_provider="openai")

載入文件

接下來,我們需要一些文件來總結。下面,我們產生一些玩具文件以用於說明目的。請參閱文件載入器操作指南整合頁面以取得其他資料來源。總結教學也包含總結部落格文章的範例。

from langchain_core.documents import Document

documents = [
Document(page_content="Apples are red", metadata={"title": "apple_book"}),
Document(page_content="Blueberries are blue", metadata={"title": "blueberry_book"}),
Document(page_content="Bananas are yelow", metadata={"title": "banana_book"}),
]
API 參考:Document

載入鏈

下面,我們定義一個簡單的提示,並使用我們的聊天模型和文件實例化鏈

from langchain.chains.combine_documents import create_stuff_documents_chain
from langchain_core.prompts import ChatPromptTemplate

prompt = ChatPromptTemplate.from_template("Summarize this content: {context}")
chain = create_stuff_documents_chain(llm, prompt)

調用鏈

由於此鏈是Runnable,因此它實作了常用的調用方法

result = chain.invoke({"context": documents})
result
'The content describes the colors of three fruits: apples are red, blueberries are blue, and bananas are yellow.'

串流

請注意,此鏈也支援個別輸出 Token 的串流

for chunk in chain.stream({"context": documents}):
print(chunk, end="|")
|The| content| describes| the| colors| of| three| fruits|:| apples| are| red|,| blueberries| are| blue|,| and| bananas| are| yellow|.||

下一步

請參閱總結操作指南,以取得其他總結策略,包括專為大量文字設計的策略。

另請參閱本教學,以取得有關總結的更多詳細資訊。


此頁面是否有幫助?