The Assistants API provides a stateful interface for building AI assistants with memory, tools, and file handling.
Creating an Assistant
from openai import OpenAI
client = OpenAI()
# Create assistant
assistant = client.beta.assistants.create(
name="Code Helper",
instructions="You are a helpful coding assistant. Help users with Python programming.",
model="gpt-4-turbo-preview",
tools=[{"type": "code_interpreter"}]
)
print(f"Assistant ID: {assistant.id}")
Managing Threads and Messages
# Create thread
thread = client.beta.threads.create()
# Add message
message = client.beta.threads.messages.create(
thread_id=thread.id,
role="user",
content="How do I reverse a string in Python?"
)
# Run assistant
run = client.beta.threads.runs.create(
thread_id=thread.id,
assistant_id=assistant.id
)
# Wait for completion
import time
while run.status != "completed":
run = client.beta.threads.runs.retrieve(
thread_id=thread.id,
run_id=run.id
)
time.sleep(1)
# Get response
messages = client.beta.threads.messages.list(thread_id=thread.id)
print(messages.data[0].content[0].text.value)
File Handling
# Upload file
file = client.files.create(
file=open("data.csv", "rb"),
purpose="assistants"
)
# Create assistant with file access
assistant = client.beta.assistants.create(
name="Data Analyst",
instructions="Analyze data files",
model="gpt-4-turbo-preview",
tools=[{"type": "code_interpreter"}],
file_ids=[file.id]
)
# Ask questions about the file
message = client.beta.threads.messages.create(
thread_id=thread.id,
role="user",
content="What's the average value in the data?"
)
Function Calling
# Define functions
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get weather for a location",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string"}
},
"required": ["location"]
}
}
}
]
assistant = client.beta.assistants.create(
name="Weather Assistant",
tools=tools,
model="gpt-4-turbo-preview"
)
# Handle function calls in run
if run.status == "requires_action":
tool_calls = run.required_action.submit_tool_outputs.tool_calls
tool_outputs = []
for call in tool_calls:
if call.function.name == "get_weather":
# Execute function
result = get_weather(call.function.arguments)
tool_outputs.append({
"tool_call_id": call.id,
"output": result
})
# Submit outputs
run = client.beta.threads.runs.submit_tool_outputs(
thread_id=thread.id,
run_id=run.id,
tool_outputs=tool_outputs
)
The Assistants API simplifies building stateful, capable AI applications!