Article
openaiagentassistants-apipythoncode-interpreterstateful-aiapi
Build a Stateful Agent with the OpenAI Assistants API
Use the OpenAI Assistants API to create a stateful AI agent with persistent conversation history and built-in tools like Code Interpreter. This handles session management, letting you focus on your application's core logic.
intermediate15 min5 steps
The play
- Set Up Your EnvironmentInstall the OpenAI Python library and configure your API key as an environment variable. The client will automatically use the `OPENAI_API_KEY` variable.
- Create an AssistantDefine your assistant's behavior. Specify instructions, a model, and enable tools. Here, we create a 'Math Tutor' that uses the Code Interpreter tool to solve math problems.
- Create a Conversation ThreadA Thread represents a single conversation and stores its message history. Create a new, empty thread for each user conversation you want to start.
- Add a Message and Run the AssistantAdd the user's message to the thread. Then, create a 'Run' to process the entire thread. The OpenAI Assistants API will execute the necessary steps, like calling the Code Interpreter.
- Check Run Status & Get the ResponseRuns are asynchronous. Poll the run's status until it is 'completed'. Once complete, you can retrieve the list of messages from the thread, which will now include the assistant's response.
Starter code
import os
import time
from openai import OpenAI
# Ensure your OPENAI_API_KEY is set as an environment variable
client = OpenAI()
# 1. Create an Assistant
assistant = client.beta.assistants.create(
name="Math Tutor",
instructions="You are a personal math tutor. Write and run Python code to answer math questions.",
tools=[{"type": "code_interpreter"}],
model="gpt-4o",
)
# 2. Create a Thread
thread = client.beta.threads.create()
# 3. Add a Message to the Thread
message = client.beta.threads.messages.create(
thread_id=thread.id,
role="user",
content="What is 9 factorial? Show your work."
)
# 4. Create a Run
run = client.beta.threads.runs.create(
thread_id=thread.id,
assistant_id=assistant.id,
instructions="Please address the user as Jane Doe. The user has a premium account."
)
print(f"Run created with ID: {run.id}")
# 5. Poll for the Run to complete
while run.status in ['queued', 'in_progress', 'cancelling']:
time.sleep(1) # Wait for 1 second
run = client.beta.threads.runs.retrieve(
thread_id=thread.id,
run_id=run.id
)
print(f"Current run status: {run.status}")
# 6. Retrieve and print the Assistant's response
if run.status == 'completed':
messages = client.beta.threads.messages.list(
thread_id=thread.id
)
# The latest message is at the beginning of the list
assistant_message = messages.data[0].content[0].text.value
print("\n--- Assistant's Response ---")
print(assistant_message)
else:
print(f"Run failed with status: {run.status}")