LangChain

[MODEL I/O - Prompts] Prompt Templates Base

LYShin 2023. 6. 27. 19:30

- 출처 : https://python.langchain.com/docs/modules/model_io/

- 이 블로그 글은 LangChain API document의 글을 기반으로 번역되었으며 이 과정에서 약간의 내용이 추가되었습니다.

- MODEL I/O는 Prompts, Language Model, Output Parser로 이루어져 있습니다.

- 본 글에서는 Prompt Templates에 대한 간략한 예시와 설명이 포함되어 있습니다.

 

 

 

Prompt

Langchain의 개발자는 프롬프트가 새로운 프로그래밍 방법이라고 소개합니다. 프롬프트는 모델에 입력을 위해 사용됩니다. 이 입력에는 다양한 Component를 포함하고 있습니다. LangChain은 프롬프트를 쉽게 만들 수 있도록 다양한 클래스와 함수를 제공하고 있습니다.

 

 

 

1. Prompt Templates

BERT, GPT와 같은 Language Model은 text를 입력으로 받습니다. 이 입력으로 주어진 text를 프롬프트라고 일컫습니다. 보통 이는 단순히 하드코딩된 문자열이라기보다는 Template, example, user input과 같은 다양한 text의 조합을 의미합니다. 

 

Prompt Template은 프롬프트를 생성하는데 재생가능한 방법을 의미합니다. 구체적으로 설명하자면, 사용자로부터 일련의 매개변수(입력)을 받아 특정한 프롬프트를 만드는 일종의 text string입니다.

 

Prompt Template은 3가지를 포함할 수 있습니다. 첫 번째는 언어모델에 대한 지시, 두 번째는 언어모델이 더 나은 응답을 생성할 수 있도록 도와주는 여러 가지 예시, 마지막으로 세 번째는 언어모델에 대한 질문입니다.

 

아래 간단한 예시를 보여드리겠습니다.

 

from langchain import PromptTemplate

template = """
You are a naming consultant for new companies.
What is a good name for a company that makes {product}?
"""

prompt = PromptTemplate.from_template(template)
print(prompt.format(product="colorful socks"))
You are a naming consultant for new companies.
What is a good name for a company that makes colorful socks?

 

예시를 살펴보면, Prompt Template에는 언어모델에 대한 지시와 언어모델에 대한 질문이 포함되어 있습니다. 유저는 간단히 `product`에 대한 정보만 입력하면, 위와 같은 문장을 언어 모델에 입력으로 사용할 수 있게 됩니다.

 

 

 

2. Create a prompt template

PromptTemplate 클래스를 사용하면 하드코딩된 프롬프트를 사용할 수 있습니다. PromptTemplate은 어떤 수의 입력 변수를 받을 수 있고, 그것을 프롬프트로 변환해줍니다.

 

간단한 예시를 통해 설명하겠습니다.

 

 

from langchain import PromptTemplate
no_input_prompt = PromptTemplate(input_variables=[], template='Tell me a joke')
print(no_input_prompt.format())
Tell me a joke

먼저, 입력 변수 없이 템플릿만 사용하여 프롬프트를 만드는 방법입니다. 이 경우 템플릿이 곧 프롬프트가 됩니다.

 

 

one_input_prompt = PromptTemplate(input_variables=['adjective'], template = 'Tell me a {adjective} joke')
print(one_input_prompt.format(adjective = 'funny'))
Tell me a funny joke

두 번째로, 템플릿과 하나의 입력변수를 사용하여 프롬프트를 만드는 방법입니다. 이제 유저는 단지 `adjective`만 입력하면 위와 같은 프롬프트를 사용할 수 있게 됩니다.

 

 

multiple_input_prompt = PromptTemplate(input_variables=['adjective','content'], template = 'Tell me a {adjective} joke about {content}')
print(multiple_input_prompt.format(adjective = 'funny', content = 'chickens'))
Tell me a funny joke about chickens

마지막으로 템플릿과 여러 입력변수를 사용하여 프롬프트를 만드는 방법입니다. 예시에서는 2개의 입력변수만을 사용했지만, 실제로 더 많은 입력변수를 사용할 수 있습니다.

 

정리하자면, PromptTemplate은 이미 정해놓은 문자열과 다양한 입력변수를 통해 프롬프트를 제작하는 클래스입니다.

 

 

 

3. Chat prompt template

PromptTemplate은 LM 뿐만 아니라 Chat model에 대해서도 사용할 수 있습니다. Chat model은 메시지의 리스트를 입력으로 받고, 이 리스트를 보통 프롬프트라고 합니다. 이 메세지의 리스트는 어떤 role과 연관되어 있다는 점에서 LM에 사용되는 raw string과는 다릅니다. 예를 들어, OpenAI의 Chat Completion API에서 메시지는 모두 AI, human, system role과 연관이 있습니다. 그러므로 PromptTemplate 대신 chat model에 연관된 prompt template을 사용하는 것이 좋습니다. 아래 보이는 SystemMessagePromptTemplate, HumanMessagePromptTemplate입니다.

from langchain.prompts import (
    ChatPromptTemplate,
    PromptTemplate,
    SystemMessagePromptTemplate,
    HumanMessagePromptTemplate,
)

 

 

역할과 관련된 메시지를 만들고 싶다면, MessagePromptTemplate을 사용할 수 있습니다. 템플릿에는 from_template 메서드가 존재하며, 이를 이용하면 쉽게 프롬프트를 작성할 수 있습니다.

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)

 

 

이보다 더 직접적으로 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_2 = SystemMessagePromptTemplate(prompt=prompt)

print(system_message_prompt == system_message_prompt_2)
True

 

 

하나 이상의 MessagePromptTemplate을 결합해 ChatPromptTemplate을 만들 수 있습니다. 

chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt])

 

 

ChatPrompteTemplateformat_prompt를 활용하여 PromptValue를 반환받을 수 있으며, PromptValue는 유저가 LLM을 사용할지, Chat model을 사용할지에 따라 string  혹은 Message 객체로 변환될 수 있습니다.

string_prompt = chat_prompt.format_prompt(input_language="English", output_language="French", text="I love programming.").to_string()
list_of_message = chat_prompt.format_prompt(input_language="English", output_language="French", text="I love programming.").to_messages()

print('string :\n', string_prompt, '\n')
print('Message :\n',list_of_message)
string :
System: You are a helpful assistant that translates English to French.
Human: I love programming. 

Message :
[SystemMessage(content='You are a helpful assistant that translates English to French.', additional_kwargs={}), HumanMessage(content='I love programming.', additional_kwargs={}, example=False)]