Data & Research

[LLM & RAG] Langchain 기초 - Prompt

물박사의 저장공간 2025. 4. 3. 00:32

1. PromptTemplate (기본 프롬프트 템플릿)

from langchain.prompts import PromptTemplate

# 프롬프트 템플릿 정의
prompt = PromptTemplate(
    input_variables=["topic"],
    template="Tell me an interesting fact about {topic}."
)

# 프롬프트 렌더링
formatted_prompt = prompt.format(topic="black holes")
print(formatted_prompt)
Tell me an interesting fact about black holes.

 

2. ChatPromptTemplate (대화형 프롬프트)

대화형 프롬프트를 이용하면 시스템 메시지, 사용자 입력, 어시스턴트 응답을 구조적으로 관리할 수 있습니다. 

from langchain.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate

# 시스템 메시지 (AI의 역할 설정)
system_prompt = SystemMessagePromptTemplate.from_template("You are a helpful assistant.")

# 사용자 메시지 (사용자의 질문)
user_prompt = HumanMessagePromptTemplate.from_template("Tell me an interesting fact about {topic}.")

# ChatPromptTemplate을 이용해 메시지 구성
chat_prompt = ChatPromptTemplate.from_messages([system_prompt, user_prompt])

# 프롬프트 렌더링
formatted_prompt = chat_prompt.format_messages(topic="black holes")
print(formatted_prompt)
[SystemMessage(content='You are a helpful assistant.'), 
 HumanMessage(content='Tell me an interesting fact about black holes.')]

 

3. Few-shot Prompting

AI에게 예제를 몇 개 제공한 후, 패턴을 학습하도록 유도하는 방식입니다. 

from langchain.prompts import FewShotPromptTemplate, PromptTemplate

# 예제 데이터
examples = [
    {"word": "serendipity", "meaning": "The occurrence of events by chance in a happy way."},
    {"word": "ephemeral", "meaning": "Lasting for a very short time."}
]

# 예제 형식 템플릿
example_prompt = PromptTemplate(
    input_variables=["word", "meaning"],
    template="Word: {word}\nMeaning: {meaning}\n"
)

# Few-shot 프롬프트 템플릿
few_shot_prompt = FewShotPromptTemplate(
    examples=examples,
    example_prompt=example_prompt,
    prefix="Give the meaning of the following word:",
    suffix="Word: {word}\nMeaning:",
    input_variables=["word"]
)

# 프롬프트 렌더링
formatted_prompt = few_shot_prompt.format(word="ineffable")
print(formatted_prompt)
Give the meaning of the following word:

Word: serendipity
Meaning: The occurrence of events by chance in a happy way.

Word: ephemeral
Meaning: Lasting for a very short time.

Word: ineffable
Meaning:

 

4. Partial Prompt (부분적으로 채워진 프롬프트)

from langchain.prompts import PromptTemplate

# 기본 프롬프트 템플릿
prompt = PromptTemplate(
    input_variables=["topic", "tone"],
    template="Write a {tone} article about {topic}."
)

# 일부 변수를 미리 채운 Partial Prompt
partial_prompt = prompt.partial(tone="humorous")

# 나머지 변수만 입력하면 됨
formatted_prompt = partial_prompt.format(topic="artificial intelligence")
print(formatted_prompt)
Write a humorous article about artificial intelligence.