728x90

2024년 05월 23일 기준

ChatPromptTemplate이란?

  • Chat model 들을 위한 Prompt Template
  • Prompt Template을 사용하면 LLM에게 전달할때 system message, human message, ai message를 구분해서 제공할 수 있다.
  • 이러한 구분은 LLM에 chat history를 제공할때 편리하고 다양한 변수들을 추가할 수 있어서 편리하다.
  • 재사용성이 좋아서 반복적인 작업을 할 떄 편리하다.

예시 코드

from langchain_core.prompts import ChatPromptTemplate

template = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful AI bot. Your name is {name}."),
    ("human", "Hello, how are you doing?"),
    ("ai", "I'm doing well, thanks!"),
    ("human", "{user_input}"),
])

prompt_value = template.invoke(
    {
        "name": "Bob",
        "user_input": "What is your name?"
    }
)

위 Prompt의 결과는 아래와 같다

Output:
ChatPromptValue(
   messages=[
       SystemMessage(content='You are a helpful AI bot. Your name is Bob.'),
       HumanMessage(content='Hello, how are you doing?'),
       AIMessage(content="I'm doing well, thanks!"),
       HumanMessage(content='What is your name?')
   ]
)

Messages Placeholder

  • "place holder"라는 키를 사용해서 Prompt 중간에 내용을 추가할 수 있다.
  • MessagesPlaceholder라는 class를 사용해도 되고 튜플형식으로 전달해도 된다.
  • 아래의 경우 invoke 시에 conversation이라는 키로 Prompt Template에 대화 내용을 전달해서 LLM의 답변을 받는다
  • template 아래에 ("human", "{input}") 이런식으로 사용자의 input도 입력받을 수 있다.
template = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful AI bot."),
    ("placeholder", "{conversation}")
    # 이런 코드로 대체 가능 MessagesPlaceholder(variable_name="conversation", optional=True)
])

prompt_value = template.invoke(
    {
        "conversation": [
            ("human", "Hi!"),
            ("ai", "How can I assist you today?"),
            ("human", "Can you make me an ice cream sundae?"),
            ("ai", "No.")
        ]
    }
)

Prompt Template의 형태

Output:
ChatPromptValue(
   messages=[
       SystemMessage(content='You are a helpful AI bot.'),
       HumanMessage(content='Hi!'),
       AIMessage(content='How can I assist you today?'),
       HumanMessage(content='Can you make me an ice cream sundae?'),
       AIMessage(content='No.'),
   ]
)

Reference

https://api.python.langchain.com/en/latest/prompts/langchain_core.prompts.chat.ChatPromptTemplate.html

+ Recent posts