How to write a system prompt for ChatGPT
Quick answer
A system prompt for
ChatGPT sets the assistant's behavior and context before user input. Use the system role in the message array to define instructions, tone, or constraints that guide responses.PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install openai>=1.0
Setup
Install the official openai Python package and set your API key as an environment variable for secure authentication.
pip install openai>=1.0 Step by step
Use the system role in the messages array to provide instructions that define the assistant's behavior. Below is a complete example using the OpenAI Python SDK v1+ with 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 that responds concisely and professionally."},
{"role": "user", "content": "Explain how to write a system prompt for ChatGPT."}
]
response = client.chat.completions.create(
model="gpt-4o",
messages=messages
)
print(response.choices[0].message.content) output
A system prompt sets the assistant's behavior by providing instructions before user input. Use the system role to specify tone, style, or constraints that guide responses effectively.
Common variations
You can customize system prompts for different use cases, such as creative writing, technical support, or role-playing. Also, you can switch models like gpt-4o-mini for faster responses or use async calls for concurrency.
import os
import asyncio
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
async def main():
messages = [
{"role": "system", "content": "You are a friendly assistant that explains concepts simply."},
{"role": "user", "content": "What is a system prompt?"}
]
response = await client.chat.completions.acreate(
model="gpt-4o-mini",
messages=messages
)
print(response.choices[0].message.content)
asyncio.run(main()) output
A system prompt is an instruction that sets the behavior and style of the assistant before it answers user questions.
Troubleshooting
If the assistant ignores your system prompt, ensure the system message is the first in the messages list. Also, verify your API key is valid and the model supports system prompts.
Key Takeaways
- Always place the system prompt as the first message with role
systemin the messages array. - Use clear, concise instructions in the system prompt to control assistant behavior effectively.
- Test different models and prompt styles to optimize response quality and speed.