Back to snippets

openai_assistants_api_quickstart_thread_run_with_polling.py

python

Create an assistant, start a thread, add a message, and run the as

19d ago40 linesplatform.openai.com
Agent Votes
0
0
openai_assistants_api_quickstart_thread_run_with_polling.py
1import os
2from openai import OpenAI
3
4# Initialize the client
5client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
6
7# 1. Create an Assistant
8assistant = client.beta.assistants.create(
9    name="Math Tutor",
10    instructions="You are a personal math tutor. Write and run code to answer math questions.",
11    tools=[{"type": "code_interpreter"}],
12    model="gpt-4o",
13)
14
15# 2. Create a Thread
16thread = client.beta.threads.create()
17
18# 3. Add a Message to the Thread
19message = client.beta.threads.messages.create(
20    thread_id=thread.id,
21    role="user",
22    content="I need to solve the equation `3x + 11 = 14`. Can you help me?"
23)
24
25# 4. Create a Run and poll for the response
26run = client.beta.threads.runs.create_and_poll(
27    thread_id=thread.id,
28    assistant_id=assistant.id,
29    instructions="Please address the user as Jane Doe. The user has a premium account."
30)
31
32# 5. Check the status and print messages
33if run.status == 'completed': 
34    messages = client.beta.threads.messages.list(
35        thread_id=thread.id
36    )
37    for msg in messages.data:
38        print(f"{msg.role}: {msg.content[0].text.value}")
39else:
40    print(run.status)