Spaces:
Sleeping
Sleeping
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}") | |