Skip to main content
Open In ColabOpen on GitHub

如何使用单个 LLM 调用总结文本

大型语言模型(LLMs)可以总结和提炼文本中的所需信息,包括大量文本。在许多情况下,尤其是对于具有较大上下文窗口的模型,这可以通过单次 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 参考:文档

加载链

下面,我们定义一个简单的提示词,并使用我们的聊天模型和文档实例化链:

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)

调用链

由于链是一个可运行对象,它实现了通常的调用方法:

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

流式传输

请注意,该链也支持单个输出令牌的流式传输:

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|.||

下一步

查看摘要 操操作指南 以获取其他摘要策略,包括那些专为更大文本量设计的策略。

另请参阅 本教程 以获取更多关于摘要的详细信息。