Nathaniel

4. Runnable(Passthrough, Parallel,Lambda) 본문

AI

4. Runnable(Passthrough, Parallel,Lambda)

Nathaniel1 2025. 3. 2. 21:36
Runnable 3대장에 대해 알아보자

 

1. RunnablePassthrough

1-1. RunnablePassthrough 사용이유??

prompt는 key:value 쌍인데 이것이 엄청 많아진다면 어떻게 다 기억할 수 있을까?

사용자가 key 값을 다 기억하지 못하기 때문에 RunnablePassthrough()를 사용해서 prompt에 바로 넣어주는 간편한 방식이며 기억하기 위한 스트레스를 해소해줄 수 있는 좋은 수단이 될 것이다.

 

기존에 chain 생성하는 단계에서 chain = prompt | llm 으로 코드를 진행했지만,

RunnablePassthrough를 사용하면 곧바로  prompt에 사용자 답변인 10을 key:value 형태로 넣어줄 수 있게 도와주는 것

runnable_chain = {"num":RunnablePassthrough()} | prompt | ChatOpenAI()

runnable_chain.invoke(10)

RunnablePassthrough 이해도



1-2. RunnablePassthrough.asign()

"입력 값으로 들어온 값의 Key:Value 쌍과 새롭게 할당된 Key:Value 쌍을 합친다"라고 생각하자

1. "num":1이 lambda x에서 x 들어간다.(입력 값 Key:Value = 'num': 1)

2. num key 값을 불러와 x["num"]에서 "num"자리에 1이 들어가고 * 3을 해준다.(새롭게 할당된 Key:Value = 'new_num': 3)

 

Lambda 함수를 사용한 RunnablePassthrough 방식을 사용할 때가 있으니, 숙지하기

2. RunnableParallel

chain1, chain2를 병렬수행해서 combines_chain.invoke("대한민국")이라는 값을 입력했을 때

RunnablePassthrough()에 "대한민국"이라는 value가 입력되어 chain1, chain2의 수도와, 면적 값을 출력하게 된다.

 

기존에는 "country" : "대한민국"이라는 값을 직접 넣어 딕셔너리 형태로 진행했지만,

RunnablePassthrough()를 Value에 넣고  invoke()에 값만 집어 넣으면 Key:Value형태가 잘 이루어진다.

결론 : 편리성을 위해서다

chain1 = (
    {"country": RunnablePassthrough()}
    | PromptTemplate.from_template("{country} 의 수도는?")
    | ChatOpenAI()
)
chain2 = (
    {"country": RunnablePassthrough()}
    | PromptTemplate.from_template("{country} 의 면적은?")
    | ChatOpenAI()
)

combined_chain = RunnableParallel(capital=chain1, area=chain2)
combined_chain.invoke("대한민국")

3. RunnableLambda, Itemgetter

3-1. itemgetter는 딕셔너리나 리스트에서 특정 key값을 꺼내오는 도구

 

3-1 예시 1 : 딕셔너리에서 값 가져오기

from operator import itemgetter

data = {"이름": "철수", "나이": 15}

# "이름"이라는 키의 값을 가져옴
getter = itemgetter("이름")
print(getter(data))  # 결과: 철수

itemgetter("이름")은 data{"이름"}과 같이, Key를 직접 입력하는 대신 itemgetter를 사용해서 유연하게 가져올 수 있다.

 

3-1  예시 2 : 리스트에서 값 가져오기

data = ["사과", "바나나", "포도"]

getter = itemgetter(1)  # 두 번째 값 가져오기
print(getter(data))  # 결과: 바나나

itemgetter(1)은 data[1]이므로 리스트의 특정 위치 값을 꺼낼 때 사용한다.

 

3-1  예시 3 : 여러 개의 값을 한 번에 가져오기

data = {"이름": "철수", "나이": 15, "키": 170}

getter = itemgetter("이름", "나이")  # 여러 개의 값을 가져오기
print(getter(data))  # 결과: ('철수', 15)

"이름"과"나이"두 개의 값을 한 번에 가져올 수도 있다.

 

3-2 RunnableLambda는 함수를 감싸서 나중에 실행할 수 있도록 만드는 도구

 

3-2 예제 1 : 간단한 함수 감싸기

from langchain_core.runnables import RunnableLambda

def square(x):
    return x * x

# 함수 감싸기
runnable = RunnableLambda(square)

# 실행하기
print(runnable.invoke(4))  # 결과: 16

 

3-2 예제 2 : 문자열 길이 구하는 함수 감싸기

def get_length(text):
    return len(text)

runnable = RunnableLambda(get_length)

print(runnable.invoke("Hello"))  # 결과: 5

 

3-2 예제 3 : itemgetter와 Lambda 함께 사용하기

data = {"word": "Hello"}

runnable = itemgetter("word") | RunnableLambda(get_length)

print(runnable.invoke(data))  # 결과: 5

 

 

우선 RunnableLambda는 매개변수가 무조건 한 개이다. 매개 변수 두 개를 감싸서 

itemgetter("word")로 data["word"] 값을 가져오고 그 값을 get_length 함수에 전달해서 길이를 구한다.

이렇게 함수들을 파이프(|)로 연결해서 자연스럽게 사용할 수 있다.

 

🔑 정리

itemgetter딕셔너리나 리스트에서 특정 값을 꺼내오는 도구

RunnableLambda함수를 감싸서 실행할 수 있도록 만드는 도구

 

안 익숙하다면? 계속 보면된다. 그냥 계속 보면서 친숙해져라~

'AI' 카테고리의 다른 글

6. Langchain Parser??  (0) 2025.03.11
5. Lagnchain-prompt-template 생성  (0) 2025.03.07
3. Langchain LCEL, Parallel  (4) 2025.03.02
RAG 코드 암기하기 D1  (0) 2025.02.26
2. Langchain → Chain 생성?  (0) 2025.02.26