How to create an OpenAI assistant
Quick answer
Use the
openai SDK v1+ to create an assistant by calling client.chat.completions.create with a conversational messages array. Initialize the OpenAI client with your API key from os.environ and specify a model like gpt-4o for best results.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 openai>=1.0to install the SDK. - Export your API key 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 simple OpenAI assistant that responds to user input using the gpt-4o model.
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello, who won the World Series in 2023?"}
]
response = client.chat.completions.create(
model="gpt-4o",
messages=messages
)
print(response.choices[0].message.content) output
The Texas Rangers won the 2023 World Series.
Common variations
You can customize your assistant by changing the model, adding more context in the system message, or using streaming responses for real-time output.
- Use
gpt-4.1orgpt-4o-minifor different performance/cost tradeoffs. - Implement async calls with
asyncioandawaitif needed. - Use the
messagesarray to maintain conversation history.
Troubleshooting
If you get authentication errors, verify your OPENAI_API_KEY environment variable is set correctly. For rate limit errors, consider retrying with exponential backoff. If the model name is invalid, check the latest supported models in the OpenAI documentation.
Key Takeaways
- Always use the official
openaiSDK v1+ with API keys from environment variables. - Start with the
gpt-4omodel for a strong assistant baseline. - Use the
messagesparameter to provide context and maintain conversation state. - Customize the
systemmessage to define your assistant's behavior. - Handle errors gracefully by checking API key validity and model availability.