Prompt Template

LLM 모델에게 명확한 지시를 내리기 위해 사용하는 템플릿이다.
사용자의 입력(input)과 매개변수(Parameters)는 프롬프트 문자열을 만드는데 사용되며, 이를 통해 일관된 언어 기반 출력을 생성하도록 유도할 수 있다.

LangChain 라이브러리
langchain_core.prompts 모듈에
PromptTemplate 클래스가 포함되어 있다.

# String Prompt Templates
from langchain_core.prompts import PromptTemplate

# ChatPrompt Templates
from langchain_core.prompts import ChatPromptTemplate

# MessagesPlaceholder Prompt Templates
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.messages import HumanMessage

String(문자열) Prompt Templates

invoke()

from langchain_core.prompts import PromptTemplate

# from_template 메소드를 이용해 PromptTemplate 객체 생성
prompt_template = PromptTemplate.from_template("가수 {singer}에 대해 소개해주세요.")

prompt_template.invoke({"singer": "fiftyfifty"})

format.messages()

from langchain_core.prompts import PromptTemplate

# template 정의
prompt_text = "가수 {singer}에 대해 30글자 이내로 소개해주세요."

# from_template 메소드를 이용해 PromptTemplate 객체 생성
prompt_template = PromptTemplate.from_template(prompt_text)

# prompt 생성
prompt_string = prompt_template.format(singer = "피프티피프티")
prompt_string

ChatPrompt Templates

invoke()

from langchain_core.prompts import ChatPromptTemplate

prompt_template = ChatPromptTemplate([
		("system", "당신은 위키백과와 나무위키를 주요 정보로 인물을 소개하는 리포터입니다."),
		("user", "가수 {singer}에 대해 소개해주세요.")
		
prompt_template.invoke({"singer": "fiftyfifty"})

format.messages()

from langchain_core.prompts import ChatPromptTemplate

# template 정의
template = [
    ("system", "당신은 위키백과와 나무위키를 주요 정보로 인물을 소개하는 리포터입니다."),
    ("user", "가수 {singer}에 대해 소개해주세요.")
]

prompt_template = ChatPromptTemplate(template)

# 메시지 리스트 생성
prompt_chat = prompt_template.format_messages(singer = "피프티피프티")
prompt_chat

MessagesPlaceholder

invoke()

from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.messages import HumanMessage

prompt_template = ChatPromptTemplate([
		("system", "당신은 위키백과와 나무위키를 주요 정보로 인물을 소개하는 리포터입니다."),
		MessagesPlaceholder("singer")
])

prompt_template.invoke({"singer": [HumanMessage(content = "피프티피프티")]})

format.messages()

from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.messages import HumanMessage

prompt_template = ChatPromptTemplate([
    ("system", "당신은 위키백과와 나무위키를 주요 정보로 인물을 소개하는 리포터입니다."),
    MessagesPlaceholder("singer")
])

# 메시지 객체의 리스트로 전달해야 함
prompt_string = prompt_template.format_messages(
    singer=[HumanMessage(content="피프티피프티")]
)

prompt_string

PromptValue란 프롬프트 템플릿이 실제로 생성한 완성된 프롬프트 정보를 담고 있는 객체이며, Message 리스트 SystemMessage, HumanMessage, AIMessage 를 포함한다.

SystemMessage: 시스템의 기능을 설명
HumanMessage: 사용자의 질문
AIMessage: AI 모델 응답

profile
IT 스터디 기록장

0개의 댓글