|
|
|
import os |
|
from getpass import getpass |
|
from openai import OpenAI |
|
import gradio as gr |
|
|
|
|
|
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY") |
|
|
|
|
|
if not OPENROUTER_API_KEY: |
|
print("Error: OPENROUTER_API_KEY not found in environment.") |
|
print("Please set your API key in the environment as 'OPENROUTER_API_KEY'.") |
|
else: |
|
client = OpenAI( |
|
base_url="https://openrouter.ai/api/v1", |
|
api_key=OPENROUTER_API_KEY, |
|
) |
|
|
|
def openrouter_chat(user_message, history): |
|
"""Send user_message and history to mistralai/devstral-small:free and append to history.""" |
|
history = history or [] |
|
|
|
|
|
|
|
|
|
messages_for_api = [] |
|
for human_message, ai_message in history: |
|
messages_for_api.append({"role": "user", "content": human_message}) |
|
if ai_message is not None: |
|
messages_for_api.append({"role": "assistant", "content": ai_message}) |
|
|
|
|
|
messages_for_api.append({"role": "user", "content": user_message}) |
|
|
|
try: |
|
|
|
resp = client.chat.completions.create( |
|
model="mistralai/devstral-small:free", |
|
messages=messages_for_api, |
|
|
|
) |
|
bot_reply = resp.choices[0].message.content |
|
|
|
history.append((user_message, bot_reply)) |
|
except Exception as e: |
|
|
|
history.append((user_message, f"Error: {e}")) |
|
|
|
|
|
return history, "" |
|
|
|
with gr.Blocks() as demo: |
|
gr.Markdown("## π¦π Gradio + OpenRouter Chat with Devstral-Small (with History)") |
|
chatbot = gr.Chatbot(label="Chat") |
|
msg_in = gr.Textbox(placeholder="Type your question hereβ¦", label="You") |
|
msg_in.submit(openrouter_chat, inputs=[msg_in, chatbot], outputs=[chatbot, msg_in]) |
|
|
|
demo.launch() |