실행하려는 체인들이 각각 독립적일때, 메모리를 더 사용해서 수행시간을 단축시키기 위해 체인을 병렬처리할 수 있다. RunnableParallel을 이용해 체인을 병렬처리해보았다. RunnableParallel역시 다른 Runnable~시리즈처럼 Runnable 표준 인터페이스를 상속한다.
구현코드
제공된 주제에 따라 간단한 설명과, 시를 써달라는 요청을 했다.

from langchain_ollama.llms import OllamaLLM model = OllamaLLM( model="gemma2:2b" )
from langchain_core.prompts import PromptTemplate prompt1 = PromptTemplate.from_template( """ {topic}에 대해서 1줄로 설명해줘: """ ) prompt2 = PromptTemplate.from_template( """ {topic}에 대한 시를 써줘. 다음 형식으로만 답변해: <title> <content> """ )
from langchain_core.runnables import RunnableParallel full_chain = RunnableParallel(desc=chain1, poem=chain2) output = { "desc": "", "poem": "" } response = full_chain.stream( {"topic": "혹등고래"} ) for chunk in response: for key in chunk: output[key] = output[key] + chunk[key] print(output["desc"]) print(output["poem"])
실행 결과
LangFuse로 결과를 확인해보면 RunnableParallel 실행 안에서 병렬적으로 2번의 생성이 일어난 것이 확인된다.



'프로그래밍 > AI,ML' 카테고리의 다른 글
CivitAI 모델 wget으로 다운받는법 (0) | 2025.01.17 |
---|---|
[LangChain] LLM Workflow: Routing 구현 (0) | 2025.01.14 |
[LangChain] LLM Workflow : Chaining 구현 (0) | 2025.01.13 |
프롬프팅 팁 (0) | 2025.01.09 |
프롬프팅의 기법 (1) | 2025.01.09 |