안녕하세요! 우리는 파이썬과 LangChain 라이브러리를 사용하여 역사적인 날짜를 맞추는 퀴즈봇을 만들 것입니다. 이 과정을 통해 다음과 같은 핵심 개념을 배우게 됩니다:
LangChain은 대형 언어 모델과의 상호 작용을 보다 쉽게 만들어주는 파이썬 라이브러리입니다. 프롬프트 템플릿, 출력 파서, 체인 등을 제공하여 개발자가 모델과의 대화를 구조화하고 제어할 수 있게 합니다.
먼저 프로젝트에 필요한 라이브러리를 설치합니다.
pip install openai langchain python-dotenv
.env
파일에 저장된 환경 변수를 로드하는 데 사용합니다.OpenAI API를 사용하려면 API 키가 필요합니다. 안전한 관리를 위해 .env
파일에 저장합니다.
# .env 파일 내용
OPENAI_API_KEY=your_openai_api_key_here
파이썬 코드에서 python-dotenv
를 사용하여 환경 변수를 로드합니다.
from dotenv import load_dotenv
load_dotenv()
import os
from langchain.chat_models import ChatOpenAI
from langchain.prompts import (
ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate
)
from langchain.output_parsers import DateTimeOutputParser
from datetime import datetime
클래스를 사용하여 코드를 구조화하면 재사용성과 유지보수성이 높아집니다.
class HistoryQuizBot:
def __init__(self):
# OpenAI의 GPT 모델 초기화
self.chat_model = ChatOpenAI(
model_name='gpt-3.5-turbo',
temperature=0,
openai_api_key=os.getenv("OPENAI_API_KEY")
)
__init__
메서드: 클래스 인스턴스가 생성될 때 실행되며, 여기서 채팅 모델을 초기화합니다.temperature=0
: 모델의 응답을 결정적으로 만들어 동일한 입력에 동일한 출력을 얻습니다.generate_question
)이 메서드는 특정 주제에 대한 역사적인 질문을 생성합니다.
def generate_question(self, topic):
# 시스템 프롬프트 설정
system_template = (
"당신은 역사적인 날짜에 대한 퀴즈를 내는 봇입니다. "
"{topic}에 관한 정확한 날짜가 정답인 퀴즈 질문을 하나 내주세요. "
"질문만 출력하고 추가 설명은 하지 마세요."
)
system_prompt = SystemMessagePromptTemplate.from_template(system_template)
{topic}
변수를 사용하여 동적으로 주제를 지정합니다.SystemMessagePromptTemplate
를 사용하여 시스템 프롬프트를 생성합니다. # 인간 프롬프트 설정
human_template = "퀴즈를 생성해주세요."
human_prompt = HumanMessagePromptTemplate.from_template(human_template)
# 프롬프트 컴파일
chat_prompt = ChatPromptTemplate.from_messages([system_prompt, human_prompt])
prompt = chat_prompt.format_prompt(topic=topic)
messages = prompt.to_messages()
format_prompt
: 프롬프트에 필요한 변수를 삽입합니다. # 질문 생성
response = self.chat_model(messages)
question = response.content.strip()
return question
get_answer
)이 메서드는 생성된 질문에 대한 정확한 날짜를 모델을 통해 얻습니다.
def get_answer(self, question):
# 출력 파서 생성
parser = DateTimeOutputParser()
datetime
객체)으로 파싱합니다.DateTimeOutputParser
: 날짜 정보를 추출하는 데 사용됩니다. # 시스템 프롬프트 설정
system_template = "당신은 역사적인 사건의 날짜를 알려주는 전문가입니다."
system_prompt = SystemMessagePromptTemplate.from_template(system_template)
# 인간 프롬프트 설정
human_template = (
"{question}\n\n"
"{format_instructions}"
)
human_prompt = HumanMessagePromptTemplate.from_template(human_template)
{question}
: 이전에 생성한 질문을 삽입합니다.{format_instructions}
: 파서가 요구하는 형식 지시사항을 삽입합니다. # 프롬프트 컴파일
chat_prompt = ChatPromptTemplate.from_messages([system_prompt, human_prompt])
prompt = chat_prompt.format_prompt(
question=question,
format_instructions=parser.get_format_instructions()
)
messages = prompt.to_messages()
parser.get_format_instructions()
: 파서가 요구하는 형식 지시사항을 얻습니다. # 정답 얻기 및 파싱
response = self.chat_model(messages)
answer = parser.parse(response.content)
return answer
datetime
객체로 변환합니다.모델의 응답은 사람이 읽기에는 좋지만, 프로그램에서 바로 사용하기에는 적합하지 않을 수 있습니다. 출력 파서를 사용하면 모델의 응답을 구조화된 형식으로 변환하여 프로그램에서 쉽게 활용할 수 있습니다.
get_user_response
)사용자로부터 날짜를 입력받는 메서드입니다.
def get_user_response(self, question):
print(f"질문: {question}")
print("날짜를 추측해 보세요.")
year = int(input("연도를 입력하세요 (예: 1969): "))
month = int(input("월을 입력하세요 (1-12): "))
day = int(input("일을 입력하세요 (1-31): "))
user_date = datetime(year, month, day)
return user_date
datetime
객체 생성: 입력받은 값을 사용하여 datetime
객체를 만듭니다.check_user_answer
)사용자의 답변과 실제 정답의 차이를 계산하여 알려주는 메서드입니다.
def check_user_answer(self, user_answer, correct_answer):
difference = abs(correct_answer - user_answer)
days_difference = difference.days
print(f"정답과 {days_difference}일 차이가 있습니다.")
datetime
객체의 차이를 계산합니다.timedelta
객체의 days
속성을 사용하여 일 수를 얻습니다.def main():
# 퀴즈봇 인스턴스 생성
bot = HistoryQuizBot()
# 주제 설정
topic = "달 착륙"
# 질문 생성
question = bot.generate_question(topic)
# 정답 얻기
correct_answer = bot.get_answer(question)
# 사용자로부터 답변 받기
user_answer = bot.get_user_response(question)
# 답변 확인
bot.check_user_answer(user_answer, correct_answer)
if __name__ == "__main__":
main()
HistoryQuizBot
의 인스턴스를 만듭니다.__name__ == "__main__"
: 이 스크립트가 직접 실행될 때만 main()
함수를 호출합니다.프롬프트 엔지니어링은 대형 언어 모델과의 상호 작용에서 매우 중요한 역할을 합니다. 올바른 프롬프트를 구성함으로써 모델이 원하는 방식으로 응답하도록 유도할 수 있습니다.
LangChain은 모델의 출력을 파싱하는 데 도움을 주는 여러 파서를 제공합니다. 이 프로젝트에서는 DateTimeOutputParser
를 사용하여 모델의 응답을 datetime
객체로 변환했습니다.
체인(Chains)은 여러 개의 프롬프트와 모델 호출을 연결하여 복잡한 작업을 수행할 수 있게 합니다. 이 프로젝트에서는 간단한 형태의 체인을 사용하여 다음과 같은 작업을 순차적으로 수행했습니다.
LangChain을 사용하면 이러한 작업들을 더 복잡하게 연결하고 관리할 수 있습니다.
실제 애플리케이션에서는 사용자 입력 오류나 모델 응답 오류에 대비한 에러 처리가 필요합니다.
이 프로젝트를 기반으로 다양한 확장이 가능합니다.
import os
from dotenv import load_dotenv
from langchain.chat_models import ChatOpenAI
from langchain.prompts import (
ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate
)
from datetime import datetime
import re
# 환경 변수 로드
load_dotenv()
class HistoryQuizBot:
def __init__(self):
self.chat_model = ChatOpenAI(
model_name='gpt-3.5-turbo',
temperature=0,
openai_api_key=os.getenv("OPENAI_API_KEY")
)
def generate_question(self, topic):
# 시스템 프롬트 설정
system_template = (
"당신은 역사적인 날짜에 대한 퀴즈를 내는 볼입니다. "
"{topic}에 관한 정확한 날짜가 정답인 퀴즈 질문을 하나 내주세요. "
"질문만 출력하고 추가 설명은 하지 마세요."
)
system_prompt = SystemMessagePromptTemplate.from_template(system_template)
# 인간 프롬트 설정
human_template = "퀴즈를 생성해주세요."
human_prompt = HumanMessagePromptTemplate.from_template(human_template)
# 프롬트 컨피백
chat_prompt = ChatPromptTemplate.from_messages([system_prompt, human_prompt])
prompt = chat_prompt.format_prompt(topic=topic)
messages = prompt.to_messages()
# 질문 생성
response = self.chat_model(messages=messages)
question = response.content.strip()
return question
def get_answer(self, question):
# 시스템 프롬트 설정
system_template = "당신은 역사적인 사건의 날짜를 알려주는 전문가입니다. 날짜는 반드시 'YYYY-MM-DD' 형식으로만 제공해 주세요."
system_prompt = SystemMessagePromptTemplate.from_template(system_template)
# 인간 프롬트 설정
human_template = "{question}에 대한 정확한 날짜를 알려주세요."
human_prompt = HumanMessagePromptTemplate.from_template(human_template)
# 프롬트 컨피백
chat_prompt = ChatPromptTemplate.from_messages([system_prompt, human_prompt])
prompt = chat_prompt.format_prompt(question=question)
messages = prompt.to_messages()
# 정답 얻기
response = self.chat_model(messages=messages)
answer_text = response.content.strip()
# 날짜 파싱 시도
try:
match = re.search(r"\d{4}-\d{2}-\d{2}", answer_text)
if match:
correct_answer = datetime.strptime(match.group(), "%Y-%m-%d")
else:
print("정확한 날짜 형식을 파싱할 수 없습니다.")
correct_answer = None
except ValueError:
print("정확한 날짜 형식을 파싱할 수 없습니다.")
correct_answer = None
return correct_answer
def get_user_response(self, question):
print(f"질문: {question}")
print("날짜를 추측해 보세요.")
try:
year = int(input("연도를 입력하세요 (예: 1969): "))
month = int(input("월을 입력하세요 (1-12): "))
day = int(input("일을 입력하세요 (1-31): "))
user_date = datetime(year, month, day)
return user_date
except ValueError:
print("잘못된 입력입니다. 다시 시도해주세요.")
return self.get_user_response(question)
def check_user_answer(self, user_answer, correct_answer):
if correct_answer is None:
print("정확한 날짜를 확인할 수 없습니다.")
return
difference = abs(correct_answer - user_answer)
days_difference = difference.days
print(f"정답과 {days_difference}일 차이가 있습니다.")
def main():
bot = HistoryQuizBot()
topic = input("퀴즈 주제를 입력하세요 (예: '제2차 세계 대전'): ")
question = bot.generate_question(topic)
correct_answer = bot.get_answer(question)
user_answer = bot.get_user_response(question)
bot.check_user_answer(user_answer, correct_answer)
if __name__ == "__main__":
main()
퀴즈 주제를 입력하세요 (예: '제2차 세계 대전'): 프랑스 혁명
질문: 프랑스 혁명이 시작된 날짜는 언제인가요?
날짜를 추측해 보세요.
연도를 입력하세요 (예: 1969): 1789
월을 입력하세요 (1-12): 7
일을 입력하세요 (1-31): 14
정답과 0일 차이가 있습니다.
이번 프로젝트를 통해 우리는 LangChain을 활용하여 대형 언어 모델과 효과적으로 상호 작용하는 방법을 배웠습니다. 특히, 프롬프트 엔지니어링과 출력 파싱의 중요성을 이해하고, 이를 통해 모델의 응답을 제어하고 활용하는 방법을 익혔습니다.
이러한 개념들은 자연어 처리 및 인공지능 애플리케이션 개발에 있어 핵심적인 요소입니다. 이번 기회를 통해 더욱 깊이 있는 이해를 하셨기를 바랍니다.
즐거운 코딩 되세요! 추가로 궁금한 점이나 도움이 필요한 부분이 있다면 언제든지 질문해 주세요.