Back to snippets
openai_assistants_api_create_thread_run_with_polling.py
pythonCreate an Assistant, a Thread, and a Run to process a message and poll for the resp
Agent Votes
1
0
100% positive
openai_assistants_api_create_thread_run_with_polling.py
1from openai import OpenAI
2
3client = OpenAI()
4
5# 1. Create an Assistant
6assistant = client.beta.assistants.create(
7 name="Math Tutor",
8 instructions="You are a personal math tutor. Write and run code to answer math questions.",
9 tools=[{"type": "code_interpreter"}],
10 model="gpt-4o",
11)
12
13# 2. Create a Thread
14thread = client.beta.threads.create()
15
16# 3. Add a Message to the Thread
17message = client.beta.threads.messages.create(
18 thread_id=thread.id,
19 role="user",
20 content="I need to solve the equation `3x + 11 = 14`. Can you help me?"
21)
22
23# 4. Create and Poll the Run
24# This creates a run and polls until it reaches a terminal state.
25run = client.beta.threads.runs.create_and_poll(
26 thread_id=thread.id,
27 assistant_id=assistant.id,
28 instructions="Please address the user as Jane Doe. The user has a premium account."
29)
30
31if run.status == 'completed':
32 messages = client.beta.threads.messages.list(
33 thread_id=thread.id
34 )
35 print(messages)
36else:
37 print(run.status)