본문 바로가기
IT/python

연산자 오버로딩 - langchain 에서 쓰는 파이프라인 관련

by 가능성1g 2025. 7. 14.
반응형

파이썬에서 연산자 오버로딩이 가능하다. 

이를 이용해서 langchain 에서는 | (or) 연산자를 파이프라인 같이 이용하고 있다.

책에 어떻게 구현이 가능한지 예제가 있어서 메모 해 둔다!

 

class CustomLCEL:
    def __init__(self, value):
        self.value = value
    def __or__(self, other): # 여기가 연산자 오버로딩!
        if callable(other):
            return CustomLCEL(other(self.value))
        else:
            raise ValueError("Right operand must be callable")
    def result(self):
        return self.value

def add_exclamation(s):
    return s + "!"

def reverse_string(s):
    return s[::-1]

custom_chain = (
    CustomLCEL("로꾸꺼 로꾸꺼 로꾸꺼 말해말")
    | add_exclamation
    | reverse_string
)
print(custom_chain.result())

 

반응형