chat = ChatOpenAI(
temperature=0.1,
streaming=True,
callbacks=[StreamingStdOutCallbackHandler()],
)
PromptTemplate : 기본
# 방식 1
t= PromptTemplate.from_template("What is the capital of {country}")
t.format(country='France')
# 방식 2
t2 = PromptTemplate(
template = "What is the capital of {country}",
input_variables=['country'], # 입력변수들을 promptTemplate에 알려주어야한다.
)
t2.format(country='France')
FewShotPromptTemplate
모델에 예제(example) 주기
모델에게 '어떻게 대답해야 하는 지에 대한 예제(example)'를 AI 모델에게 주는 것이
prompt 를 사용해서 '어떻게 대답해야 하는지 알려주는 것'보다 훨씬 좋다
FewShotPromptTemplate 이 하는 일이 바로 그거다!
- 이를 통해 예제(샘플)를 형식화(포맷) 할수 있다.
- 이런 예제들을 데이터베이스등에 저장시켜놓고 활용할수도 있다
예시들을 활용하는 예
고객지원 봇
다른 고객들과의 대화 기록, 많은 기록들...
LLM 에게 '어떻게 고객에게 대응' 하는지 알려줄떄.
from langchain_core.prompts.few_shot import FewShotPromptTemplate
# 예제들 (examples)준비
# 모델더러 나에세 '이런식으로 답변해줬으면 좋겠다' 라고 제시.
examples = [
{
"question":"What do you know about France?",
# 원라는 형식의 답변..
"answer":"""
Here is what I know:
Capital: Paris
Language: French
Food: Wine and Cheese
Currency: Euro
"""
},
{
"question": "What do you know about Italy?",
"answer": """
I know this:
Capital: Rome
Language: Italian
Food: Pizza and Pasta
Currency: Euro
""",
},
{
"question": "What do you know about Greece?",
"answer": """
I know this:
Capital: Athens
Language: Greek
Food: Souvlaki and Feta Cheese
Currency: Euro
""",
},
]
# FewShotPromptTemplate 사용
# 포맷 준비 <- exmples 로 포맷팅 할거다
example_template ="""
Human: {question}
AI:{answer}
"""
#{question}과 {answer} 는 위 examples 와 동일한 key를 사용하여 작성해두어야 한다.
example_prompt = PromptTemplate.from_template(example_template)
prompt = FewShotPromptTemplate(
example_prompt=example_prompt, #사용할 prompt
examples=examples, # 준비된 예제들
# 유저의 질문을 넣어 주자
suffix = "Human: What do you know abount {country}?", # 질문은 example 과 동일한 형식
input_variables=['country']
)
chain = prompt | chat
chain.invoke({
"country":"Thailand",
})
FewShotChatMessagePromptTemplate
from langchain_core.prompts.few_shot import FewShotChatMessagePromptTemplate
examples = [
{
"country":"France",
"answer":"""
Here is what I know:
Capital: Paris
Language: French
Food: Wine and Cheese
Currency: Euro
"""
},
{
"country": "Italy",
"answer": """
I know this:
Capital: Rome
Language: Italian
Food: Pizza and Pasta
Currency: Euro
""",
},
{
"country": "Greece",
"answer": """
I know this:
Capital: Athens
Language: Greek
Food: Souvlaki and Feta Cheese
Currency: Euro
""",
},
]
example_prompt = ChatPromptTemplate.from_messages([
('human','What do you know abount {country}?'), # 반드시 example과 동일한 key 로!
('ai','{answer}')
])
example_prompt = FewShotChatMessagePromptTemplate(
example_prompt= example_prompt,
examples=examples,
#suffix = 는 필요없다.
)
final_prompt = ChatPromptTemplate.from_messages([
("system", "You are a geography expert, you give short answers."),
example_prompt,#!!
('human','What do you know abount {country}?'), # example_prompt 의 human메시지와 동일
# 이래서 suffix= 는 필요없던 것이다.
])
chain = final_prompt | chat
chain.invoke({'country':'Germany'})
ExampleSelector
LengthBasedExampleSelector
from langchain_core.example_selectors.length_based import LengthBasedExampleSelector
# LengthBasedExampleSelector 는 기본적으로
# - 예제(example) 들을 형식화 할 수 있고
# - 예제의 양이 얼마나 되는지를 확인할수 있다.
# 그러면, 사용자가 설정해 놓은 세팅값에 따라 prompt 에 알맞은 예제를 골라준다.
examples = [
{
"country": "France",
"answer": """
Here is what I know:
Capital: Paris
Language: French
Food: Wine and Cheese
Currency: Euro
""",
},
{
"country": "Italy",
"answer": """
I know this:
Capital: Rome
Language: Italian
Food: Pizza and Pasta
Currency: Euro
""",
},
{
"country": "Greece",
"answer": """
I know this:
Capital: Athens
Language: Greek
Food: Souvlaki and Feta Cheese
Currency: Euro
""",
},
]
example_prompt = PromptTemplate.from_template("Human:{country}\nAI:{answer}")
example_selector = LengthBasedExampleSelector(
examples=examples,
example_prompt=example_prompt, #포맷팅되는 양을 계산하기 위해선 example_prompt
max_length=180, # 예제의 양을 얼마나 허용해줄지 지정. max_length 값보다 긴 예제는 제외.
# LengthBasedExampleSelector의 max_length 는 단어의 개수 단위
# 글자의 개수 나 토큰의 개수가 아니다
)
prompt = FewShotPromptTemplate(
example_prompt=example_prompt,
# examples= 대신에 example_selector = 지정
# examples= <-'모든' 예제를 가지고 포맷팅.
example_selector=example_selector,
suffix="Human: What do you know about {country}?",
input_variables=['country']
)
# 포맷팅 동작 확인
prompt.format(country="Brazil")
Custom ExampleSelector (BaseExampleSelector)
from langchain_core.example_selectors.base import BaseExampleSelector
# BaseExampleSelector 의 구현객체를 만드려면
# 상속 받은뒤 select_examples() 과 add_example() 을 반드시 오버라이딩 해주어야 한다.
class RandomExampleSelector(BaseExampleSelector):
def __init__(self,examples):
self.examples = examples # 이번 예제에선 examples는 list
# select_examples()
# 입력에 따라 어떠한 샘플을 사용할지 select 함
def select_examples(self,input_variables):
from random import choice
return [choice(self.examples)] # examples 에서 무작위 1개 선탣하여 list 로 만들어 리턴
# add_example()
# 이미 존재하는 example에 example을 추가
def add_example(self,example):
self.examples.append(example)
example_selector = RandomExampleSelector(examples=examples)
prompt = FewShotPromptTemplate(
example_prompt=example_prompt,
example_selector=example_selector,
suffix="Human: What do you know about {country}?",
input_variables=['country']
)'AI > LLM' 카테고리의 다른 글
| LangChain - streaming = 과 callbacks (0) | 2026.05.25 |
|---|---|
| LangChain - Chaining Chains 사용해보기 (0) | 2026.05.24 |
| LangChain - LCEL (0) | 2026.05.23 |
| LangChain OutputParser (0) | 2026.05.19 |
| LangChain 시작 (0) | 2026.05.15 |