LCEL이란?

LangChain에서 chain을 구성하는 방법입니다. 프롬프트나 LLM을 | 로 연결하여 작성하고 처리의 연쇄를 구성합니다.

유스케이스

  • 프롬프트 템플릿을 채우고, 그 결과를 챗 모델에 제공하고 결과를 파이썬 객체로 변환하고 싶다.
  • 프롬프팅으로 단계별로 생각하게 하고 그 결과를 요약하게 하고 싶다
  • 출력을 얻은 후에 서비스 정책에 위반되지 않는지 확인하고 싶다
  • 출력 결과를 바탕으로 SQL을 실행하여 데이터를 분석하고 싶다.

1. Prompt와 Model 연결하기

from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI

prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful assistant that can answer questions."),
    ("human", "{input}")
])

model = ChatOpenAI(model = "gpt-4o-mini", temperature = 0.0)

# 체인 생성
chain = prompt | model

ai_message = chain.invoke({"input": "What is the capital of France?"})
print(ai_message.content)

2. Prompt, Model, Output Parser 연결하기

from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser

prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful assistant that can answer questions."),
    ("human", "{input}")
])

model = ChatOpenAI(model = "gpt-4o-mini", temperature = 0.0)

chain = prompt | model | StrOutputParser()

output = chain.invoke({"input": "프랑스에서 가장 맛있다고 하는 요리는?"})

print(output)

3. Prompt, Model, Pydantic Output Parser 연결하기

from langchain_core.output_parsers import PydanticOutputParser
from pydantic import BaseModel, Field, List

# 응답 형식 모델 설정
class Recipe(BaseModel):
    dish: str = Field(description = "먹고싶은 음식의 이름")
    recipe: str = Field(description = "음식의 요리법")
    ingredient: List[str] = Field(description = "필요한 재료의 목록")

# 연쇄 처리할 부분
prompt = ChatPromptTemplate.from_messages([
    ("system", "사용자가 입력한 음식의 요리법과 필요한 재료목록을 찾아주세요.",
    "{format_instructions}"),
    ("human", "{input}")
])

output_parser = PydanticOutputParser(pydantic_object = Recipe)
prompt_input = prompt.partial(
    format_instructions = output_parser.get_format_instructions()
)

model = ChatOpenAI(model = "gpt-4o-mini", temperature = 0.0).bind(
    response_format = {"type": "json_object"}
)

chain = prompt_input | model | output_parser

output = chain.invoke({"input": "당근 카레"})

4. 간단한 구조화된 출력 방법

# 동일한 기능을 하는 간단한 다른 방법
chain2 = prompt | model.with_structured_output(Recipe)

output2 = chain2.invoke({"input": "양파 카레"})

📚 추가로 알아볼 내용

1. LCEL의 고급 연산자들

RunnableParallel (병렬 실행):

from langchain_core.runnables import RunnableParallel

# 여러 작업을 동시에 실행
parallel_chain = RunnableParallel(
    summary=prompt | model | StrOutputParser(),
    keywords=keyword_prompt | model | StrOutputParser(),
    sentiment=sentiment_prompt | model | StrOutputParser()
)

RunnableLambda (함수 변환):

from langchain_core.runnables import RunnableLambda

def format_input(x):
    return {"input": x.upper()}

chain = RunnableLambda(format_input) | prompt | model

RunnableBranch (조건부 분기):

from langchain_core.runnables import RunnableBranch

chain = RunnableBranch(
    (lambda x: "question" in x.lower(), question_chain),
    (lambda x: "summary" in x.lower(), summary_chain),
    default_chain  # 기본값
)

2. 체인 디버깅과 모니터링

# 중간 결과 확인
from langchain_core.runnables import RunnablePassthrough

def debug_print(x):
    print(f"Debug: {x}")
    return x

debug_chain = (
    prompt
    | RunnableLambda(debug_print)  # 프롬프트 결과 확인
    | model
    | RunnableLambda(debug_print)  # 모델 응답 확인
    | output_parser
)

LangSmith 트레이싱:

import os
os.environ["LANGCHAIN_TRACING_V2"] = "true"
os.environ["LANGCHAIN_API_KEY"] = "your-api-key"

# 자동으로 모든 체인 실행이 트레이싱됨

3. 에러 핸들링 전략

from langchain_core.runnables import RunnableWithFallbacks

# 메인 체인이 실패하면 폴백 체인 실행
resilient_chain = primary_chain.with_fallbacks([fallback_chain])

# 커스텀 에러 핸들링
def safe_invoke(chain, input_data):
    try:
        return chain.invoke(input_data)
    except Exception as e:
        return f"Error occurred: {str(e)}"

safe_chain = RunnableLambda(lambda x: safe_invoke(main_chain, x))

4. 스트리밍 최적화

# 토큰 단위 스트리밍
for chunk in chain.stream({"input": "긴 텍스트를 처리하세요"}):
    print(chunk, end="", flush=True)

# 배치 처리로 효율성 증대
inputs = [{"input": f"질문 {i}"} for i in range(10)]
results = chain.batch(inputs)

🔍 학습하면서 알게 된 점

1. 파이프 연산자(|)의 내부 동작 원리

LCEL의 | 연산자는 Python의 __or__ 매직 메서드를 오버라이드합니다:

# 내부적으로 이렇게 동작
def __or__(self, other):
    return RunnableSequence(first=self, last=other)

핵심 인사이트:

  • 각 Runnable은 invoke(), stream(), batch() 메서드를 구현
  • 타입 힌트를 통해 입출력 타입 검증 가능
  • 체인은 실제로 RunnableSequence 객체

2. 입출력 타입 일치의 중요성

# 타입 불일치 예시 (에러 발생)
prompt_returns_messages = ChatPromptTemplate.from_template("Hello {name}")
parser_expects_string = StrOutputParser()

# 올바른 연결
chain = prompt_returns_messages | model | parser_expects_string

주의사항:

  • ChatPromptTemplate → AIMessage 객체 출력
  • StrOutputParser → AIMessage.content (string) 추출
  • 중간에 모델이 AIMessage 생성해야 함

3. with_structured_output()의 장점

# 기존 방식 (복잡함)
chain1 = (
    prompt
    | model.bind(response_format={"type": "json_object"})
    | PydanticOutputParser(pydantic_object=Recipe)
)

# 새로운 방식 (간단함)
chain2 = prompt | model.with_structured_output(Recipe)

내부적으로 수행되는 작업:

  1. 프롬프트에 JSON 스키마 자동 추가
  2. Function Calling 또는 JSON 모드 설정
  3. 자동 파싱 및 검증

4. 성능 최적화 팁

1. 불필요한 중간 변환 제거:

# 비효율적
chain = prompt | model | StrOutputParser() | RunnableLambda(str.strip)

# 효율적
def clean_output(ai_msg):
    return ai_msg.content.strip()

chain = prompt | model | RunnableLambda(clean_output)

2. 캐싱 활용:

from langchain.globals import set_llm_cache
from langchain.cache import InMemoryCache

set_llm_cache(InMemoryCache())
# 동일한 입력에 대해 캐시된 결과 반환

5. 실제 프로덕션 환경에서의 베스트 프랙티스

1. 환경별 설정 분리:

# config.py
class Config:
    def __init__(self, env="development"):
        if env == "production":
            self.temperature = 0.1  # 안정적
            self.max_tokens = 500
        else:
            self.temperature = 0.7  # 창의적
            self.max_tokens = 1000

config = Config(os.getenv("ENVIRONMENT", "development"))
model = ChatOpenAI(temperature=config.temperature)

2. 에러 복구 체인:

def create_resilient_chain(primary, fallback):
    return primary.with_fallbacks([
        fallback,
        RunnableLambda(lambda x: "죄송합니다. 일시적 오류가 발생했습니다.")
    ])

3. 로깅 및 메트릭:

import time
from functools import wraps

def measure_chain_performance(chain):
    def wrapper(input_data):
        start_time = time.time()
        result = chain.invoke(input_data)
        duration = time.time() - start_time

        # 메트릭 수집
        logger.info(f"Chain execution took {duration:.2f}s")
        return result

    return RunnableLambda(wrapper)

6. 메모리 효율성 고려사항

스트리밍 활용:

# 메모리 효율적인 대용량 처리
def process_large_document(doc_chunks):
    for chunk in doc_chunks:
        yield chain.stream({"input": chunk})

가비지 컬렉션:

import gc

# 대량 배치 처리 후 메모리 정리
results = chain.batch(large_input_list)
gc.collect()  # 명시적 가비지 컬렉션