본문 바로가기
AI/LangChain

[#LangChain] 07. LCEL의 이해와 활용

by dopal2 2026. 2. 27.
반응형

1. LCEL이란?

LCEL(LangChain Expression Language)은 다양한 구성 요소를 단일 체인으로 결합하는 언어입니다. | 기호는 UNIX 명령어 파이프 연산자와 유사하며, 한 구성 요소의 출력을 다음 구성 요소의 입력으로 즉시 전달하는 역할을 수행합니다.

핵심 개념: Runnable

LCEL을 이해하려면 Runnable 클래스를 알아야 합니다. 모든 LCEL 컴포넌트의 기본 클래스로, 우리가 사용하는 대부분의 도구가 이를 상속받습니다.

  • stream: 응답의 청크를 스트리밍 방식으로 출력합니다.
  • invoke: 입력값에 대해 체인을 단발성으로 호출합니다.
  • batch: 여러 입력 리스트에 대해 체인을 한 번에 호출합니다.

다양한 Runnable 종류

  • Chain: 여러 Runnable을 순차적으로 실행합니다.
  • RunnableMap: 여러 Runnable을 병렬로 실행합니다.
  • RunnableSequence: Runnable의 시퀀스를 정의합니다.
  • RunnableLambda: 사용자 정의 파이썬 함수를 Runnable 규격으로 래핑합니다.

2. LCEL의 장점

📝 코드 가독성
복잡한 로직을 명확하고 간결하게 표현 가능
🛠️ 유지보수성
모듈화된 구조로 부분 수정이 용이
⚡ 성능
비동기 실행 및 자동 최적화 지원
🚀 확장성
새로운 컴포넌트의 쉬운 추가와 통합

3. 실습 진행: 국가별 메뉴 추천 시스템

"국가 대표 음식 선정 → 해당 메뉴 분석" 과정을 LCEL로 구현해 보겠습니다.

① 국가명-대표메뉴 체인 생성

from langchain_core.prompts import PromptTemplate   
from langchain_core.output_parsers import StrOutputParser

country_prompt = PromptTemplate(
    template="You are a chef. Please introduce ONLY the name of the most traditional dish in {country}.",
    input_variables=["country"]
)

# LCEL: 프롬프트 | 모델 | 파서
country_chain = country_prompt | llm | StrOutputParser()
print(country_chain.invoke({"country":"korea"}))

## 결과 값 : Bibimbap

② 메뉴-소개 체인 생성 (Pydantic)

class Menu(BaseModel):
    name: str = Field(description="menu name")
    ingredients: str = Field(description="cooking ingredients")
    flavor: str = Field(description="menu flavor")

structured_llm = llm.with_structured_output(Menu)
menu_prompt = PromptTemplate(
    template="You are a cook. Please explain about {menu} briefly.",
    input_variables=["menu"]
)

menu_chain = menu_prompt | structured_llm

# 결과값
# name='Bibimbap' ingredients='Soy sauce, garlic, ginger, tomatoes (optional), onions, fish sauce or soy based balsamic vinegar, rice, tofu or bamboo, vegetable dim sum (chickpeas or lentils), etc.' flavor='Rich in carbs and protein from the rice and vegetables; spices like soy sauce, garlic, ginger, and possibly fish sauce add a spicy kick to the mix. The combination of beans and rice makes it unique and flavorful.'

③ 국가-메뉴-소개 통합 체인 (Total Chain)

앞선 두 체인을 하나로 엮어줍니다. 첫 번째 체인의 결과가 두 번째 체인의 입력으로 자동 전달됩니다.

# 통합 체인 생성
total_chain = country_chain | menu_chain

result = total_chain.invoke({"country":"korea"})

print(result)

# 결과값
# name='Kimchi...' ingredients='golden rice, thick sauce...' flavor="tangy, sweet, and savory..."

4. RunnablePassthrough란?

데이터를 수정하지 않고 그대로 다음 단계로 전달하거나, 흐름 중간에 새로운 값을 추가할 때 사용합니다.

from langchain_core.runnables import RunnablePassthrough

# 사용자가 입력한 문자열이 그대로 {country} 자리에 들어갑니다.
chain = {"country": RunnablePassthrough()} | country_prompt | llm

 

변수가 여러 개 일때는, 키 지정을 해야합니다.

from langchain_core.runnables import RunnablePassthrough

# 다중 변수 키 지정 방식
passthrough_chain = {"country": RunnablePassthrough(), "menu": RunnablePassthrough()} | total_chain
passthrough_chain.invoke({"country":"korea", "menu":"Bibimbap"})

# 국가-메뉴설명에는 키가 여러개인것이 의미가 없음....

 

결과

📝 마무리 및 회고

LCEL 학습을 통해 랭체인을 실제 비즈니스 로직에 어떻게 녹여내는지 확인했습니다.

이제 어느정도 랭체인을 어떻게 사용해야하는지 알게된것 같습니다.

다음 포스팅부터는 랭체인의 또 다른 강력한 기능인 RAG(검색 증강 생성)를 직접 구현해 보겠습니다.

반응형

댓글