|
import gradio as gr |
|
import ssl |
|
from openai import OpenAI |
|
import time |
|
|
|
|
|
try: |
|
_create_unverified_https_context = ssl._create_unverified_context |
|
except AttributeError: |
|
pass |
|
else: |
|
ssl._create_default_https_context = _create_unverified_https_context |
|
|
|
|
|
client = OpenAI( |
|
base_url='https://api.openai-proxy.org/v1', |
|
api_key='sk-Nxf8HmLpfIMhCd83n3TOr00TR57uBZ0jMbAgGCOzppXvlsx1', |
|
) |
|
|
|
|
|
def openai_api_call(messages, retries=3, delay=5): |
|
for attempt in range(retries): |
|
try: |
|
completion = client.chat.completions.create( |
|
model="gpt-3.5-turbo", |
|
messages=messages, |
|
timeout=10 |
|
) |
|
return completion.choices[0].message.content |
|
except Exception as e: |
|
print(f"Attempt {attempt + 1} failed: {e}") |
|
time.sleep(delay) |
|
return "Sorry, I am having trouble connecting to the server. Please try again later." |
|
|
|
|
|
def chatbot_response(message, history): |
|
|
|
messages = [{"role": "system", "content": "You are a dynamic study resoruce database named Arcana. Your goal is to help students study and excel their exams."}] |
|
for human, assistant in history: |
|
messages.append({"role": "user", "content": human}) |
|
messages.append({"role": "assistant", "content": assistant}) |
|
messages.append({"role": "user", "content": message}) |
|
|
|
|
|
response = openai_api_call(messages) |
|
return response |
|
|
|
|
|
iface = gr.ChatInterface( |
|
chatbot_response, |
|
chatbot=gr.Chatbot(height=300), |
|
textbox=gr.Textbox(placeholder="Type your message here...", container=False, scale=7), |
|
title="Review With Arcana", |
|
description="ArcanaUI v0.7", |
|
theme="soft", |
|
examples=[ |
|
"What is Hydrogen Bonding?", |
|
"Tell me the difference between impulse and force.", |
|
"Tell me a joke that Calculus students will know.", |
|
"How should I review for the AP Biology Exam?" |
|
], |
|
cache_examples=False, |
|
retry_btn=None, |
|
undo_btn="Delete Previous", |
|
clear_btn="Clear", |
|
) |
|
|
|
|
|
iface.launch(share=True) |
|
|