Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,20 +2,18 @@ import os
|
|
| 2 |
import gradio as gr
|
| 3 |
from openai import OpenAI
|
| 4 |
|
| 5 |
-
# ---- Configuration ----
|
| 6 |
-
|
| 7 |
HF_API_KEY = os.getenv("HF_TOKEN")
|
| 8 |
|
| 9 |
client = OpenAI(
|
| 10 |
base_url="https://router.huggingface.co/v1",
|
| 11 |
-
api_key=HF_API_KEY
|
| 12 |
)
|
| 13 |
|
| 14 |
-
# ---- Chat function ----
|
| 15 |
def chat_with_model(user_message, history):
|
| 16 |
if history is None:
|
| 17 |
history = []
|
| 18 |
|
|
|
|
| 19 |
messages = [{"role": "system", "content": "You are a helpful assistant."}]
|
| 20 |
for human, bot in history:
|
| 21 |
messages.append({"role": "user", "content": human})
|
|
@@ -28,22 +26,27 @@ def chat_with_model(user_message, history):
|
|
| 28 |
model="openai/gpt-oss-20b:nebius",
|
| 29 |
messages=messages
|
| 30 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
-
|
| 33 |
-
history.append((user_message, assistant_reply))
|
| 34 |
-
return assistant_reply, history
|
| 35 |
|
| 36 |
except Exception as e:
|
| 37 |
-
|
|
|
|
|
|
|
| 38 |
|
| 39 |
|
| 40 |
-
# ---- Gradio UI ----
|
| 41 |
with gr.Blocks() as demo:
|
| 42 |
-
gr.Markdown("# 🤖
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
text_input.submit(
|
|
|
|
| 48 |
|
| 49 |
demo.launch()
|
|
|
|
| 2 |
import gradio as gr
|
| 3 |
from openai import OpenAI
|
| 4 |
|
|
|
|
|
|
|
| 5 |
HF_API_KEY = os.getenv("HF_TOKEN")
|
| 6 |
|
| 7 |
client = OpenAI(
|
| 8 |
base_url="https://router.huggingface.co/v1",
|
| 9 |
+
api_key=HF_API_KEY,
|
| 10 |
)
|
| 11 |
|
|
|
|
| 12 |
def chat_with_model(user_message, history):
|
| 13 |
if history is None:
|
| 14 |
history = []
|
| 15 |
|
| 16 |
+
# Build the full conversation history for the API
|
| 17 |
messages = [{"role": "system", "content": "You are a helpful assistant."}]
|
| 18 |
for human, bot in history:
|
| 19 |
messages.append({"role": "user", "content": human})
|
|
|
|
| 26 |
model="openai/gpt-oss-20b:nebius",
|
| 27 |
messages=messages
|
| 28 |
)
|
| 29 |
+
|
| 30 |
+
reply = completion.choices[0].message["content"]
|
| 31 |
+
|
| 32 |
+
# Append to history in correct Gradio format (tuple)
|
| 33 |
+
history.append((user_message, reply))
|
| 34 |
|
| 35 |
+
return history, history
|
|
|
|
|
|
|
| 36 |
|
| 37 |
except Exception as e:
|
| 38 |
+
error_msg = f"Error: {str(e)}"
|
| 39 |
+
history.append((user_message, error_msg))
|
| 40 |
+
return history, history
|
| 41 |
|
| 42 |
|
|
|
|
| 43 |
with gr.Blocks() as demo:
|
| 44 |
+
gr.Markdown("# 🤖 Chat with HuggingFace Router (OpenAI Compatible)")
|
| 45 |
+
|
| 46 |
+
chatbot = gr.Chatbot(height=500)
|
| 47 |
+
text_input = gr.Textbox(label="Type your message")
|
| 48 |
+
|
| 49 |
+
text_input.submit(chat_with_model, [text_input, chatbot], [chatbot, chatbot])
|
| 50 |
+
text_input.submit(lambda: "", None, text_input)
|
| 51 |
|
| 52 |
demo.launch()
|