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

# Structured Prompting Techniques

> Master advanced prompt structuring methods for complex tasks and consistent results

Structured prompting techniques help you break down complex requests into manageable components, resulting in more accurate and reliable AI responses. These methods are particularly useful for multi-step tasks, technical work, and scenarios requiring precise outputs.

## XML-style structured prompts

Using XML-like tags to organize prompt components improves clarity and helps AI models parse your requirements.

### Basic structure

```xml theme={null}
<task>
Create a REST API endpoint for user authentication
</task>

<requirements>
- Accept email and password via POST request
- Validate credentials against database
- Return JWT token on success
- Return appropriate error codes for failures
</requirements>

<constraints>
- Use Express.js and TypeScript
- Follow REST best practices
- Include rate limiting
- Add comprehensive error handling
</constraints>

<output_format>
Provide the complete TypeScript code with inline comments explaining security considerations.
</output_format>
```

<Tip>
  ZeroTwo's AI models are trained to recognize and respect structured formatting, making this approach highly effective for complex requests.
</Tip>

### Multi-section prompts

For complex tasks with multiple phases:

```xml theme={null}
<context>
I'm building a e-commerce platform. We need to implement a shopping cart system that handles product additions, quantity updates, and price calculations including tax and shipping.
</context>

<current_state>
We have:
- Product database with prices
- User authentication system
- Basic React frontend with Redux
</current_state>

<requirements>
1. Redux slice for cart management
2. Persistent cart storage (localStorage)
3. Real-time price calculations
4. Tax calculation based on user location
5. Shipping cost estimation
</requirements>

<deliverables>
- Redux cart slice with actions and reducers
- React hooks for cart operations
- TypeScript interfaces for cart items
- Unit tests for calculation logic
</deliverables>

<questions>
- Should cart persist across devices?
- How should we handle out-of-stock items?
- Maximum items per cart?
</questions>
```

## Step-by-step decomposition

Breaking complex tasks into explicit steps ensures thorough, sequential execution.

### Sequential task structure

<CodeGroup>
  ```text Problem-solving structure theme={null}
  I need to optimize this slow database query. Let's approach this systematically:

  Step 1: Analyze the current query execution plan
  Step 2: Identify bottlenecks and missing indexes
  Step 3: Propose optimizations
  Step 4: Provide the optimized query
  Step 5: Explain expected performance improvements

  Current query:
  [paste query here]

  Please work through each step explicitly before moving to the next.
  ```

  ```text Development workflow theme={null}
  Create a user profile page following this workflow:

  Phase 1 - Data model:
  - Define TypeScript interfaces
  - Specify required and optional fields
  - Include validation rules

  Phase 2 - Backend:
  - Create API endpoint
  - Implement data fetching
  - Add error handling

  Phase 3 - Frontend:
  - Design component structure
  - Implement UI with Tailwind CSS
  - Add loading and error states

  Phase 4 - Testing:
  - Write unit tests
  - Add integration tests
  - Include edge case scenarios

  Work through each phase completely before proceeding to the next.
  ```
</CodeGroup>

## Template-based prompts

Reusable templates ensure consistency across similar tasks.

### Code review template

```text theme={null}
Review the following code according to this checklist:

Code: [paste code]

Review criteria:
□ Correctness - Does the code work as intended?
□ Security - Are there vulnerabilities?
□ Performance - Any optimization opportunities?
□ Readability - Is it clear and well-structured?
□ Best practices - Does it follow language conventions?
□ Error handling - Are edge cases covered?
□ Testing - Is the code testable?

For each issue found:
1. Severity level (Critical/High/Medium/Low)
2. Description of the problem
3. Recommended fix
4. Code example of the fix
```

### API design template

```text theme={null}
Design a REST API endpoint with the following template:

Purpose: [Describe what this endpoint does]
Method: [GET/POST/PUT/DELETE]
Path: [/api/v1/resource]
Authentication: [Required/Optional/None]

Request:
- Headers: [List required headers]
- Parameters: [Query or path parameters]
- Body: [JSON structure if applicable]

Response:
- Success (200): [JSON structure]
- Created (201): [JSON structure if applicable]
- Error (4xx/5xx): [Error format]

Validation rules:
[List validation requirements]

Rate limits:
[Specify rate limiting]

Example request:
[Provide complete example]

Example response:
[Provide complete example]
```

### Documentation template

```text theme={null}
Document this function/class/module:

Code: [paste code]

Required sections:
1. Overview - What it does and why it exists
2. Parameters - Each parameter with type and description
3. Returns - Return value type and description
4. Exceptions - What errors can be thrown
5. Usage examples - At least 2 realistic examples
6. Notes - Important considerations or gotchas
7. Related - Links to related functions or documentation

Format the output as JSDoc/TypeDoc/Python docstring [specify format].
```

## Constraint-based prompting

Explicitly defining constraints produces outputs that meet specific requirements.

### Strict constraint format

```text theme={null}
Generate a password validation function with these exact constraints:

MUST include:
✓ Minimum 12 characters
✓ At least one uppercase letter
✓ At least one lowercase letter
✓ At least one number
✓ At least one special character (!@#$%^&*)
✓ TypeScript with strict types
✓ Comprehensive error messages

MUST NOT include:
✗ External dependencies
✗ Regex longer than 100 characters
✗ Any console.log statements
✗ More than 50 lines of code

OUTPUT requirements:
- Function signature: validatePassword(password: string): ValidationResult
- Return interface with isValid boolean and errors array
- Include JSDoc comments
- Include 5 unit test cases
```

## Conditional logic in prompts

Guide the AI to make decisions based on specified criteria.

```text theme={null}
Recommend a state management solution for my React app:

App characteristics:
- Team size: [specify]
- App complexity: [simple/moderate/complex]
- API integration: [yes/no]
- Real-time features: [yes/no]
- Performance critical: [yes/no]

Decision logic:
IF complexity is simple AND no real-time features:
  RECOMMEND: React Context API
ELSE IF moderate complexity OR small team:
  RECOMMEND: Zustand
ELSE IF complex with many async operations:
  RECOMMEND: Redux Toolkit
ELSE IF real-time features:
  RECOMMEND: Jotai or Recoil

For the recommendation:
1. Explain why it fits the criteria
2. Provide setup code
3. Show example usage
4. List pros and cons
5. Suggest migration path if needed
```

## Chain-of-thought prompting

Encourage the AI to show its reasoning process for better results.

<Steps>
  <Step title="Explicit reasoning request">
    Add phrases that trigger step-by-step thinking:

    ```text theme={null}
    Let's solve this problem step by step, showing all reasoning:

    Problem: [describe problem]

    Please:
    1. Identify the key challenges
    2. Consider multiple approaches
    3. Evaluate pros and cons of each
    4. Select the best approach with justification
    5. Implement the solution
    6. Explain why this solution is optimal
    ```
  </Step>

  <Step title="Self-critique prompts">
    ```text theme={null}
    Implement a caching layer for our API, then:

    1. Review your implementation
    2. Identify potential issues
    3. Consider edge cases
    4. Propose improvements
    5. Provide the refined version

    Be your own critic and iterate to the best solution.
    ```
  </Step>
</Steps>

## Comparison and analysis structures

For evaluating options systematically:

### Decision matrix format

```text theme={null}
Compare Next.js, Remix, and Gatsby for our documentation site:

Evaluation criteria (rate 1-5 and explain):

Performance:
- Next.js: [rating + explanation]
- Remix: [rating + explanation]
- Gatsby: [rating + explanation]

Developer experience:
- Next.js: [rating + explanation]
- Remix: [rating + explanation]
- Gatsby: [rating + explanation]

SEO capabilities:
- Next.js: [rating + explanation]
- Remix: [rating + explanation]
- Gatsby: [rating + explanation]

Community & ecosystem:
- Next.js: [rating + explanation]
- Remix: [rating + explanation]
- Gatsby: [rating + explanation]

Learning curve:
- Next.js: [rating + explanation]
- Remix: [rating + explanation]
- Gatsby: [rating + explanation]

Final recommendation with reasoning:
[Provide detailed justification]
```

## Persona-based structured prompts

Assign specific roles for domain expertise:

```text theme={null}
Act as a senior security engineer conducting a code security audit.

Code to audit: [paste code]

Audit framework:
1. OWASP Top 10 vulnerabilities check
2. Authentication and authorization review
3. Input validation analysis
4. Data exposure risks
5. Cryptography usage review
6. Dependency security check
7. Error handling security

For each category:
- List findings (if any)
- Severity rating
- Exploitation scenario
- Remediation steps with code examples
- Prevention best practices

Format output as a professional security audit report.
```

## Combining techniques

The most effective prompts often combine multiple structuring techniques:

```xml theme={null}
<role>Senior full-stack architect</role>

<task>Design a real-time notification system</task>

<context>
E-commerce platform with 100K daily active users. Currently using REST APIs. Need to add real-time order updates, chat support, and system alerts.
</context>

<requirements>
MUST have:
- Real-time bidirectional communication
- Scalable to 100K concurrent connections
- Fallback for older browsers
- Message persistence
- Reconnection handling

NICE to have:
- Typing indicators
- Read receipts
- Message history
</requirements>

<deliverables>
Step 1: Architecture design
- Technology choices with justification
- System components diagram description
- Data flow explanation

Step 2: Implementation plan
- Backend: WebSocket server setup
- Frontend: Client connection management
- Database: Message storage schema

Step 3: Code examples
- Server-side event handling
- Client-side connection management
- Error handling and reconnection logic

Step 4: Deployment considerations
- Scaling strategy
- Monitoring approach
- Cost estimation
</deliverables>

<constraints>
- Budget: AWS infrastructure, moderate budget
- Timeline: 4 weeks
- Team: 3 developers
- Must integrate with existing Node.js/React stack
</constraints>
```

## Best practices for structured prompts

<Warning>
  **Avoid over-structuring:**

  * Don't use excessive formatting for simple requests
  * Balance structure with readability
  * Adapt complexity to task requirements
</Warning>

<Tip>
  **Do leverage structure for:**

  * Multi-phase projects
  * Complex technical implementations
  * Tasks requiring specific output formats
  * Situations where consistency matters
  * When you need to reuse similar prompts
</Tip>

## Saving and reusing structures

<Steps>
  <Step title="Use custom instructions">
    Save frequently used structures in [custom instructions](/chat/custom-instructions) for automatic inclusion.
  </Step>

  <Step title="Create specialized assistants">
    Build [assistants](/assistants/create) with embedded structured prompting for specific use cases.
  </Step>

  <Step title="Maintain a prompt library">
    Keep a collection of effective structured prompts for different task types.
  </Step>
</Steps>

## Next steps

<CardGroup cols={2}>
  <Card title="Few-shot learning" icon="graduation-cap" href="/prompts/few-shot-and-demos">
    Enhance structured prompts with examples
  </Card>

  <Card title="Custom instructions" icon="sliders" href="/prompts/custom-instructions-patterns">
    Make structured prompts persistent
  </Card>

  <Card title="Create assistants" icon="robot" href="/assistants/create">
    Build assistants with structured behaviors
  </Card>

  <Card title="Token management" icon="gauge" href="/prompts/tokens-and-limits">
    Optimize structured prompts for token efficiency
  </Card>
</CardGroup>
