File size: 1,593 Bytes
b875a81
efedb8c
b875a81
 
 
 
efedb8c
bd7188e
efedb8c
 
 
 
 
 
 
 
b875a81
efedb8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b875a81
 
efedb8c
 
b875a81
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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 = {}

@app.route("/chat", methods=["POST"])
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)