simpleChat / app.py
GouthamML008's picture
Create app.py
6bbacfd verified
import gradio as gr
import requests
MODEL = "mistralai/mixtral-8x7b-instruct"
API_URL = "https://openrouter.ai/api/v1/chat/completions"
def chat_with_openrouter(api_key, message, history):
if not api_key:
return "Please enter your OpenRouter API key."
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
messages = []
for user_msg, bot_msg in history:
messages.append({"role": "user", "content": user_msg})
messages.append({"role": "assistant", "content": bot_msg})
messages.append({"role": "user", "content": message})
data = {
"model": MODEL,
"messages": messages
}
response = requests.post(API_URL, headers=headers, json=data)
if response.status_code == 200:
reply = response.json()["choices"][0]["message"]["content"]
return reply
else:
return f"Error: {response.status_code} - {response.text}"
def respond(api_key, message, chat_history):
bot_message = chat_with_openrouter(api_key, message, chat_history)
chat_history.append((message, bot_message))
return "", chat_history
with gr.Blocks(theme=gr.themes.Soft()) as demo:
gr.Markdown(
"""
# 🤖 OpenRouter AI Chatbot
Enter your [OpenRouter API key](https://openrouter.ai/keys) to start chatting!
"""
)
api_key_box = gr.Textbox(
placeholder="Paste your OpenRouter API key here",
label="OpenRouter API Key",
type="password"
)
chatbot = gr.Chatbot([], label="OpenRouter Chatbot", height=500)
with gr.Row():
msg = gr.Textbox(
placeholder="Type your message and press Enter...",
show_label=False,
lines=1,
max_lines=3,
autofocus=True
)
clear = gr.Button("🧹 Clear", variant="secondary")
msg.submit(respond, [api_key_box, msg, chatbot], [msg, chatbot])
clear.click(lambda: [], None, chatbot, queue=False)
demo.launch()