langchain中用|链接不用的流。这是怎么实现的!
output_parser = StrOutputParser()
chain = prompt | model | output_parser
这是 他们都实现了__or__方法。下边是一个示例
class CustomProcessor:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
def __or__(self, other):
# 当使用 | 操作符时,这里会被调用
name = f"{self.name} > {other.name}"
return CustomProcessor(name)
if __name__ == "__main__":
# 创建不同的处理步骤
prompt_processor = CustomProcessor("PromptProcessor")
model_processor = CustomProcessor("ModelProcessor")
output_parser = CustomProcessor("OutputParser")
# 使用自定义的 | 语法
chain = prompt_processor | model_processor | output_parser
# 处理数据
input_data = "Some input data"
# result = chain.process(input_data)
print(chain)
首先执行 prompt_processor 和 model_processor的__init__。 然后,执行prompt_processor的__or__ ,这个时候other就是后边哪个类的对象,也就是model_processor。 然后执行,output_parser的__init__,接下来执行model_processor的__or__。 最末尾一个的时候,只有机会执行__init__,并没有机会执行__ or__。 Python 提供了多种运算符重载方法,允许您自定义类的实例在执行各种运算时的行为。这些方法通常以双下划线开头和结尾,称为“魔术方法”或“特殊方法”。以下是一些常见的运算符重载方法及其用途:
-
算术运算符:
__add__(self, other): 定义加法操作。__sub__(self, other): 定义减法操作。__mul__(self, other): 定义乘法操作。__truediv__(self, other): 定义真除法操作。__floordiv__(self, other): 定义地板除法操作。__mod__(self, other): 定义取模操作。__pow__(self, other): 定义幂运算。
-
比较运算符:
__eq__(self, other): 定义等于操作。__ne__(self, other): 定义不等于操作。__lt__(self, other): 定义小于操作。__le__(self, other): 定义小于等于操作。__gt__(self, other): 定义大于操作。__ge__(self, other): 定义大于等于操作。
-
位运算符:
__and__(self, other): 定义按位与操作。__or__(self, other): 定义按位或操作。__xor__(self, other): 定义按位异或操作。__lshift__(self, other): 定义左移操作。__rshift__(self, other): 定义右移操作。
-
赋值运算符:
__iadd__(self, other): 定义加法赋值操作。__isub__(self, other): 定义减法赋值操作。__imul__(self, other): 定义乘法赋值操作。- 等等,与算术运算符类似,但返回结果会赋值给左侧操作数。
-
一元运算符:
__neg__(self): 定义取反操作。__pos__(self): 定义取正操作。__invert__(self): 定义按位取反操作。
-
其他运算符:
__getitem__(self, key): 定义索引操作,如使用obj[key]。__setitem__(self, key, value): 定义设置索引操作,如使用obj[key] = value。__delitem__(self, key): 定义删除索引操作,如使用del obj[key]。__call__(self, *args, **kwargs): 定义函数调用操作,如使用obj()。
这些运算符重载方法使得您可以创建行为类似于内建类型的自定义对象,从而使代码更加直观和易于理解。