1. LangChain?

sea·2025년 3월 13일
post-thumbnail

✅ LangChain 체인 구조

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)  # "서울입니다."

🔍 여러 작업(Intent)에 따른 체인 활용

다양한 목적의 작업이 혼합되어 있을 때, 체인을 작업별로 구성하면 관리가 쉽다.

예시:

# 정확한 답변을 위한 체인
chain_fact = prompt_fact | model_fact | parser

# 창의적인 답변을 위한 체인
chain_creative = prompt_creative | model_creative | parser

📌 OutputParser 종류와 활용법

OutputParser는 모델의 출력을 원하는 데이터 타입으로 변환해준다. 대표적인 Parser의 종류는 다음과 같다.

OutputParser설명사용 예시
StrOutputParser문자열 그대로 반환기본 챗봇 응답
CommaSeparatedListOutputParser쉼표로 구분된 목록을 리스트로 변환키워드 리스트 추출
NumberedListOutputParser숫자 목록을 리스트로 변환순서가 있는 리스트 응답
JSONOutputParserJSON 텍스트를 Python dict로 변환표, 구조화 데이터 처리
PydanticOutputParser정의한 Pydantic 클래스로 구조화앱 연동, 데이터 검증
DatetimeOutputParser날짜 텍스트를 datetime으로 변환일정 관리
BooleanOutputParser텍스트를 True/False로 변환예/아니오 답변 처리
RetryOutputParser파싱 실패 시 자동 재시도오류 관리가 필요한 작업

🛠️ PydanticOutputParser 사용 예시

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

✏️

  • LangChain의 체인 구조는 코드의 모듈화와 재사용성을 높인다.
  • OutputParser를 활용하면 LLM의 출력을 원하는 형태로 편리하게 관리할 수 있다.

적절한 체인과 Parser를 선택하면 효율적인 LLM 기반 프로젝트 개발이 가능하다.

profile
달려가는중

0개의 댓글