AI/LLM

[LangChain] PromptTemplate & ChatPromptTemplate

dragonhyeon 2025. 10. 7. 23:11
728x90
반응형

PromptTemplate

  • 단일 문자열 템플릿 기반
from langchain.prompts import PromptTemplate


prompt = PromptTemplate(
    input_variables=[
        'sports',
        'player'
    ],
    template="How does {player} think of {sports}?",
)

formatted = prompt.format(
    sports='soccer',
    player='sonny',
)
print(formatted)
# How does sonny think of soccer?

result = llm.invoke(input=prompt.format(
    sports='soccer',
    player='sonny',
))
print(result)
# content='Sonny thinks of soccer as the greatest sport in the world. He is passionate about ...
  • input_variables 를 지정하지 않는 방법도 존재. from_template 사용
from langchain.prompts import PromptTemplate


TEMPLATE = 'How does {player} think of {sports}?'

input_dict = {
    'sports': 'soccer',
    'player': 'sonny',
}

prompt = PromptTemplate.from_template(template=TEMPLATE)

print(prompt.format(sports='soccer', player='sonny'))
# How does sonny think of soccer?

print(prompt.invoke(input=input_dict))
# text='How does sonny think of soccer?'

print(llm.invoke(input=prompt.format(sports='soccer', player='sonny')))
# content='Sonny thinks of soccer as a passion and a way of life. He sees ...

print(llm.invoke(input=prompt.invoke(input=input_dict)))
# content="Sonny thinks of soccer as the greatest sport in the world ...

chain = RunnableSequence(prompt, llm, StrOutputParser())
print(chain.invoke(input=input_dict))
# Sonny thinks of soccer as the greatest sport in the world. He is pa ...

chain = prompt | llm | StrOutputParser()
print(chain.invoke(input=input_dict))
# Sonny thinks of soccer as the greatest sport in the world. He is pa ...

ChatPromptTemplate

  • 여러 메시지 (시스템/사용자/AI) 를 모아 대화 프롬프트를 만드는 게 목적
  • 생성자를 직접 호출할 수 없고 반드시 클래스 메서드 (from_template or from_messages) 를 통해 인스턴스를 만들어야 함
    • from_template: PromptTemplate 처럼 단일 문자열을 템플릿으로 쓰려는 경우 (사용자 입력 한 줄이 필요한 경우)
    • from_messages: 여러 메시지 (시스템/사용자/어시스턴트) 를 미리 정의하는 방식
      • 역할별 메시지를 만드는 템플릿 클래스
        • SystemMessagePromptTemplate
        • HumanMessagePromptTemplate
        • AIMessagePromptTemplate
      • 최신 LangChain 에서는 보통 ChatPromptTemplate.from_messages([("system", "..."), ("human", "...")]) 이렇게 더 간단한 문법을 권장
        • 내부적으로는 여전히 SystemMessagePromptTemplate 같은 클래스 사용
  • 역할:
    • OpenAI API: system / user / assistant / tool
    • LangChain: system / human / ai / tool
      • tool 은 직접적으로 ChatPromptTemplate 작성시에 사용되지는 않음
    • OpenAI API 와 LangChain 에서 사용하는 역할의 이름이 다르지만 같은 역할을 수행하며 LangChain 에서 alias 를 제공하는 것 뿐
      • human → user
      • ai → assistant
prompt = ChatPromptTemplate.from_template(template=TEMPLATE)
print(prompt.format(sports='soccer', player='sonny'))
# Human: How does sonny think of soccer?

prompt = ChatPromptTemplate.from_messages(messages=[
    ("I like {sports}"),
    ("I like {player} the most"),
])
print(prompt.format(sports='soccer', player='sonny'))
# Human: I like soccer
# Human: I like sonny the most

prompt = ChatPromptTemplate.from_messages(messages=[
    SystemMessagePromptTemplate.from_template("You are {player}"),
    HumanMessagePromptTemplate.from_template("How much do you like {sports}?"),
])
print(prompt.format(sports='soccer', player='sonny'))
# System: You are sonny
# Human: How much do you like soccer?

prompt = ChatPromptTemplate.from_messages(messages=[
    ("system", "You are {player}"),
    ("human", "How much do you like {sports}?"),
])
print(prompt.format(sports='soccer', player='sonny'))
# System: You are sonny
# Human: How much do you like soccer?

chain = prompt | llm
print(chain.invoke(input=input_dict))
# content="I don't have personal feelings, but I can provide a lot of information about ...

포맷팅 메서드

  • .format:
    • plain string (그냥 문자열) 반환
  • .format_prompt:
    • PromptValue 객체 반환
      • .to_messages() 으로 변환 가능
      • .to_string() 으로 변환 가능
  • .format_messages:
    • ChatPromptTemplate 전용
    • 메시지 리스트 (HumanMessage, SystemMessage, AIMessage 등) 를 반환
prompt = ChatPromptTemplate.from_template(template=TEMPLATE)

formatted = prompt.format(sports='soccer', player='sonny')
print(formatted)
# Human: How does sonny think of soccer?

formatted = prompt.format_prompt(sports='soccer', player='sonny')
print(formatted)
# messages=[HumanMessage(content='How does sonny think of soccer?', additional_kwargs={}, response_metadata={})]

formatted = prompt.format_messages(sports='soccer', player='sonny')
print(formatted)
# [HumanMessage(content='How does sonny think of soccer?', additional_kwargs={}, response_metadata={})]
.format 사용시 해당 string 내용 자체가 나오고 invoke 사용시 dict 로 입력을 전달하며 결과는 text=, content= 과 같은 형태로 나옵니다.
728x90
반응형

'AI > LLM' 카테고리의 다른 글

[LangChain] LCEL  (2) 2025.10.10
[LangChain] 개요  (2) 2025.10.02
Prompt Engineering  (2) 2025.09.24
OpenAI API  (5) 2025.08.19
LangChain  (3) 2025.05.08