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

# Prompt Engineering

> Learn how to write effective prompts for better AI-generated code

## Writing Effective Prompts <Icon icon="bolt-lightning" />

The quality of your prompts directly impacts the quality of AI-generated code. Here's how to craft prompts that get you the best results.

## Prompt Structure

### Basic Template

```text theme={null}
[Context] + [Task] + [Requirements] + [Format/Style]
```

**Example:**

```text theme={null}
I'm building a React e-commerce app. Create a product card component that displays product image, name, price, and add-to-cart button. Use Tailwind CSS for styling and include hover effects.
```

### Advanced Template

For complex tasks, use this structure:

```text theme={null}
**Context**: [Project details, tech stack, existing code]
**Goal**: [What you want to achieve]
**Requirements**: [Specific features, constraints, standards]
**Input/Output**: [Data formats, API structures]
**Style**: [Coding standards, frameworks, libraries]
```

## Prompt Categories

### Code Generation

<AccordionGroup>
  <Accordion title="Frontend Components">
    ```text theme={null}
    Create a React component for [component name] that:
    - [Feature 1]
    - [Feature 2] 
    - [Feature 3]

    Requirements:
    - Use TypeScript
    - Style with [CSS framework]
    - Include [accessibility features]
    - Handle [error cases]

    Props interface should include: [list props]
    ```
  </Accordion>

  <Accordion title="Backend APIs">
    ```text theme={null}
    Build a [framework] API endpoint that:
    - Method: [GET/POST/PUT/DELETE]
    - Route: [/api/path]
    - Functionality: [what it does]

    Requirements:
    - Validate input with [validation library]
    - Connect to [database type]
    - Return [response format]
    - Handle errors: [error cases]
    - Include authentication: [auth method]
    ```
  </Accordion>

  <Accordion title="Database Schemas">
    ```text theme={null}
    Design a [database type] schema for [use case]:

    Tables needed:
    - [Table 1]: [fields and types]
    - [Table 2]: [fields and types]

    Relationships:
    - [relationship descriptions]

    Requirements:
    - Include indexes for [performance needs]
    - Add constraints for [data integrity]
    - Consider [scalability factors]
    ```
  </Accordion>
</AccordionGroup>

### Code Review & Refactoring

<AccordionGroup>
  <Accordion title="Code Review">
    ```text theme={null}
    Please review code for:
    - Performance issues
    - Security vulnerabilities
    - Best practices adherence
    - Code style consistency

    Suggest specific improvements with examples.
    ```
  </Accordion>

  <Accordion title="Refactoring">
    ```text theme={null}
    Refactor code to:
    - [Improvement goal 1]
    - [Improvement goal 2]
    - Follow [coding standard]
    - Maintain backward compatibility

    Please explain the changes you make.
    ```
  </Accordion>
</AccordionGroup>

### Debugging & Troubleshooting

```text theme={null}
I'm getting this error: [error message]

Context:
- Framework: [framework name]
- Environment: [development/production]
- Browser/Node version: [version]

Code that's causing the issue:
[Insert problematic code]

What I've tried:
- [Attempted solution 1]
- [Attempted solution 2]

Please help me fix this and explain what caused it.
```

## Example Prompts

### Frontend Development

<CodeGroup>
  ```text React Dashboard theme={null}
  Create a React dashboard component with:
  - Sidebar navigation with icons
  - Header with user profile dropdown
  - Main content area with cards showing metrics
  - Responsive design using Tailwind CSS
  - Dark/light theme toggle
  - TypeScript interfaces for all props
  ```

  ```text Vue.js Form theme={null}
  Build a Vue.js contact form with:
  - Fields: name, email, message
  - Real-time validation
  - Submit button with loading state
  - Error handling and success messages
  - Composition API syntax
  - Tailwind CSS styling
  ```
</CodeGroup>

### Backend Development

<CodeGroup>
  ```text Express API theme={null}
  Create an Express.js API for a blog platform:
  - Routes: GET /posts, POST /posts, PUT /posts/:id, DELETE /posts/:id
  - MongoDB integration with Mongoose
  - JWT authentication middleware
  - Input validation with Joi
  - Error handling middleware
  - Rate limiting
  ```

  ```text Python FastAPI theme={null}
  Build a FastAPI service for image processing:
  - Upload endpoint accepting multiple image formats
  - Resize, crop, and format conversion functions
  - Async processing with background tasks
  - Response with processed image URLs
  - Error handling for invalid files
  - Pydantic models for request/response
  ```
</CodeGroup>

### Full-Stack Applications

```text CRUD App theme={null}
Create a full-stack task management app:

Frontend (React + TypeScript):
- Task list with add, edit, delete, complete functionality
- Filter by status (all, active, completed)
- Responsive design with Tailwind CSS

Backend (Node.js + Express):
- REST API with CRUD operations
- PostgreSQL database with Prisma ORM
- JWT authentication

Features:
- User registration and login
- Real-time updates with WebSocket
- Dark mode toggle
- Mobile-responsive design
```

## Advanced Techniques

### Context Building

For larger projects, build context step by step so ChatAndBuild can keep track of all your needs.

1. **Start with overview**: "I'm building a \[type] application with \[tech stack]"
2. **Add specifics**: Share relevant code, file structure, or requirements
3. **Reference previous work**: "Based on the component we created earlier..."

### Iterative Refinement

Use follow-up prompts to refine results:

```text theme={null}
The code you generated is good, but can you:
1. Add error handling for [specific case]
2. Optimize the [specific function] for performance
3. Add comments explaining [complex logic]
4. Make it more accessible by [specific improvement]
```

### Multi-Step Tasks

Break complex tasks into steps:

```text theme={null}
I want to build a real-time chat application. Let's start with:

Step 1: Create the basic UI components (chat window, message list, input field)

After this, we'll work on:
- WebSocket integration
- User authentication
- Message persistence
- Typing indicators
```

## Common Mistakes to Avoid

<Warning>
  **Vague Requirements**

  ❌ "Build me a website"
  ✅ "Create a React portfolio website with header, hero section, projects grid, and contact form"
</Warning>

<Warning>
  **Missing Context**

  ❌ "Fix this code \[code snippet]"
  ✅ "This React component isn't updating state correctly. It should \[expected behavior]. Here's the code: \[snippet]"
</Warning>

<Warning>
  **Overloading Prompts**

  ❌ Asking for an entire application in one prompt
  ✅ Breaking it down into components, features, and iterations
</Warning>

## Prompt Library

Save and reuse effective prompts:

### Component Templates

```text theme={null}
React Component Template:
Create a React [component type] component that [main functionality].

Props:
- [prop1]: [type] - [description]
- [prop2]: [type] - [description]

Styling: [CSS framework/approach]
State management: [if needed]
Accessibility: [requirements]
Testing: [if needed]
```

### API Templates

```text theme={null}
API Endpoint Template:
Create a [framework] API endpoint:

Route: [method] [path]
Purpose: [what it does]
Authentication: [requirements]
Validation: [input rules]
Response format: [structure]
Error handling: [scenarios]
```

<Tip>
  **Pro Tip**: Start a conversation with "Help me build \[project type]" and let the AI ask clarifying questions. This often leads to better, more targeted prompts.
</Tip>

<Note>
  Looking for more specific examples? Check out our [chat interface guide](/docs/chat/introduction) and [workbench documentation](/docs/workbench/editor).
</Note>
