File size: 2,021 Bytes
6bbacfd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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()