如何在单次LLM调用中进行文本摘要
LLM 可以从文本中总结或提取所需信息,包括大量文本。在许多情况下,特别是对于具有更大上下文窗口的模型,这可以通过一次 LLM 调用充分实现。
LangChain 实现了一个简单的预构建链,它将所需上下文“填充”到提示中,用于总结和其他目的。在本指南中,我们将演示如何使用此链。
加载聊天模型
我们首先加载一个聊天模型
选择 聊天模型
pip install -qU "langchain[google-genai]"
import getpass
import os
if not os.environ.get("GOOGLE_API_KEY"):
os.environ["GOOGLE_API_KEY"] = getpass.getpass("Enter API key for Google Gemini: ")
from langchain.chat_models import init_chat_model
llm = init_chat_model("gemini-2.0-flash", model_provider="google_genai")
加载文档
接下来,我们需要一些要总结的文档。下面,我们生成一些示例文档以作说明之用。请参阅文档加载器操作指南和集成页面以获取更多数据源。总结教程也包含一个总结博客文章的示例。
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)
调用链
由于该链是一个可运行对象,它实现了常规的调用方法
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|.||
下一步
请参阅总结操作指南以了解其他总结策略,包括为处理大量文本而设计的策略。
另请参阅本教程以获取更多关于总结的详细信息。