Hoonsi

랭체인(LangChain) - 모듈(Modules) > 모델 I/O (Model I/O) > 프롬프트(Prompts) > 프롬프트 템플릿(Prompt templates) 본문

기획, 개발, 마케팅, AI/랭체인(LangChain)

랭체인(LangChain) - 모듈(Modules) > 모델 I/O (Model I/O) > 프롬프트(Prompts) > 프롬프트 템플릿(Prompt templates)

훈시스 2023. 7. 20. 11:06

언어 모델은 텍스트를 입력으로 받는데, 이러한 텍스트를 일반적으로 프롬프트라고 합니다. 일반적으로 이것은 단순히 하드코딩된 문자열이 아니라 템플릿, 몇 가지 예제 및 사용자 입력의 조합입니다. LangChain은 프롬프트를 쉽게 구성하고 작업할 수 있도록 여러 클래스와 함수를 제공합니다.

 

#프롬프트 템플릿(prompt template)이란 무엇인가요?


프롬프트 템플릿은 프롬프트를 생성하는 재현 가능한 방법을 말합니다. 여기에는 최종 사용자로부터 일련의 매개변수를 받아 프롬프트를 생성할 수 있는 텍스트 문자열("템플릿")이 포함되어 있습니다.

프롬프트 템플릿에는 다음을 포함할 수 있습니다:

  • 언어 모델에 대한 지침
  • 언어 모델이 더 나은 응답을 생성하는 데 도움이 되는 몇 가지 샷 예제 세트,
  • 언어 모델에 대한 질문.

다음은 가장 간단한 예입니다:

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)
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?

 

#프롬프트 템플릿 만들기


PromptTemplate 클래스를 사용하여 간단한 하드코딩 프롬프트를 만들 수 있습니다. 프롬프트 템플릿은 입력 변수를 얼마든지 사용할 수 있으며 프롬프트를 생성하도록 서식을 지정할 수 있습니다.

from langchain import PromptTemplate

# An example prompt with no input variables
no_input_prompt = PromptTemplate(input_variables=[], template="Tell me a joke.")
no_input_prompt.format()
# -> "Tell me a joke."

# An example prompt with one input variable
one_input_prompt = PromptTemplate(input_variables=["adjective"], template="Tell me a {adjective} joke.")
one_input_prompt.format(adjective="funny")
# -> "Tell me a funny joke."

# An example prompt with multiple input variables
multiple_input_prompt = PromptTemplate(
    input_variables=["adjective", "content"], 
    template="Tell me a {adjective} joke about {content}."
)
multiple_input_prompt.format(adjective="funny", content="chickens")
# -> "Tell me a funny joke about chickens."

'input_variables'를 수동으로 지정하고 싶지 않다면, 'from_template' 클래스 메서드를 사용하여 '프롬프트 템플릿(PromptTemplate)'를 생성할 수도 있습니다. 'langchain'은 전달된 '템플릿(template')을 기반으로 'input_variables'가 자동으로 추론합니다.

template = "Tell me a {adjective} joke about {content}."

prompt_template = PromptTemplate.from_template(template)
prompt_template.input_variables
# -> ['adjective', 'content']
prompt_template.format(adjective="funny", content="chickens")
# -> Tell me a funny joke about chickens.

원하는 방식으로 프롬프트의 형식을 지정하는 사용자 지정 프롬프트 템플릿을 만들 수 있습니다. 자세한 내용은 사용자 지정 프롬프트 템플릿을 참조하세요.

 

#채팅 프롬프트 템플릿(Chat prompt template)


채팅 모델은 채팅 메시지 목록을 입력으로 받습니다. 이 목록을 흔히 프롬프트라고 합니다. 이러한 채팅 메시지는 모든 메시지가 역할과 연관되어 있다는 점에서 원시 문자열(LLM 모델에 전달되는)과 다릅니다.

예를 들어 OpenAI 채팅 완료 API에서 채팅 메시지는 AI, 사람 또는 시스템 역할에 연결될 수 있습니다. 이 모델은 시스템 채팅 메시지의 지시를 더 밀접하게 따르도록 되어 있습니다.

LangChain은 프롬프트를 쉽게 구성하고 작업할 수 있도록 몇 가지 프롬프트 템플릿을 제공합니다. 기본 채팅 모델의 잠재력을 최대한 활용하기 위해 채팅 모델을 쿼리할 때 PromptTemplate 대신 이러한 채팅 관련 프롬프트 템플릿을 사용하는 것이 좋습니다.

from langchain.prompts import (
    ChatPromptTemplate,
    PromptTemplate,
    SystemMessagePromptTemplate,
    AIMessagePromptTemplate,
    HumanMessagePromptTemplate,
)
from langchain.schema import (
    AIMessage,
    HumanMessage,
    SystemMessage
)

역할과 연결된 메시지 템플릿을 만들려면 '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'을 좀 더 직접적으로 구성하고 싶다면, 예를 들어 외부에서 PromptTemplate을 생성한 다음 이를 전달할 수 있습니다:

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)

assert system_message_prompt == system_message_prompt_2

그런 다음 하나 이상의 'MessagePromptTemplates'으로부터 "ChatPromptTemplate"을 빌드할 수 있습니다. 'ChatPromptTemplate'의 'format_prompt'를 사용하면 형식이 지정된 값을 LLM 또는 채팅 모델에 입력으로 사용할지 여부에 따라 문자열 또는 메시지 개체로 변환할 수 있는 'PromptValue'를 반환합니다.

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

# get a chat completion from the formatted messages
chat_prompt.format_prompt(input_language="English", output_language="French", text="I love programming.").to_messages()
    [SystemMessage(content='You are a helpful assistant that translates English to French.', additional_kwargs={}),
     HumanMessage(content='I love programming.', additional_kwargs={})]