## Agent Plugin

The Agent Plugin seamlessly integrates an AI-powered chat agent into your Laravel application, providing real-time, interactive customer support and information retrieval capabilities. Users can engage with the AI agent to ask questions about products, services, and general inquiries, receiving intelligent and context-aware responses.

### Core Functionality

*   **AI-Powered Chat:** Leverages the NeuronAI framework and OpenAI's large language models to provide human-like conversational interactions.
*   **Contextual Understanding:** The AI agent (PharmacyAgent) is trained with specific instructions to act as a friendly and professional pharmacy customer support, prioritizing safety, accuracy, and privacy.
*   **Product Information Retrieval:** Utilizes a custom `GetProducts` tool to search your pharmacy database in real-time for product details based on customer queries.
*   **Real-time Communication:** Employs Laravel Broadcasting with Laravel Reverb to deliver AI responses instantly to the frontend, ensuring a smooth and responsive user experience.
*   **Structured AI Output:** AI responses are generated in a structured format (`ProductOutput`), including product name, ID, and a conversational response, allowing for rich frontend display.
*   **Interactive Frontend:** A Vue.js-based chat widget provides a dynamic interface for user input and displaying conversation history, featuring chat bubbles for both user and AI messages.

### Installation

1.  Download the Agent Plugin from the pharmacy repository.
2.  Place the plugin files into your application's `plugins` directory.
3.  Install the required Composer dependencies:
    ```json
    "neuron-core/neuron-ai": "^2.8",
    "openai-php/client": "^0.18.0",
    "laravel/reverb": "^1.0"
    ```
    Run `composer update` to install these.
4. Setup Laravel Reverb by following the [official documentation](https://laravel.com/docs/11.x/reverb).
5. Add the Agent Plugin service provider to your `config/app.php` providers array if not auto-discovered:
    ```php
    'providers' => [
        // Other Service Providers

        Agent\AgentServiceProvider::class,
    ],
    ```

### Configuration

#### Environment variables (`.env`)

Only the plugin toggle and Laravel Reverb (broadcasting) are configured via `.env`. **API keys and model are not** — see the next section.

```env
AGENT_ENABLED=true # Enables the plugin (routes, migrations, admin menu)

BROADCAST_CONNECTION=reverb # Critical for enabling Reverb broadcasting
REVERB_APP_ID="my-app-id" # Must match Reverb server's app ID
REVERB_APP_KEY="my-app-key" # Must match Reverb server's app key
REVERB_APP_SECRET="my-app-secret" # Must match Reverb server's app secret
REVERB_HOST="127.0.0.1" # Host where Reverb is listening (e.g. 127.0.0.1 or service name in Docker)
REVERB_PORT=8090 # Port where Reverb is listening
REVERB_SCHEME=http # http or https
```

> **Note:** `REVERB_PORT` must not collide with your app's HTTP port. On installs where `APP_PORT=8080` (e.g. the default Docker setup), run Reverb on a different port such as `8090`.

For frontend integration, set the matching Vite variables:
```env
VITE_REVERB_APP_KEY="${REVERB_APP_KEY}"
VITE_REVERB_HOST="${REVERB_HOST}"
VITE_REVERB_PORT="${REVERB_PORT}"
VITE_REVERB_SCHEME="${REVERB_SCHEME}"
```

#### API keys & model (admin panel)

The **OpenAI API key, Pinecone API key, model, and embedding model are configured in the admin panel**, not in `.env`. They are managed under **AI Agent → Settings** and stored encrypted (via the `OptionalEncrypted` cast) in the `agent_settings` table.

After enabling the plugin and running migrations, open **AI Agent → Settings** and enter your OpenAI API key before using the chat. The agent will refuse to respond until a key is set.

### Usage

1.  **Start the Reverb Server:**
    In your development environment, start the Reverb server. If running within a Docker container, execute:
    ```bash
    php artisan reverb:start --debug # --debug for detailed output
    ```
    Ensure the host and port match your `REVERB_HOST` and `REVERB_PORT` settings in `.env`.

2.  **Integrate the Chat Widget:**
    Include the main Vue chat widget component (`AgentChatPopup.vue` or `ChatWidget.vue`) in your application's layout. For example, in a Blade template:
    ```blade
    <div id="app">
        {{-- Your main application content --}}
        <agent-chat-popup location="bottom-right"></agent-chat-popup>
    </div>
    ```
    Ensure your Vue application is properly initialized and mounts this component.

3.  **Backend API Endpoints:**
    The plugin registers the following API routes:
    *   `POST /agent/chat`: For sending user text messages to the AI agent.
    *   `POST /agent/voice`: For submitting audio files for transcription (Whisper API).

### Laravel Broadcasting Setup

The Agent Plugin heavily relies on Laravel's event broadcasting capabilities, specifically using Laravel Reverb for real-time WebSocket communication.

To ensure events from the backend are successfully pushed to your frontend:

1.  **Configure `.env`:** As detailed in the [Configuration](#configuration) section, ensure `BROADCAST_CONNECTION=reverb` and all `REVERB_` variables are correctly set.
2.  **Run Reverb Server:** The `php artisan reverb:start` command (or equivalent Docker setup) must be actively running and accessible by your Laravel application.
3.  **Frontend Listener:** Your frontend application (e.g., Vue.js with Laravel Echo) must be initialized to connect to your Reverb server and subscribe to the relevant channels. The `AgentChatComponent.vue` is configured to listen on the `public-updates` channel for `new.notification` events.
    Example `Laravel Echo` setup (typically in `resources/js/bootstrap.js`):
    ```javascript
    import Echo from 'laravel-echo';
    import Pusher from 'pusher-js'; // Reverb is compatible with the Pusher client

    window.Pusher = Pusher;

    window.Echo = new Echo({
        broadcaster: 'reverb',
        key: import.meta.env.VITE_REVERB_APP_KEY,
        wsHost: import.meta.env.VITE_REVERB_HOST,
        wsPort: import.meta.env.VITE_REVERB_PORT ?? 80,
        wssPort: import.meta.env.VITE_REVERB_PORT ?? 443,
        forceTLS: (import.meta.env.VITE_REVERB_SCHEME ?? 'https') === 'https',
        enabledTransports: ['ws', 'wss'],
    });
    ```
4. Make sure **PCNTL** (Process Control Extenstions) is enabled in your environment. This is required for Laravel Reverb to function correctly as it is what communicates with the kernel operation (Please ask helpdesk if this is not available in Cpanel).
5. Please request helpdesk to expose port 8080 as reverb server runs on that port.

For more in-depth information on Laravel Broadcasting and Reverb, please refer to the official documentation:
*   [**Laravel Broadcasting Documentation**](https://laravel.com/docs/11.x/broadcasting)
*   [**Laravel Reverb Documentation**](https://laravel.com/docs/11.x/reverb)
