aiqcamp commited on
Commit
ff0c5c1
·
verified ·
1 Parent(s): 68d2e60

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -0
app.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 2) The actual app
2
+ import os
3
+ from getpass import getpass
4
+ from openai import OpenAI
5
+ import gradio as gr
6
+
7
+ # ——— Configure your OpenRouter key ———
8
+ OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
9
+
10
+ # Check if the API key was retrieved
11
+ if not OPENROUTER_API_KEY:
12
+ print("Error: OPENROUTER_API_KEY not found in environment.")
13
+ print("Please set your API key in the environment as 'OPENROUTER_API_KEY'.")
14
+ else:
15
+ client = OpenAI(
16
+ base_url="https://openrouter.ai/api/v1",
17
+ api_key=OPENROUTER_API_KEY,
18
+ )
19
+
20
+ def openrouter_chat(user_message, history):
21
+ """Send user_message and history to mistralai/devstral-small:free and append to history."""
22
+ history = history or []
23
+
24
+ # Build the messages list from the history and the current user message
25
+ # Gradio history is a list of tuples [(user_msg, bot_msg), ...]
26
+ # We need to convert it to the OpenAI API format: list of dicts [{"role": "user", "content": ...}, {"role": "assistant", "content": ...}, ...]
27
+ messages_for_api = []
28
+ for human_message, ai_message in history:
29
+ messages_for_api.append({"role": "user", "content": human_message})
30
+ if ai_message is not None: # Only add assistant message if it exists
31
+ messages_for_api.append({"role": "assistant", "content": ai_message})
32
+
33
+ # Add the current user message
34
+ messages_for_api.append({"role": "user", "content": user_message})
35
+
36
+ try:
37
+ # Call the model with the mistralai/Devstral-Small-2505 for full conversation history
38
+ resp = client.chat.completions.create(
39
+ model="mistralai/devstral-small:free",
40
+ messages=messages_for_api,
41
+ # you can tweak max_tokens, temperature, etc. here
42
+ )
43
+ bot_reply = resp.choices[0].message.content
44
+ # Append the user message and bot reply to the history for Gradio display
45
+ history.append((user_message, bot_reply))
46
+ except Exception as e:
47
+ # Handle potential errors and append an error message to the history
48
+ history.append((user_message, f"Error: {e}"))
49
+
50
+
51
+ return history, ""
52
+
53
+ with gr.Blocks() as demo:
54
+ gr.Markdown("## 🦜🔗 Gradio + OpenRouter Chat with Devstral-Small (with History)")
55
+ chatbot = gr.Chatbot(label="Chat")
56
+ msg_in = gr.Textbox(placeholder="Type your question here…", label="You")
57
+ msg_in.submit(openrouter_chat, inputs=[msg_in, chatbot], outputs=[chatbot, msg_in])
58
+
59
+ demo.launch()