Self-built OpenAI Assistant - How to avoid loading file and creating assistant obj every time during conversation between user and Assistant?

I built a dialogbox to simulate Assistant Playground. I uploaded a Word file and sent user entered question to back-end assistant, displayed AI’s response in dialogbox, see example code below. It works OK.
However, when user keeps asking questions, my back-end code loads file again and create a brand-new assistant and thread object to process it.
How do I make back-end code to process subsequent Q/A within created thread object, like Assistant Playground ?

------- sample code here ----------

data = json.loads(request.body)

kbase_file = openai.files.create(
file=open(“test.docx”, “rb”),
purpose=“assistants”
)

my_assistant = openai.beta.assistants.create(
instructions = “assistant instructions here”,
name=“test”,
tools=[{“type”: “retrieval”}],
model=“gpt-4-1106-preview”,
file_ids=[kbase_file.id],
)

thread = openai.beta.threads.create()

thread_message = openai.beta.threads.messages.create(
thread_id = thread.id,
role = “user”,
content = data[‘data’] # user entered question
)

run = openai.beta.threads.runs.create(
thread_id = thread.id,
assistant_id = my_assistant.id
)
runID = run.id
time.sleep(70) # Wait for x second

run = openai.beta.threads.runs.retrieve(
thread_id = thread.id,
run_id = runID
)

thread_messages = openai.beta.threads.messages.list(thread.id)

for msg in thread_messages.data:
print(msg.role + ": " + msg.content[0].text.value)
# return JsonResponse({“message”: msg.role + ": " + msg.content[0].text.value})

Welcome @integrum.shijun

If you’re running this code in a loop then that’s expected to happen as it’s exactly what this code does.

ok, looks like I should make file, assistant and thread as ‘global’ object, and put message and run in a loop. Is that right?

Just need to keep them out of the loop. Rest depends on how the rest of your code is implemented.

1 Like

Got it, will try again. Thanks a lot for your help.