gschatbot_1 / chatbot.py
songhune's picture
Update space
1c3da04
raw
history blame
2.77 kB
import os
import json
from datetime import datetime
from openai import OpenAI
from huggingface_hub import InferenceClient
from dotenv import load_dotenv
from scenario_handler import ScenarioHandler
# Initialize the OpenAI client
load_dotenv()
api_key = os.getenv('OPENAI_API_KEY')
+ client = InferenceClient(
base_url=...,
api_key=...,
)
# ์ „์—ญ ๋Œ€ํ™” ๊ธฐ๋ก ๋ฐ ScenarioHandler ์ธ์Šคํ„ด์Šค
global_history = []
scenario_handler = ScenarioHandler() # ์ „์—ญ์œผ๋กœ ScenarioHandler ์ธ์Šคํ„ด์Šค ์ƒ์„ฑ
def get_global_history():
global global_history
return global_history
def set_global_history(history):
global global_history
global_history = history
def chatbot_response(response, context={}):
history = get_global_history() # ์ „์—ญ ๋ณ€์ˆ˜ ์‚ฌ์šฉ
# Ensure all items in history are dictionaries with 'role' and 'content' keys
if not all(isinstance(h, dict) and 'role' in h and 'content' in h for h in history):
history = [] # Reset history if it is invalid
# Add user's message to history
history.append({"role": "user", "content": response})
# Initialize messages
if len(history) == 1: # ์ฒซ ๋Œ€ํ™”์ผ ๊ฒฝ์šฐ
messages = scenario_handler.get_response(history[0]['content'].strip().lower())
else:
messages=history # ์ด์ „ ๋Œ€ํ™” ๊ธฐ๋ก ์ถ”๊ฐ€
# Generate the assistant's response
api_response = client.chat.completions.create(
model="gpt-4",
temperature=0.8,
top_p=0.9,
max_tokens=300,
n=1,
frequency_penalty=0.5,
presence_penalty=0.5,
messages=messages
)
# Get the assistant's response text
assistant_response = api_response.choices[0].message.content
# Append the assistant's response to history
if len(history) == 1: # ์ฒซ ๋Œ€ํ™”์ผ ๊ฒฝ์šฐ
history.append(messages[0])
history.append({"role": "assistant", "content": assistant_response})
set_global_history(history) # ์—…๋ฐ์ดํŠธ๋œ ๊ธฐ๋ก ์„ค์ •
# Check if the user wants to end the session
if response.strip().lower() == "์ข…๋ฃŒ":
save_history(history) # Save the history if the keyword "์ข…๋ฃŒ" is detected
return "์„ธ์…˜์„ ์ €์žฅํ•˜๊ณ  ์ข…๋ฃŒํ•ฉ๋‹ˆ๋‹ค."
# Return the assistant's response
return assistant_response
def save_history(history):
# Generate a timestamped filename for the JSON file
os.makedirs('logs', exist_ok=True)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = os.path.join('logs', f'chat_history_{timestamp}.json')
# Save session history to a JSON file
with open(filename, 'w', encoding='utf-8') as file:
json.dump(history, file, ensure_ascii=False, indent=4)
print(f"History saved to {filename}")