프롬프트는 검색 기반 언어 모델 시스템에서 핵심적인 역할을 하는 단계입니다. 이 단계는 최종 사용자의 질문이나 명령을 바탕으로 적절한 응답을 생성하기 위해 필요한 모든 정보를 언어 모델에 제공하는 역할을 합니다.
문맥(Context) 설정:
정보 통합:
응답 품질 향상:
RAG 시스템에서의 프롬프트는 일반적으로 다음과 같은 구조를 가집니다:
지시사항(Instruction):
질문(사용자 입력 질문):
문맥(검색된 정보):
예시 프롬프트:
당신은 질문-답변(Question-Answer) Task 를 수행하는 AI 어시스턴트 입니다.
검색된 문맥(context)을 사용하여 질문(question)에 답하세요.
만약, 문맥(context)으로부터 답을 찾을 수 없다면 '모른다' 고 말하세요.
한국어로 대답하세요.
#Question:
{이곳에 사용자가 입력한 질문이 삽입됩니다}
#Context:
{이곳에 검색된 정보가 삽입됩니다}
프롬프트 단계는 RAG 시스템에서 매우 중요한 역할을 합니다. 이 단계는 언어 모델이 사용자의 질문에 최적화된 방식으로 응답을 생성할 수 있도록 돕습니다. 프롬프트가 잘 구성되지 않으면, 모델의 성능이 저하되고 사용자 만족도가 떨어질 수 있습니다.
프롬프트는 언어 모델의 작업을 안내하고 문맥을 제공하며, 모델이 정확하고 관련성 높은 응답을 생성하도록 돕는 필수적인 요소입니다. 잘 설계된 프롬프트는 RAG 시스템 전체의 성능을 높이고, 사용자가 원하는 정보를 정확하게 제공할 수 있게 합니다.
from dotenv import load_dotenv
load_dotenv()
True
# LangSmith 추적을 설정합니다. https://smith.langchain.com
from langchain_teddynote import logging
# 프로젝트 이름을 설정합니다.
logging.langsmith("CH02-Prompt")
LangSmith 추적을 시작합니다.
[프로젝트명]
CH02-Prompt
from langchain_openai import ChatOpenAI
llm = ChatOpenAI()
from_template()
메소드를 사용하여 PromptTemplate
객체 생성변수를 { 변수 }
로 묶어서 템플릿을 정의합니다.
from langchain_core.prompts import PromptTemplate
# 템플릿 정의. {country}는 변수로, 이후에 값이 들어갈 자리를 의미
template = "{country}의 수도는 어디인가요?"
# from_template 메소드를 이용하여 PromptTemplate 객체 생성
prompt = PromptTemplate.from_template(template)
prompt
# PromptTemplate(input_variables=['country'], template='{country}의 수도는 어디인가요?')
프롬프트 생성:
# prompt 생성. format 메소드를 이용하여 변수에 값을 넣어줌
prompt = prompt.format(country="대한민국")
prompt
# '대한민국의 수도는 어디인가요?'
체인 생성 및 실행:
# 체인 생성
chain = prompt | llm
# country 변수에 입력된 값이 자동으로 치환되어 수행됨
response = chain.invoke("대한민국").content
print(response)
# '대한민국의 수도는 서울입니다.'
PromptTemplate
객체 생성과 동시에 prompt
생성# template 정의
template = "{country}의 수도는 어디인가요?"
# PromptTemplate 객체를 활용하여 prompt_template 생성
prompt = PromptTemplate(
template=template,
input_variables=["country"],
)
# prompt 생성
prompt.format(country="대한민국")
# '대한민국의 수도는 어디인가요?'
복수의 변수를 사용하는 예제:
# template 정의
template = "{country1}과 {country2}의 수도는 각각 어디인가요?"
# PromptTemplate 객체를 활용하여 prompt_template 생성
prompt = PromptTemplate(
template=template,
input_variables=["country1"],
partial_variables={"country2": "미국"}, # partial_variables를 사용하여 일부 변수를 미리 지정
)
# prompt 생성
prompt.format(country1="대한민국")
# '대한민국과 미국의 수도는 각각 어디인가요?'
Partial을 사용한 체인 생성 및 실행:
prompt_partial = prompt.partial(country2="캐나다")
chain = prompt_partial | llm
# 체인 실행
response = chain.invoke("대한민국").content
print(response)
# '대한민국의 수도는 서울이며, 캐나다의 수도는 오타와입니다.'
partial
은 항상 동일하게 유지해야 하는 변수를 처리할 때 유용합니다. 예를 들어, 항상 현재 날짜를 표시하고자 할 때 사용할 수 있습니다.
from datetime import datetime
# 날짜를 반환하는 함수 정의
def get_today():
return datetime.now().strftime("%B %d")
prompt = PromptTemplate(
template="오늘의 날짜는 {today} 입니다. 오늘이 생일인 유명인 {n}명을 나열해 주세요. 생년월일을 표기해주세요.",
input_variables=["n"],
partial_variables={"today": get_today},
)
# prompt 생성 및 체인 실행
chain = prompt | llm
response = chain.invoke(3).content
print(response)
# 예시 출력: '1. Nicole Kidman - 1967년 6월 20일 ...'
from langchain_core.prompts import load_prompt
# YAML 파일로부터 템플릿 읽어오기
prompt = load_prompt("prompts/fruit_color.yaml")
prompt.format(fruit="사과")
# '사과의 색깔이 뭐야?'
# 다른 예제
prompt2 = load_prompt("prompts/capital.yaml")
print(prompt2.format(country="대한민국"))
# '대한민국의 수도에 대해서 알려주세요...'
ChatPromptTemplate
은 대화 목록을 프롬프트로 주입하고자 할 때 사용됩니다.
from langchain_core.prompts import ChatPromptTemplate
# ChatPromptTemplate 정의
chat_prompt = ChatPromptTemplate.from_template("{country}의 수도는 어디인가요?")
chat_prompt.format(country="대한민국")
# 'Human: 대한민국의 수도는 어디인가요?'
다양한 메시지 유형을 사용한 예제:
chat_template = ChatPromptTemplate.from_messages(
[
("system", "당신은 친절한 AI 어시스턴트입니다. 당신의 이름은 {name} 입니다."),
("human", "반가워요!"),
("ai", "안녕하세요! 무엇을 도와드릴까요?"),
("human", "{user_input}"),
]
)
messages = chat_template.format_messages(
name="테디", user_input="당신의 이름은 무엇입니까?"
)
response = llm.invoke(messages).content
print(response)
# '제 이름은 테디입니다. 필요한 도움이 있으면 언제든지 말씀해주세요!'
MessagePlaceholder
는 포맷 중에 렌더링할 메시지를 완전히 제어할 수 있도록 돕습니다.
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
chat_prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"당신은 요약 전문 AI 어시스턴트입니다. 당신의 임무는 주요 키워드로 대화를 요약하는 것입니다.",
),
MessagesPlaceholder(variable_name="conversation"),
("human", "지금까지의 대화를 {word_count} 단어로 요약합니다."),
]
)
formatted_chat_prompt = chat_prompt.format(
word_count=5,
conversation=[
("human", "안녕하세요! 저는 오늘 새로 입사한 테디 입니다."),
("ai", "반가워요! 앞으로 잘 부탁 드립니다."),
],
)
print(formatted_chat_prompt)
# System: 당신은 요약 전문 AI 어시스턴트입니다...
체인 생성 및 실행:
chain = chat_prompt | llm | StrOutputParser()
response = chain.invoke(
{
"word_count": 5,
"conversation": [
("human", "안녕하세요! 저는 오늘 새로 입사한 테디 입니다."),
("ai", "반가워요! 앞으로 잘 부탁 드립니다."),
],
}
).content
print(response)
# '새로운 입사자 테디 만남.'
from dotenv import load_dotenv
load_dotenv()
True
# LangSmith 추적을 설정합니다. https://smith.langchain.com
from langchain_teddynote import logging
# 프로젝트 이름을 설정합니다.
logging.langsmith("CH02-Prompt")
LangSmith 추적을 시작합니다.
[프로젝트명]
CH02-Prompt
from langchain_openai import ChatOpenAI
from langchain_teddynote.messages import stream_response
# 객체 생성
llm = ChatOpenAI(
temperature=0, # 창의성
model_name="gpt-4-turbo", # 모델명
)
# 질의내용
question = "대한민국의 수도는 뭐야?"
# 질의
answer = llm.stream(question)
stream_response(answer)
# 대한민국의 수도는 서울입니다.
from langchain_core.prompts.few_shot import FewShotPromptTemplate
from langchain_core.prompts import PromptTemplate
from langchain_core.output_parsers import StrOutputParser
# 예제 설정
examples = [
{
"question": "스티브 잡스와 아인슈타인 중 누가 더 오래 살았나요?",
"answer": """이 질문에 추가 질문이 필요한가요: 예.
추가 질문: 스티브 잡스는 몇 살에 사망했나요?
중간 답변: 스티브 잡스는 56세에 사망했습니다.
추가 질문: 아인슈타인은 몇 살에 사망했나요?
중간 답변: 아인슈타인은 76세에 사망했습니다.
최종 답변은: 아인슈타인
""",
},
{
"question": "네이버의 창립자는 언제 태어났나요?",
"answer": """이 질문에 추가 질문이 필요한가요: 예.
추가 질문: 네이버의 창립자는 누구인가요?
중간 답변: 네이버는 이해진에 의해 창립되었습니다.
추가 질문: 이해진은 언제 태어났나요?
중간 답변: 이해진은 1967년 6월 22일에 태어났습니다.
최종 답변은: 1967년 6월 22일
""",
},
{
"question": "율곡 이이의 어머니가 태어난 해의 통치하던 왕은 누구인가요?",
"answer": """이 질문에 추가 질문이 필요한가요: 예.
추가 질문: 율곡 이이의 어머니는 누구인가요?
중간 답변: 율곡 이이의 어머니는 신사임당입니다.
추가 질문: 신사임당은 언제 태어났나요?
중간 답변: 신사임당은 1504년에 태어났습니다.
추가 질문: 1504년에 조선을 통치한 왕은 누구인가요?
중간 답변: 1504년에 조선을 통치한 왕은 연산군입니다.
최종 답변은: 연산군
""",
},
{
"question": "올드보이와 기생충의 감독이 같은 나라 출신인가요?",
"answer": """이 질문에 추가 질문이 필요한가요: 예.
추가 질문: 올드보이의 감독은 누구인가요?
중간 답변: 올드보이의 감독은 박찬욱입니다.
추가 질문: 박찬욱은 어느 나라 출신인가요?
중간 답변: 박찬욱은 대한민국 출신입니다.
추가 질문: 기생충의 감독은 누구인가요?
중간 답변: 기생충의 감독은 봉준호입니다.
추가 질문: 봉준호는 어느 나라 출신인가요?
중간 답변: 봉준호는 대한민국 출신입니다.
최종 답변은: 예
""",
},
]
# 예제 프롬프트 생성
example_prompt = PromptTemplate.from_template(
"Question:\n{question}\nAnswer:\n{answer}"
)
print(example_prompt.format(**examples[0]))
출력 예시:
Question:
스티브 잡스와 아인슈타인 중 누가 더 오래 살았나요?
Answer:
이 질문에 추가 질문이 필요한가요: 예.
추가 질문: 스티브 잡스는 몇 살에 사망했나요?
중간 답변: 스티브 잡스는 56세에 사망했습니다.
추가 질문: 아인슈타인은 몇 살에 사망했나요?
중간 답변: 아인슈타인은 76세에 사망했습니다.
최종 답변은: 아인슈타인
prompt = FewShotPromptTemplate(
examples=examples,
example_prompt=example_prompt,
suffix="Question:\n{question}\nAnswer:",
input_variables=["question"],
)
question = "Google이 창립된 연도에 Bill Gates의 나이는 몇 살인가요?"
final_prompt = prompt.format(question=question)
print(final_prompt)
출력 예시:
Question:
Google이 창립된 연도에 Bill Gates의 나이는 몇 살인가요?
Answer:
결과 출력:
# 결과 출력
answer = llm.stream(final_prompt)
stream_response(answer)
# 이 질문에 추가 질문이 필요한가요: 예.
# 추가 질문: Google은 언제 창립되었나요?
# 중간 답변: Google은 1998년에 창립되었습니다.
# 추가 질문: Bill Gates는 언제 태어났나요?
# 중간 답변: Bill Gates는 1955년 10월 28일에 태어났습니다.
# 최종 답변은: 1998년에 Bill Gates의 나이는 43세였습니다.
from langchain_core.example_selectors import (
MaxMarginalRelevanceExampleSelector,
SemanticSimilarityExampleSelector,
)
from langchain_openai import OpenAIEmbeddings
from langchain_chroma import Chroma
# Vector DB 생성 (저장소 이름, 임베딩 클래스)
chroma = Chroma("example_selector", OpenAIEmbeddings())
example_selector = SemanticSimilarityExampleSelector.from_examples(
examples, # 선택 가능한 예시 목록
OpenAIEmbeddings(), # 임베딩 생성
Chroma, # VectorStore 클래스
k=1, # 생성할 예시의 수
)
# 입력과 가장 유사한 예시를 선택
question = "Google이 창립된 연도에 Bill Gates의 나이는 몇 살인가요?"
selected_examples = example_selector.select_examples({"question": question})
print(f"입력에 가장 유사한 예시:\n{question}\n")
for example in selected_examples:
print(f'question:\n{example["question"]}')
print(f'answer:\n{example["answer"]}')
출력 예시:
입력에 가장 유사한 예시:
Google이 창립된 연도에 Bill Gates의 나이는 몇 살인가요?
question:
네이버의 창립자는 언제 태어났나요?
answer:
이 질문에 추가 질문이 필요한가요: 예.
추가 질문: 네이버의 창립자는 누구인가요?
중간 답변: 네이버는 이해진에 의해 창립되었습니다.
추가 질문: 이해진은 언제 태어났나요?
중간 답변: 이해진은 1967년 6월 22일에 태어났습니다.
최종 답변은: 1967년 6월 22일
# 예제 설정 및 FewShotChatMessagePromptTemplate 생성
from langchain_core.prompts import ChatPromptTemplate, FewShotChatMessagePromptTemplate
from langchain_core.example_selectors import SemanticSimilarityExampleSelector
from langchain_openai import OpenAIEmbeddings
from langchain_chroma import Chroma
chroma = Chroma("fewshot_chat", OpenAIEmbeddings())
example_prompt = ChatPromptTemplate.from_messages(
[
("human", "{instruction}:\n{input}"),
("ai", "{answer}"),
]
)
example_selector = SemanticSimilarityExampleSelector.from_examples(
examples, # 선택 가능한 예시 목록
OpenAIEmbeddings(), # 임베딩 생성
chroma, # VectorStore 클래스
k=1, # 생성할 예시의 수
)
few_shot_prompt = FewShotChatMessagePromptTemplate(
example_selector=example_selector,
example_prompt=example_prompt,
)
Example Selector를 사용한 FewShotPromptTemplate 생성:
final_prompt = ChatPromptTemplate.from_messages(
[
("system", "You are a helpful assistant."),
few_shot_prompt,
("human", "{instruction}\n{input}"),
]
)
# 체인 생성 및 실행
chain = final_prompt | llm
question = {
"instruction": "회의록을 작성해 주세요",
"input": "2023년 12월 26일, ABC 기술 회사의 제품 개발 팀은 새로운 모바일 애플리케이션 프로젝트에 대한 주간 진행 상황 회의를 가졌다. 이 회
---
## <span style="color:#ff4500">🏖️ 03. LangChain Hub 사용 예제
LangChain Hub는 사용자가 공유할 수 있는 다양한 프롬프트를 저장하는 리포지토리입니다. 이 리포지토리를 통해 프롬프트를 쉽게 가져오거나 업로드할 수 있습니다. 아래는 LangChain Hub에서 프롬프트를 가져오고 사용하는 방법과 자신의 프롬프트를 업로드하는 방법을 설명한 예제입니다.
### <span style="color:#1e90ff"> 1. Hub로부터 프롬프트 받아오기
LangChain Hub에서 특정 프롬프트를 가져오려면 `hub.pull()` 메소드를 사용합니다. 최신 버전 또는 특정 커밋 ID를 사용하여 프롬프트를 가져올 수 있습니다.
```python
from langchain import hub
# 가장 최신 버전의 프롬프트를 가져옵니다.
prompt = hub.pull("rlm/rag-prompt")
# 프롬프트 내용 출력
print(prompt)
출력 예시:
input_variables=['context', 'question']
metadata={'lc_hub_owner': 'rlm', 'lc_hub_repo': 'rag-prompt', 'lc_hub_commit_hash': '50442af133e61576e74536c6556cefe1fac147cad032f4377b60c436e6cdcb6e'}
messages=[HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=['context', 'question'], template="You are an assistant for question-answering tasks. Use the following pieces of retrieved context to answer the question. If you don't know the answer, just say that you don't know. Use three sentences maximum and keep the answer concise.\nQuestion: {question} \nContext: {context} \nAnswer:"))]
특정 버전의 프롬프트를 가져오려면 커밋 ID를 지정할 수 있습니다.
# 특정 버전의 프롬프트를 가져옵니다.
prompt = hub.pull("rlm/rag-prompt:50442af1")
print(prompt)
출력 예시:
ChatPromptTemplate(input_variables=['context', 'question'],
metadata={'lc_hub_owner': 'rlm', 'lc_hub_repo': 'rag-prompt', 'lc_hub_commit_hash': '50442af133e61576e74536c6556cefe1fac147cad032f4377b60c436e6cdcb6e'},
messages=[HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=['context', 'question'], template="You are an assistant for question-answering tasks. Use the following pieces of retrieved context to answer the question. If you don't know the answer, just say that you don't know. Use three sentences maximum and keep the answer concise.\nQuestion: {question} \nContext: {context} \nAnswer:"))])
LangChain Hub에 자신의 프롬프트를 업로드할 수 있습니다. 업로드된 프롬프트는 다른 사용자와 공유할 수 있으며, 나중에 다시 가져와 사용할 수도 있습니다.
from langchain.prompts import ChatPromptTemplate
# 새로운 프롬프트 생성
prompt = ChatPromptTemplate.from_template(
"주어진 내용을 바탕으로 다음 문장을 요약하세요. 답변은 반드시 한글로 작성하세요\n\nCONTEXT: {context}\n\nSUMMARY:"
)
print(prompt)
출력 예시:
ChatPromptTemplate(input_variables=['context'],
messages=[HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=['context'],
template='주어진 내용을 바탕으로 다음 문장을 요약하세요. 답변은 반드시 한글로 작성하세요\n\nCONTEXT: {context}\n\nSUMMARY:'))])
프롬프트를 LangChain Hub에 업로드합니다.
from langchain import hub
# 프롬프트를 허브에 업로드
hub.push("teddynote/simple-summary-korean", prompt)
업로드 후 출력된 URL:
출력: 'https://smith.langchain.com/hub/teddynote/simple-summary-korean/0e296563'
이제 Hub에 성공적으로 업로드된 프롬프트를 다시 가져와서 사용할 수 있습니다.
from langchain import hub
# 허브로부터 프롬프트 가져오기
pulled_prompt = hub.pull("teddynote/simple-summary-korean")
# 프롬프트 내용 출력
print(pulled_prompt)
출력 예시:
input_variables=['context']
metadata={'lc_hub_owner': 'teddynote', 'lc_hub_repo': 'simple-summary-korean', 'lc_hub_commit_hash': '0e296563564b581e5ad77089b035596246c2b96046f8db0503355dd3c275d056'}
messages=[HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=['context'], template='주어진 내용을 바탕으로 다음 문장을 요약하세요. 답변은 반드시 한글로 작성하세요\n\nCONTEXT: {context}\n\nSUMMARY:'))]
이 방법을 사용하여 LangChain Hub의 다양한 프롬프트를 활용하고, 자신의 프롬프트를 업로드 및 공유할 수 있습니다.
LangChain Hub는 사용자가 공유할 수 있는 다양한 프롬프트를 저장하는 리포지토리입니다. 이 리포지토리를 통해 프롬프트를 쉽게 가져오거나 업로드할 수 있습니다. 아래는 LangChain Hub에서 프롬프트를 가져오고 사용하는 방법과 자신의 프롬프트를 업로드하는 방법을 설명한 예제입니다.
LangChain Hub에서 특정 프롬프트를 가져오려면 hub.pull()
메소드를 사용합니다. 최신 버전 또는 특정 커밋 ID를 사용하여 프롬프트를 가져올 수 있습니다.
from langchain import hub
# 가장 최신 버전의 프롬프트를 가져옵니다.
prompt = hub.pull("rlm/rag-prompt")
# 프롬프트 내용 출력
print(prompt)
출력 예시:
input_variables=['context', 'question']
metadata={'lc_hub_owner': 'rlm', 'lc_hub_repo': 'rag-prompt', 'lc_hub_commit_hash': '50442af133e61576e74536c6556cefe1fac147cad032f4377b60c436e6cdcb6e'}
messages=[HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=['context', 'question'], template="You are an assistant for question-answering tasks. Use the following pieces of retrieved context to answer the question. If you don't know the answer, just say that you don't know. Use three sentences maximum and keep the answer concise.\nQuestion: {question} \nContext: {context} \nAnswer:"))]
특정 버전의 프롬프트를 가져오려면 커밋 ID를 지정할 수 있습니다.
# 특정 버전의 프롬프트를 가져옵니다.
prompt = hub.pull("rlm/rag-prompt:50442af1")
print(prompt)
출력 예시:
ChatPromptTemplate(input_variables=['context', 'question'],
metadata={'lc_hub_owner': 'rlm', 'lc_hub_repo': 'rag-prompt', 'lc_hub_commit_hash': '50442af133e61576e74536c6556cefe1fac147cad032f4377b60c436e6cdcb6e'},
messages=[HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=['context', 'question'], template="You are an assistant for question-answering tasks. Use the following pieces of retrieved context to answer the question. If you don't know the answer, just say that you don't know. Use three sentences maximum and keep the answer concise.\nQuestion: {question} \nContext: {context} \nAnswer:"))])
LangChain Hub에 자신의 프롬프트를 업로드할 수 있습니다. 업로드된 프롬프트는 다른 사용자와 공유할 수 있으며, 나중에 다시 가져와 사용할 수도 있습니다.
from langchain.prompts import ChatPromptTemplate
# 새로운 프롬프트 생성
prompt = ChatPromptTemplate.from_template(
"주어진 내용을 바탕으로 다음 문장을 요약하세요. 답변은 반드시 한글로 작성하세요\n\nCONTEXT: {context}\n\nSUMMARY:"
)
print(prompt)
출력 예시:
ChatPromptTemplate(input_variables=['context'],
messages=[HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=['context'],
template='주어진 내용을 바탕으로 다음 문장을 요약하세요. 답변은 반드시 한글로 작성하세요\n\nCONTEXT: {context}\n\nSUMMARY:'))])
프롬프트를 LangChain Hub에 업로드합니다.
from langchain import hub
# 프롬프트를 허브에 업로드
hub.push("teddynote/simple-summary-korean", prompt)
업로드 후 출력된 URL:
출력: 'https://smith.langchain.com/hub/teddynote/simple-summary-korean/0e296563'
이제 Hub에 성공적으로 업로드된 프롬프트를 다시 가져와서 사용할 수 있습니다.
from langchain import hub
# 허브로부터 프롬프트 가져오기
pulled_prompt = hub.pull("teddynote/simple-summary-korean")
# 프롬프트 내용 출력
print(pulled_prompt)
출력 예시:
input_variables=['context']
metadata={'lc_hub_owner': 'teddynote', 'lc_hub_repo': 'simple-summary-korean', 'lc_hub_commit_hash': '0e296563564b581e5ad77089b035596246c2b96046f8db0503355dd3c275d056'}
messages=[HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=['context'], template='주어진 내용을 바탕으로 다음 문장을 요약하세요. 답변은 반드시 한글로 작성하세요\n\nCONTEXT: {context}\n\nSUMMARY:'))]
이 방법을 사용하여 LangChain Hub의 다양한 프롬프트를 활용하고, 자신의 프롬프트를 업로드 및 공유할 수 있습니다.
이 예제에서는 LangChain Hub에 개인화된 프롬프트를 업로드하는 방법을 설명합니다. 이 과정을 통해 특정 요구에 맞는 프롬프트를 작성하고, 이를 LangChain Hub에 저장하여 나중에 쉽게 재사용하거나 공유할 수 있습니다.
아래는 다양한 유형의 프롬프트를 작성하고 이를 LangChain Hub에 업로드하는 과정입니다.
from langchain import hub
from langchain.prompts import PromptTemplate, ChatPromptTemplate
# LangChain 사용자 ID
PROMPT_OWNER = "teddynote"
# 요약 프롬프트 작성
prompt_title = "summary-stuff-documents"
prompt_template = """Please summarize the sentence according to the following REQUEST.
REQUEST:
1. Summarize the main points in bullet points.
2. Each summarized sentence must start with an emoji that fits the meaning of each sentence.
3. Use various emojis to make the summary more interesting.
4. DO NOT include any unnecessary information.
CONTEXT:
{context}
SUMMARY:"""
prompt = PromptTemplate.from_template(prompt_template)
# LangChain Hub에 프롬프트 업로드
hub.push(f"{PROMPT_OWNER}/{prompt_title}", prompt)
# Map 프롬프트 작성
prompt_title = "map-prompt"
prompt_template = """You are a helpful expert journalist in extracting the main themes from the GIVEN DOCUMENTS below.
Please provide a comprehensive summary of the GIVEN DOCUMENTS in numbered list format.
The summary should cover all the key points and main ideas presented in the original text, while also condensing the information into a concise and easy-to-understand format.
Please ensure that the summary includes relevant details and examples that support the main ideas, while avoiding any unnecessary information or repetition.
The length of the summary should be appropriate for the length and complexity of the original text, providing a clear and accurate overview without omitting any important information.
GIVEN DOCUMENTS:
{docs}
FORMAT:
1. main theme 1
2. main theme 2
3. main theme 3
...
CAUTION:
- DO NOT list more than 5 main themes.
Helpful Answer:"""
prompt = PromptTemplate.from_template(prompt_template)
# LangChain Hub에 프롬프트 업로드
hub.push(f"{PROMPT_OWNER}/{prompt_title}", prompt)
# Reduce 프롬프트 작성
prompt_title = "reduce-prompt"
prompt_template = """You are a helpful expert in summary writing.
You are given numbered lists of summaries.
Extract the top 10 most important insights from the summaries.
Then, write a summary of the insights in KOREAN.
LIST OF SUMMARIES:
{doc_summaries}
Helpful Answer:"""
prompt = PromptTemplate.from_template(prompt_template)
# LangChain Hub에 프롬프트 업로드
hub.push(f"{PROMPT_OWNER}/{prompt_title}", prompt)
# Chain of Density 프롬프트 작성
prompt_title = "chain-of-density-reduce-korean"
prompt_template = """You are a helpful expert in summary writing. You are given lists of summaries.
Please sum up previously summarized sentences according to the following REQUEST.
REQUEST:
1. Summarize the main points in bullet points in KOREAN.
2. Each summarized sentence must start with an emoji that fits the meaning of each sentence.
3. Use various emojis to make the summary more interesting.
4. MOST IMPORTANT points should be organized at the top of the list.
5. DO NOT include any unnecessary information.
LIST OF SUMMARIES:
{doc_summaries}
Helpful Answer:"""
prompt = PromptTemplate.from_template(prompt_template)
# LangChain Hub에 프롬프트 업로드
hub.push(f"{PROMPT_OWNER}/{prompt_title}", prompt)
# Metadata Tagger 프롬프트 작성
prompt_title = "metadata-tagger"
prompt_template = """Given the following product review, conduct a comprehensive analysis to extract key aspects mentioned by the customer, with a focus on evaluating the product's design and distinguishing between positive aspects and areas for improvement.
Identify primary features or attributes of the product that the customer appreciated or highlighted, specifically looking for mentions related to the feel of the keys, sound produced by the keys, overall user experience, charging aspect, and the design of the product, etc.
Assess the overall tone of the review (positive, neutral, or negative) based on the sentiment expressed about these attributes.
Additionally, provide a detailed evaluation of the design, outline the positive aspects that the customer enjoyed, and note any areas of improvement or disappointment mentioned.
Extract the customer's rating of the product on a scale of 1 to 5, as indicated at the beginning of the review.
Summarize your findings in a structured JSON format, including an array of keywords, evaluations for design, satisfaction points, improvement areas, the assessed tone, and the numerical rating.
INPUT:
{input}"""
prompt = ChatPromptTemplate.from_template(prompt_template)
# LangChain Hub에 프롬프트 업로드
hub.push(f"{PROMPT_OWNER}/{prompt_title}", prompt)
# Chain of Density 프롬프트 작성 (버전 2)
prompt_title = "chain-of-density-map-korean"
prompt_template = """Article: {ARTICLE}
You will generate increasingly concise, entity-dense summaries of the above article.
Repeat the following 2 steps 3 times.
Step 1. Identify 1-3 informative entities (";" delimited) from the article which are missing from the previously generated summary.
Step 2. Write a new, denser summary of identical length which covers every entity and detail from the previous summary plus the missing entities.
A missing entity is:
- relevant to the main story,
- specific yet concise (100 words or fewer),
- novel (not in the previous summary),
- faithful (present in the article),
- anywhere (can be located anywhere in the article).
Guidelines:
- The first summary should be long (8-10 sentences, ~200 words) yet highly non-specific, containing little information beyond the entities marked as missing. Use overly verbose language and fillers (e.g., "this article discusses") to reach ~200 words.
- Make every word count: rewrite the previous summary to improve flow and make space for additional entities.
- Make space with fusion, compression, and removal of uninformative phrases like "the article discusses".
- The summaries should become highly dense and concise yet self-contained, i.e., easily understood without the article.
- Missing entities can appear anywhere in the new summary.
- Never drop entities from the previous summary. If space cannot be made, add fewer new entities.
Remember, use the exact same number of words for each summary.
Answer "Missing Entities" and "Denser_Summary" as in TEXT format.
Use only KOREAN language to reply."""
prompt = ChatPromptTemplate.from_template(prompt_template)
# LangChain Hub에 프롬프트 업로드
hub.push(f"{PROMPT_OWNER}/{prompt_title}", prompt)
# RAG 문서 프롬프트 작성 (한국어)
prompt_title = "rag-prompt-korean"
system_message = """당신은 질문-답변(Question-Answering)을 수행하는 친절한 AI 어시스턴트입니다. 당신의 임무는 주어진 문맥(context) 에서 주어진 질문(question) 에 답하는 것입니다.
검색된 다음 문맥(context) 을 사용하여 질문(question) 에 답하세요. 만약, 주어진 문맥(context) 에서 답을 찾을 수 없다면, 답을 모른다면 `주어진 정보에서 질문에 대한 정보를 찾을 수 없습니다` 라고 답하세요.
한글로 답변해 주세요. 단, 기술적인 용어나 이름은 번역하지 않고 그대로 사용해 주세요. Don't narrate the answer, just answer the question. Let's think step-by-step."""
human_message = """#Question:
{question}
#Context:
{context}
#Answer:"""
prompt = ChatPromptTemplate.from_messages([("system", system_message), ("human", human_message)])
hub.push(f"{PROMPT_OWNER}/{prompt_title}", prompt, parent_commit_hash="latest")
이러한 과정을 통해 다양한 프롬프트를 작성하고, LangChain Hub에 업로드하여 공유하거나 나중에 재사용할 수 있습니다. 각 프롬프트는 특정 요구에 맞춰 작성되었으며, 다양한 사용 사례에 맞게 커스터마이징할 수 있습니다.