如何在单个 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_openai import ChatOpenAI
llm = ChatOpenAI(model="gpt-4o-mini")
加载文档
接下来,我们需要一些文档来进行总结。下面,我们生成一些玩具文档用于说明目的。有关其他数据源,请参阅文档加载器操作指南和集成页面。总结教程还包括一个总结博客文章的示例。
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)
调用链
因为该链是一个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.'
流式传输
请注意,该链还支持单个输出令牌的流式传输
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|.||
下一步
有关其他总结策略,包括为大量文本设计的策略,请参阅总结操作指南。
有关总结的更多详细信息,另请参阅本教程。