Dify工作流中的LLM节点:_fetch_memory方法

本文使用Dify v1.4.0版本,使用qwen-vl-max-latest作为多模态大模型。主要介绍了Dify工作流中的LLM节点的_fetch_memory方法的执行流程。

一.Chatflow流程例子

SYSTEM:

执行指令{{#sys.query#}}。

USER:

{{#sys.query#}}
{{#sys.files#}}

比如,用户在对话的时候,上传了一张图像,并且配上文字:一句话描述图像

二._fetch_memory源码

源码位置:dify\api\core\workflow\nodes\llm\node.py

这个函数用于获取对话记忆,是LLM节点处理对话历史的关键组件。这个函数在工作流执行过程中确保LLM模型能够访问到之前的对话历史,从而提供连贯的对话体验。

def_fetch_memory(
    self, node_data_memory: Optional[MemoryConfig], model_instance: ModelInstance
)
 -> Optional[TokenBufferMemory]:

ifnot node_data_memory:
returnNone

# get conversation id
    conversation_id_variable = self.graph_runtime_state.variable_pool.get(
        ["sys", SystemVariableKey.CONVERSATION_ID.value]
    )
ifnot isinstance(conversation_id_variable, StringSegment):
returnNone
    conversation_id = conversation_id_variable.value

# get conversation
    conversation = (
        db.session.query(Conversation)
        .filter(Conversation.app_id == self.app_id, Conversation.id == conversation_id)
        .first()
    )

ifnot conversation:
returnNone

    memory = TokenBufferMemory(conversation=conversation, model_instance=model_instance)

return memory

1. 参数检查

首先检查是否提供了内存配置参数。如果没有提供(为None),则直接返回None,表示不需要使用对话历史功能。

ifnot node_data_memory:
returnNone

2. 获取对话ID

从工作流运行时状态的变量池中获取系统变量CONVERSATION_ID,这是识别当前对话的唯一标识符。

conversation_id_variable = self.graph_runtime_state.variable_pool.get(
    ["sys", SystemVariableKey.CONVERSATION_ID.value]
)

3. 类型验证

检查获取的变量是否为StringSegment类型。如果不是,返回None,因为需要字符串类型的对话ID

ifnot isinstance(conversation_id_variable, StringSegment):
returnNone

4. 提取对话ID值

从变量对象中提取实际的对话ID字符串值。

conversation_id = conversation_id_variable.value

5. 数据库查询

通过SQLAlchemy查询从数据库中获取对话记录,查询条件是应用ID和对话ID必须匹配。

conversation = (
    db.session.query(Conversation)
    .filter(Conversation.app_id == self.app_id, Conversation.id == conversation_id)
    .first()
)

6. 对话记录检查

如果数据库中没有找到对应的对话记录,返回None。

ifnot conversation:
returnNone

7. 创建内存对象

创建一个TokenBufferMemory实例,传入对话记录和模型实例,用于管理对话历史和令牌消耗。

memory = TokenBufferMemory(conversation=conversation, model_instance=model_instance)

8. 返回结果

返回创建的内存对象,后续可用于获取对话历史并管理令牌使用。

return memory

参考文献

[1] Dify工作流中的LLM节点:_fetch_memory方法:https://z0yrmerhgi8.feishu.cn/wiki/AeOwwORUminlZnkE3DNcYZFJnib

[2] LLMNode类:https://github.com/langgenius/dify/blob/1.4.0/api/core/workflow/nodes/llm/node.py


知识星球服务内容:Dify源码剖析及答疑,Dify对话系统源码,NLP电子书籍报告下载,公众号所有付费资料。加微信buxingtianxia21进NLP工程化资料群

(文:NLP工程化)

发表评论