How to create a thread in OpenAI Assistants API
Quick answer
Use the OpenAI Python SDK to create a thread by calling
client.assistants.threads.create() with the assistant ID and initial messages. This starts a new conversation thread under the specified assistant.PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install openai>=1.0
Setup
Install the official OpenAI Python SDK and set your API key as an environment variable.
- Run
pip install openaito install the SDK. - Set your API key in your shell:
export OPENAI_API_KEY='your_api_key_here'(Linux/macOS) orsetx OPENAI_API_KEY "your_api_key_here"(Windows).
pip install openai Step by step
This example shows how to create a new thread in the OpenAI Assistants API by specifying the assistant ID and sending an initial user message. The response contains the thread ID and the assistant's reply.
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
# Replace with your assistant ID
assistant_id = "your-assistant-id"
# Create a new thread with an initial user message
response = client.assistants.threads.create(
assistant=assistant_id,
messages=[{"role": "user", "content": "Hello, can you help me?"}]
)
thread_id = response.id
assistant_reply = response.messages[0].content
print(f"Thread ID: {thread_id}")
print(f"Assistant reply: {assistant_reply}") output
Thread ID: thrd_1234567890abcdef Assistant reply: Hello! How can I assist you today?
Common variations
You can create threads asynchronously or use different models by specifying parameters in the create() call. To continue a conversation, use the thread ID with client.assistants.threads.update(). The OpenAI Assistants API supports streaming responses and custom system messages.
import asyncio
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
async def create_thread_async():
response = await client.assistants.threads.acreate(
assistant="your-assistant-id",
messages=[{"role": "user", "content": "Start async thread."}]
)
print(f"Async thread ID: {response.id}")
asyncio.run(create_thread_async()) output
Async thread ID: thrd_async_abcdef123456
Troubleshooting
- If you get a
401 Unauthorizederror, verify yourOPENAI_API_KEYenvironment variable is set correctly. - If the assistant ID is invalid, you will receive a
404 Not Founderror; double-check your assistant ID. - For network issues, ensure your internet connection is stable and the OpenAI API endpoint is reachable.
Key Takeaways
- Use
client.assistants.threads.create()with the assistant ID and initial messages to start a thread. - Always set your API key in
os.environ["OPENAI_API_KEY"]to authenticate requests. - You can create threads asynchronously with
acreate()for non-blocking calls. - Check error codes like 401 and 404 to troubleshoot authentication and resource issues.
- Use the returned thread ID to continue conversations or manage threads.