Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import openai
|
3 |
+
import os
|
4 |
+
import time
|
5 |
+
from flask import Flask, request, jsonify
|
6 |
+
from threading import Thread
|
7 |
+
|
8 |
+
openai.api_key = os.getenv("OPENAI_API_KEY")
|
9 |
+
assistant_id = os.getenv("OPENAI_ASSISTANT_ID")
|
10 |
+
|
11 |
+
# Flask app for API
|
12 |
+
flask_app = Flask(__name__)
|
13 |
+
|
14 |
+
@flask_app.route("/chat", methods=["POST"])
|
15 |
+
def chat():
|
16 |
+
user_input = request.json.get("message", "")
|
17 |
+
if not user_input:
|
18 |
+
return jsonify({"error": "Empty input"}), 400
|
19 |
+
|
20 |
+
try:
|
21 |
+
# Step 1: Create thread
|
22 |
+
thread = openai.beta.threads.create()
|
23 |
+
openai.beta.threads.messages.create(
|
24 |
+
thread_id=thread.id,
|
25 |
+
role="user",
|
26 |
+
content=user_input
|
27 |
+
)
|
28 |
+
|
29 |
+
# Step 2: Run assistant
|
30 |
+
run = openai.beta.threads.runs.create(
|
31 |
+
thread_id=thread.id,
|
32 |
+
assistant_id=assistant_id
|
33 |
+
)
|
34 |
+
|
35 |
+
# Step 3: Poll until done
|
36 |
+
while True:
|
37 |
+
status = openai.beta.threads.runs.retrieve(thread_id=thread.id, run_id=run.id)
|
38 |
+
if status.status == "completed":
|
39 |
+
break
|
40 |
+
elif status.status == "failed":
|
41 |
+
return jsonify({"error": "Run failed"}), 500
|
42 |
+
time.sleep(1)
|
43 |
+
|
44 |
+
# Step 4: Get response
|
45 |
+
messages = openai.beta.threads.messages.list(thread_id=thread.id)
|
46 |
+
for msg in reversed(messages.data):
|
47 |
+
if msg.role == "assistant":
|
48 |
+
return jsonify({"response": msg.content[0].text.value})
|
49 |
+
|
50 |
+
return jsonify({"response": "No reply."})
|
51 |
+
except Exception as e:
|
52 |
+
return jsonify({"error": str(e)}), 500
|
53 |
+
|
54 |
+
# Gradio UI (optional, for testing)
|
55 |
+
def chat_gradio(message):
|
56 |
+
response = chat().get_json()["response"]
|
57 |
+
return response
|
58 |
+
|
59 |
+
# Mount Flask app in a background thread
|
60 |
+
def launch_flask():
|
61 |
+
flask_app.run(host="0.0.0.0", port=7861)
|
62 |
+
|
63 |
+
thread = Thread(target=launch_flask)
|
64 |
+
thread.start()
|
65 |
+
|
66 |
+
# Optional Gradio front-end (not used if only HTML talks to Flask)
|
67 |
+
demo = gr.Interface(fn=chat_gradio, inputs="text", outputs="text", title="LOR Chat Assistant")
|
68 |
+
demo.launch(server_name="0.0.0.0", server_port=7860, share=True)
|