LangChain의 프롬프트 템플릿은 언어 모델과의 상호작용을 더욱 효율적으로 만들어주는 강력한 도구입니다.
이 글에서는 LangChain의 프롬프트 템플릿 활용법과 효과적인 프롬프트 설계를 위한 팁을 소개합니다.
LangChain의 'PromptTemplate' 클래스를 사용하면 재사용 가능한 프롬프트 템플릿을 쉽게 만들 수 있습니다.
기본적인 사용법은 다음과 같습니다.
from langchain import PromptTemplate
template = "Write a {length} story about: {content}"
prompt_template = PromptTemplate.from_template(template)
prompt = prompt_template.format(
length="2-sentence",
content="The hometown of a legendary data scientist"
)
이 방식을 통해 중복으로 프롬프트를 생성할 수 있으며, 코드의 재사용성도 높일 수 있습니다.
LangChain은 대화의 이전 상태를 저장하고 이를 프롬프트 생성에 활용할 수 있습니다.
이를 통해 더 일관성 있고 관련된 응답을 얻을 수 있습니다.
사용자 입력과 환경 변화에 따라 프롬프트 내용을 동적으로 조정할 수 있습니다.
이는 복잡한 대화 또는 다양한 사용자 요구를 처리하는 데 유용합니다.
프롬프트 템플릿에 조건문을 포함시켜 상황에 따라 다른 지시사항을 제공할 수 있습니다.
advanced_template = PromptTemplate(
input_variables=["user_query", "additional_context"],
template="Explain: {user_query}. {additional_context if additional_context else 'No additional context provided.'}"
)
예시를 포함한 프롬프트 템플릿을 만들어 모델의 성능을 향상시킬 수 있습니다.
examples = [
{"query": "How are you?", "answer": "I can't complain but sometimes I still do."},
{"query": "What time is it?", "answer": "It's time to get a watch."}
]
example_template = """
User: {query}
AI: {answer}
"""
example_prompt = PromptTemplate(
input_variables=["query", "answer"],
template=example_template
)
함수를 사용하여 현재 날짜/시간을 자동으로 프롬프트에 포함시킬 수 있습니다.
from datetime import datetime
def _get_datetime():
now = datetime.now()
return now.strftime("%m/%d/%Y, %H:%M:%S")
prompt = PromptTemplate(
template="Tell me a {adjective} joke about the day {date}",
input_variables=["adjective"],
partial_variables={"date": _get_datetime}
)
좀 더 복잡한 프롬프트 템플릿 예시를 살펴보겠습니다.
from langchain import PromptTemplate
from langchain.prompts import FewShotPromptTemplate
# 기본 템플릿 생성
system_template = """You are an AI assistant that helps users with {task}.
Follow these guidelines:
- Be concise and clear
- Provide practical examples
- Explain technical terms if necessary
"""
# 사용자 입력을 위한 템플릿
user_template = """
User Query: {query}
Additional Context: {context}
Your detailed response:
"""
# 전체 프롬프트 템플릿 조합
complete_template = PromptTemplate.from_template(
system_template + user_template
)
# 변수 값 설정 및 프롬프트 생성
final_prompt = complete_template.format(
task="programming questions",
query="How do I handle exceptions in Python?",
context="I'm a beginner learning about error handling."
)
이런 접근 방식을 통해 복잡한 프롬프트 구조도 체계적으로 관리할 수 있습니다.
LangChain의 프롬프트 템플릿을 활용하면 더 효율적이고 유연한 AI 애플리케이션을 개발할 수 있습니다.
지속적인 실험과 개선을 통해 최적의 프롬프트 설계를 찾아나가는 것이 중요합니다.