How to beginner · 3 min read

How to use constraints in prompts

Quick answer
Use constraints in prompts by explicitly specifying rules, formats, or limits the AI must follow, such as word count, style, or content restrictions. Embedding these constraints clearly in the prompt ensures the model generates outputs that meet your exact requirements.

PREREQUISITES

  • Python 3.8+
  • OpenAI API key (free tier works)
  • pip install openai>=1.0

Setup

Install the openai Python package and set your API key as an environment variable for secure access.

bash
pip install openai>=1.0

Step by step

Use explicit constraints in your prompt to control the AI's output. For example, limit the response to 50 words and require a formal tone.

python
import os
from openai import OpenAI

client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])

prompt = (
    "Write a formal summary of the benefits of AI in healthcare. "
    "Limit the response to exactly 50 words. "
    "Do not include any technical jargon."
)

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": prompt}]
)

print(response.choices[0].message.content)
output
AI improves healthcare by enabling faster diagnoses, personalized treatments, and efficient data management. It enhances patient outcomes while reducing costs, all explained clearly without complex terms.

Common variations

You can apply constraints for different models, use streaming for real-time output, or implement asynchronous calls for efficiency.

python
import os
from openai import OpenAI

client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])

async def constrained_prompt_async():
    prompt = (
        "Generate a bulleted list of 3 key AI ethics principles. "
        "Each bullet must be one sentence and no longer than 15 words."
    )

    response = await client.chat.completions.acreate(
        model="gpt-4o",
        messages=[{"role": "user", "content": prompt}]
    )

    print(response.choices[0].message.content)

import asyncio
asyncio.run(constrained_prompt_async())
output
- Transparency: AI decisions should be explainable.
- Fairness: Avoid bias in AI outcomes.
- Privacy: Protect user data rigorously.

Troubleshooting

If the AI ignores constraints, make them more explicit or break complex constraints into simpler steps. Also, verify the model supports your constraint style.

Key Takeaways

  • Explicitly state constraints in your prompt to guide AI output precisely.
  • Use clear, simple language for constraints to improve model compliance.
  • Test constraints with different models and adjust wording if ignored.
Verified 2026-04 · gpt-4o
Verify ↗