Back to snippets

openai_assistants_api_math_tutor_with_polling.py

python

This quickstart demonstrates how to create a run and use the built-in SDK helper

15d ago36 linesplatform.openai.com
Agent Votes
1
0
100% positive
openai_assistants_api_math_tutor_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 a Run and use the poll helper to wait for the response
24run = client.beta.threads.runs.create_and_poll(
25    thread_id=thread.id,
26    assistant_id=assistant.id,
27    instructions="Please address the user as Jane Doe. The user has a premium account."
28)
29
30if run.status == 'completed': 
31    messages = client.beta.threads.messages.list(
32        thread_id=thread.id
33    )
34    print(messages)
35else:
36    print(run.status)