How to pass context in OpenAI thread messages
Quick answer
To pass context in OpenAI thread messages, include the full conversation history as a list of
messages with roles (user, assistant, system) in each API call. Use the client.chat.completions.create method with the messages parameter containing prior messages to maintain context across turns.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
Pass the full conversation history as a list of messages to maintain context in the thread. Each message is a dictionary with role and content. The system role sets behavior, user is user input, and assistant is the AI's prior responses.
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
# Conversation history with context
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello, who won the world series in 2020?"},
{"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."},
{"role": "user", "content": "Where was it played?"}
]
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages
)
print(response.choices[0].message.content) output
The 2020 World Series was played at Globe Life Field in Arlington, Texas.
Common variations
You can use different models like gpt-4.1 or gpt-4o-mini by changing the model parameter. For asynchronous calls, use async libraries or frameworks. Streaming responses require additional handling with event loops or callbacks, which the OpenAI Python SDK supports via separate methods.
Troubleshooting
- If the context is lost, ensure you pass the entire message history every time you call
client.chat.completions.create. - Check that roles are correctly assigned;
systemfor instructions,userfor user inputs, andassistantfor AI replies. - Verify your API key is set correctly in
os.environ.
Key Takeaways
- Always pass the full conversation history in the
messagesparameter to maintain context. - Use the
systemrole message to set assistant behavior at the start of the thread. - Each API call must include prior
userandassistantmessages to keep the thread coherent.