
LangChain에서 체인은 일반적으로 아래와 같은 구조로 구성된다.
chain = PromptTemplate | Model | OutputParser
from langchain.prompts import PromptTemplate
from langchain.chat_models import ChatOpenAI
from langchain.schema.output_parser import StrOutputParser
# 구성 요소 정의
prompt = PromptTemplate.from_template("{country}의 수도는 어디야?")
model = ChatOpenAI(api_key="API_KEY", temperature=0.1)
parser = StrOutputParser()
# 체인 구성 및 사용
chain = prompt | model | parser
answer = chain.invoke({"country": "대한민국"})
print(answer) # "서울입니다."
다양한 목적의 작업이 혼합되어 있을 때, 체인을 작업별로 구성하면 관리가 쉽다.
예시:
# 정확한 답변을 위한 체인
chain_fact = prompt_fact | model_fact | parser
# 창의적인 답변을 위한 체인
chain_creative = prompt_creative | model_creative | parser
OutputParser는 모델의 출력을 원하는 데이터 타입으로 변환해준다. 대표적인 Parser의 종류는 다음과 같다.
| OutputParser | 설명 | 사용 예시 |
|---|---|---|
| StrOutputParser | 문자열 그대로 반환 | 기본 챗봇 응답 |
| CommaSeparatedListOutputParser | 쉼표로 구분된 목록을 리스트로 변환 | 키워드 리스트 추출 |
| NumberedListOutputParser | 숫자 목록을 리스트로 변환 | 순서가 있는 리스트 응답 |
| JSONOutputParser | JSON 텍스트를 Python dict로 변환 | 표, 구조화 데이터 처리 |
| PydanticOutputParser | 정의한 Pydantic 클래스로 구조화 | 앱 연동, 데이터 검증 |
| DatetimeOutputParser | 날짜 텍스트를 datetime으로 변환 | 일정 관리 |
| BooleanOutputParser | 텍스트를 True/False로 변환 | 예/아니오 답변 처리 |
| RetryOutputParser | 파싱 실패 시 자동 재시도 | 오류 관리가 필요한 작업 |
PydanticOutputParser는 데이터 구조 및 타입 검증을 자동으로 처리해준다. (Pydantic-ai 라이브러리 설치 필요)
from langchain.output_parsers import PydanticOutputParser
from pydantic import BaseModel, Field
from typing import List
# 데이터 모델 정의
class CityPopulation(BaseModel):
city: str = Field(description="도시 이름")
population: int = Field(description="인구 수")
class PopulationData(BaseModel):
cities: List[CityPopulation]
# Parser 정의
parser = PydanticOutputParser(pydantic_object=PopulationData)
# 모델 출력 예시
model_output = '''
{
"cities": [
{"city": "서울", "population": 9700000},
{"city": "부산", "population": 3300000}
]
}
'''
# 파싱된 결과
parsed_data = parser.parse(model_output)
print(parsed_data.cities[0].city) # 서울
print(parsed_data.cities[0].population) # 9700000
적절한 체인과 Parser를 선택하면 효율적인 LLM 기반 프로젝트 개발이 가능하다.