Update app.py
Browse files
app.py
CHANGED
@@ -1,36 +1,30 @@
|
|
1 |
import gradio as gr
|
2 |
-
import
|
|
|
3 |
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
def query_api(messages):
|
10 |
-
headers = {"Authorization": f"Bearer {API_KEY}"}
|
11 |
-
payload = {
|
12 |
-
"model": "gpt-3.5-turbo", # or whatever model you're using
|
13 |
-
"messages": messages
|
14 |
-
}
|
15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
16 |
try:
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
except Exception as e:
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
response = requests.post(FALLBACK_API, headers=headers, json=payload, timeout=10)
|
27 |
-
response.raise_for_status()
|
28 |
-
return response.json()["choices"][0]["message"]["content"]
|
29 |
-
except Exception as e2:
|
30 |
-
print(f"[ERROR] Fallback API also failed: {e2}")
|
31 |
-
return "❌ Both the primary and fallback services are unavailable right now."
|
32 |
|
33 |
-
# Gradio Chatbot UI (without unsupported params)
|
34 |
chat = gr.Chatbot(
|
35 |
label="Conversation",
|
36 |
avatar_images=(None, None),
|
@@ -40,15 +34,9 @@ chat = gr.Chatbot(
|
|
40 |
render_markdown=True
|
41 |
)
|
42 |
|
43 |
-
def respond(user_message, history):
|
44 |
-
history = history or []
|
45 |
-
bot_reply = query_api([{"role": "user", "content": user_message}])
|
46 |
-
history.append((user_message, bot_reply))
|
47 |
-
return history
|
48 |
-
|
49 |
with gr.Blocks() as demo:
|
50 |
chatbot = chat
|
51 |
-
msg = gr.Textbox()
|
52 |
msg.submit(respond, [msg, chatbot], chatbot)
|
53 |
|
54 |
if __name__ == "__main__":
|
|
|
1 |
import gradio as gr
|
2 |
+
from openai import OpenAI
|
3 |
+
import os
|
4 |
|
5 |
+
client = OpenAI(
|
6 |
+
api_key=os.getenv("OPENAI_API_KEY"),
|
7 |
+
base_url="https://api.chatanywhere.tech/v1"
|
8 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
|
10 |
+
def respond(user_message, history):
|
11 |
+
history = history or []
|
12 |
+
messages = [{"role": "system", "content": "You are a helpful assistant."}]
|
13 |
+
for human, ai in history:
|
14 |
+
messages.append({"role": "user", "content": human})
|
15 |
+
messages.append({"role": "assistant", "content": ai})
|
16 |
+
messages.append({"role": "user", "content": user_message})
|
17 |
try:
|
18 |
+
response = client.chat.completions.create(
|
19 |
+
model="gpt-3.5-turbo",
|
20 |
+
messages=messages
|
21 |
+
)
|
22 |
+
bot_reply = response.choices[0].message.content
|
23 |
except Exception as e:
|
24 |
+
bot_reply = f"❌ Error: {e}"
|
25 |
+
history.append((user_message, bot_reply))
|
26 |
+
return history
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
|
|
|
28 |
chat = gr.Chatbot(
|
29 |
label="Conversation",
|
30 |
avatar_images=(None, None),
|
|
|
34 |
render_markdown=True
|
35 |
)
|
36 |
|
|
|
|
|
|
|
|
|
|
|
|
|
37 |
with gr.Blocks() as demo:
|
38 |
chatbot = chat
|
39 |
+
msg = gr.Textbox(placeholder="Type your message here...")
|
40 |
msg.submit(respond, [msg, chatbot], chatbot)
|
41 |
|
42 |
if __name__ == "__main__":
|