How to constrain AI behavior with system prompt
system prompt to set explicit instructions that constrain AI behavior before user input. This controls tone, style, and output scope by defining rules or roles, ensuring consistent and safe responses. For example, in OpenAI's chat.completions.create, pass a system message with constraints to guide the model.PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install openai>=1.0
Setup
Install the OpenAI Python SDK and set your API key as an environment variable to securely authenticate requests.
pip install openai>=1.0 Step by step
Use the system message to constrain AI behavior by specifying clear instructions. Below is a complete example using the OpenAI SDK v1+ to create a chat completion where the AI is instructed to respond only with polite, concise answers.
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are a polite assistant who answers concisely and never provides opinions."},
{"role": "user", "content": "Explain quantum computing in simple terms."}
]
)
print(response.choices[0].message.content) Quantum computing uses quantum bits that can be in multiple states simultaneously, enabling faster problem-solving for certain tasks.
Common variations
You can constrain behavior with other models like Anthropic's Claude by using the system= parameter. Also, streaming responses or async calls can be used for real-time constraints.
import os
import anthropic
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
message = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=200,
system="You are a helpful assistant who only answers factual questions and refuses to speculate.",
messages=[{"role": "user", "content": "What is the meaning of life?"}]
)
print(message.content[0].text) I'm here to provide factual information. The meaning of life is a philosophical question without a definitive factual answer.
Troubleshooting
If the AI ignores constraints, ensure your system prompt is explicit and placed as the first message. Avoid ambiguous language and test with different phrasings. Also, verify you are using the correct SDK version and model that supports system prompts.
Key Takeaways
- Always place the system prompt as the first message to set behavior constraints.
- Use explicit, clear instructions in the system prompt to guide AI responses effectively.
- Different SDKs require different ways to pass system instructions; follow their latest patterns.
- Test constraints with varied inputs to ensure consistent AI behavior.
- If constraints fail, refine prompt clarity and verify SDK and model compatibility.