Spaces:
Running
Running
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import gradio as gr
|
| 3 |
+
from openai import OpenAI
|
| 4 |
+
|
| 5 |
+
# Fetch the API key from Hugging Face Spaces Secrets
|
| 6 |
+
# Ensure you named your secret "API_KEY" in your Space settings
|
| 7 |
+
OPENROUTER_API_KEY = os.environ.get("API_KEY")
|
| 8 |
+
|
| 9 |
+
# Initialize the client with OpenRouter's base URL
|
| 10 |
+
client = OpenAI(
|
| 11 |
+
base_url="https://openrouter.ai",
|
| 12 |
+
api_key=OPENROUTER_API_KEY,
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
def predict(message, history):
|
| 16 |
+
if not OPENROUTER_API_KEY:
|
| 17 |
+
yield "Error: API_KEY secret is missing in Hugging Face Space settings."
|
| 18 |
+
return
|
| 19 |
+
|
| 20 |
+
# Convert Gradio history format to OpenAI format
|
| 21 |
+
messages = []
|
| 22 |
+
for user_msg, assistant_msg in history:
|
| 23 |
+
messages.append({"role": "user", "content": user_msg})
|
| 24 |
+
messages.append({"role": "assistant", "content": assistant_msg})
|
| 25 |
+
|
| 26 |
+
# Add the current user message
|
| 27 |
+
messages.append({"role": "user", "content": message})
|
| 28 |
+
|
| 29 |
+
try:
|
| 30 |
+
# Call the OpenRouter API stream
|
| 31 |
+
# You can change the model string to any model supported by OpenRouter
|
| 32 |
+
response = client.chat.completions.create(
|
| 33 |
+
model="meta-llama/llama-3-8b-instruct:free",
|
| 34 |
+
messages=messages,
|
| 35 |
+
stream=True
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
# Yield chunks as they arrive for a smooth typing effect
|
| 39 |
+
partial_message = ""
|
| 40 |
+
for chunk in response:
|
| 41 |
+
if chunk.choices[0].delta.content:
|
| 42 |
+
partial_message += chunk.choices[0].delta.content
|
| 43 |
+
yield partial_message
|
| 44 |
+
|
| 45 |
+
except Exception as e:
|
| 46 |
+
yield f"An error occurred: {str(e)}"
|
| 47 |
+
|
| 48 |
+
# Create the standard Gradio ChatInterface
|
| 49 |
+
demo = gr.ChatInterface(
|
| 50 |
+
fn=predict,
|
| 51 |
+
title="OpenRouter Chatbot",
|
| 52 |
+
description="A chatbot powered by OpenRouter and Gradio running on Hugging Face Spaces.",
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
if __name__ == "__main__":
|
| 56 |
+
demo.launch()
|