AI/LangChain

LCEL 인터페이스 정리: Runnable 구조와 주요 메서드

불타는고굼이 2025. 3. 28. 14:24
반응형

LCEL 인터페이스 정리: Runnable 구조와 주요 메서드

LangChain Expression Language(LCEL)는 체인 컴포넌트를 함수형으로 연결할 수 있도록 설계된 구조이며, 모든 컴포넌트는 Runnable 인터페이스를 구현해야 한다. LCEL의 핵심은 이 Runnable 프로토콜을 따르는 클래스들 간의 연결에 있으며, 해당 구조를 기반으로 체인을 구성하고 실행한다.

Runnable 인터페이스 개요

LCEL에서 사용되는 모든 구성 요소(PromptTemplate, LLM, OutputParser 등)는 내부적으로 Runnable 추상 클래스 또는 프로토콜을 구현하며, 아래 메서드를 기본적으로 지원한다.

지원 메서드 목록

  • invoke(input): 단일 입력 실행 (동기 방식)
  • batch(inputs): 여러 입력을 동시에 실행
  • stream(input): 토큰 단위로 실시간 응답
  • ainvoke(input): 비동기 단일 입력 실행
  • abatch(inputs): 비동기 다중 입력 실행
  • astream(input): 비동기 스트리밍

실행 흐름 예시

prompt: RunnablePromptTemplate
llm: RunnableLLM
parser: RunnableOutputParser

# 체인 연결
chain = prompt | llm | parser

# 실행
result = chain.invoke({"question": "LCEL의 인터페이스는?"})

RunnableMap

입력 데이터를 여러 개의 Runnable에 분기하여 전달할 수 있는 구조이다. 입력 key별로 Runnable을 지정할 수 있다.

from langchain.schema.runnable import RunnableMap

chain = RunnableMap({
  "question": PromptTemplate.from_template("Q: {question}\nA:"),
  "context": lambda _: "기본 맥락"
})

RunnableLambda

람다 함수 또는 커스텀 로직을 체인 내에 삽입할 때 사용하는 래퍼 클래스이다.

from langchain.schema.runnable import RunnableLambda

multiply = RunnableLambda(lambda x: x * 10)
result = multiply.invoke(3)  # 출력: 30

RunnableSequence

여러 Runnable 컴포넌트를 순차적으로 연결하는 체인을 생성할 때 사용하는 클래스이다. 파이프(|) 연산자 없이 명시적으로 체인을 구성할 수 있다.

from langchain.schema.runnable import RunnableSequence

sequence = RunnableSequence(first=prompt, middle=llm, last=parser)

동기 vs 비동기 메서드 차이

메서드 용도 설명
invoke단일 입력기본 실행 메서드 (동기)
batch다중 입력여러 개의 입력을 한 번에 실행
stream스트리밍출력을 스트림으로 수신 (토큰 단위)
ainvoke단일 입력비동기 실행
abatch다중 입력비동기 방식의 배치 실행
astream스트리밍비동기 스트리밍 출력

LCEL에서 활용 가능한 주요 Runnable 클래스

  • PromptTemplate: 입력값을 템플릿 문자열로 변환
  • ChatOpenAI: LLM 호출 (Chat 방식)
  • StrOutputParser: 문자열로 출력 파싱
  • RunnableLambda: 람다 함수 실행
  • RunnableMap: 입력값 분기 처리
  • RunnableSequence: 명시적 체인 구성
728x90
반응형