Skip to content

Instantly share code, notes, and snippets.

@msabramo
Created December 7, 2024 20:03
Show Gist options
  • Save msabramo/8510f323afaadeb4c7d1d447f1adeb12 to your computer and use it in GitHub Desktop.
Save msabramo/8510f323afaadeb4c7d1d447f1adeb12 to your computer and use it in GitHub Desktop.
Chaining in Python a la LangChain LCEL
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