Skip to main content
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.
import os
from upsonic import AutonomousAgent
from upsonic.interfaces import InterfaceManager, WhatsAppInterface

agent = AutonomousAgent(
    model="openai/gpt-4o-mini",
    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 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:
import os
from upsonic import Agent
from upsonic.interfaces import InterfaceManager, WhatsAppInterface, InterfaceMode

agent = Agent(
    model="openai/gpt-4o-mini",
    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

ParameterTypeDefaultDescription
agentAgentRequiredUpsonic Agent instance.
verify_tokenOptional[str]NoneWhatsApp webhook verification token (or set WHATSAPP_VERIFY_TOKEN).
app_secretOptional[str]NoneWhatsApp app secret for signature validation (or set WHATSAPP_APP_SECRET).
namestr"WhatsApp"Interface name.
modeUnion[InterfaceMode, str]InterfaceMode.TASKTASK or CHAT.
reset_commandOptional[str]"/reset"Message text that resets chat session (CHAT mode). Set None to disable.
storageOptional[Storage]NoneStorage backend for chat sessions (CHAT mode).
allowed_numbersOptional[List[str]]NoneWhitelist of phone numbers (e.g. "905551234567"). None = allow all.
heartbeat_recipientOptional[str]NoneExplicit WhatsApp phone number for heartbeat delivery. Auto-detected from first incoming message if omitted.

Key Methods

MethodParametersReturn TypeDescription
attach_routesNoneAPIRouterReturns the FastAPI router and attaches endpoints.
is_user_allowedsender: strboolWhether 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.