How to format messages array in OpenAI chat API
role key with values like user, assistant, or system, and a content key with the message text. For example, [{"role": "user", "content": "Hello"}] is the minimal valid format for the messages parameter in the OpenAI chat API.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 environment:
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
Format the messages array as a list of dictionaries with role and content. Use the OpenAI client from the SDK to send a chat completion request.
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, how do I format the messages array?"}
]
response = client.chat.completions.create(
model="gpt-4o",
messages=messages
)
print(response.choices[0].message.content) You format the messages array as a list of dictionaries, each with a 'role' and 'content' key. Roles include 'system', 'user', and 'assistant'.
Common variations
You can omit the system message if you don't need to set context, or add multiple user and assistant messages to simulate conversation history. Different models like gpt-4o-mini use the same message format. Async calls and streaming responses require different client methods but the message format remains consistent.
import asyncio
import os
from openai import OpenAI
async def async_chat():
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
messages = [
{"role": "user", "content": "Hello asynchronously!"}
]
response = await client.chat.completions.acreate(
model="gpt-4o",
messages=messages
)
print(response.choices[0].message.content)
asyncio.run(async_chat()) Hello asynchronously! How can I assist you today?
Troubleshooting
If you get errors like InvalidRequestError or 400 Bad Request, check that each message dictionary has both role and content keys and that roles are valid strings (user, assistant, system). Also ensure your API key is set correctly in os.environ.
Key Takeaways
- Always format the messages array as a list of dicts with 'role' and 'content' keys.
- Use roles 'system', 'user', and 'assistant' to define message context and flow.
- The latest OpenAI Python SDK requires the messages parameter exactly as a list of role-content dicts.
- Async and streaming calls keep the same message format but use different client methods.
- Validate your environment variable for the API key to avoid authentication errors.