OpenAI Assistants API Python SDK example
Quick answer
Use the
OpenAI Python SDK to interact with the assistants endpoint by creating a client with your API key and calling client.assistants.chat.completions.create() with the assistant ID and messages. This enables building AI assistants with simple, clean Python code.PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install openai>=1.0
Setup
Install the official openai Python SDK version 1.0 or higher and set your OpenAI API key as an environment variable.
- Install SDK:
pip install openai>=1.0 - Set environment variable in your shell:
export OPENAI_API_KEY='your_api_key_here'
pip install openai>=1.0 Step by step
This example shows how to create a chat completion using the OpenAI Assistants API with the Python SDK. Replace your-assistant-id with your actual assistant ID.
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
response = client.assistants.chat.completions.create(
assistant_id="your-assistant-id",
messages=[{"role": "user", "content": "Hello, how can you assist me today?"}]
)
print(response.choices[0].message.content) output
Hello! I'm here to help you with any questions or tasks you have. What would you like to do today?
Common variations
You can customize the assistant interaction by:
- Changing the
assistant_idto target different assistants. - Adding multiple messages for context.
- Using different models if supported by your assistant.
- Implementing asynchronous calls with
asyncioandawait(requires Python 3.7+).
import asyncio
import os
from openai import OpenAI
async def main():
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
response = await client.assistants.chat.completions.acreate(
assistant_id="your-assistant-id",
messages=[{"role": "user", "content": "Can you provide a summary of today's news?"}]
)
print(response.choices[0].message.content)
asyncio.run(main()) output
Here's a summary of today's top news stories: ...
Troubleshooting
If you encounter authentication errors, verify your OPENAI_API_KEY environment variable is set correctly. For assistant_id errors, confirm the ID is valid and you have access to that assistant. Network issues may require retry logic or checking your internet connection.
Key Takeaways
- Use
client.assistants.chat.completions.create()withassistant_idto interact with OpenAI Assistants. - Always load your API key from
os.environto keep credentials secure. - Async calls are supported for scalable assistant interactions.
- Verify your assistant ID and API key if you encounter errors.
- The OpenAI Python SDK v1+ is required for this integration.