Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from openai import OpenAI
|
3 |
+
|
4 |
+
# Set your API key and base URL
|
5 |
+
API_KEY = os.getenv("API_KEY")
|
6 |
+
BASE_URL = "https://openrouter.ai/api/v1"
|
7 |
+
|
8 |
+
# Initialize the OpenAI client with OpenRouter settings
|
9 |
+
client = OpenAI(
|
10 |
+
base_url=BASE_URL,
|
11 |
+
api_key=API_KEY,
|
12 |
+
)
|
13 |
+
|
14 |
+
st.title("Chat with OpenRouter API")
|
15 |
+
|
16 |
+
# Initialize session state for storing the conversation if it doesn't exist
|
17 |
+
if 'messages' not in st.session_state:
|
18 |
+
st.session_state.messages = [
|
19 |
+
{"role": "assistant", "content": "Hello! How can I help you today?"}
|
20 |
+
]
|
21 |
+
|
22 |
+
# Display the conversation
|
23 |
+
for msg in st.session_state.messages:
|
24 |
+
if msg["role"] == "user":
|
25 |
+
st.markdown(f"**User:** {msg['content']}")
|
26 |
+
else:
|
27 |
+
st.markdown(f"**Assistant:** {msg['content']}")
|
28 |
+
|
29 |
+
# Input field for user to type a new message
|
30 |
+
user_input = st.text_input("Your message:", key="input")
|
31 |
+
|
32 |
+
if st.button("Send") and user_input:
|
33 |
+
# Append the user's message to the conversation
|
34 |
+
st.session_state.messages.append({"role": "user", "content": user_input})
|
35 |
+
|
36 |
+
# Call the OpenRouter API using the chosen (different) model
|
37 |
+
try:
|
38 |
+
response = client.chat.completions.create(
|
39 |
+
extra_headers={
|
40 |
+
"HTTP-Referer": "http://your-site-url.com", # Optional
|
41 |
+
"X-Title": "Your Site Title" # Optional
|
42 |
+
},
|
43 |
+
extra_body={},
|
44 |
+
model="deepseek/deepseek-v3-large:free", # Changed model
|
45 |
+
messages=st.session_state.messages,
|
46 |
+
)
|
47 |
+
assistant_reply = response.choices[0].message.content
|
48 |
+
except Exception as e:
|
49 |
+
assistant_reply = f"An error occurred: {str(e)}"
|
50 |
+
|
51 |
+
# Append the assistant's reply and refresh the UI
|
52 |
+
st.session_state.messages.append({"role": "assistant", "content": assistant_reply})
|
53 |
+
st.experimental_rerun()
|