from langchain.chat_models import ChatOpenAI
from langchain.prompts import PromptTemplate
from langchain.prompts.few_shot import FewShotPromptTemplate
from langchain.callbacks import StreamingStdOutCallbackHandler
chat = ChatOpenAI(
model="gpt-3.5-turbo",
temperature=0.1,
streaming=True,
callbacks=[
StreamingStdOutCallbackHandler(),
],
)
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
""",
},
]
example_template = """
Human: {question}
AI: {answer}
"""
example_prompt = PromptTemplate.from_template(example_template)
few_shot_prompt = FewShotPromptTemplate(
examples=examples,
example_prompt=example_prompt,
suffix="Human: What do you know about {country}?",
input_variables=["question"],
)
chain = few_shot_prompt | chat
chain.invoke({"country": "Turkey"})
이 코드는 LangChain을 사용하여 OpenAI의 gpt-3.5-turbo 모델과 함께 Few-Shot Learning 기법을 적용한 질문-응답 시스템을 구축하는 예제입니다. 아래에서 코드의 주요 부분을 설명하겠습니다.
📌 1. Chat Model 설정 (ChatOpenAI)
from langchain.chat_models import ChatOpenAI
from langchain.callbacks import StreamingStdOutCallbackHandler
chat = ChatOpenAI(
model="gpt-3.5-turbo",
temperature=0.1,
streaming=True,
callbacks=[
StreamingStdOutCallbackHandler(),
],
)
✅ 설명
• ChatOpenAI: OpenAI의 챗봇 모델(gpt-3.5-turbo)을 사용하기 위한 LangChain의 래퍼 클래스.
• temperature=0.1: 낮은 온도로 설정하여 응답을 더 일관되고 논리적으로 만듦 (높을수록 창의적, 낮을수록 사실 기반).
• streaming=True: 실시간으로 응답을 스트리밍하여 표시.
• callbacks=[StreamingStdOutCallbackHandler()]: 응답이 바로 출력되도록 하는 콜백 핸들러.
📌 2. Few-Shot 예제 데이터 설정 (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
""",
},
]
✅ 설명
• examples 리스트에는 Few-Shot Learning을 위한 예제 데이터가 포함됨.
• question과 answer 형식으로 구성되어 있으며, 모델이 특정 패턴을 학습할 수 있도록 돕는다.
• 예제 데이터는 특정 국가(프랑스, 이탈리아, 그리스)에 대한 정보를 제공.
📌 3. 예제 템플릿 설정 (PromptTemplate)
from langchain.prompts import PromptTemplate
example_template = """
Human: {question}
AI: {answer}
"""
example_prompt = PromptTemplate.from_template(example_template)
✅ 설명
• PromptTemplate.from_template(example_template): 예제 데이터를 특정 형식으로 구성하는 프롬프트 템플릿을 생성.
• 각 예제는 다음과 같은 형태가 됨:
Human: What do you know about France?
AI: Here is what I know:
Capital: Paris
Language: French
Food: Wine and Cheese
Currency: Euro
📌 4. Few-Shot 프롬프트 구성 (FewShotPromptTemplate)
from langchain.prompts.few_shot import FewShotPromptTemplate
few_shot_prompt = FewShotPromptTemplate(
examples=examples,
example_prompt=example_prompt,
suffix="Human: What do you know about {country}?",
input_variables=["question"],
)
✅ 설명
• FewShotPromptTemplate은 기존 examples(예제 데이터)를 활용하여 모델이 유사한 질문에 답변을 잘하도록 유도함.
• suffix="Human: What do you know about {country}?"
• 사용자가 입력한 국가(country)에 대해 질문하는 형식으로 생성됨.
• input_variables=["question"]: 변수로 question을 사용하지만, 사실 country가 핵심.
📌 5. 체인 연결 (chain)
chain = few_shot_prompt | chat
✅ 설명
• few_shot_prompt와 chat을 체인 형태로 연결하여 프롬프트를 자동으로 모델에 전달.
• LangChain의 | 연산자를 활용하여 프롬프트 → 챗 모델의 파이프라인을 구축.
📌 6. 체인 실행 (invoke)
chain.invoke({"country": "Turkey"})
✅ 설명
• invoke({"country": "Turkey"}): country="Turkey"을 입력하면 프롬프트가 자동으로 생성되어 OpenAI 모델에 전달됨.
• 최종 프롬프트 예시:
Human: What do you know about France?
AI: Here is what I know:
Capital: Paris
Language: French
Food: Wine and Cheese
Currency: Euro
Human: What do you know about Italy?
AI: I know this:
Capital: Rome
Language: Italian
Food: Pizza and Pasta
Currency: Euro
Human: What do you know about Greece?
AI: I know this:
Capital: Athens
Language: Greek
Food: Souvlaki and Feta Cheese
Currency: Euro
Human: What do you know about Turkey?
• 이제 OpenAI 모델이 학습한 패턴을 기반으로 터키에 대한 정보를 생성하여 응답함.
🔥 전체적인 코드 흐름
ChatOpenAI를 설정하여 GPT-3.5를 사용.
Few-Shot Learning을 위해 나라별 예제 데이터를 정의.
PromptTemplate을 사용하여 데이터의 포맷을 정리.
FewShotPromptTemplate을 이용하여 학습된 데이터와 새로운 질문을 결합.
chain.invoke({"country": "Turkey"})를 실행하면 터키에 대한 정보를 생성.
✅ 이 코드가 유용한 이유
• Few-Shot Learning을 활용하여 모델이 특정 패턴을 학습하고 유사한 질문에 대해 좋은 답변을 생성함.
• 기존 데이터(examples)를 확장하면 더 많은 국가 정보를 쉽게 추가할 수 있음.
• LangChain을 사용하여 프롬프트 엔지니어링을 효율적으로 수행할 수 있음.
📌 추가 개선 가능점
• examples 리스트에 여러 국가를 추가하면 모델의 성능이 향상될 수 있음.
• 응답을 더 깔끔하게 정리하거나 JSON 형식으로 변환 가능.
• Memory 기능을 추가하여 대화형 챗봇처럼 작동하도록 확장할 수 있음.