- 출처 : https://python.langchain.com/docs/modules/model_io/
- 이 블로그 글은 LangChain API document의 글을 기반으로 번역되었으며 이 과정에서 약간의 내용이 추가되었습니다.
- MODEL I/O는 Prompts, Language Model, Output Parser로 이루어져 있습니다.
- 본 글에서는 Few shot examples for chat models, Format template output, Template formats를 다룹니다.
이번 세션에서는 Chat model에서 Few shot examples을 어떻게 사용해야 하는지에 대해 다룹니다. 아직까지 많은 연구자로부터 Few shot prompt 방식에 대한 논의가 진행 중이며, 어떤 방식이 최선의 방식인지에 대한 어떤 단서는 없는 것 같습니다. 이에 따라 LangChain에서도 어떤 특정한 추상화를 확정하고 있지 않고, 기존에 존재하는 추상화를 사용하고 있습니다.
Chat model에서 Few shot examples을 사용하는 첫 번째 방법은 Human/Ai message를 번갈아가면서 사용하여 예시를 만드는 것입니다. 아래 예시를 보겠습니다.
from langchain.chat_models import ChatOpenAI
from langchain import PromptTemplate, LLMChain
from langchain.prompts.chat import (
ChatPromptTemplate,
SystemMessagePromptTemplate,
AIMessagePromptTemplate,
HumanMessagePromptTemplate,
)
from langchain.schema import AIMessage, HumanMessage, SystemMessage
chat = ChatOpenAI(temperature=0)
template = "You are a helpful assistant that translates english to pirate."
system_message_prompt = SystemMessagePromptTemplate.from_template(template)
example_human = HumanMessagePromptTemplate.from_template("Hi")
example_ai = AIMessagePromptTemplate.from_template("Argh me mateys")
human_template = "{text}"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)
chat_prompt = ChatPromptTemplate.from_messages(
[system_message_prompt, example_human, example_ai, human_message_prompt]
)
chat_prompt.messages
[SystemMessagePromptTemplate(prompt=PromptTemplate(input_variables=[], output_parser=None, partial_variables={}, template='You are a helpful assistant that translates english to pirate.', template_format='f-string', validate_template=True), additional_kwargs={}),
HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=[], output_parser=None, partial_variables={}, template='Hi', template_format='f-string', validate_template=True), additional_kwargs={}),
AIMessagePromptTemplate(prompt=PromptTemplate(input_variables=[], output_parser=None, partial_variables={}, template='Argh me mateys', template_format='f-string', validate_template=True), additional_kwargs={}),
HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=['text'], output_parser=None, partial_variables={}, template='{text}', template_format='f-string', validate_template=True), additional_kwargs={})]
위와 같은 방식으로 Human message와 AI message를 활용하여 예시를 만드는 방법을 통해 Few shot examples을 사용할 수 있습니다. 위 프롬프트를 활용하여 번역을 수행해보겠습니다.
chain = LLMChain(llm=chat, prompt=chat_prompt)
chain.run("I love programming.")
"I be lovin' the art of code plunderin'."
OpenAI의 API를 사용하는 경우는 다른 방법을 이용할 수 있습니다. OpenAI는 name parameter를 옵션으로 제공하며 Few shot prompting을 수행할 때 System Message와 함께 사용하는 것이 권장됩니다. 예시를 함께 보겠습니다.
template = "You are a helpful assistant that translates english to pirate."
system_message_prompt = SystemMessagePromptTemplate.from_template(template)
example_human = SystemMessagePromptTemplate.from_template(
"Hi", additional_kwargs={"name": "example_user"}
)
example_ai = SystemMessagePromptTemplate.from_template(
"Argh me mateys", additional_kwargs={"name": "example_assistant"}
)
human_template = "{text}"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)
chat_prompt = ChatPromptTemplate.from_messages(
[system_message_prompt, example_human, example_ai, human_message_prompt]
)
chat_prompt.messages
[SystemMessagePromptTemplate(prompt=PromptTemplate(input_variables=[], output_parser=None, partial_variables={}, template='You are a helpful assistant that translates english to pirate.', template_format='f-string', validate_template=True), additional_kwargs={}),
SystemMessagePromptTemplate(prompt=PromptTemplate(input_variables=[], output_parser=None, partial_variables={}, template='Hi', template_format='f-string', validate_template=True), additional_kwargs={'name': 'example_user'}),
SystemMessagePromptTemplate(prompt=PromptTemplate(input_variables=[], output_parser=None, partial_variables={}, template='Argh me mateys', template_format='f-string', validate_template=True), additional_kwargs={'name': 'example_assistant'}),
HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=['text'], output_parser=None, partial_variables={}, template='{text}', template_format='f-string', validate_template=True), additional_kwargs={})]
위와 같은 방식으로 System Message만 활용하여 예시를 만드는 방법을 통해 Few shot examples을 사용할 수 있습니다. 위 프롬프트를 활용하여 번역을 수행해 보겠습니다.
chain = LLMChain(llm=chat, prompt=chat_prompt)
chain.run("I love programming.")
"I be lovin' the art of code plunderin'."
템플릿은 총 3가지의 객체 형태로 변환이 가능합니다. 첫 번째는 String입니다. 이는 일반적인 LLM에 사용됩니다. 두 번째는 Message가 담긴 List입니다. 이는 보통 Chat model에 사용됩니다. 마지막으로 세 번째는 ChatPromptValue입니다. 이는 프롬프트를 string 형태 혹은 Chat message 형태로 변환이 가능한 객체입니다.
예시로 이전 세션에서 구현한 chat_prompt를 활용하여 ChatPromptValue에 대해 다뤄보겠습니다.
CPT = chat_prompt.format_prompt(input_language="English", output_language="French", text="I love programming.")
CPT
ChatPromptValue(messages=[SystemMessage(content='You are a helpful assistant that translates english to pirate.', additional_kwargs={}), HumanMessage(content='Hi', additional_kwargs={}, example=False), AIMessage(content='Argh me mateys', additional_kwargs={}, example=False), HumanMessage(content='I love programming.', additional_kwargs={}, example=False)])
위와 같이 템플릿은 ChatPromptValue 형태로 변환이 가능합니다. 이 객체는 string과 message 객체로 변환 가능합니다. to_string() 메소드를 사용하면 프롬프트를 String으로 변환합니다.
output = chat_prompt.format(text="I love programming.")
output_2 = CPT.to_string()
if output == output_2:
print('output과 output_2는 같습니다. 아래는 output의 내용입니다. \n')
print(output)
output과 output_2는 같습니다. 아래는 output의 내용입니다.
System: You are a helpful assistant that translates english to pirate.
System: Hi
System: Argh me mateys
Human: I love programming.
반면 to_messages() 메소드를 사용하면 프롬프트를 Message 형태로 변환합니다.
output = chat_prompt.format_messages(text="I love programming.")
output_2 = CPT.to_messages()
if output == output_2:
print('output과 output_2는 같습니다. 아래는 output의 내용입니다. \n')
print(output)
output과 output_2는 같습니다. 아래는 output의 내용입니다.
[SystemMessage(content='You are a helpful assistant that translates english to pirate.', additional_kwargs={}), SystemMessage(content='Hi', additional_kwargs={'name': 'example_user'}), SystemMessage(content='Argh me mateys', additional_kwargs={'name': 'example_assistant'}), HumanMessage(content='I love programming.', additional_kwargs={}, example=False)]
디폴트로 PromptTemplate은 Python의 f-string을 취합니다. 하지만 template_format을 인자를 사용하면 다른 template format을 명시할 수 있습니다. LangChain 현재 Jinja2와 f-string을 지원합니다.
jinja2_template = "Tell me a {{ adjective }} joke about {{ content }}"
prompt_template = PromptTemplate.from_template(template=jinja2_template, template_format="jinja2")
print(prompt_template.format(adjective="funny", content="chickens"),'\n')
print(prompt_template.template_format)
Tell me a funny joke about chickens
jinja2
[MODEL I/O - Prompts] Example selectors (0) | 2023.07.04 |
---|---|
[MODEL I/O - Prompts] Prompt templates - 3 (0) | 2023.07.03 |
[MODEL I/O - Prompts] Prompt templates - 1 (0) | 2023.06.29 |
[MODEL I/O - Prompts] Prompt Templates Base (0) | 2023.06.27 |
Quick start (0) | 2023.06.23 |
댓글 영역