# AI Section Builder

The AI Section Builder uses Claude 4.5 Sonnet to automatically generate and create custom field configurations from plain text requirements.

## Overview

Instead of manually creating fields one by one, describe what you need in plain English, and the AI will:
1. Analyze your requirements
2. Design appropriate field configurations
3. Select the best field types for each piece of data
4. Organize fields logically with section headers
5. Create all fields automatically in Filevine

## Location

The AI Section Builder is located at the top of the **Customs Editor** tab in the extension sidebar.

## Setup

### First-Time Configuration

1. Open the extension sidebar
2. Navigate to the "Customs Editor" tab
3. Click "Generate Fields with AI"
4. You'll be prompted to enter your **Anthropic API key**
5. The API key is securely stored and only needs to be entered once

### Getting an API Key

1. Visit [Anthropic Console](https://console.anthropic.com/)
2. Sign up or log in
3. Navigate to API Keys section
4. Create a new API key
5. Copy the key (starts with `sk-ant-`)

## Usage

### Basic Workflow

1. **Fill in the form fields:**
   - Organization ID (auto-populated if logged in)
   - Project Type ID (auto-populated if a project is selected)
   - Click "Load Sections" to load available custom sections
   - Select the target section

2. **Describe your requirements:**
   ```
   I need a medical intake form with:
   - Patient demographics (name, DOB, address, phone, email)
   - Emergency contact information
   - Primary care physician details
   - Insurance information (provider, policy number, group number)
   - Current medications list
   - Known allergies
   - Medical history notes
   ```

3. **Click "Generate Fields with AI"**

4. **Watch the progress:**
   - AI analyzes requirements
   - Fields are generated
   - Fields are created in Filevine sequentially
   - Progress indicator shows success/failure for each field

### Example Requirements

**Legal Case Intake:**
```
Create a case intake form with client information, case details, and billing setup:
- Client name, contact info, and preferred contact method
- Case type and description
- Important dates (incident date, statute of limitations)
- Opposing party information
- Billing arrangement (hourly, contingency, flat fee)
- Retainer amount and payment schedule
```

**Real Estate Transaction:**
```
Build a property transaction tracker with:
- Property address and details (sqft, bedrooms, bathrooms)
- Purchase price and closing date
- Buyer and seller information
- Lender details and loan amount
- Inspection dates and results
- Title company information
- Key deadlines and milestones
```

**Employee Onboarding:**
```
Employee onboarding checklist with:
- Personal information (name, SSN, address, emergency contacts)
- Position details (title, department, start date, salary)
- Benefits selections (health, dental, vision, 401k)
- Equipment assigned (laptop, phone, access cards)
- Training completion dates
- Document signatures (handbook, I-9, W-4)
```

## Field Types

The AI automatically selects appropriate field types:

- **Text fields** for names, descriptions, notes
- **Date fields** for deadlines and important dates
- **Currency fields** for monetary amounts
- **Yes/No fields** for binary choices
- **Person fields** for contacts and team members
- **Dropdown lists** for predefined options
- **Number fields** for quantities and counts
- **Section headers** to organize related fields

## Progress Tracking

The progress panel shows real-time status:

- **⚙️ Processing** - AI is analyzing or fields are being created
- **✓ Success** - Step completed successfully
- **✗ Error** - Step failed (with error message)
- Each created field is listed with its ID

## Error Handling

Common issues and solutions:

### "AI Service not configured"
- You need to enter your Anthropic API key
- Click the generate button and follow the prompt

### "Not authenticated"
- You must be logged into Filevine
- Use the "Check Connection" button in the Documents tab

### "Failed to load sections"
- Verify Organization ID and Project Type ID are correct
- Check that you have permissions for that project type

### Some fields failed to create
- The progress panel shows which fields succeeded and which failed
- Failed fields include error messages
- Successfully created fields are still saved

## Cost Considerations

The AI Section Builder uses the Claude API:
- Each generation uses Claude Sonnet 4.5
- Typical cost: $0.003 - $0.015 per request (depending on complexity)
- Only charged when you click "Generate Fields with AI"
- No cost for loading sections or checking configuration

## Tips for Best Results

1. **Be specific:** The more detail you provide, the better the field configurations
2. **Group related items:** Mention logical groupings (e.g., "contact information section")
3. **Specify requirements:** Indicate which fields should be required
4. **Mention validation:** If you need specific formats (phone numbers, email, etc.)
5. **Include examples:** Provide example values to clarify field purposes

## API Key Security

- API keys are stored locally in Chrome's secure storage
- Keys are never transmitted except to Anthropic's API
- Keys are only accessible to this extension
- You can clear your key by uninstalling the extension

## Technical Details

### Architecture
1. **Frontend** ([sidebar.html](../src/sidebar/sidebar.html)) - Form UI
2. **Sidebar Controller** ([sidebar.js](../src/sidebar/sidebar.js)) - Form handling and progress tracking
3. **Background Script** ([index.js](../src/background/index.js)) - Message routing
4. **AI Service** ([ai-service.js](../src/background/ai-service.js)) - Claude API integration
5. **Web API Client** ([web-api-client.js](../src/background/web-api-client.js)) - Filevine API calls

### Message Flow
```
User Input
   ↓
Sidebar Form Submit
   ↓
Background: Check API Key
   ↓
AI Service: Generate Fields (Claude API)
   ↓
Background: Create Fields (Sequential)
   ↓
Progress Updates (Real-time)
   ↓
Results Display
```

## Future Enhancements

Potential improvements:
- Preview fields before creating
- Edit generated configurations
- Save templates for reuse
- Bulk section creation
- Import requirements from files
- Export field configurations
- Field validation rules
- Conditional field logic

## Related Documentation

- [Custom Field Creator](./CUSTOM_FIELD_CREATOR.md) - Manual field creation
- [Filevine API Documentation](https://support.filevine.io/en/collections/4135869-api-overview)
- [Anthropic API Documentation](https://docs.anthropic.com/claude/reference/getting-started-with-the-api)
