Spaces:
Sleeping
Sleeping
| from flask import Flask, request, jsonify | |
| import openai | |
| import os | |
| app = Flask(__name__) | |
| # Set your OpenAI API key | |
| openai.api_key = os.environ['OPENAI_API_KEY'] | |
| # Your Assistant ID (from platform.openai.com) | |
| ASSISTANT_ID = "asst_izF6HxamgRWJf8RnMf7tdoMA" | |
| # Store thread IDs per session/user if needed | |
| thread_store = {} | |
| def chat(): | |
| user_input = request.json.get("message") | |
| user_id = request.json.get("user_id", "default") | |
| # Create a thread if not exists | |
| if user_id not in thread_store: | |
| thread = openai.beta.threads.create() | |
| thread_store[user_id] = thread.id | |
| thread_id = thread_store[user_id] | |
| # Step 1: Add message to thread | |
| openai.beta.threads.messages.create( | |
| thread_id=thread_id, | |
| role="user", | |
| content=user_input | |
| ) | |
| # Step 2: Run the assistant | |
| run = openai.beta.threads.runs.create( | |
| thread_id=thread_id, | |
| assistant_id=ASSISTANT_ID | |
| ) | |
| # Step 3: Wait for completion (polling) | |
| import time | |
| while True: | |
| run_status = openai.beta.threads.runs.retrieve(thread_id=thread_id, run_id=run.id) | |
| if run_status.status == "completed": | |
| break | |
| elif run_status.status == "failed": | |
| return jsonify({"error": "Run failed"}), 500 | |
| time.sleep(1) | |
| # Step 4: Fetch response | |
| messages = openai.beta.threads.messages.list(thread_id=thread_id) | |
| response_text = messages.data[0].content[0].text.value | |
| return jsonify({"response": response_text}) | |
| if __name__ == "__main__": | |
| app.run(debug=True) | |