Langchain对管道操作符|的重构实现链式流程

目录

一、管道操作符

  1. Python 中的管道操作符
    在 Python 3.10 及以上版本中,管道操作符 | 主要用于以下场景:

(1)集合操作

管道操作符可以用于集合的并集操作。

bash 复制代码
set1 = {1, 2, 3}
set2 = {3, 4, 5}
result = set1 | set2  # 并集: {1, 2, 3, 4, 5}

(2)类型联合

在类型注解中,| 可以表示"或"的关系。

bash 复制代码
def func(x: int | float) -> int | float:
    return x * 2

(3)模式匹配

在 match 语句中,| 可以用于匹配多个模式。

bash 复制代码
value = 3
match value:
    case 1 | 2 | 3:
        print("Small number")
    case _:
        print("Other number")

二、LangChain 的链式流程

在 LangChain 中,管道操作符 | 用于将多个步骤串联起来,形成一个链式流程。

bash 复制代码
chain = (
    {"question": RunnablePassthrough()}
    | prompt_template
    | llm
    | output_parser
)

每一步的输出会作为下一步的输入。

这种设计使得代码更加模块化和可读。

三、源码剖析

在 LangChain 的实际源码中,管道操作符的实现位于 langchain/schema/runnable.py 文件中。以下是一些关键代码片段:

bash 复制代码
class Runnable:
    def __or__(self, other: Union["Runnable", Callable]) -> "RunnableSequence":
        from langchain.schema.runnable import RunnableSequence
        return RunnableSequence([self, other])

or 方法,它是 Python 中的特殊方法(也称为魔术方法或双下方法)。or 方法用于重载 | 操作符的行为。具体来说,这段代码的作用是允许一个对象与另一个对象(或可调用对象)通过 | 操作符连接,并返回一个新的 RunnableSequence 对象。
or 方法定义了 | 操作符的行为。当你在代码中使用 | 操作符连接两个对象时,Python 会调用左侧对象的 or 方法,并将右侧对象作为参数传递。

bash 复制代码
step1 = Runnable()
step2 = Runnable()

# 使用 | 操作符连接两个对象
chain = step1 | step2

Union["Runnable", Callable] 的含义

Union 是 Python 类型注解中的一个工具,表示"或"的关系。Union["Runnable", Callable] 表示 other 可以是以下两种类型之一:

Runnable:一个实现了 Runnable 接口的对象。

Callable:一个可调用对象(如函数、lambda 表达式等)。

链式流程有递归的思想

bash 复制代码
from typing import Union, Callable

class Runnable:
    def __or__(self, other: Union["Runnable", Callable]) -> "RunnableSequence":
        if callable(other):
            # 如果 other 是可调用对象,将其包装为 Runnable
            other = RunnableWrapper(other)
        return RunnableSequence(self, other)

class RunnableSequence:
    def __init__(self, first: Runnable, second: Runnable):
        self.first = first
        self.second = second

    def run(self, input):
        # 先运行第一个步骤
        intermediate = self.first.run(input)
        # 再运行第二个步骤
        return self.second.run(intermediate)

class RunnableWrapper(Runnable):
    def __init__(self, func: Callable):
        self.func = func

    def run(self, input):
        return self.func(input)
相关推荐
我星期八休息1 分钟前
Linux系统编程—库制作与原理
linux·运维·服务器·数据结构·人工智能·python·散列表
AiTop1006 分钟前
智谱AI推出ZCube组网架构:大模型推理性能与成本双突破,重构智算基础设施
人工智能·重构·架构
Cloud_Shy6188 分钟前
Python 数据分析基础入门:《Excel Python:飞速搞定数据分析与处理》学习笔记系列(第十二章 用户定义函数 上篇)
python·数据分析·excel·pandas
BU摆烂会噶23 分钟前
【LangGraph】House_Agent 实战(四):预定流程 —— 中断与人工干预
android·人工智能·python·langchain
AI玫瑰助手23 分钟前
Python运算符:比较运算符(等于不等等于大于小于)与返回值
android·开发语言·python
AI技术控23 分钟前
LangChain 是什么?从零开始学会 LangChain 的工程实践指南
人工智能·语言模型·自然语言处理·langchain·nlp
幂律智能28 分钟前
从AI使用风险到合同智能审查重构企业风控能力
人工智能·重构
GIOTTO情35 分钟前
Infoseek舆情处置系统的技术实现与落地实践
python
new_dev1 小时前
Python实现Android自动化打包工具:加固、签名、多渠道一键完成
android·python·自动化
天天进步20151 小时前
从零打造 Python 全栈项目:智能教学辅助系统
开发语言·人工智能·python