Created
December 7, 2024 20:03
-
-
Save msabramo/8510f323afaadeb4c7d1d447f1adeb12 to your computer and use it in GitHub Desktop.
Chaining in Python a la LangChain LCEL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from abc import ABC, abstractmethod | |
class Operator(ABC): | |
@abstractmethod | |
def __call__(self, *args, **kwargs): | |
... | |
def __or__(self, other): | |
class ChainedOperator(Operator): | |
def __call__(_self, *args, **kwargs): | |
return other(self(*args, **kwargs)) | |
return ChainedOperator() | |
class Add(Operator): | |
def __init__(self, value): | |
self.value = value | |
def __call__(self, x: int): | |
return x + self.value | |
class Multiply(Operator): | |
def __init__(self, value): | |
self.value = value | |
def __call__(self, y: int): | |
return y * self.value | |
chain = Add(5) | Multiply(2) | Multiply(3) | |
output = chain(3) # should return 48 | |
print(output) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment