[MODEL I/O - Langauge Models] Chat Model How to
- 출처 : https://python.langchain.com/docs/modules/model_io/
- 이 블로그 글은 LangChain API document의 글을 기반으로 번역되었으며 이 과정에서 약간의 내용이 추가되었습니다.
- MODEL I/O는 Prompts, Language Model, Output Parser로 이루어져 있습니다.
- How-to에서는 Langchain에서 Chat Model을 다루는 여러 가지 방법에 대해 설명합니다.
- 본 글에서는 LLMChain, Prompts, Streaming에 대해 다룹니다.
1. LLMChain
Chat model의 LLMChain은 이전 LLM의 Chain과 유사합니다. 프롬프트와 모델만 준비하면 됩니다.
from langchain import LLMChain
from langchain.prompts import PromptTemplate
from langchain.prompts.chat import (
ChatPromptTemplate,
SystemMessagePromptTemplate,
HumanMessagePromptTemplate,
)
template="You are a helpful assistant that translates {input_language} to {output_language}. {text} , transalte : "
chat_prompt = PromptTemplate.from_template(template=template)
chat = ChatOpenAI()
chain = LLMChain(llm=chat, prompt = chat_prompt)
chain.run(input_language="English", output_language="French", text="I love programming.")
"J'aime la programmation."
2. Prompts
Chat model을 위한 프롬프트는 문자열 대신 메시지를 기반으로 합니다. 한 개 이상의 MessagePromptTemplate으로 ChatPromptTemplate을 만들 수 있습니다. ChatPromptTemplate의 format_prompt를 사용하여 PromptValue를 반환받을 수 있는데, 이를 문자열 또는 메시지 객체로 변환하여 사용할 수 있습니다. 변환 방식은 현재 LLM model과 Chat model 중 어떤 모델을 사용하는지에 따라 달라집니다.
이를 편하게 사용하기 위해 from_template 메소드가 존재합니다. 이 템플릿을 사용하면 다음과 같이 구현할 수 있습니다.
from langchain import PromptTemplate
from langchain.prompts.chat import (
ChatPromptTemplate,
SystemMessagePromptTemplate,
HumanMessagePromptTemplate,
)
template="You are a helpful assistant that translates {input_language} to {output_language}."
system_message_prompt = SystemMessagePromptTemplate.from_template(template)
human_template="{text}"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)
chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt])
chat(chat_prompt.format_prompt(input_language="English", output_language="French", text="I love programming.").to_messages())
AIMessage(content="J'adore la programmation.", additional_kwargs={}, example=False)
만약, MessagePromptTemplate을 바로 구현하고 싶다면, 다음과 같이 구현하면 됩니다.
prompt=PromptTemplate(
template="You are a helpful assistant that translates {input_language} to {output_language}.",
input_variables=["input_language", "output_language"],
)
system_message_prompt = SystemMessagePromptTemplate(prompt=prompt)
system_message_prompt
SystemMessagePromptTemplate(prompt=PromptTemplate(input_variables=['input_language', 'output_language'], output_parser=None, partial_variables={}, template='You are a helpful assistant that translates {input_language} to {output_language}.', template_format='f-string', validate_template=True), additional_kwargs={})
3. Streaming
일부 Chat model은 streaming response를 제공합니다. 이를 통해 전체 응답을 기다리는 대신 한 글자 씩 바로 확인할 수 있습니다. 만약 App을 사용하는 유저에게 응답의 생성이 되고 있는 과정을 보여주고 싶을 때 유용합니다.
from langchain.chat_models import ChatOpenAI
from langchain.schema import (
HumanMessage,
)
from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
chat = ChatOpenAI(streaming=True, callbacks=[StreamingStdOutCallbackHandler()], temperature=0)
resp = chat([HumanMessage(content="Write me a song about snow world.")])
Verse 1:
In the land of snow and ice
Where the world is pure and nice
The snowflakes fall so gracefully
And the mountains stand so majestically
Chorus:
Welcome to the snow world
Where the snowflakes swirl and twirl
The beauty of this place is surreal
A winter wonderland that's so ideal
#... 이후 생략