使用LangGraph替代RefineDocumentsChain进行文档总结

在处理长文本时,通常需要将其拆分为较小的文档块,逐个分析以得到总结结果。这类操作常用的策略是RefineDocumentsChain,但使用LangGraph可以实现更加灵活的操作流程。本文将通过一个简单的示例展示如何利用LangGraph替代RefineDocumentsChain进行文档总结。

技术背景介绍

RefineDocumentsChain是一种用于处理长文本的策略,其基本思路是:

  • 将文本拆分为较小的文档。
  • 对第一个文档应用处理过程。
  • 根据下一个文档更新或细化结果。
  • 重复以上步骤直至完成。

当总结的文本超出LLM(如GPT-3)的上下文窗口时,这种方法尤其有效。相比之下,LangGraph的实现更具优势,因为它允许我们在执行过程中动态监控和调节执行顺序,还支持流式处理和组件模块化扩展。

核心原理解析

LangGraph通过定义状态图和条件边来管理流程。与RefineDocumentsChain不同,它不仅提供了更高的可观测性,还可以轻松扩展以加入其他行为(如调用工具)。

代码实现演示

以下是一个LangGraph实现文档总结的示例。

代码实现

首先,我们定义一些简单的文档用于演示:

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"}),
]

接下来,我们使用LangGraph替代RefineDocumentsChain来总结文档:

import operator
from typing import List, Literal, TypedDict

from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnableConfig
from langchain_openai import ChatOpenAI
from langgraph.constants import Send
from langgraph.graph import END, START, StateGraph

# 使用稳定可靠的API服务
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)

# 定义总结和细化提示
summarize_prompt = ChatPromptTemplate([("human", "Write a concise summary of the following: {context}")])
initial_summary_chain = summarize_prompt | llm | StrOutputParser()

refine_template = """
Produce a final summary.

Existing summary up to this point:
{existing_answer}

New context:
------------
{context}
------------

Given the new context, refine the original summary.
"""
refine_prompt = ChatPromptTemplate([("human", refine_template)])

refine_summary_chain = refine_prompt | llm | StrOutputParser()

# 定义状态数据结构
class State(TypedDict):
    contents: List[str]
    index: int
    summary: str

# 初始总结节点
async def generate_initial_summary(state: State, config: RunnableConfig):
    summary = await initial_summary_chain.ainvoke(state["contents"][0], config)
    return {"summary": summary, "index": 1}

# 细化总结节点
async def refine_summary(state: State, config: RunnableConfig):
    content = state["contents"][state["index"]]
    summary = await refine_summary_chain.ainvoke({"existing_answer": state["summary"], "context": content}, config)
    return {"summary": summary, "index": state["index"] + 1}

# 判断是否继续细化
def should_refine(state: State) -> Literal["refine_summary", END]:
    return END if state["index"] >= len(state["contents"]) else "refine_summary"

# 构建图
graph = StateGraph(State)
graph.add_node("generate_initial_summary", generate_initial_summary)
graph.add_node("refine_summary", refine_summary)
graph.add_edge(START, "generate_initial_summary")
graph.add_conditional_edges("generate_initial_summary", should_refine)
graph.add_conditional_edges("refine_summary", should_refine)
app = graph.compile()

# 执行流程并打印细化后的总结
async for step in app.astream({"contents": [doc.page_content for doc in documents]}, stream_mode="values"):
    if summary := step.get("summary"):
        print(summary)

结果输出

通过该实现,我们逐步得到了文档的总结:

Apples are typically red in color.
Apples are typically red in color, while blueberries are blue.
Apples are typically red in color, blueberries are blue, and bananas are yellow.

应用场景分析

通过LangGraph可以实现对文档处理的灵活管理,适用于长文档的总结、评论提取等场景。同时,它的灵活性也使得集成更多复杂操作成为可能。

实践建议

  • 对于需动态监控总结过程的应用场景,推荐使用LangGraph。
  • 可以根据需求在LangGraph中增加更多自定义节点,实现更复杂的文档处理逻辑。

如果遇到问题欢迎在评论区交流。
—END—

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值