PromptTemplate은 프롬프트를 만들 때 변수 치환 등을 통해 동적으로 프롬프트를 구성할 수 있게 도와주는 클래스이다. 이걸 활용하면 복잡한 프롬프트를 더 효율적으로 관리할 수 있다.
LangChain 라이브러리에서 PromptTemplate을 활용해 프롬프트를 생성하는 기본 방법
프롬프트 템플릿의 중요성과 기본 사용법을 익혀보자
rom_template() 메소드를 사용해 PromptTemplate 객체 만들기
from langchain_core.prompts import PromptTemplate
# 템플릿 정의: {country}는 나중에 값이 들어갈 변수
template = "{country}의 수도는 어디인가요?"
# from_template 메소드를 이용해 PromptTemplate 객체 생성
prompt = PromptTemplate.from_template(template)
# 변수에 값을 넣어 프롬프트 생성
prompt = prompt.format(country="대한민국")
print(prompt)
# 대한민국 수도는 어디인가요?
생성한 프롬프트를 LLM과 연결해 실제 답변 엳기
chain = prompt | llm
response = chain.invoke("미국").채ㅜㅅ둣
priint(respone)
PromptTemplate을 더 효율적으로 사용하는 방법
특히, 변수 채우기, partial_variables 사용 방법
from_template() 메소드를 사용하지 않고 직접 PromptTemplate 객체 생성
from langchain_core.prompts import PromptTemplate
# 템플릿 정의
template = "뮤지컬 {musical}의 가장 유명한 넘버는 무엇인가요?"
# PromptTemplate 객체 생성
prompt = PromptTemplate(template=template, input_variables=["musical"])
# 변수에 값을 넣어 프롬프트 생성
formatted_prompt = prompt.format(musical="위키드")
print(formatted_prompt)
# 출력 : 뮤지컬 위키드의 가장 유명한 넘버는 무엇인가요?
부분적으로 변수를 미리 채워놓고 나머지 변수를 나중에 채우는 방법
# 템플릿 정의
template = "뮤지컬 {musical1}과 {musical2}의 가장 유명한 넘버는 각각 무엇인가요?"
# partial_variables를 사용해 musical2를 미리 채움
prompt = PromptTemplate(
template=template,
input_variables=["musical1"],
partial_variables={"musical2": "지킬앤하이드"}
)
# 변수 채워서 프롬프트 생성
formatted_prompt = prompt.format(musical1="라이온킹")
print(formatted_prompt)
#출력 : 뮤지컬 라이온킹과 지킬앤하이드의 가장 유명한 넘버는 각각 무엇인가요?
partial(): 부분 변수를 채울 수 있는 메소드
prompt = PromptTemplate.from_template(template)
partial_prompt = prompt.partial(musical2 = "마틸다")
formatted_prompt = partial_prompt.format(musical1 = "위키드")
print(formatted_prompt)
# 출력 : 뮤지컬 위키드과 마틸다의 가장 유명한 넘버는 각각 무엇인가요?