[LangChain] Output Parser

pysun·2024년 11월 5일

LangChain

목록 보기
4/13

Output Parser

  • llm의 응답을 특정 형태로 변형할 때 사용
  • langchain의 BaseOutputParser 클래스를 상속 받아 OutputParser를 커스터마이징 할 수 있음
from langchain.schema import BaseOutputParser

# 콤마로 이뤄진 string을 input으로 받으면 콤마 단위로 나누는 OutputParser
class CommaOutputParser(BaseOutputParser)
	def parse(self, text):
    	items = text.stip().split(',')
        return list(map(str.strip, items))
        
parser = CommaOutputParser()
parser.parse('안녕, 내이름은, pysun이야')
['안녕', '내이름은', 'pysun이야']

OutputParser를 활용해서 chain 만들기

# chain: 위 내용을 한번에 수행할 수 있음
# 모든 요소를 합쳐서 하나하나 result를 반환할 때까지 수행

### invoke를 수행 시 동작원리 ###
# 1. 딕셔너리 값이 template에 전달 된 후 template 수행
# 2. template output(PromptValue)이 Chat model input(PromptValue)에 전달
# 3. Chat model의 output(ChatMessage)이 커스텀한 파서의 input으로 들어감
# 4. 파서까지 통과한 결과 출력

from langchain_openai import ChatOpenAI
from langchain.prompts import ChatPromptTemplate

chat = ChatOpenAI(temperature=0.1)

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}')
])

chain = template | chat | CommaOutputParser()

chain.invoke({
		'max_items':10,
        'question':'what are the pokemons?'
})
['bulbasaur',
 'charmander',
 'squirtle',
 'pikachu',
 'jigglypuff',
 'eevee',
 'snorlax',
 'bulbasaur',
 'charmander',
 'squirtle']
profile
배움의 흔적이 성장으로 이어지는 공간

0개의 댓글