Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,13 +1,64 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
import os
|
| 3 |
import requests
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
groq_key = os.getenv("GROQ_API_KEY")
|
| 6 |
-
MODEL = "
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
status_msg = "❌ Chưa set GROQ_API_KEY"
|
| 9 |
if groq_key:
|
| 10 |
-
status_msg = f"✅
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
def call_groq(messages):
|
| 13 |
url = "https://api.groq.com/openai/v1/chat/completions"
|
|
@@ -25,42 +76,105 @@ def call_groq(messages):
|
|
| 25 |
|
| 26 |
try:
|
| 27 |
response = requests.post(url, headers=headers, json=data, timeout=20)
|
| 28 |
-
if response.status_code
|
| 29 |
-
return f"❌ Model lỗi. Thử: llama-3.3-70b-versatile"
|
| 30 |
-
return response.json()["choices"][0]["message"]["content"]
|
| 31 |
-
except:
|
| 32 |
-
# Fallback model nếu lỗi
|
| 33 |
-
data["model"] = "mixtral-8x7b-32768"
|
| 34 |
-
try:
|
| 35 |
-
response = requests.post(url, headers=headers, json=data, timeout=20)
|
| 36 |
return response.json()["choices"][0]["message"]["content"]
|
| 37 |
-
|
| 38 |
-
|
|
|
|
| 39 |
|
| 40 |
-
def respond(message, history):
|
| 41 |
-
|
| 42 |
-
return "", history + [{"role": "assistant", "content": status_msg}]
|
| 43 |
|
| 44 |
-
|
| 45 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
reply = call_groq(messages)
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
-
|
| 51 |
-
|
|
|
|
|
|
|
|
|
|
| 52 |
gr.Markdown(f"**Status:** {status_msg}")
|
| 53 |
|
| 54 |
-
chatbot = gr.Chatbot(height=500, avatar_images=("👤", "🤖"))
|
| 55 |
-
|
| 56 |
with gr.Row():
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
|
| 61 |
-
|
| 62 |
-
send_btn.click(respond, [msg, chatbot], [msg, chatbot])
|
| 63 |
-
clear_btn.click(lambda: [], None, chatbot)
|
| 64 |
|
| 65 |
if __name__ == "__main__":
|
| 66 |
-
demo.launch(
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import os
|
| 3 |
import requests
|
| 4 |
+
import json
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
import hashlib
|
| 7 |
|
| 8 |
groq_key = os.getenv("GROQ_API_KEY")
|
| 9 |
+
MODEL = "llama3-groq-70b-8192-tool-use-preview" # Model 2026 preview
|
| 10 |
+
|
| 11 |
+
# User management
|
| 12 |
+
users = {} # {username: {"token": hash, "history": []}}
|
| 13 |
+
current_user = None
|
| 14 |
|
| 15 |
status_msg = "❌ Chưa set GROQ_API_KEY"
|
| 16 |
if groq_key:
|
| 17 |
+
status_msg = f"✅ Groq {MODEL} Ready"
|
| 18 |
+
|
| 19 |
+
def hash_token(token):
|
| 20 |
+
return hashlib.sha256(token.encode()).hexdigest()
|
| 21 |
+
|
| 22 |
+
def login(username, password):
|
| 23 |
+
global current_user
|
| 24 |
+
token = hash_token(f"{username}:{password}")
|
| 25 |
+
if token in users:
|
| 26 |
+
current_user = username
|
| 27 |
+
return f"✅ Đăng nhập thành công: {username}", gr.update(visible=True), gr.update(visible=False)
|
| 28 |
+
else:
|
| 29 |
+
return "❌ Sai tên đăng nhập/mật khẩu", gr.update(visible=False), gr.update(visible=True)
|
| 30 |
+
|
| 31 |
+
return "❌ Lỗi đăng nhập", gr.update(visible=False), gr.update(visible=True)
|
| 32 |
+
|
| 33 |
+
def logout():
|
| 34 |
+
global current_user
|
| 35 |
+
current_user = None
|
| 36 |
+
return "👋 Đã đăng xuất", gr.update(visible=False), gr.update(visible=True), []
|
| 37 |
+
|
| 38 |
+
def save_chat(username, message, reply):
|
| 39 |
+
"""Lưu tin nhắn vào history user"""
|
| 40 |
+
if username not in users:
|
| 41 |
+
users[username] = {"history": []}
|
| 42 |
+
|
| 43 |
+
users[username]["history"].append({
|
| 44 |
+
"timestamp": datetime.now().strftime("%H:%M"),
|
| 45 |
+
"user": message,
|
| 46 |
+
"ai": reply
|
| 47 |
+
})
|
| 48 |
+
|
| 49 |
+
# Giữ 50 tin nhắn gần nhất
|
| 50 |
+
if len(users[username]["history"]) > 50:
|
| 51 |
+
users[username]["history"] = users[username]["history"][-50:]
|
| 52 |
+
|
| 53 |
+
def load_history(username):
|
| 54 |
+
"""Load lịch sử chat"""
|
| 55 |
+
if username in users and users[username]["history"]:
|
| 56 |
+
return [
|
| 57 |
+
[{"role": "user", "content": h["user"]},
|
| 58 |
+
{"role": "assistant", "content": h["ai"]}]
|
| 59 |
+
for h in users[username]["history"][-10:]
|
| 60 |
+
]
|
| 61 |
+
return []
|
| 62 |
|
| 63 |
def call_groq(messages):
|
| 64 |
url = "https://api.groq.com/openai/v1/chat/completions"
|
|
|
|
| 76 |
|
| 77 |
try:
|
| 78 |
response = requests.post(url, headers=headers, json=data, timeout=20)
|
| 79 |
+
if response.status_code == 200:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
return response.json()["choices"][0]["message"]["content"]
|
| 81 |
+
return f"❌ Lỗi {response.status_code}"
|
| 82 |
+
except:
|
| 83 |
+
return "❌ Không kết nối Groq"
|
| 84 |
|
| 85 |
+
def respond(message, history, username):
|
| 86 |
+
global current_user
|
|
|
|
| 87 |
|
| 88 |
+
if not current_user:
|
| 89 |
+
return "", history, "❌ Vui lòng đăng nhập!"
|
| 90 |
+
|
| 91 |
+
# Simple messages (no complex history)
|
| 92 |
+
messages = [
|
| 93 |
+
{"role": "system", "content": "Bạn là NodeAI - trợ lý AI tiếng Việt thông minh, hữu ích."},
|
| 94 |
+
{"role": "user", "content": message}
|
| 95 |
+
]
|
| 96 |
|
| 97 |
reply = call_groq(messages)
|
| 98 |
+
|
| 99 |
+
# Lưu history
|
| 100 |
+
save_chat(current_user, message, reply)
|
| 101 |
+
|
| 102 |
+
new_history = history + [{"role": "user", "content": message}, {"role": "assistant", "content": reply}]
|
| 103 |
+
return "", new_history, f"👤 {current_user}"
|
| 104 |
|
| 105 |
+
def load_user_history(username):
|
| 106 |
+
return load_history(username)
|
| 107 |
+
|
| 108 |
+
with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue")) as demo:
|
| 109 |
+
gr.Markdown("# 🚀 NodeAI - AI Chat với Login & History")
|
| 110 |
gr.Markdown(f"**Status:** {status_msg}")
|
| 111 |
|
|
|
|
|
|
|
| 112 |
with gr.Row():
|
| 113 |
+
# Sidebar - Login & History
|
| 114 |
+
with gr.Column(scale=1, min_width=300):
|
| 115 |
+
gr.Markdown("## 👤 Tài khoản")
|
| 116 |
+
|
| 117 |
+
with gr.Group(visible=True) as login_group:
|
| 118 |
+
username = gr.Textbox(label="Tên đăng nhập", placeholder="yourname")
|
| 119 |
+
password = gr.Textbox(label="Mật khẩu", type="password")
|
| 120 |
+
login_btn = gr.Button("🔐 Đăng nhập", variant="primary")
|
| 121 |
+
|
| 122 |
+
with gr.Group(visible=False) as user_group:
|
| 123 |
+
gr.Markdown("### ✅ Đã đăng nhập")
|
| 124 |
+
user_info = gr.Markdown("**Chưa có user**")
|
| 125 |
+
logout_btn = gr.Button("🚪 Đăng xuất", variant="stop")
|
| 126 |
+
load_history_btn = gr.Button("📚 Load History")
|
| 127 |
+
|
| 128 |
+
history_display = gr.Chatbot(
|
| 129 |
+
height=300,
|
| 130 |
+
label="Lịch sử chat",
|
| 131 |
+
visible=False
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
# Main Chat
|
| 135 |
+
with gr.Column(scale=4):
|
| 136 |
+
chatbot = gr.Chatbot(height=500, avatar_images=("👤", "🤖"))
|
| 137 |
+
status_display = gr.Markdown("**Chưa đăng nhập**")
|
| 138 |
+
|
| 139 |
+
with gr.Row():
|
| 140 |
+
msg = gr.Textbox(placeholder="Hỏi NodeAI...", scale=7)
|
| 141 |
+
send_btn = gr.Button("Gửi", variant="primary", scale=1)
|
| 142 |
+
clear_btn = gr.Button("🗑️", scale=1)
|
| 143 |
+
|
| 144 |
+
# Events
|
| 145 |
+
login_btn.click(
|
| 146 |
+
login,
|
| 147 |
+
inputs=[username, password],
|
| 148 |
+
outputs=[status_display, user_group, login_group]
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
logout_btn.click(
|
| 152 |
+
logout,
|
| 153 |
+
outputs=[status_display, login_group, user_group, history_display]
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
load_history_btn.click(
|
| 157 |
+
load_user_history,
|
| 158 |
+
inputs=gr.State(),
|
| 159 |
+
outputs=history_display
|
| 160 |
+
).then(
|
| 161 |
+
lambda x: gr.update(visible=True),
|
| 162 |
+
outputs=[history_display]
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
send_btn.click(
|
| 166 |
+
respond,
|
| 167 |
+
inputs=[msg, chatbot, gr.State()],
|
| 168 |
+
outputs=[msg, chatbot, status_display]
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
msg.submit(
|
| 172 |
+
respond,
|
| 173 |
+
inputs=[msg, chatbot, gr.State()],
|
| 174 |
+
outputs=[msg, chatbot, status_display]
|
| 175 |
+
)
|
| 176 |
|
| 177 |
+
clear_btn.click(lambda: [], outputs=chatbot)
|
|
|
|
|
|
|
| 178 |
|
| 179 |
if __name__ == "__main__":
|
| 180 |
+
demo.launch()
|