> ## Documentation Index
> Fetch the complete documentation index at: https://docs-v1.latitude.so/llms.txt
> Use this file to discover all available pages before exploring further.

# Constraint-Based Prompting

> Learn how to implement constraint-based prompting to guide AI outputs through explicit limitations and parameters

## What is Constraint-Based Prompting?

Constraint-based prompting is a technique that involves explicitly defining boundaries, requirements, and limitations for AI responses. Rather than relying solely on open-ended instructions, this approach establishes clear parameters that the AI must work within. These constraints can guide everything from content format and structure to style, tone, reasoning processes, and output length, ensuring the generation aligns precisely with user needs.

## Why Use Constraint-Based Prompting?

* **Precision Control**: Ensures outputs adhere to specific requirements and formats
* **Reduced Unwanted Content**: Limits AI responses to explicitly permitted areas
* **Consistency Improvement**: Creates predictable, uniform outputs across multiple generations
* **Focus Enhancement**: Guides the AI to concentrate on the most relevant aspects of a request
* **Complexity Management**: Helps simplify complex tasks by establishing clear boundaries
* **Quality Assurance**: Sets minimum quality standards that responses must meet
* **Creativity Within Bounds**: Enables creative freedom within well-defined parameters

## Basic Implementation in Latitude

Here's a simple constraint-based prompting example for content creation:

```markdown Format-Constrained Response theme={null}
---
provider: OpenAI
model: gpt-4o
temperature: 0.7
---

# Constrained Content Generation

Please generate content that strictly adheres to the following constraints:

## Topic:
{{ topic }}

## Format Constraints:
- Maximum length: 300 words
- Must include exactly 5 paragraphs
- Each paragraph must be 2-4 sentences
- Must include exactly 3 bullet points in the middle paragraph
- Must include a one-sentence summary at the end in bold text

## Style Constraints:
- Tone: Professional and informative
- Avoid: Jargon, colloquialisms, and first-person references
- Vocabulary level: Accessible to general audience (avoid specialized terminology)

## Content Constraints:
- Must include at least 2 specific examples
- Must present balanced perspective with multiple viewpoints
- No speculative content without clear indication (use phrases like "may," "might," "research suggests")
- No claims requiring citations that aren't provided

## Response:
[Generate content that strictly adheres to all constraints above]
```

## Advanced Implementation with Hierarchical Constraints

Let's create a more sophisticated example that implements hierarchical constraints:

<CodeGroup>
  ```markdown Hierarchical Constraint System theme={null}
  ---
  provider: OpenAI
  model: gpt-4o
  temperature: 0.7
  ---

  <step>
  # Constraint Definition and Planning

  Let's define a hierarchical constraint system for addressing this task:

  ## Task:
  {{ task_description }}

  ## Primary Constraints (Must Follow):
  1. Content must be factually accurate
  2. Output must follow the specified structure: [structure details]
  3. Total length must be between [min] and [max] words
  4. Must directly address the core question without tangents

  ## Secondary Constraints (Should Follow):
  1. Content should incorporate key terms: [list key terms]
  2. Examples should come from diverse domains
  3. Language should be accessible to [target audience]
  4. Complex concepts should be explained with analogies

  ## Tertiary Constraints (When Possible):
  1. Include relevant quantitative data when available
  2. Consider multiple perspectives on controversial aspects
  3. Highlight limitations in current knowledge
  4. Connect to broader implications

  ## Constraint Conflicts Resolution Plan:
  If constraints conflict, prioritize in this order:
  1. Primary constraints always take precedence
  2. Secondary constraints yield to primary but override tertiary
  3. Tertiary constraints are implemented only when not compromising higher-level constraints
  </step>

  <step>
  # Content Generation Under Constraints

  Now I'll generate content following the hierarchical constraint system:

  ## Approach:
  I'll start by ensuring all primary constraints are fully satisfied, then incorporate secondary constraints, and finally add tertiary elements where possible without compromising the higher constraints.

  ## Content Framework:
  [Outline the basic structure that will satisfy primary structural constraints]

  ## Initial Draft:
  [Generate content adhering strictly to primary constraints while incorporating as many secondary constraints as possible]
  </step>

  <step>
  # Constraint Compliance Verification

  Let me verify that my response meets all constraints:

  ## Primary Constraint Verification:
  1. Factual accuracy check: [Verification]
  2. Structure compliance: [Verification]
  3. Length requirement: [Verification]
  4. Core question focus: [Verification]

  ## Secondary Constraint Verification:
  1. Key terms inclusion: [Verification]
  2. Example diversity: [Verification]
  3. Language accessibility: [Verification]
  4. Analogy usage: [Verification]

  ## Tertiary Constraint Implementation:
  1. Quantitative data inclusion: [Verification]
  2. Multiple perspectives: [Verification]
  3. Knowledge limitations: [Verification]
  4. Broader implications: [Verification]

  ## Adjustments Needed:
  [Identify any constraints not yet fully satisfied]
  </step>

  <step>
  # Final Constrained Output

  Based on the verification, here is the final output with all constraint levels satisfied:

  ## Final Response:
  [Provide the completed response that satisfies all constraints according to their priority levels]

  ## Constraint Satisfaction Summary:
  - Primary constraints: [Summary of how all primary constraints were met]
  - Secondary constraints: [Summary of how secondary constraints were implemented]
  - Tertiary constraints: [Summary of which tertiary constraints were incorporated]
  - Constraint conflicts encountered: [Any conflicts that arose and how they were resolved]
  </step>
  ```
</CodeGroup>

In this advanced example:

1. **Hierarchical Structure**: Constraints are organized by priority level
2. **Explicit Planning**: The first step focuses on constraint definition and planning
3. **Verification Step**: A dedicated step checks compliance with each constraint
4. **Conflict Resolution**: A clear approach for handling constraint conflicts
5. **Traceability**: The final output includes a summary of how constraints were satisfied

## Parameter-Based Constraints for Technical Content

Use constraint-based prompting to ensure technical accuracy and specification compliance:

<CodeGroup>
  ```markdown Technical Parameter Constraints theme={null}
  ---
  provider: OpenAI
  model: gpt-4o
  temperature: 0.2
  ---

  # Technical Document Generation with Parameter Constraints

  Generate a technical document that strictly conforms to the following parameter constraints:

  ## Document Type:
  {{ document_type }}

  ## Technical Domain:
  {{ technical_domain }}

  ## Parameter Constraints:

  ### Numerical Parameters:
  - Value ranges must stay within: {{ parameter_ranges }}
  - Precision: Use {{ precision_level }} significant figures
  - Units: Always use SI units with explicit notation
  - Statistical significance: Only include results with p < 0.05
  - Measurement uncertainty: Always specify with ± notation

  ### Technical Vocabulary Constraints:
  - Terminology: Use only standard terms from {{ standard_reference }}
  - Abbreviations: Define all abbreviations at first use
  - Naming conventions: Follow {{ naming_convention }} for all variables
  - Technical level: Appropriate for {{ audience_expertise_level }}

  ### Format Constraints:
  - Section hierarchy: Must include [Introduction, Methods, Results, Discussion]
  - Data presentation: All quantitative data must be in tables or graphs
  - Equations: Must be numbered and referenced in text
  - Citations: Follow {{ citation_style }} format

  ### Domain-Specific Constraints:
  {{ domain_specific_constraints }}

  ## Output Requirements:
  Generate a complete technical document that satisfies all parameter constraints above. For any parameter that cannot be satisfied due to insufficient information, explicitly state the assumption made.
  ```
</CodeGroup>

## Multi-Constraint System with Validation

Create a system that applies multiple constraint types and validates compliance:

<CodeGroup>
  ```markdown Multi-Constraint System theme={null}
  ---
  provider: OpenAI
  model: gpt-4o
  temperature: 0.6
  type: agent
  agents:
    - agents/content_creator
    - agents/constraint_validator
    - agents/refinement_agent
  ---

  # Multi-Constraint Content System

  ## Task:
  {{ task_description }}

  ## Constraint Categories:
  1. **Content constraints**: What information must be included or excluded
  2. **Format constraints**: Structural and presentational requirements
  3. **Style constraints**: Tone, voice, and language requirements
  4. **Logic constraints**: Reasoning and argument requirements
  5. **Source constraints**: Requirements for evidence and citations

  Each agent has a specialized role in ensuring constraint compliance while producing high-quality content.

  ## Process:
  1. **Content Creator**: Develops initial content adhering to all constraints
  2. **Constraint Validator**: Checks compliance across all constraint categories
  3. **Refinement Agent**: Makes necessary adjustments to ensure full compliance

  Coordinate to produce a final output that fully satisfies all constraints while maintaining quality and coherence.
  ```

  ```markdown agents/content_creator theme={null}
  ---
  provider: OpenAI
  model: gpt-4o
  temperature: 0.7
  type: agent
  ---

  # Content Creator

  I am a content creator who generates material within strict constraint boundaries.

  ## Task Analysis:
  First, I'll analyze {{ task_description }} to identify all implicit and explicit requirements.

  ## Constraint Internalization:
  I'll internalize all constraints across the five categories:
  - Content constraints: [List specific constraints]
  - Format constraints: [List specific constraints]
  - Style constraints: [List specific constraints]
  - Logic constraints: [List specific constraints]
  - Source constraints: [List specific constraints]

  ## Content Creation Strategy:
  I'll develop content by:
  1. Creating a constraint-compliant outline
  2. Developing each section while continuously checking against constraints
  3. Integrating all elements while maintaining constraint boundaries

  ## Initial Content:
  [Generate content that attempts to satisfy all constraints]
  ```

  ```markdown agents/constraint_validator theme={null}
  ---
  provider: OpenAI
  model: gpt-4o
  temperature: 0.3
  type: agent
  ---

  # Constraint Validator

  I am a validator who systematically checks content against all constraint categories.

  ## Validation Methodology:
  I will evaluate the content creator's output against each constraint using a systematic approach:

  ## Content Constraint Validation:
  - Required elements: [Check for each required element]
  - Prohibited elements: [Check for any prohibited elements]
  - Coverage requirements: [Verify topic coverage]

  ## Format Constraint Validation:
  - Structure requirements: [Verify structural elements]
  - Length requirements: [Verify word/character counts]
  - Formatting specifications: [Check for required formatting]

  ## Style Constraint Validation:
  - Tone consistency: [Evaluate tone against requirements]
  - Language specifications: [Check vocabulary and phrasing]
  - Stylistic elements: [Verify required stylistic features]

  ## Logic Constraint Validation:
  - Reasoning patterns: [Verify logical structure]
  - Argument requirements: [Check argument construction]
  - Consistency: [Identify any logical contradictions]

  ## Source Constraint Validation:
  - Citation requirements: [Verify citation format and presence]
  - Evidence standards: [Check quality of supporting evidence]
  - Authority requirements: [Verify source credibility as required]

  ## Validation Report:
  [Provide detailed validation results for each constraint category, identifying any violations]
  ```

  ```markdown agents/refinement_agent theme={null}
  ---
  provider: OpenAI
  model: gpt-4o
  temperature: 0.5
  type: agent
  ---

  # Refinement Agent

  I am a refinement specialist who adjusts content to ensure full constraint compliance.

  ## Refinement Approach:
  After reviewing the validation report, I'll make targeted adjustments to bring the content into full compliance with all constraints.

  ## Constraint Violation Analysis:
  [Analyze validation report to identify all constraint violations]

  ## Prioritized Refinement Plan:
  1. Critical violations that fundamentally compromise the output
  2. Major violations that significantly affect quality or compliance
  3. Minor violations that require small adjustments

  ## Refinement Implementation:
  [Make specific changes to address each violation while preserving overall quality]

  ## Final Compliance Check:
  [Verify that all refinements successfully address the identified violations]

  ## Refined Output:
  [Present the final constraint-compliant content]
  ```
</CodeGroup>

## Best Practices for Constraint-Based Prompting

<AccordionGroup>
  <Accordion title="Constraint Design">
    **Effective Constraint Types**:

    * **Boundary constraints**: Define limits (min/max words, allowed topics)
    * **Format constraints**: Specify structure and organization
    * **Content constraints**: Dictate what must be included or excluded
    * **Process constraints**: Guide how the AI should reason or approach the task
    * **Quality constraints**: Set standards for output quality
    * **Style constraints**: Define tone, voice, and language characteristics

    **Constraint Clarity**:

    * Use precise, unambiguous language
    * Provide examples where appropriate
    * Quantify constraints when possible (exact numbers rather than "some" or "few")
    * Explicitly state what is not allowed as well as what is required
    * Group related constraints together logically
    * Use hierarchical organization for complex constraint sets
  </Accordion>

  <Accordion title="Constraint Balance">
    **Finding the Right Balance**:

    * Too few constraints may result in unfocused or irrelevant outputs
    * Too many constraints can be restrictive and conflict with each other
    * Prioritize constraints by importance to guide conflict resolution
    * Consider which aspects need tight control versus creative freedom
    * Match constraint strictness to the criticality of requirements
    * Balance positive constraints (must include) with negative constraints (must avoid)

    **Handling Constraint Conflicts**:

    * Establish explicit priority hierarchy for constraints
    * Identify potential conflicts before implementation
    * Provide guidance on resolving competing constraints
    * Allow flexibility in less critical constraints
    * Consider using "soft" constraints (preferences) alongside "hard" constraints (requirements)
    * Include conflict resolution principles in the prompt
  </Accordion>

  <Accordion title="Implementation Techniques">
    **Constraint Structure**:

    * List constraints clearly in categorized sections
    * Consider using numbered or bulleted lists for clarity
    * Use bold or italics to emphasize critical constraints
    * Include both general principles and specific requirements
    * Explicitly label constraint types (e.g., "Format Constraint:")
    * Use tables for complex parameter constraints

    **Verification Methods**:

    * Request explicit confirmation of constraint compliance
    * Ask for justifications of how each constraint was addressed
    * Include a post-generation checklist for self-verification
    * Request identification of any constraints that couldn't be fully satisfied
    * Consider multi-step generation with dedicated verification step
    * Use separate agents for generation and verification in complex cases
  </Accordion>

  <Accordion title="Use Case Selection">
    **Best Applications**:

    * Technical documentation with strict requirements
    * Standardized reports and forms
    * Regulated content (legal, medical, financial)
    * Educational materials with specific pedagogical requirements
    * Brand-compliant marketing content
    * Safety-critical information
    * Multi-author collaborative projects requiring consistency

    **Less Suitable Cases**:

    * Highly creative or exploratory tasks
    * Open-ended brainstorming
    * Artistic expression without defined parameters
    * Casual conversation or entertainment contexts
    * Tasks where constraints cannot be clearly defined in advance
  </Accordion>
</AccordionGroup>

## Advanced Techniques

### Adaptive Constraint Systems

Create constraint systems that adapt based on initial outputs:

<CodeGroup>
  ```markdown Adaptive Constraints theme={null}
  ---
  provider: OpenAI
  model: gpt-4o
  temperature: 0.7
  ---

  <step>
  # Initial Constraint Set

  For this task on {{ topic }}, I'll start with a baseline set of constraints:

  ## Initial Constraints:
  1. Content must address {{ specific_aspect }} of the topic
  2. Response should be approximately 400-600 words
  3. Tone should be informative and neutral
  4. Include at least 2 examples to illustrate key points
  5. Structure should include introduction, main points, and conclusion

  ## Initial Output:
  [Generate content following these initial constraints]
  </step>

  <step as="constraint_assessment" schema={{{
    type: "object",
    properties: {
      additional_constraints: {
        type: "array",
        items: {
          type: "string"
        }
      },
      relaxed_constraints: {
        type: "array",
        items: {
          type: "string"
        }
      },
      constraint_conflicts: {
        type: "boolean"
      }
    },
    required: ["additional_constraints", "relaxed_constraints", "constraint_conflicts"]
  }}}>
  # Constraint Assessment

  Based on the initial output, let me assess the constraint system:

  ## Output Evaluation:
  - Does the output meet all constraints effectively?
  - Are there areas where quality could be improved with additional constraints?
  - Are there constraints that proved too restrictive?
  - Do any constraints conflict with producing the best possible output?

  ## Constraint System Adjustment:
  Based on this analysis, I recommend:

  1. Additional constraints needed: [Identify 0-3 new constraints that would improve output]
  2. Constraints to relax: [Identify 0-2 constraints that should be relaxed]
  3. Constraint conflicts: [Identify whether any constraints are in conflict]
  </step>

  <step>
  # Refined Constraint System

  Based on the assessment, here is the refined constraint system:

  ## Added Constraints:
  {{ for constraint in constraint_assessment.additional_constraints }}
  - {{ constraint }}
  {{ endfor }}

  ## Relaxed Constraints:
  {{ for constraint in constraint_assessment.relaxed_constraints }}
  - {{ constraint }}
  {{ endfor }}

  {{ if constraint_assessment.constraint_conflicts }}
  ## Resolved Conflicts:
  [Explain how the constraint conflicts were resolved]
  {{ endif }}

  ## Final Constraint Set:
  [List the complete set of refined constraints]

  ## Output Under Refined Constraints:
  [Generate new content following the refined constraint system]
  </step>
  ```
</CodeGroup>

<Note>This example uses [structured outputs](/guides/prompt-manager/json-output) to capture the constraint assessment results and dynamically update the constraint system.</Note>

### Constraint-Based Creativity

Use constraints to enhance creativity rather than limit it:

<CodeGroup>
  ```markdown Creative Constraint Framing theme={null}
  ---
  provider: OpenAI
  model: gpt-4o
  temperature: 0.8
  ---

  # Creativity Through Constraints

  ## Creative Challenge:
  {{ creative_challenge }}

  ## Constraint-Based Approach:
  Instead of unlimited freedom, we'll use specific constraints as creativity catalysts.

  ## Constraint Set:
  1. **Medium constraint**: Must use {{ specific_medium }}
  2. **Structural constraint**: Must follow {{ structural_pattern }}
  3. **Element constraint**: Must incorporate these elements: {{ required_elements }}
  4. **Technique constraint**: Must utilize {{ specific_technique }}
  5. **Perspective constraint**: Must be experienced from {{ specific_perspective }}

  ## Creative Process:
  1. **Constraint Analysis**: How can each constraint spark innovative thinking?
     - Medium constraint enables...
     - Structural constraint creates opportunity for...
     - Element constraints suggest connections between...
     - Technique constraint pushes boundaries by...
     - Perspective constraint shifts thinking through...

  2. **Constraint Interaction**: How do these constraints interact to create unique possibilities?
     - Constraint combinations that create interesting tensions...
     - Constraints that amplify each other's creative potential...
     - Unexpected possibilities emerging from constraint intersections...

  3. **Constraint-Driven Solution**:
     [Generate a creative solution that embraces all constraints as creative opportunities rather than limitations]

  ## Reflection on Constraint Benefits:
  [Analyze how the constraints led to more creative outcomes than an unconstrained approach would have produced]
  ```
</CodeGroup>

## Integration with Other Techniques

Constraint-based prompting works well combined with other prompting techniques:

* **Chain-of-Thought + Constraints**: Guide reasoning steps with specific constraints at each stage
* **Few-Shot Learning + Constraints**: Provide examples that demonstrate constraint compliance
* **Iterative Refinement + Constraints**: Progressively adjust constraints between iterations
* **Self-Consistency + Constraints**: Generate multiple outputs under the same constraints and find the best
* **Template-Based Prompting + Constraints**: Build templates with embedded constraint systems

The key is to use constraints strategically to channel the AI's capabilities toward your specific requirements while allowing appropriate flexibility where beneficial.

## Related Techniques

Explore these complementary prompting techniques to enhance your AI applications:

### Structure and Control

* **[Template-Based Prompting](./template-based-prompting)** - Use consistent structures to guide AI responses
* **[Constitutional AI](./constitutional-ai)** - Guide AI responses through principles and constraints
* **[Meta-Prompting](./meta-prompting)** - Use AI to optimize and improve prompts themselves

### Process Guidance

* **[Chain-of-Thought](./chain-of-thought)** - Break down complex problems into step-by-step reasoning
* **[Socratic Questioning](./socratic-questioning)** - Guide reasoning through systematic inquiry
* **[Iterative Refinement](./iterative-refinement)** - Progressively improve answers through multiple passes

### Quality Enhancement

* **[Self-Consistency](./self-consistency)** - Generate multiple solutions and find consensus
* **[Retrieval-Augmented Generation](./retrieval-augmented-generation)** - Enhance responses with external knowledge
* **[Few-Shot Learning](./few-shot-learning)** - Use examples to guide AI behavior
