The question came up in the middle of a voice demo. The Omilia agent had just identified the caller, looked up an order and opened a case, all over the phone, and someone across the table asked: "does it work the same on WhatsApp?"

It does, but not on its own. Omilia Cloud Platform (OCP) exposes the agent through a Chat API, Freshdesk receives WhatsApp as tickets, and there is no ready-made connector between the two. You wire the ends together. This is the path we built and tested on a real phone, with the code and the screens.

A heads-up first: Red Lotus is a Freshworks partner. Even so, the "What bothers us" section lists the limits we hit, because they shape the design.

What you will build

Four pieces, and only one of them is your code:

  • The Freshdesk WhatsApp channel, already connected. That is this tutorial's starting point.
  • A Freddy AI Agent Studio AI Agent, attached to the number, which runs a workflow on every customer message.
  • The bridge: your own HTTP endpoint, POST /whatsapp/turn, which takes {phone, text}, talks to OCP and returns text ready to send.
  • The OCP task agent, the same one that handles voice, called through the Chat API.
FRESHDESKOMILIA OCPCustomerWhatsAppWhatsApp channelone ticket per conversationFreddy AI Agentworkflow + API actionSupport grouphuman agentYour bridgeone dialog per phonePOST /whatsapp/turnChat API/chat/dialogsTask agentsame as on voiceYour APIstools{phone, text}reply_text, handoffBearerhandoff
Fig. 1 · Four pieces, only one is your code

Why a bridge in the middle? Because a Studio API action makes one HTTP call and reads fields from the response, and that is all. It does not keep the dialog_id between messages, it does not call again when OCP answers with an announcement, and it cannot fall back to an apology if OCP is slow. The bridge does those three things, and Freddy keeps the job it is good at: receiving the message and delivering the answer.

Prerequisites

  • WhatsApp connected to a Freshdesk account, with the number listed under Admin › Channels › WhatsApp.
  • Freddy AI Agent Studio enabled on the account. It is licensed separately; check your plan.
  • An OCP app with a working task agent, and console access to edit and deploy it.
  • Somewhere with public HTTPS to host the bridge. Ours runs on Azure Functions with Python, but anything that answers HTTP will do.
  • A phone with WhatsApp that is not the company number, for testing.

Step 1: get the OCP agent ready for text

The agent you built for voice almost works as is. Three changes to its Instructions save you trouble.

Channel. The bridge opens each dialog with the input field channel = whatsapp. Tell the agent what to do with it: short sentences, numbers as digits, no "say" or "tell me". If the app declares input fields, add channel and caller_number to the list, or the agent will not see the values.

Continuity. This one cost us an afternoon. Without an explicit instruction, the agent sometimes completed its task right after answering a topic. The answer came back as ANNOUNCEMENT, with no question, and the customer's next message got EXIT. The dialog died, and the next message opened a new one with the greeting and the ID request all over again, mid-conversation. Raising the no-input limit in the console changed nothing. What fixed it were these lines (the agent speaks Brazilian Portuguese, so the instructions are in Portuguese too):

NO WHATSAPP: quando o campo channel vale whatsapp, escreva mensagens curtas, de uma a três frases. Escreva números com algarismos (pedido 1001, R$ 1.249,90, 25/09). Não peça para o cliente falar; peça para digitar ou enviar.
CONTINUIDADE: depois de responder a qualquer assunto, termine sempre com a pergunta 'Posso ajudar em mais alguma coisa?' e aguarde a resposta do cliente. Nunca conclua a tarefa logo depois de responder ou de usar uma ferramenta: conclua somente depois que o cliente disser que não precisa de mais nada ou depois da transferência.
FALHAS: se uma ferramenta falhar, não fale em erro técnico. Tente mais uma vez; se falhar de novo, peça desculpas e ofereça um especialista.

In short: on WhatsApp keep it to one to three sentences with digits for numbers; after every topic always ask "anything else I can help with?" and wait, and only complete the task when the customer says they are done or after a transfer; and if a tool fails, retry once, then apologise and offer a specialist.

Deploy. After saving, run Deploy › Deploy all. The Chat API serves the published version; without the deploy you test the old text and conclude the change did not work.

Step 2: get a Chat API key and talk to the agent from a terminal

In the OCP console, create a Chat API key for the app. The key identifies the app: one app, one key. Before writing any code, talk to the agent from a terminal:

curl -s https://us1-m.ocp.ai/chat/dialogs \
  -H "Authorization: Bearer $OCP_CHAT_KEY" \
  -H "Content-Type: application/json" \
  -d '{
        "utterance": "oi",
        "input_fields": {"channel": "whatsapp", "caller_number": "+5511900000000"}
      }'

The response, trimmed to what the bridge uses:

{
  "dialog_id": "8c1f0e2a-…",
  "action_type": "ASK",
  "responses": [
    {
      "prompts": [
        {"content": "Olá! Aqui é o assistente virtual da Acme. Para continuar, pode me informar seu CPF?"}
      ]
    }
  ]
}

Three fields matter. dialog_id identifies the conversation: send it back on every following message, without input_fields. responses[].prompts[].content is what the agent wants to say, sometimes in more than one block. And action_type tells you what the agent expects from you now. The host us1-m.ocp.ai is our region's; check yours in the console.

The action_type is the contract

This is where most integrations trip. OCP does not answer "one message per message". It answers with an action, and only one of them means "now wait for the customer":

The bridge sends"utterance"OCP answersaction_typeASKsend the text, wait for the customerANNOUNCEMENT · BACKENDsend "[noinput]" again, up to 4 timesTRANSFERhandoff = atendente, drop the dialogEXITsend the text, drop the dialog"[noinput]", same dialog_id
Fig. 2 · Only ASK means 'wait for the customer'
  • ASK: the agent asked something. Send the text and wait.
  • ANNOUNCEMENT and BACKEND: the agent said something or called a tool, and has more to say. On voice, the caller's silence pushes the conversation along; on text, nobody pushes. The bridge sends "[noinput]" on the same dialog and collects the texts, at most four times.
  • TRANSFER: the agent wants a human. Send the text, drop the dialog and flag the handoff.
  • EXIT: the agent is done. Send the text and drop the dialog; the next message starts a new one.

Step 3: write the bridge

The bridge has a small contract: phone and text go in, and out comes text that can always be sent plus a handoff flag. It never returns an error to Studio. If OCP is down, the customer gets an apology in Portuguese and can try again.

The turn

import time
import httpx

OCP_URL = "https://us1-m.ocp.ai/chat/dialogs"
IDLE_SECONDS = 15 * 60                    # a dialog dies after 15 quiet minutes
FOLLOW_UP = {"ANNOUNCEMENT", "BACKEND"}   # the agent has more to say
MAX_FOLLOW_UPS = 4

SAY_SORRY = "Desculpe, estou com uma instabilidade agora. Pode repetir sua mensagem em instantes?"
SAY_TRANSFER = "Vou te transferir para um especialista. Só um instante."
SAY_GOODBYE = "Obrigado pelo contato. Até logo!"


def ocp(dialog_id, utterance, fields, deadline):
    body = {"utterance": utterance}
    if dialog_id:
        body["dialog_id"] = dialog_id      # later turns: the dialog id only
    else:
        body["input_fields"] = fields      # first turn: what the agent should know
    response = httpx.post(OCP_URL, json=body, timeout=max(0.5, deadline - time.monotonic()),
                          headers={"Authorization": f"Bearer {OCP_CHAT_KEY}"})
    response.raise_for_status()
    return response.json()


def prompts(response):
    return [p["content"].strip()
            for block in response.get("responses") or []
            for p in block.get("prompts") or []
            if (p.get("content") or "").strip()]


def turn(key, phone, text, budget=9.0):
    """One customer message in, one sendable answer out. Never raises."""
    deadline = time.monotonic() + budget
    utterance = (text or "").strip() or "[noinput]"
    fields = {"channel": "whatsapp", "caller_number": phone}

    row = store.get(key)
    live = row and time.time() - row["last_at"] < IDLE_SECONDS
    dialog_id = row["dialog_id"] if live else None

    try:
        try:
            response = ocp(dialog_id, utterance, fields, deadline)
        except httpx.HTTPStatusError as error:
            if not (dialog_id and 400 <= error.response.status_code < 500):
                raise
            dialog_id = None               # OCP forgot the dialog: start over, same message
            response = ocp(None, utterance, fields, deadline)
    except httpx.HTTPError:
        return {"reply_text": SAY_SORRY, "action": "continue", "transfer": False,
                "handoff": None, "fallback": True}

    dialog_id = response.get("dialog_id") or dialog_id
    texts = prompts(response)
    action_type = str(response.get("action_type") or "").upper()
    trail = [action_type]
    for _ in range(MAX_FOLLOW_UPS):
        if action_type not in FOLLOW_UP:
            break
        try:
            response = ocp(dialog_id, "[noinput]", fields, deadline)
        except httpx.HTTPError:
            break                          # send what we have
        texts += prompts(response)
        action_type = str(response.get("action_type") or "").upper()
        trail.append(action_type)
    log.info("turn ***%s: %s", key[-4:], " > ".join(trail))   # action types only, never text

    action = {"TRANSFER": "transfer", "EXIT": "end"}.get(action_type, "continue")
    if action == "continue":
        store.put(key, {"dialog_id": dialog_id, "last_at": time.time()})
    else:
        store.delete(key)

    default = {"transfer": SAY_TRANSFER, "end": SAY_GOODBYE}.get(action, SAY_SORRY)
    return {
        "reply_text": "\n\n".join(texts) or default,
        "action": action,                                  # continue | transfer | end
        "transfer": action == "transfer",
        "handoff": "atendente" if action == "transfer" else None,
        "fallback": False,
    }

The details that justify the code:

  • One dialog per phone, with an expiry. The key is the number, digits only. After 15 quiet minutes, the next message opens a new dialog. Keep this somewhere that survives restarts (Table Storage, Redis, a database); process memory does not work on serverless.
  • A 4xx on an old dialog means start over, not fail. If OCP forgot the dialog on its side, the bridge opens a new one with the same message. The customer never notices.
  • One time budget for the whole turn. Every call shares the same deadline, 9 seconds on Freshdesk. The idea is to stay under what the API action waits for. We did not find that limit documented, so we left headroom.
  • Logs without content. Log the action_type trail (ASK, BACKEND > ASK, ANNOUNCEMENT > EXIT) and the last four digits of the phone. That trail is what exposed the continuity problem, and the conversation text never had to be in the log.

The endpoint

import hmac


@app.post("/whatsapp/turn")
def whatsapp_turn(request):
    if not hmac.compare_digest(request.headers.get("x-api-key", ""), BRIDGE_KEY):
        return json_response(401, {"ok": False})
    body = request.json() or {}
    phone = str(body.get("phone") or "")
    key = "".join(ch for ch in phone if ch.isdigit()) or "anon"   # one dialog per phone
    data = turn(key, phone, str(body.get("text") or ""), budget=9.0)
    return json_response(200, {"ok": True, "data": data})        # always 200: Freddy must have a reply

What Studio receives:

{
  "ok": true,
  "data": {
    "reply_text": "Obrigado! Seu cadastro foi confirmado. Em que posso ajudar?",
    "action": "continue",
    "transfer": false,
    "handoff": null,
    "fallback": false
  }
}

Note handoff. It looks redundant next to transfer, and it is. In our tests, Studio conditions were only reliable for testing empty or filled; comparing a boolean gave odd results. So the bridge returns "atendente" when it is time to transfer and null otherwise, and the workflow condition becomes "handoff is none".

Step 4: create the API action in Freddy AI Agent Studio

In Freshdesk, open Freddy AI Agent Studio and go to Library › API actions. Create a new action. It has five tabs, and three of them need care.

Authentication

First create a Custom authentication with the x-api-key header and your bridge's key. Two gotchas: once an action uses the authentication, it can no longer be edited (to rotate the key, create a new one and swap it in the actions), and ticking Hide on the value breaks the test button.

Connect API tab of the action: POST, JSON, the bridge URL and the Custom authentication with the x-api-key header
Connect API: the authentication becomes a locked header

Body

Under Inputs to be used, declare phone and text. On the Connect API tab: POST, JSON payload, the bridge URL, and the two variables in the body:

{
  "phone": "{{phone}}",
  "text": "{{text}}"
}
Body tab of the action with the JSON payload holding the phone and text variables
The body: two variables, nothing else

The workflow's Collect info block fills both variables, in Step 5. Keep accents out of action and input names; Studio rejects them.

Outputs

Under Define outputs, declare the fields the workflow will read. The path starts with data. because the bridge wraps everything in {ok, data}. The description is required and Freddy's model reads it, so write what the field means:

Define outputs tab with data.action, data.handoff, data.transfer, data.fallback and data.reply_text
The outputs the workflow reads

Run Test API with a phone number and an "oi" before moving on. If the response carries your agent's greeting, half the work is done.

Step 5: build the workflow

Create an AI Agent (or use the one that will sit on the number) and, inside it, a workflow. Ours has four blocks and two paths:

Workflow in Freddy AI Agent Studio: User message trigger, Collect info, Execute API action and two condition paths
The whole workflow: four blocks, two paths
  1. User message trigger. Freddy uses the description to decide whether a message fires the workflow. Write one that catches everything: "Any customer message on WhatsApp: greeting, CPF, order number, question, complaint, exchange…". A narrow description leaves messages like a bare order number unanswered.
  2. Collect info. Fills phone and text from the conversation, without asking the customer anything.
  3. Execute API action. The action from Step 4.
  4. Condition paths. If handoff is none, a Custom response with reply_text. On the Else path, an Agent handoff to the support group, also with reply_text, so the customer reads the bot's goodbye before the human joins.

An agent takes up to 20 workflows, but this tutorial needs one. All the intelligence lives in OCP; Freddy carries messages back and forth.

Step 6: attach the AI Agent to the number

In Admin › Channels › WhatsApp, open the number, click Configure and pick Start with AI Agent. Select the agent from Step 5. A number takes a single agent; if another one is answering there, it is replaced.

This is the only screen without a screenshot here: the number we used was disconnected from Freshdesk after testing.

Step 7: test on a real phone

Studio's preview runs on a webchat, not on WhatsApp, and our action returned error F102 there. Do not waste time on it: send a message from a phone to the number. A turn with a tool call in the middle looks like this:

CustomerWhatsAppFreddy AI AgentworkflowBridge/whatsapp/turnOCP/chat/dialogs"I need my invoice"User message → Collect infoPOST {phone, text}{dialog_id, utterance}BACKEND (called a tool){dialog_id, "[noinput]"}ASK + prompts200 {reply_text, handoff: null}Custom response: reply_textall inside the 9 s budget
Fig. 3 · One turn: the BACKEND never reaches the customer

A test script that catches problems early:

  1. "oi": the agent's greeting arrives within a few seconds.
  2. Identification and a lookup: the answer arrives as a single message, even when OCP returned BACKEND before ASK.
  3. A second topic after the first: the agent carries on without asking for the ID again. If it asks, go back to the continuity instruction and to Deploy all.
  4. "I want to talk to a person": the bot's goodbye arrives and the ticket lands in the handoff group.
  5. A wrong OCP key on the bridge: the customer gets the apology, not silence.
  6. Fifteen quiet minutes: the next message starts a new dialog, with the greeting.

What bothers us

It works, and it held up in a live demo. But it is not the cleanest fit, and you should know before you promise anything:

  • Text only on the way out. Studio blocks send formatted text. Buttons, lists and media do not go out this way; if your agent produces a PDF, it becomes a link.
  • Two AI engines on the same turn. Freddy interprets the message to fire the workflow and OCP interprets it again. A trigger with a narrow description drops messages OCP would have understood.
  • One agent per number. You cannot split the same number between native Freddy and OCP by topic.
  • Limited test tooling. The preview does not work for this flow, the locked authentication forces a rebuild to rotate the key, and Hide breaks the test.
  • Two bills. Every conversation goes through Freddy AI Agent and OCP. Do the math with both prices.

If your WhatsApp lives in Zendesk, the design changes: there the bridge receives a webhook and answers straight through the messaging API, with files and a typing indicator. That is in the Omilia on Zendesk WhatsApp tutorial.

Checklist before production

ItemWhy
Persistent dialog storeServerless restarts and loses process memory
Turn budget under the action's timeoutThe customer gets the apology, not silence
A plan to rotate the bridge keyStudio authentication cannot be edited once in use
Logs without text or full phone numbersPrivacy law, and you do not need them to debug
Continuity instruction and Deploy allWithout it the dialog dies mid-conversation
Handoff test into the right groupThe ticket has to land in someone's queue

Leandro is the founder of Red Lotus Tecnologia, specialized in implementing, supporting, and evolving Freshdesk for support teams in Brazil.