Assistants API: Building Stateful Assistants
Deep dive into the Assistants API as a stateful evolution of Chat Completions: Thread, Run, Message primitives, built-in Code Interpreter and File Search tools, and run lifecycle management.
Create a Customer Support assistant instructed to answer only return-related questions. Open a Thread, send 3 messages in a row, and verify the context persists across requests.
Copy and adapt to your context. Text in angle brackets should be replaced.
assistant = client.beta.assistants.create(
name="Support Agent",
instructions=(
"You are a customer support agent. "
"Only answer questions about returns and refunds. "
"Be concise and polite."
),
model="gpt-4o",
)
thread = client.beta.threads.create()
def ask(question: str) -> str:
client.beta.threads.messages.create(
thread_id=thread.id, role="user", content=question
)
run = client.beta.threads.runs.create_and_poll(
thread_id=thread.id, assistant_id=assistant.id
)
msgs = client.beta.threads.messages.list(thread_id=thread.id)
return msgs.data[0].content[0].text.value