# AI Quick Reference

## Instant Copy-Paste Examples

### Basic Setup
```php
require_once __DIR__ . '/../core/AI.php';
$ai = AI::getInstance();
```

### Check Availability
```php
if (!$ai->isAvailable()) {
    return $this->fallbackMethod();
}
```

### Simple Chat
```php
$response = $ai->chat('Explain invoice processing');
```

### Chat with Context
```php
$response = $ai->chat(
    'How should I respond?',
    'You are a professional customer support agent'
);
```

### Extract Data from Text
```php
$text = "John Smith, john@acme.com, 555-1234";
$data = $ai->extractData($text, ['name', 'email', 'phone']);
// Returns: ['name' => 'John Smith', 'email' => 'john@acme.com', ...]
```

### Sentiment Analysis
```php
$sentiment = $ai->analyze($feedback, 'sentiment');
// Returns: "positive", "negative", or "neutral"
```

### Intent Detection
```php
$intent = $ai->analyze($message, 'intent');
// Returns: one-word intent like "question", "complaint", "request"
```

### Generate Suggestion
```php
$suggestion = $ai->suggest(
    "Customer is upset about late delivery",
    "customer support representative"
);
```

### Generate Text
```php
$description = $ai->generate("Write a product description for: Widget X2000");
```

## ERP-Specific Examples

### Support Ticket Response
```php
$ai = AI::getInstance();
$context = "Issue: {$ticket['subject']}\nDetails: {$ticket['description']}";
$response = $ai->suggest($context, 'support agent');
```

### Invoice Validation
```php
$prompt = "Invoice: \${$amount}, Customer avg: \${$avg}. Is this unusual?";
$analysis = $ai->generate($prompt);
```

### Customer Sentiment
```php
$sentiment = $ai->analyze($customerNote, 'sentiment');
// Store in database
$this->customerModel->update($id, ['sentiment' => $sentiment]);
```

### Quick Customer Create
```php
$input = $_POST['quick_input']; // "John at Acme, john@acme.com"
$data = $ai->extractData($input, ['name', 'company', 'email', 'phone']);
```

### Email Classification
```php
$category = $ai->analyze($emailBody, 'category');
$priority = $ai->analyze($emailBody, 'intent');
```

## Advanced Options

### Use Different Model
```php
$ai->setModel('mistral:7b');
```

### Longer Timeout
```php
$ai->setTimeout(120); // 2 minutes
```

### Control Creativity
```php
$response = $ai->chat($prompt, null, [
    'temperature' => 0.3  // Lower = more focused
]);
```

## Error Handling Pattern

```php
$ai = AI::getInstance();

// Check service
if (!$ai->isAvailable()) {
    return $this->manualMethod();
}

// Make request
$result = $ai->chat($prompt);

// Handle failure
if ($result === null) {
    error_log('AI failed for: ' . $id);
    return $this->defaultResponse();
}

return $result;
```

## Test Commands

```bash
# Test service
curl http://localhost:11434/api/tags

# Test from CLI
ollama run llama3.2:3b "Hello"

# Test from PHP
php tests2/test_ai.php

# List models
ollama list
```

## Common Issues

### "AI not available"
```bash
brew services restart ollama
```

### Slow responses
```php
$ai->setModel('phi3:mini'); // Use faster model
```

### Want better quality
```bash
ollama pull llama3.1:8b
```
```php
$ai->setModel('llama3.1:8b');
```

## Controller Template

```php
<?php
class MyController extends Controller {
    
    public function aiFeature() {
        $ai = AI::getInstance();
        
        if (!$ai->isAvailable()) {
            return $this->json(['error' => 'AI unavailable'], 503);
        }
        
        $result = $ai->chat($_POST['prompt']);
        
        if ($result === null) {
            return $this->json(['error' => 'AI request failed'], 500);
        }
        
        return $this->json(['success' => true, 'result' => $result]);
    }
}
```

## Model Selection Guide

**Fast & Light**: `phi3:mini` (1.5GB)  
**Balanced**: `llama3.2:3b` (2GB) ✓ Installed  
**Quality**: `mistral:7b` (4GB)  
**Best**: `llama3.1:8b` (5GB)

Download: `ollama pull model_name`

## Files to Reference

- **Examples**: `AI_USAGE_EXAMPLES.md`
- **Setup**: `AI_README.md`
- **Success**: `AI_INSTALLATION_SUCCESS.md`
- **Test**: `tests2/test_ai.php`
- **Code**: `core/AI.php`
