상세 컨텐츠

본문 제목

[MODEL I/O - Prompts] Prompt templates - 3

LangChain

by LYShin 2023. 7. 3. 19:30

본문

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

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

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

- 본 글에서는 Type of MessagePromptTemplate, Partial prompt templates, Composition를 다룹니다.

 

 

 

1. Type of Message Prompt Template

 

LangChainMessagePromptTemplate의 여러 가지 타입을 제공합니다. 가장 일반적으로 사용되는 템플릿은 AIMessagePromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate입니다. 이 세 가지는 각각 AIMessage, SystemMessage, HumanMessage를 생성합니다. 만약 Chat model이 임의의 역할을 가진 Chat Message를 지원하는 경우, ChatMessagePromptTemplate을 사용할 수 있으며 이를 통해 사용자는 역할 이름을 지정할 수 있습니다.

from langchain.prompts import ChatMessagePromptTemplate

prompt = "May the {subject} be with you"

chat_message_prompt = ChatMessagePromptTemplate.from_template(role="Jedi", template=prompt)
chat_message_prompt.format(subject="force")
ChatMessage(content='May the force be with you', additional_kwargs={}, role='Jedi')

 

LangChainMessagePlaceholder를 제공합니다. 이것은 메시지를변환하는 동안 전체적인 컨트롤을 할 수 있게 합니다. 이는 message prompt template에 어떤 역할을 사용할지 확신할 수 없거나, 변환하는 동안 메시지의 리스트를 추가하고 싶은 경우 유용합니다.

from langchain.prompts import MessagesPlaceholder

human_prompt = "Summarize our conversation so far in {word_count} words."
human_message_template = HumanMessagePromptTemplate.from_template(human_prompt)
chat_prompt = ChatPromptTemplate.from_messages([MessagesPlaceholder(variable_name="conversation"), human_message_template])

human_message = HumanMessage(content="What is the best way to learn programming?")
ai_message = AIMessage(content="""\
1. Choose a programming language: Decide on a programming language that you want to learn.

2. Start with the basics: Familiarize yourself with the basic programming concepts such as variables, data types and control structures.

3. Practice, practice, practice: The best way to learn programming is through hands-on experience\
""")

chat_prompt.format_prompt(conversation=[human_message, ai_message], word_count="10").to_messages()
[HumanMessage(content='What is the best way to learn programming?', additional_kwargs={}, example=False),
 AIMessage(content='1. Choose a programming language: Decide on a programming language that you want to learn.\n\n2. Start with the basics: Familiarize yourself with the basic programming concepts such as variables, data types and control structures.\n\n3. Practice, practice, practice: The best way to learn programming is through hands-on experience', additional_kwargs={}, example=False),
 HumanMessage(content='Summarize our conversation so far in 10 words.', additional_kwargs={}, example=False)]

 

위에서 구성한 프롬프트를 활용하여 chain을 만들고, Chat model에 입력해 보겠습니다.

chain = LLMChain(llm=chat_llm, prompt=chat_prompt)
chain.run({'conversation':[human_message, ai_message],'word_count':'10'})
'Best way to learn programming: choose language, basics, practice consistently.'

 

 

 

2. Partial prompt templates

 

때때로 프롬프트 템플릿을 부분적으로 사용해야 하는 경우가 발생합니다. LangChain에서는 이런 경우 사용할 수 있는 두 가지 방법을 제공합니다. 

 

2-1. Parital With Strings

 

prompt template을 부분적으로 떼어내어 사용하려는 일반적인 예시 중 하나는 변수 중 일부를 다른 변수보다 먼저 얻는 경우입니다.

예를 들어, Question과 Context라는 두 가지 변수를 요구하는 프롬프트 템플릿이 있다고 생각해 봅시다. 만약 Question 변수를 Chain의 앞에서 얻고, Context 변수를 이후에 얻는다면, 두 가지 변수를 사용할 때까지 기다리는 것이 불편할 것입니다. 대신, Question 변수를 가진 프롬프트 템플릿을 부분적으로 떼내어 사용할 수 있습니다.

 

from langchain.prompts import PromptTemplate

# 1
prompt = PromptTemplate(template="Question : {Qustion}\nContext : {Context}", input_variables=["foo", "bar"])
partial_prompt = prompt.partial(Question="What is this?")
print(partial_prompt.format(context="Context"))
Question : What is this?
Context : Context

 

 

2-2. Partial With Functions

두 번째 방법은 함수와 함께 사용하는 방법입니다. 프롬프트에 시간과 같이 어떤 변수를 항상 가져오고 싶은 경우 사용할 수 있습니다.

예를 들어, 항상 최근 날짜를 가져와야 하는 프롬프트를 가지고 있다고 생각해 봅시다. 프롬프트에서 하드코딩할 수 없고, 다른 input variable과 함께 사용하는 것은 조금 어렵습니다. 이 케이스에서는 최근 날짜를 반환하는 함수와 함께 사용하는 것이 가장 유용할 것입니다. 

먼저, 현재 날짜와 시간을 출력하는 함수를 만듭니다.

from datetime import datetime

def _get_datetime():
    now = datetime.now()
    return now.strftime("%m/%d/%Y, %H:%M:%S")
    
print(_get_datetime())
07/01/2023, 12:47:07

 

구현한 함수를 프롬프트에 사용합니다.

prompt = PromptTemplate(
    template="Tell me a {adjective} joke about the day {date}", 
    input_variables=["adjective", "date"]
)
partial_prompt = prompt.partial(date=_get_datetime)
print(partial_prompt.format(adjective="funny"))
Tell me a funny joke about the day 07/01/2023, 12:49:04

 

 

 

3. Composition

 

이번 섹션에서는 Multiple prompts를 구성하는 방법을 다룹니다. 이는 프롬프트의 일부를 재사용하는 경우 아주 유용합니다. LangChain PipelinePrompt를 사용하여 쉽게 구현할 수 있습니다. 

PilelinePrompt는 두 가지 구성요소를 갖습니다. 하나는 Final prompt이고, 다른 하나는 Pipeline prompt입니다. Final prompt는 반환되는 마지막 프롬프트입니다. Pipeline prompts는 (string name, prompt template)으로 구성된 리스트입니다. 예시를 통해 자세히 살펴보겠습니다. 예시는 (introduction, prompt), (example, prompt), (start, prompt)로 구성된 Pipeline을 사용하여 하나의 프롬프트를 만드는 과정입니다.

 

먼저, Final prompt를 먼저 구현하겠습니다. Final prompt에는 총 세 개의 프롬프트로 구성됩니다.

from langchain.prompts.pipeline import PipelinePromptTemplate
from langchain.prompts.prompt import PromptTemplate

full_template = """{introduction}

{example}

{start}"""
full_prompt = PromptTemplate.from_template(full_template)

 

다음으로 Pipeline prompt에 구성될 세 개의 프롬프트를 구현하겠습니다. 필요한 프롬프트는 introduction, example, start입니다. 세 개의 프롬프트를 만든 후, 이름과 템플릿으로 구성된 튜플로 Pipeline prompts를 구현합니다.

introduction_template = """You are impersonating {person}."""
introduction_prompt = PromptTemplate.from_template(introduction_template)


example_template = """Here's an example of an interaction: 

Q: {example_q}
A: {example_a}"""
example_prompt = PromptTemplate.from_template(example_template)


start_template = """Now, do this for real!

Q: {input}
A:"""
start_prompt = PromptTemplate.from_template(start_template)


input_prompts = [
    ("introduction", introduction_prompt),
    ("example", example_prompt),
    ("start", start_prompt)
]

 

이제, PipelinePrompt 구성에 필요한 요소를 구현했습니다. Final prompt와 pipeline prompt를 사용하여 PipelinePrompt를 구현하고, 이를 활용하여 프롬프트를 작성하겠습니다.

pipeline_prompt = PipelinePromptTemplate(final_prompt=full_prompt, pipeline_prompts=input_prompts)
final_prompt = pipeline_prompt.format(
    person = 'Elon Musk',
    example_q = "What's your favorite car?",
    example_a = "Tesla",
    input = "What's your favorite social media site?"
)
print(final_prompt)
You are impersonating Elon Musk.

Here's an example of an interaction: 

Q: What's your favorite car?
A: Tesla

Now, do this for real!

Q: What's your favorite social media site?
A:

 

마지막으로 이를 LLM에 입력해 보겠습니다.

llm = OpenAI()
llm(final_prompt)
'Twitter.'

 

관련글 더보기

댓글 영역