> ## Documentation Index
> Fetch the complete documentation index at: https://docs.upsonic.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# WhatsApp

> Host agents as WhatsApp applications

Use the WhatsApp interface to serve Agents via WhatsApp. It mounts webhook routes on a FastAPI app and sends responses back to WhatsApp users and threads.

## Setup

Required environment variables:

* `WHATSAPP_VERIFY_TOKEN` (for webhook verification)

* `WHATSAPP_ACCESS_TOKEN` (required by WhatsAppTools for sending messages)

* `WHATSAPP_PHONE_NUMBER_ID` (required by WhatsAppTools for sending messages)

* Optional (production): `WHATSAPP_APP_SECRET` (for webhook signature validation)

## Operating Modes

* **TASK** (default) – Each message is processed as an independent task; no conversation history. Best for one-off queries and stateless bots.
* **CHAT** – Messages from the same sender share a conversation session. The agent remembers context. Best for conversational and support use cases.

## Heartbeat

When used with an `AutonomousAgent` that has `heartbeat=True`, the interface periodically sends the agent's `heartbeat_message` to the agent, then delivers the response to the WhatsApp recipient.

The target recipient is resolved automatically from the first incoming message. You can also set it explicitly via `heartbeat_recipient`.

```python theme={null}
import os
from upsonic import AutonomousAgent
from upsonic.interfaces import InterfaceManager, WhatsAppInterface

agent = AutonomousAgent(
    model="anthropic/claude-sonnet-4-6",
    name="WhatsAppBot",
    heartbeat=True,
    heartbeat_period=30,
    heartbeat_message="Summarize any new updates.",
)

whatsapp = WhatsAppInterface(
    agent=agent,
    verify_token=os.getenv("WHATSAPP_VERIFY_TOKEN"),
    app_secret=os.getenv("WHATSAPP_APP_SECRET"),
    mode="chat",
    # heartbeat_recipient="905551234567",  # optional explicit override
)

manager = InterfaceManager(interfaces=[whatsapp])

if __name__ == "__main__":
    manager.serve(host="0.0.0.0", port=8000)
```

## Reset Command (CHAT mode only)

In CHAT mode, senders can clear their conversation by sending the reset command (e.g. `/reset`) as a message. Configure it with `reset_command`; set to `None` to disable.

If the agent has a `workspace` configured, the reset command will also trigger a dynamic greeting message based on the workspace configuration. See [Workspace](/concepts/agents/advanced/workspace) for details.

## Access Control (Whitelist)

Pass `allowed_numbers` (list of phone numbers in international format, e.g. `["905551234567"]`). Only those numbers are processed; others receive "This operation not allowed". Omit `allowed_numbers` (or set `None`) to allow all senders.

## Example Usage

Create an agent, expose it with the `WhatsAppInterface` interface, and serve via `InterfaceManager`. Example with **CHAT** mode, reset command, and optional whitelist:

```python theme={null}
import os
from upsonic import Agent
from upsonic.interfaces import InterfaceManager, WhatsAppInterface, InterfaceMode

agent = Agent(
    model="anthropic/claude-sonnet-4-6",
    name="WhatsAppBot",
)

whatsapp = WhatsAppInterface(
    agent=agent,
    verify_token=os.getenv("WHATSAPP_VERIFY_TOKEN"),
    app_secret=os.getenv("WHATSAPP_APP_SECRET"),
    mode=InterfaceMode.CHAT,
    reset_command="/reset",
    allowed_numbers=["905551234567", "14155551234"],
)

manager = InterfaceManager(interfaces=[whatsapp])

if __name__ == "__main__":
    manager.serve(host="0.0.0.0", port=8000, reload=False)
```

## Core Components

* `WhatsAppInterface` (interface): Wraps an Upsonic `Agent` for WhatsApp via FastAPI.

* `InterfaceManager.serve`: Serves the FastAPI app using Uvicorn.

## `WhatsAppInterface` Interface

Main entry point for Upsonic WhatsApp applications.

### Initialization Parameters

| Parameter             | Type                        | Default              | Description                                                                                                  |
| --------------------- | --------------------------- | -------------------- | ------------------------------------------------------------------------------------------------------------ |
| `agent`               | `Agent`                     | Required             | Upsonic `Agent` instance.                                                                                    |
| `verify_token`        | `Optional[str]`             | `None`               | WhatsApp webhook verification token (or set `WHATSAPP_VERIFY_TOKEN`).                                        |
| `app_secret`          | `Optional[str]`             | `None`               | WhatsApp app secret for signature validation (or set `WHATSAPP_APP_SECRET`).                                 |
| `name`                | `str`                       | `"WhatsApp"`         | Interface name.                                                                                              |
| `mode`                | `Union[InterfaceMode, str]` | `InterfaceMode.TASK` | `TASK` or `CHAT`.                                                                                            |
| `reset_command`       | `Optional[str]`             | `"/reset"`           | Message text that resets chat session (CHAT mode). Set `None` to disable.                                    |
| `storage`             | `Optional[Storage]`         | `None`               | Storage backend for chat sessions (CHAT mode).                                                               |
| `allowed_numbers`     | `Optional[List[str]]`       | `None`               | Whitelist of phone numbers (e.g. `"905551234567"`). `None` = allow all.                                      |
| `heartbeat_recipient` | `Optional[str]`             | `None`               | Explicit WhatsApp phone number for heartbeat delivery. Auto-detected from first incoming message if omitted. |

### Key Methods

| Method            | Parameters    | Return Type | Description                                                            |
| ----------------- | ------------- | ----------- | ---------------------------------------------------------------------- |
| `attach_routes`   | None          | `APIRouter` | Returns the FastAPI router and attaches endpoints.                     |
| `is_user_allowed` | `sender: str` | `bool`      | Whether the sender number is in the whitelist (or whitelist disabled). |

## Endpoints

Mounted under the `/whatsapp` prefix:

### `GET /whatsapp/webhook`

* Verifies WhatsApp webhook (`hub.challenge`).

* Returns `hub.challenge` on success; `403` on token mismatch; `500` if `WHATSAPP_VERIFY_TOKEN` missing.

### `POST /whatsapp/webhook`

* Receives WhatsApp messages and events.

* Validates signature (`X-Hub-Signature-256`); skipped if `WHATSAPP_APP_SECRET` not configured.

* Processes text, image, video, audio, and document messages via the agent.

* Sends replies (splits long messages; uploads and sends generated images).

* Responses: `200 {"status": "processing"}`, `200 {"status": "ignored"}`, or `200 {"status": "invalid_payload"}`, `403` invalid signature, `500` errors.

### `GET /whatsapp/health`

* Health/status of the interface.
