Skip to main content
Open In ColabOpen on GitHub

如何在一次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|.||

下一步

查看摘要 操操作指南 以了解其他摘要策略,包括适用于大量文本的策略。

另请参阅 此教程 以了解有关摘要的更多详细信息。