Spaces:
Running
Running
| import os | |
| import requests | |
| import traceback | |
| import gradio as gr | |
| from dotenv import load_dotenv | |
| # Load secrets (from Hugging Face Spaces "Variables and secrets") | |
| load_dotenv() | |
| # Configuration | |
| OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY") | |
| OPENROUTER_MODEL = os.getenv("OPENROUTER_MODEL") | |
| APP_TITLE = os.getenv("APP_TITLE", "Selva Chat Bot") | |
| OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions" | |
| def chatbot_fn(message, history): | |
| """ | |
| message: latest user input (string) | |
| history: list of tuples (user, bot) | |
| """ | |
| try: | |
| if not OPENROUTER_API_KEY: | |
| return history + [(message, "β API key not configured.")] | |
| # Convert Gradio history to OpenRouter messages format | |
| messages = [{"role": "system", "content": "You are a helpful, concise, and friendly assistant for Selva's Chat-Bot."}] | |
| for user_msg, bot_msg in history: | |
| messages.append({"role": "user", "content": user_msg}) | |
| messages.append({"role": "assistant", "content": bot_msg}) | |
| # Add latest user query | |
| messages.append({"role": "user", "content": message}) | |
| # API request | |
| headers = { | |
| "Authorization": f"Bearer {OPENROUTER_API_KEY}", | |
| "Content-Type": "application/json", | |
| "X-Title": APP_TITLE, | |
| } | |
| body = { | |
| "model": OPENROUTER_MODEL, | |
| "messages": messages, | |
| "temperature": 0.7, | |
| "max_tokens": 1000, | |
| } | |
| response = requests.post(OPENROUTER_URL, headers=headers, json=body, timeout=30) | |
| if response.status_code != 200: | |
| error_data = response.json() if response.headers.get('content-type') == 'application/json' else {"error": response.text} | |
| error_message = error_data.get("error", "API request failed") | |
| return history + [(message, f"β Error: {error_message}")] | |
| data = response.json() | |
| reply = ( | |
| data.get("choices", [{}])[0] | |
| .get("message", {}) | |
| .get("content", "Sorry, I couldn't generate a response.") | |
| ) | |
| return history + [(message, reply)] | |
| except requests.exceptions.Timeout: | |
| return history + [(message, "β Request timeout. Please try again.")] | |
| except Exception as e: | |
| traceback.print_exc() | |
| return history + [(message, f"β Internal error: {e}")] | |
| # Gradio Chatbot UI | |
| with gr.Blocks(title=APP_TITLE) as demo: | |
| gr.Markdown(f"# π€ {APP_TITLE}") | |
| chatbot = gr.Chatbot(height=500) | |
| msg = gr.Textbox(placeholder="Type your message here...") | |
| clear = gr.Button("Clear") | |
| def user_submit(user_message, chat_history): | |
| return "", chatbot_fn(user_message, chat_history) | |
| msg.submit(user_submit, [msg, chatbot], [msg, chatbot]) | |
| clear.click(lambda: None, None, chatbot, queue=False) | |
| # Hugging Face Spaces entrypoint | |
| if __name__ == "__main__": | |
| demo.launch(server_name="0.0.0.0", server_port=7860, debug=True, pwa=True) | |