Spaces:
Running
Running
File size: 5,398 Bytes
0588a72 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 |
import gradio as gr
import requests
import json
import os
from datetime import datetime
# API configuration from environment variables
API_ENDPOINT = os.getenv("API_ENDPOINT", "none")
API_TOKEN = os.getenv("API_TOKEN")
def get_ai_response(message, history):
messages = [{"role": "user", "content": "You are a helpful assistant"}]
for user_msg, ai_msg in history:
messages.append({"role": "user", "content": user_msg})
messages.append({"role": "assistant", "content": ai_msg})
messages.append({"role": "user", "content": message})
payload = {
"model": "RekaAI/reka-flash-3",
"messages": messages,
"stream": False,
"max_tokens": 1024,
"temperature": 0.7
}
headers = {
"Authorization": f"Bearer {API_TOKEN}",
"Content-Type": "application/json"
}
try:
response = requests.post(API_ENDPOINT, headers=headers, json=payload)
response.raise_for_status()
return response.json()["choices"][0]["message"]["content"]
except Exception as e:
return f"Error: {str(e)}"
def chat_interface(message, history, stored_history):
if history is None:
history = []
ai_response = get_ai_response(message, history)
history.append((message, ai_response))
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
if stored_history is None:
stored_history = []
stored_history.insert(0, { # Insert at beginning for reverse chronological order
"timestamp": timestamp,
"user": message,
"ai": ai_response
})
return history, stored_history
# Modern black and white CSS
custom_css = """
body {
background-color: #1a1a1a;
color: #ffffff;
font-family: 'Arial', sans-serif;
}
#chatbot {
height: 60vh;
background-color: #2d2d2d;
border: 1px solid #404040;
border-radius: 8px;
}
#sidebar {
background-color: #242424;
padding: 10px;
border-right: 1px solid #404040;
height: 80vh;
overflow-y: auto;
}
#history_list {
list-style: none;
padding: 0;
}
.history-item {
background-color: #333333;
margin: 5px 0;
padding: 10px;
border-radius: 5px;
cursor: pointer;
}
.history-item:hover {
background-color: #404040;
}
input, button {
background-color: #333333;
color: #ffffff;
border: 1px solid #404040;
border-radius: 5px;
}
button:hover {
background-color: #404040;
}
"""
with gr.Blocks(css=custom_css, title="Modern AI Chatbot") as demo:
with gr.Row():
# Sidebar for history
with gr.Column(scale=1, min_width=300, elem_id="sidebar"):
gr.Markdown("## Chat History")
history_display = gr.HTML(label="Previous Conversations")
clear_history_btn = gr.Button("Clear History")
# Main chat area
with gr.Column(scale=3):
chatbot = gr.Chatbot(elem_id="chatbot")
with gr.Row():
message = gr.Textbox(
placeholder="Type your message...",
show_label=False,
container=False,
elem_classes="input-box"
)
submit_btn = gr.Button("Send", size="sm")
clear_chat_btn = gr.Button("Clear Chat")
# States
chat_state = gr.State([])
history_state = gr.State([])
def update_history_display(stored_history):
if not stored_history:
return "<p>No history yet</p>"
html = "<ul id='history_list'>"
for item in stored_history[:10]: # Limit to last 10 conversations
html += f"""
<li class='history-item'>
<small>{item['timestamp']}</small><br>
<strong>You:</strong> {item['user'][:50]}...<br>
<strong>AI:</strong> {item['ai'][:50]}...
</li>
"""
html += "</ul>"
return html
# Event handlers
submit_btn.click(
chat_interface,
[message, chat_state, history_state],
[chatbot, history_state]
).then(
update_history_display,
history_state,
history_display
).then(
lambda: "",
None,
message
)
clear_chat_btn.click(
lambda: ([], None),
None,
[chatbot, chat_state]
)
clear_history_btn.click(
lambda: ([], None),
None,
[history_state, history_display]
)
# Initial load
demo.load(
lambda: ([], []),
None,
[chat_state, history_state]
).then(
update_history_display,
history_state,
history_display
)
# Update local storage
demo.change(
None,
history_state,
None,
_js="""(stored_history) => {
localStorage.setItem('chat_history', JSON.stringify(stored_history));
}"""
).then(
update_history_display,
history_state,
history_display
)
# Load from local storage
demo.load(
lambda: json.loads(localStorage.getItem('chat_history') or '[]'),
None,
history_state,
_js="""() => {
return localStorage.getItem('chat_history') || '[]';
}"""
).then(
update_history_display,
history_state,
history_display
)
demo.launch() |