Adventure Time - Finn 3
본문 바로가기
AI/LLM

LangChain OutputParser

by hyun9_9 2026. 5. 19.

Output Parser 란

LLM(대형 언어 모델))에서 생성된 출력을 처리하고 원하는 형식으로 변환하는데 사용되는 유틸리티이다.

이를 통해 생성하는 텍스트를 구조화된데이터로 변환하거나 특정 규칙에 따라 데이터를 추출할 수 있다.

1. 출력 구조화

모델의 텍스트 응답을 파싱하여 JSON, 딕셔너리, 목록과 같은 프로그래밍에서 사용 가능한 구조화된 데이터로 변환 한다.

2. 출력 검증

모델이 예상치 못한 출력을 반환할경우 적절한 에러 메시지를 제공하거나 기본값을 반환하도록 처리할 수 있다.

3. 출력 표준화

언어 모델의 출력이 항상 일관된 형식으로 제공되도록 보장한다.

 

BaseOuputParser

커스텀 OutputParser 를 정의해 사용

from langchain_core.output_parsers.base import BaseOutputParser

# "aaa,bbb,ccc,ddd" -> ['aaa','bbb','ccc','ddd]로 변환하는 OutputParser
class CommaOutputParser(BaseOutputParser):
    # parse() 메소드를 반드시 구현해야 한다.
    #   매개변수: 입력텍스트
    #   리턴: 원하는 형태로 리턴
    def parse(self,text):
        items = text.strip().split(",")
        return list(map(str.strip,items))
        
p = CommaOutputParser()
p.parse(" Hello, how, are, you")
# ['Hello', 'how', 'are', 'you']


#output parser 적용

template = ChatPromptTemplate.from_messages([
    ('system',"""
        You are a list generating machine.
        Everything you are asked will be answered 
        with a comma separated list of max {max_items} in lowercase.
        Do NOT reply with anything else.
    """),
    ('human',"{question}"),
])

prompt = template.format_messages(
    max_items=10,
    question="What are the colors?",
)
result = chat.invoke(prompt)
p = CommaOutputParser()
p.parse(result.content)

'AI > LLM' 카테고리의 다른 글

LangChain - streaming = 과 callbacks  (0) 2026.05.25
LangChain - Chaining Chains 사용해보기  (0) 2026.05.24
LangChain - LCEL  (0) 2026.05.23
LangChain 시작  (0) 2026.05.15