# Cambodia Travel Assistant - Complete AI Implementation Guide

## Overview

Your Cambodia Travel Assistant is now powered by **three AI technologies**:

1. **NLP (Natural Language Processing)** - Intent detection & entity extraction
2. **ChatGPT API** - Advanced conversational AI for travel advice
3. **Dialogflow** - Google's intent classification & webhook fulfillment
4. **Rule-Based System** - Fast, reliable fallback responses

---

## Architecture

```
User Question
    ↓
NLP Service (Intent Detection & Entity Extraction)
    ↓
Rule-Based Matcher (Fast Local Response)
    ↓ [if no match]
Dialogflow (Intent Classification)
    ↓ [if available]
ChatGPT API (Flexible AI Response)
    ↓ [if no success]
Default Response Fallback
```

---

## Installation & Setup

### 1. OpenAI API Key (ChatGPT)

**Required:** ChatGPT API key for advanced travel advice generation.

#### Steps:

1. Go to [OpenAI Platform](https://platform.openai.com/account/api-keys)
2. Create an API key
3. Add to `.env`:
    ```env
    OPENAI_API_KEY=sk_your_key_here
    ```

### 2. Dialogflow (Optional but Recommended)

**Optional:** Google Cloud Dialogflow for structured intent handling.

#### Setup Steps:

1. Go to [Google Cloud Console](https://console.cloud.google.com/)
2. Create a new project
3. Enable Dialogflow API
4. Create a service account with JSON key
5. Create a Dialogflow agent with intents:
    - `find_hotel` - hotel search
    - `itinerary_request` - trip planning
    - `best_beaches` - beach recommendations
    - `cheap_restaurants` - budget dining

6. Configure `.env`:

    ```env
    DIALOGFLOW_PROJECT_ID=your-project-id
    DIALOGFLOW_CREDENTIALS_PATH=/path/to/credentials.json
    DIALOGFLOW_LANGUAGE_CODE=en
    ```

7. (Optional) Set webhook URL for fulfillment:
    ```
    https://yourdomain.com/assistant/dialogflow-webhook
    ```

### 3. Environment Variables

Update your `.env` file:

```env
# AI Services
OPENAI_API_KEY=sk_your_openai_api_key_here
OPENAI_ORGANIZATION_ID=

# Dialogflow (Google Cloud)
DIALOGFLOW_PROJECT_ID=
DIALOGFLOW_CREDENTIALS_PATH=
DIALOGFLOW_LANGUAGE_CODE=en
```

---

## File Structure

```
app/
├── Http/
│   └── Controllers/
│       └── AssistantController.php    # Main controller with all logic
├── Services/
│   ├── NLPService.php                # Intent detection & entity extraction
│   ├── ChatGPTService.php            # OpenAI ChatGPT integration
│   └── DialogflowService.php         # Google Dialogflow integration
config/
├── services.php                       # Added OpenAI & Dialogflow config
resources/
└── views/
    └── assistant/
        └── index.blade.php            # Enhanced UI with AI badges
```

---

## Service Classes

### NLPService

**Purpose:** Extract intent and entities from user questions

**Methods:**

- `detectIntent(string $question)` - Returns intent analysis with confidence
- `extractEntities(string $question)` - Extracts locations, duration, budget
- `calculateSimilarity(string $str1, string $str2)` - String similarity matching
- `requiresExternalData(string $intent)` - Check if intent needs API call

**Example:**

```php
$nlp = new NLPService();
$analysis = $nlp->detectIntent("Find cheap hotels near Angkor Wat");
// Output:
// [
//   'intents' => ['hotel_search', 'budget_inquiry'],
//   'primary_intent' => 'hotel_search',
//   'confidence' => 0.8
// ]

$entities = $nlp->extractEntities("I have 5 days and $300");
// Output:
// [
//   'duration_days' => 5,
//   'budget' => 300
// ]
```

### ChatGPTService

**Purpose:** Generate conversational travel advice using OpenAI's GPT model

**Methods:**

- `generateTravelAdvice(string $question, array $context)` - Get AI response
- `streamTravelAdvice(string $question, callable $callback)` - Stream real-time response
- `setModel(string $model)` - Change model (gpt-3.5-turbo, gpt-4, etc.)

**Example:**

```php
$chatgpt = new ChatGPTService();
$response = $chatgpt->generateTravelAdvice(
    "Best beaches for families in Cambodia?",
    ['intent' => 'beach_inquiry', 'location' => 'beach']
);
```

### DialogflowService

**Purpose:** Handle structured intent classification and webhook fulfillment

**Methods:**

- `detectIntentText(string $question)` - Send to Dialogflow API
- `handleWebhookRequest(array $request)` - Process Dialogflow webhook
- `isAvailable()` - Check if Dialogflow is configured

---

## How It Works

### Request Flow

1. **User sends question** → `/assistant/chat` POST endpoint
2. **NLP Analysis** → `NLPService::detectIntent()` & `::extractEntities()`
3. **Rule-Based Match** → Check against 50+ travel pattern rules
4. **Dialogflow** (if no match) → Send to Dialogflow for intent classification
5. **ChatGPT** (if Dialogflow fails) → Use OpenAI for natural response
6. **Fallback** → Return default helpful message

### Response Structure

```json
{
    "reply": "The best beaches in Cambodia include Koh Rong...",
    "source": "chatgpt",
    "confidence": 0.95
}
```

**Source values:**

- `rule-based` - Matched predefined pattern
- `dialogflow` - Processed by Google Dialogflow
- `chatgpt` - Generated by OpenAI ChatGPT
- `default` - Fallback response

---

## Routes

```php
// Get assistant page
GET /assistant

// Send message and get response
POST /assistant/chat
  Payload: { question: "Where should I visit?" }

// Dialogflow webhook (for fulfillment)
POST /assistant/dialogflow-webhook
  Payload: { queryResult: {...} } (from Dialogflow)
```

---

## Frontend Features

The UI (`resources/views/assistant/index.blade.php`) includes:

- **Real-time typing indicator** - Shows "AI is thinking..."
- **AI source badges** - Displays which technology answered
- **12 sample questions** - Quick-start prompts
- **Gradient design** - Modern, professional appearance
- **Keyboard shortcuts** - Enter to send, Shift+Enter for new line
- **Auto-scroll** - Chat scrolls to latest message
- **Mobile responsive** - Works on phones and tablets
- **Tech stack display** - Shows enabled AI technologies

---

## Customization Guide

### Add More Intent Patterns (NLPService)

Edit `NLPService::detectIntent()`:

```php
'your_intent_name' => [
    '/pattern1\b/',
    '/pattern2\b/',
],
```

### Add More Rule-Based Responses (AssistantController)

Edit `AssistantController::getReplyRules()`:

```php
'/\b(pattern|regex)\b/' => "Your response text here",
```

### Customize ChatGPT System Prompt

Edit `ChatGPTService::buildSystemPrompt()`:

```php
protected function buildSystemPrompt(array $context = []): string
{
    $base = "Your custom system prompt...";
    // ... modify based on context
    return $base;
}
```

### Add Dialogflow Intents

Create intents in your Dialogflow console:

1. Log in to Dialogflow
2. Create new intent (e.g., "special_offer")
3. Add training phrases
4. Set webhook fulfillment in `DialogflowService::handleWebhookRequest()`

---

## Troubleshooting

### ChatGPT Not Responding

```
Error: "OpenAI API key not configured"
```

**Solution:** Add `OPENAI_API_KEY` to `.env`

```
Error: "Unable to generate response"
```

**Solution:** Check OpenAI account has credits

### Dialogflow Not Available

```
Error: "Dialogflow not configured"
```

**Solution:** Set `DIALOGFLOW_PROJECT_ID` and `DIALOGFLOW_CREDENTIALS_PATH` in `.env`

### NLP Not Detecting Intent

**Solution:** Add more patterns to `NLPService::detectIntent()`

```php
'your_intent' => [
    '/more|patterns|to|match/',
],
```

---

## Performance Tips

1. **Cache Common Questions** - Store frequent Q&A pairs in Redis
2. **Rate Limit ChatGPT** - Avoid excessive API calls
3. **Use Rule-Based First** - Predefined responses are instant
4. **Monitor Costs** - ChatGPT usage charged by tokens

---

## API Costs (Estimated Monthly)

| Service                 | Cost          | Usage                     |
| ----------------------- | ------------- | ------------------------- |
| ChatGPT (gpt-3.5-turbo) | $0.01-$0.03   | Per 1K tokens             |
| Dialogflow              | Free tier     | Up to 180K requests/month |
| OpenAI API              | Pay-as-you-go | ~$0.002 per request       |

---

## Next Steps

1. ✅ Add `OPENAI_API_KEY` to `.env`
2. ✅ Test assistant at `/assistant`
3. 🔲 (Optional) Set up Dialogflow
4. 🔲 (Optional) Add more rule-based responses
5. 🔲 Monitor API usage and costs
6. 🔲 Fine-tune system prompt for better responses

---

## Support & Resources

- **OpenAI API Docs:** https://platform.openai.com/docs
- **Dialogflow Docs:** https://cloud.google.com/dialogflow/docs
- **Laravel Docs:** https://laravel.com/docs
- **NLP Concepts:** https://en.wikipedia.org/wiki/Natural_language_processing

---

## License

This implementation follows your project's existing license.
