import google.generativeai as genai import os import json from google.generativeai.types import content_types
class PersistentGeminiChat: def __init__(self, model_name='gemini-2.5-flash', session_file='gemini_chat.json'): genai.configure(api_key=os.environ['GOOGLE_API_KEY']) self.model = genai.GenerativeModel(model_name) self.session_file = session_file
history = self.load_history() self.chat = self.model.start_chat(history=history)
def load_history(self): """저장된 대화 불러오기""" try: with open(self.session_file, 'r', encoding='utf-8') as f: data = json.load(f)
history = [] for msg in data: history.append({ 'role': msg['role'], 'parts': [msg['content']] }) return history except FileNotFoundError: return []
def save_history(self): """대화 저장""" history_data = [] for msg in self.chat.history: history_data.append({ 'role': msg.role, 'content': msg.parts[0].text })
with open(self.session_file, 'w', encoding='utf-8') as f: json.dump(history_data, f, ensure_ascii=False, indent=2)
def send(self, message): """메시지 전송 및 자동 저장""" response = self.chat.send_message(message) self.save_history() return response.text
chat = PersistentGeminiChat()
print(chat.send('안녕하세요!')) print(chat.send('내 이름은 김철수야'))
|