Spaces:
Running
Running
added correct gradio code
Browse files
app.py
CHANGED
|
@@ -1,56 +1,36 @@
|
|
| 1 |
import os
|
| 2 |
-
import traceback
|
| 3 |
import requests
|
| 4 |
-
|
| 5 |
-
|
| 6 |
from dotenv import load_dotenv
|
| 7 |
|
| 8 |
-
# Load
|
| 9 |
load_dotenv()
|
| 10 |
|
| 11 |
# Configuration
|
| 12 |
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
|
| 13 |
-
OPENROUTER_MODEL = os.getenv("OPENROUTER_MODEL"
|
| 14 |
APP_TITLE = os.getenv("APP_TITLE", "Selva Chat Bot")
|
| 15 |
OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions"
|
| 16 |
|
| 17 |
-
# Create Flask app
|
| 18 |
-
app = Flask(__name__)
|
| 19 |
-
|
| 20 |
-
# Enable CORS for all routes
|
| 21 |
-
CORS(app, origins=["*"])
|
| 22 |
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
def health():
|
| 29 |
-
redacted = OPENROUTER_API_KEY[:8] + "..." if OPENROUTER_API_KEY else ""
|
| 30 |
-
return jsonify({"ok": True, "model": OPENROUTER_MODEL, "key": redacted})
|
| 31 |
-
|
| 32 |
-
@app.route("/api/chat", methods=["POST"])
|
| 33 |
-
def chat():
|
| 34 |
try:
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
history = payload.get("history") or []
|
| 38 |
|
| 39 |
-
|
| 40 |
-
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
# Build messages array
|
| 46 |
-
messages = []
|
| 47 |
-
if not any(m.get("role") == "system" for m in history):
|
| 48 |
-
messages.append({
|
| 49 |
-
"role": "system",
|
| 50 |
-
"content": "You are a helpful, concise, and friendly assistant for Selva's Chat-Bot."
|
| 51 |
-
})
|
| 52 |
-
messages.extend([m for m in history if m.get("role") in ("system", "user", "assistant")])
|
| 53 |
-
messages.append({"role": "user", "content": user_message})
|
| 54 |
|
| 55 |
# API request
|
| 56 |
headers = {
|
|
@@ -58,20 +38,19 @@ def chat():
|
|
| 58 |
"Content-Type": "application/json",
|
| 59 |
"X-Title": APP_TITLE,
|
| 60 |
}
|
| 61 |
-
|
| 62 |
body = {
|
| 63 |
"model": OPENROUTER_MODEL,
|
| 64 |
"messages": messages,
|
| 65 |
"temperature": 0.7,
|
| 66 |
-
"max_tokens": 1000
|
| 67 |
}
|
| 68 |
|
| 69 |
response = requests.post(OPENROUTER_URL, headers=headers, json=body, timeout=30)
|
| 70 |
|
| 71 |
if response.status_code != 200:
|
| 72 |
error_data = response.json() if response.headers.get('content-type') == 'application/json' else {"error": response.text}
|
| 73 |
-
error_message = error_data.get("error",
|
| 74 |
-
return
|
| 75 |
|
| 76 |
data = response.json()
|
| 77 |
reply = (
|
|
@@ -80,19 +59,28 @@ def chat():
|
|
| 80 |
.get("content", "Sorry, I couldn't generate a response.")
|
| 81 |
)
|
| 82 |
|
| 83 |
-
return
|
| 84 |
|
| 85 |
except requests.exceptions.Timeout:
|
| 86 |
-
return
|
| 87 |
-
except requests.exceptions.RequestException as e:
|
| 88 |
-
print(f"Request error: {e}")
|
| 89 |
-
return jsonify({"error": "Failed to connect to AI service."}), 503
|
| 90 |
except Exception as e:
|
| 91 |
-
print(f"Unexpected error: {e}")
|
| 92 |
traceback.print_exc()
|
| 93 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
|
| 95 |
-
# Hugging Face
|
| 96 |
if __name__ == "__main__":
|
| 97 |
-
|
| 98 |
-
app.run(host="0.0.0.0", port=port, debug=False)
|
|
|
|
| 1 |
import os
|
|
|
|
| 2 |
import requests
|
| 3 |
+
import traceback
|
| 4 |
+
import gradio as gr
|
| 5 |
from dotenv import load_dotenv
|
| 6 |
|
| 7 |
+
# Load secrets (from Hugging Face Spaces "Variables and secrets")
|
| 8 |
load_dotenv()
|
| 9 |
|
| 10 |
# Configuration
|
| 11 |
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
|
| 12 |
+
OPENROUTER_MODEL = os.getenv("OPENROUTER_MODEL")
|
| 13 |
APP_TITLE = os.getenv("APP_TITLE", "Selva Chat Bot")
|
| 14 |
OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions"
|
| 15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
+
def chatbot_fn(message, history):
|
| 18 |
+
"""
|
| 19 |
+
message: latest user input (string)
|
| 20 |
+
history: list of tuples (user, bot)
|
| 21 |
+
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
try:
|
| 23 |
+
if not OPENROUTER_API_KEY:
|
| 24 |
+
return history + [(message, "❌ API key not configured.")]
|
|
|
|
| 25 |
|
| 26 |
+
# Convert Gradio history to OpenRouter messages format
|
| 27 |
+
messages = [{"role": "system", "content": "You are a helpful, concise, and friendly assistant for Selva's Chat-Bot."}]
|
| 28 |
+
for user_msg, bot_msg in history:
|
| 29 |
+
messages.append({"role": "user", "content": user_msg})
|
| 30 |
+
messages.append({"role": "assistant", "content": bot_msg})
|
| 31 |
|
| 32 |
+
# Add latest user query
|
| 33 |
+
messages.append({"role": "user", "content": message})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
# API request
|
| 36 |
headers = {
|
|
|
|
| 38 |
"Content-Type": "application/json",
|
| 39 |
"X-Title": APP_TITLE,
|
| 40 |
}
|
|
|
|
| 41 |
body = {
|
| 42 |
"model": OPENROUTER_MODEL,
|
| 43 |
"messages": messages,
|
| 44 |
"temperature": 0.7,
|
| 45 |
+
"max_tokens": 1000,
|
| 46 |
}
|
| 47 |
|
| 48 |
response = requests.post(OPENROUTER_URL, headers=headers, json=body, timeout=30)
|
| 49 |
|
| 50 |
if response.status_code != 200:
|
| 51 |
error_data = response.json() if response.headers.get('content-type') == 'application/json' else {"error": response.text}
|
| 52 |
+
error_message = error_data.get("error", "API request failed")
|
| 53 |
+
return history + [(message, f"❌ Error: {error_message}")]
|
| 54 |
|
| 55 |
data = response.json()
|
| 56 |
reply = (
|
|
|
|
| 59 |
.get("content", "Sorry, I couldn't generate a response.")
|
| 60 |
)
|
| 61 |
|
| 62 |
+
return history + [(message, reply)]
|
| 63 |
|
| 64 |
except requests.exceptions.Timeout:
|
| 65 |
+
return history + [(message, "❌ Request timeout. Please try again.")]
|
|
|
|
|
|
|
|
|
|
| 66 |
except Exception as e:
|
|
|
|
| 67 |
traceback.print_exc()
|
| 68 |
+
return history + [(message, f"❌ Internal error: {e}")]
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
# Gradio Chatbot UI
|
| 72 |
+
with gr.Blocks(title=APP_TITLE) as demo:
|
| 73 |
+
gr.Markdown(f"# 🤖 {APP_TITLE}")
|
| 74 |
+
chatbot = gr.Chatbot(height=500)
|
| 75 |
+
msg = gr.Textbox(placeholder="Type your message here...")
|
| 76 |
+
clear = gr.Button("Clear")
|
| 77 |
+
|
| 78 |
+
def user_submit(user_message, chat_history):
|
| 79 |
+
return "", chatbot_fn(user_message, chat_history)
|
| 80 |
+
|
| 81 |
+
msg.submit(user_submit, [msg, chatbot], [msg, chatbot])
|
| 82 |
+
clear.click(lambda: None, None, chatbot, queue=False)
|
| 83 |
|
| 84 |
+
# Hugging Face Spaces entrypoint
|
| 85 |
if __name__ == "__main__":
|
| 86 |
+
demo.launch(server_name="0.0.0.0", server_port=7860, debug=True, pwa=True)
|
|
|