프롬프트 템플릿(Prompt Template)
- 프름프트를 형식화하기 위해 템플릿 사용
- 장점: 유효성 검사 가능, 템플릿을 디스크 등에 저장하고 로드할 수 있음
PromptTemplate
- string을 이용해서 템플릿을 만들 수 있는 클래스
- 메소드
👉 from_template: 프롬프트 템플릿 형식화
👉 format: 변수에 값을 할당
👉 invoke: 프롬프트를 llm에 전달하여 값 반환
from langchain_openai import ChatOpenAI
from langchain.prompts import PromptTemplate
chat = ChatOpenAI(temperature=0.1)
template = PromptTemplate.from_template(
'What is the distance between {country_a} and {country_b}'
)
prompt = template.format(country_a='south korea', country_b='japan')
chat.invoke(prompt)
AIMessage(content='The distance between South Korea and Japan is approximately 219 kilometers (136 miles) at the closest point, which is between the Korean peninsula and the Japanese island of Kyushu.', response_metadata={'token_usage': {'completion_tokens': 36, 'prompt_tokens': 17, 'total_tokens': 53, 'prompt_tokens_details': {'cached_tokens': 0}, 'completion_tokens_details': {'reasoning_tokens': 0}}, 'model_name': 'gpt-3.5-turbo', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}, id='run-9acdfdf0-ee24-42d6-8735-a37e59eb2930-0')
ChatPromptTemplate
- message(리스트)를 이용해서 템플릿을 만들 수 있는 클래스
- 메소드
👉 from_messages: system, ai, human을 각각 튜플 형태로 구성 후 리스트로 묶어 템플릿화
👉 format_messages: 변수에 값을 할당
👉 invoke: 프롬프트를 llm에 전달하여 값 반환
from langchain_openai import ChatOpenAII
from langchain.prompts import ChatPromptTemplate
chat = ChatOpenAI(temperature=0.1)
template = ChatPromptTemplate.from_messages([
('system', 'you are a geography export. and you only reply in {language}'),
('ai', '안녕? 내 이름은 {name}이야!'),
('human', 'what is the distance between {country_a} and {country_b}. also, what is your name?')
])
prompt = template.format_messages(language='korean',
name='세종',
country_a='south korea',
country_b='japan')
chain.invoke(prompt)
AIMessage(content='한국과 일본 사이의 거리는 약 220km입니다. 제 이름은 세종이에요.', response_metadata={'token_usage': {'completion_tokens': 33, 'prompt_tokens': 62, 'total_tokens': 95, 'prompt_tokens_details': {'cached_tokens': 0}, 'completion_tokens_details': {'reasoning_tokens': 0, 'accepted_prediction_tokens': 0, 'rejected_prediction_tokens': 0}}, 'model_name': 'gpt-3.5-turbo', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}, id='run-46e348d4-5598-42b0-b71a-5a73e8f60278-0')