# ai agent

Modul **AI Agent** memungkinkan AI eksternal (Wanovasi AI, OpenAI agent wrapper, atau third-party LLM platform) memproses pesan masuk dari kontak WhatsApp dan mengirim balasan otomatis. Koneksi menggunakan **OAuth 2.0 dengan PKCE** untuk keamanan maksimum.

## 1. Arsitektur

```
┌──────────────────┐  1. Pesan masuk   ┌────────────────────┐
│ Kontak WhatsApp  │ ────────────────▶ │ Innovasia Panel    │
└──────────────────┘                   └─────────┬──────────┘
                                                 │ 2. Forward ke AI
                                                 ▼
                                       ┌────────────────────┐
                                       │  AI Agent Platform │
                                       │  (Wanovasi AI)     │
                                       └─────────┬──────────┘
                                                 │ 3. AI reply via
                                                 │    /send-message
                                                 ▼
┌──────────────────┐  4. Kirim balasan ┌────────────────────┐
│ Kontak WhatsApp  │ ◀──────────────── │ Innovasia Panel    │
└──────────────────┘                   └────────────────────┘
```

## 2. Menghubungkan AI Agent

{% stepper %}
{% step %}

#### Buka Halaman Konfigurasi

**Master Data → AI Agent**

> **Screenshot:** *\[screenshot halaman AI Agent dengan tombol "Hubungkan"]*
> {% endstep %}

{% step %}

#### Klik "Hubungkan AI Agent"

Sistem akan redirect ke halaman authorization AI Agent dengan PKCE flow:

```
GET {ai_base_url}/integration-request?
    response_type=code
    &client_id={client_id}
    &redirect_uri=https://<domain-anda>/master-data/ai-agent/complete
    &code_challenge={PKCE_CHALLENGE}
    &code_challenge_method=S256
    &state={opaque_state}
    &scope=messaging
```

{% endstep %}

{% step %}

#### Login & Authorize di AI Platform

User login di AI Agent platform dan memberikan izin akses.

> **Screenshot:** *\[screenshot halaman authorization AI platform]*
> {% endstep %}

{% step %}

#### Callback & Token Exchange

AI platform redirect kembali ke:

```
https://<domain-anda>/master-data/ai-agent/complete?code={auth_code}&state={state}
```

Sistem validasi state, lalu tukar code menjadi access token:

```
POST {ai_base_url}/integration-token
Content-Type: application/x-www-form-urlencoded

grant_type=authorization_code
&code={received_code}
&code_verifier={PKCE_VERIFIER}
&redirect_uri=https://<domain-anda>/master-data/ai-agent/complete
&client_id={client_id}
```

{% endstep %}

{% step %}

#### Token Tersimpan

Token disimpan di `ai_agent_token` (company config). Status berubah jadi **Connected**.

> **Screenshot:** *\[screenshot halaman AI Agent setelah connected dengan badge hijau]*
> {% endstep %}
> {% endstepper %}

## 3. Endpoint Inbound — AI → Innovasia

AI Agent mengirim balasan ke kontak via endpoint ini. Sistem akan relay ke WhatsApp.

### 3.1 Endpoint

```
POST https://<domain-anda>/api/v1/integration/ai/send-message
```

### 3.2 Headers

| Header         | Value                                    |
| -------------- | ---------------------------------------- |
| `x-api-key`    | API Key terdaftar (middleware `api.key`) |
| `Content-Type` | `application/json`                       |

### 3.3 Body Parameters

| Field     | Tipe   | Wajib | Keterangan                                                   |
| --------- | ------ | ----- | ------------------------------------------------------------ |
| `to`      | String | ✓     | Nomor WhatsApp tujuan (62xxx)                                |
| `type`    | String | ✓     | `text` / `image` / `video` / `document` / `catalog` / `flow` |
| `text`    | String | —     | Isi pesan untuk `type=text`                                  |
| `url`     | String | —     | URL media untuk `type=image/video/document`                  |
| `catalog` | Object | —     | Konfigurasi katalog untuk `type=catalog`                     |
| `flow`    | Object | —     | Konfigurasi flow untuk `type=flow`                           |
| `label`   | String | —     | Caption / button label                                       |

### 3.4 Contoh Payload

**Text:**

```json
{
  "to": "628123456789",
  "type": "text",
  "text": "Halo, ada yang bisa kami bantu?"
}
```

**Document:**

```json
{
  "to": "628123456789",
  "type": "document",
  "url": "https://website.com/brosur.pdf",
  "label": "Brosur Produk Kami"
}
```

**Image:**

```json
{
  "to": "628123456789",
  "type": "image",
  "url": "https://cdn.website.com/promo.jpg",
  "label": "Promo Ramadhan 2025"
}
```

## 4. Keamanan PKCE

PKCE (Proof Key for Code Exchange) mencegah authorization code interception attack.

| Komponen         | Deskripsi                                                                |
| ---------------- | ------------------------------------------------------------------------ |
| `code_verifier`  | Random 43-128 chars, di-generate di sisi Innovasia, disimpan di session  |
| `code_challenge` | `BASE64URL(SHA256(code_verifier))`, dikirim dalam request awal           |
| `state`          | Opaque token (disimpan di `plain_token`), mencegah CSRF, expire 10 menit |
| `code`           | One-time-use authorization code dari AI platform                         |

## 5. Environment Variables

```env
AI_BASE_URL=https://your-ai-platform.com
AI_AGENT_BASE_URL=https://api.your-ai-platform.com
```

## 6. File Sistem

| File                                                    | Fungsi                        |
| ------------------------------------------------------- | ----------------------------- |
| `modules/Integration/Http/Controllers/AIController.php` | OAuth flow + endpoint inbound |
| `config/ai.php`                                         | Konfigurasi URL AI platform   |
| `modules/Integration/Models/IntegrationSession.php`     | State/code\_verifier storage  |

## 7. Flow Integrasi End-to-End

1. **Kontak kirim pesan WA** → masuk ke Innovasia via webhook Meta.
2. **Innovasia forward** pesan ke AI Agent (mekanisme: polling atau push, tergantung AI platform).
3. **AI proses** dan generate balasan.
4. **AI panggil** `POST /api/v1/integration/ai/send-message` dengan API Key.
5. **Innovasia relay** ke WhatsApp Cloud API → kontak terima pesan.

## 8. Troubleshooting

| Gejala                            | Solusi                                                         |
| --------------------------------- | -------------------------------------------------------------- |
| State expired / mismatch          | Coba ulang koneksi. State berlaku 10 menit.                    |
| Invalid code\_verifier            | Pastikan session tidak reset selama flow (cookies aktif).      |
| Pesan AI tidak terkirim           | Cek `storage/logs/laravel.log`. Pastikan WhatsApp token valid. |
| 401 saat POST /send-message       | Header `x-api-key` tidak cocok dengan IntegrationSecret aktif. |
| AI tidak terima pesan dari kontak | Verifikasi webhook Meta → Innovasia → forward ke AI endpoint.  |

## 9. Best Practices

* **API Key untuk AI Agent** sebaiknya berbeda dari API Key partner integrasi lain (prinsip least-privilege).
* **Rate-limit** balasan AI di sisi AI platform untuk mencegah spam / billing overshoot.
* **Validasi nomor tujuan** sebelum kirim — cegah AI mengirim ke nomor yang bukan kontak aktif.
* **Log setiap balasan AI** untuk audit & tuning prompt.

## 10. Support

* **WhatsApp:** 0823-1548-6886


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.innovasia.id/dokumentasi/external-api/ai-agent.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
