Architecture of a WhatsApp AI agent

The parts of an AI agent on the official WhatsApp API: webhook, queue, worker, model, state and sending, and where each one tends to fail.

An AI agent on WhatsApp looks simple on paper: a message arrives, the model writes a reply, the API sends it. What separates a demo from a system that survives production is everything around the model call. This article describes the minimal architecture that holds up, piece by piece, for people building the agent inside their own system on top of the official API.

What are the parts of a WhatsApp AI agent?

There are six: a webhook endpoint that receives the event, a queue, a worker that processes it, the language model, a state store and the send call. None is optional in production, because each one fixes a specific failure that shows up on its own once volume grows.

  • Webhook: receives the event, verifies the signature, deduplicates by event id and answers 2xx. It does nothing else.
  • Queue: separates receiving from processing. It is what lets you answer the webhook fast and absorb spikes.
  • Worker: builds the conversation context, calls the model, runs tools and sends the reply.
  • Model: generates the text or decides to call a tool. It can be swapped without touching the rest.
  • State: the conversation history and the flag saying a person has taken over. It lives in a database, not in process memory.
  • Send: the API call that replies, with an idempotency key derived from the incoming message.

CRPRO Hub delivers the `message.received` event to your webhook and takes the reply on `POST /api/v1/channels/{id}/messages`. The AI agent guide in the docs (in Portuguese) shows the full code of a simple agent; this article focuses on why the structure looks like this.

Why can the model not run inside the webhook?

Because the webhook has a short deadline and the model has an unpredictable duration. Hub expects a 2xx response within 10 seconds; a language model call, especially with tools and a long history, can exceed that. When it does, the delivery counts as failed and comes back, your code calls the model again, and both cost and latency double.

There is a second, costlier effect: an endpoint that keeps failing can be paused. So the rule never bends. The webhook handler does four things, all fast: verify the signature, check whether the event id was already seen, publish the job to the queue and return 2xx. The webhooks reference describes the signature headers and the redelivery policy.

Deduplicating by event id matters because delivery is at least once. The same message can arrive twice, and without deduplication the agent answers the customer twice.

What does the flow look like, from event to reply?

The flow has seven steps in order: the event arrives, the signature is verified, the id is deduplicated, the job is queued, the worker loads state, the model replies and the send goes out with the idempotency key. Only the first four happen inside the webhook deadline.

// worker.js — takes a job from the queue and replies async function processar(job) { const { canal, para, messageId, texto } = job const conversa = await estado.carregar(canal, para) // history + "human took over" flag if (conversa.humanoAssumiu) return const resposta = await modelo.responder({ sistema: SISTEMA, historico: conversa.mensagens.slice(-20), entrada: texto, }) // Same key for the same event: reprocessing does not duplicate the reply. await enviarTexto(canal, para, resposta, 'ia-' + messageId) await estado.anexar(canal, para, texto, resposta) }

Three details in the snippet deserve attention. First, the worker checks the flag that a person took over before spending a model call. Second, the history sent to the model is cut to the latest messages, which keeps cost and latency predictable. Third, the idempotency key comes from the incoming message id, not from a random value: if the job runs twice, the send body is identical and the API returns the original send instead of dispatching a second reply.

That last point has a trap. If the worker calls the model again on the second run, the text changes, and the same key with a different body comes back as an idempotency key reuse error (409). The fix is to store the generated text next to the message id and reuse it on the retry.

Where should conversation state live?

In a database, indexed by channel and contact, never in process memory. A deploy, a restart or a second worker instance wipes or splits that memory, and the agent starts forgetting the conversation or replying twice.

The minimal state has three fields: recent messages, the flag that a person took over, and the timestamp of the customer’s last message. The third lets you tell, at reply time, whether the 24-hour service window is still open; a late reply outside the window comes back with error 131047. If the agent uses long-term memory, it is a separate layer, covered in another article in this series.

DataWhere it livesWhy
Recent historyDatabase, per channel and contactSurvives deploys and multiple instances
Human took overDatabase, same recordThe worker checks it before calling the model
Customer’s last messageDatabase, same recordComputes the 24-hour window
Text already generated per messageDatabase or cacheMakes reprocessing idempotent

What happens when a step fails?

Each step needs its own policy, and the queue is what makes that possible. If the model is down, the job goes back to the queue with growing delay; if the send API refuses, the error decides whether a retry is worthwhile; if everything fails, the job lands in a dead-letter queue and the conversation goes to a person.

  • Model unavailable or slow: requeue with growing backoff and, after a retry limit, tell the customer and call a person.
  • Send refused for rate: respect the backoff. The per-contact limit is about one message every 6 seconds, and two automated systems talking to each other hit it fast (error 131056).
  • Send refused for window: do not retry; the way out is an approved template (error 131047).
  • Duplicate job: the idempotency key and the stored text prevent the second reply.

An agent that goes silent is worse than one that admits the problem. For any failure that does not resolve itself, the last line of defense is always the same: alert the team and tell the customer a person will continue.

What changes if the number is also used on the phone?

What the agent has to watch changes: when someone on the team replies from the phone, Hub delivers `message.echo`, and that event should mark the conversation as taken over by a person. The worker then stops answering that conversation on its own, without running over the human agent.

For that the endpoint must also subscribe to `message.echo`, besides `message.received`. And the inverse filter matters: an endpoint subscribed to every event receives `message.sent` and `message.status` for the agent’s own replies, and answering them creates a loop. Filter by event type right in the handler. Coexistence also has a lower throughput ceiling, 20 messages per second, which rarely matters for an agent but does for anyone sending in bulk.

With the six parts in place, swapping the model, adding a tool or changing the human handoff policy stops being a rewrite and becomes a local change in the worker.

Frequently asked questions

Can I call the model directly in the webhook if it usually answers fast?

It is not safe. The deadline is 10 seconds and model time varies with history size, tools and provider load. One slow call is enough for the delivery to fail and come back. Queue the job and return 2xx first.

Do I need a real queue or is a background process enough?

At low volume, a jobs table in your own database works. What matters is the property: receiving finishes before processing and the job survives a restart. A dedicated queue pays off with several workers and spikes.

How do I stop the agent from answering the same message twice?

In two layers: deduplicate the event by id in the webhook and use an idempotency key derived from the incoming message id when sending. Store the generated text so you can reuse it if the job runs again.

Can state live only in the worker’s memory?

Not in production. Deploys, restarts and more than one instance make memory vanish or diverge. Use a database indexed by channel and contact.

Fontes

Documentação oficial da Meta, conferida em 31 de outubro de 2026.