Skip to content

Bring Your Own AI

Mcdavid Obioha edited this page Dec 2, 2026 · 1 revision

Bring Your Own AI

Available from v0.8.0. Works in the React package and the script-tag build.

The widget has no AI SDK in it and never handles an API key. You give it two optional functions (or a ready-made adapter that calls your own server), and it adds three things:

  • Polish with AI: a button under the message box that rewrites a rough note into a clear message, with one-click Undo.
  • Smart routing: pick the right agent (Sales or Support) from what the visitor wrote.
  • Instant replies: answer simple questions inside the widget before anyone opens WhatsApp.
Widget (browser)  ──▶  Your server (/api/whatsapp-ai)  ──▶  Claude / OpenAI / Ollama
                       holds the secret key                   returns text or routing

Never put an API key in the browser. Everything a page does is visible in the network tab. Point the widget at your own route, edge function or AI gateway, and rate limit it. Copy-paste proxies are in Backend Recipes.

Option 1: createOpenAICompatibleAI

For any endpoint that speaks the /v1/chat/completions format: OpenAI, Claude through OpenRouter or LiteLLM, Cloudflare AI Gateway, Groq, Ollama, or your own proxy.

import { WhatsAppChat } from 'whatsapp-chat-widget-react';
import { createOpenAICompatibleAI } from 'whatsapp-chat-widget-react/adapters';

// Create once, outside your component.
const ai = createOpenAICompatibleAI({
  endpoint: '/api/whatsapp-ai',
  model: 'gpt-4.1-mini',
  enableRouting: true,
  systemPrompt: 'We run a furniture studio in Lagos. Open Mon to Sat, 9am to 5pm. Delivery takes 3 to 5 days.',
});

<WhatsAppChat
  title="Support Team"
  agents={[
    { id: 'sales', name: 'Sales', role: 'Quotes and pricing', phoneNumber: '+2348000000001' },
    { id: 'support', name: 'Tech Support', role: 'Orders and delivery', phoneNumber: '+2348000000002' },
  ]}
  ai={ai}
/>

In the script build, use the global: ai: WhatsAppChatWidget.createOpenAICompatibleAI({ ... }).

Options

Option Type What it does
endpoint string Required. Full URL (or path) of a /v1/chat/completions endpoint. Use your own server, never a provider URL with a key.
model string Required. Sent as model in the request. If your proxy chooses the model, this can be any label.
headers Record<string, string> Extra request headers. Not secret: visitors can read them.
systemPrompt string For polishing, replaces the default instructions. For routing, it is added as business context before the fixed instructions, so put your hours, prices and FAQ answers here.
enableRouting boolean Adds routeAndTriage. Default false, so you only pay for polishing unless you opt in.

What it sends

Each call is one request:

POST <endpoint>
Content-Type: application/json

{
  "model": "gpt-4.1-mini",
  "temperature": 0.3,
  "messages": [
    { "role": "system", "content": "..." },
    { "role": "user", "content": "..." }
  ]
}

It reads the answer from choices[0].message.content. It does not send max_tokens, so cap that in your proxy. Requests are aborted after 20 seconds.

  • Polishing. system is your systemPrompt, or a default: rewrite the message clearly and politely, keep the meaning, facts and language, add nothing, reply with the message only. The page title is added when known. user is the visitor's text.
  • Routing. system is your systemPrompt (if any) followed by fixed instructions that ask for one JSON object: suggestedAgentId, instantReply, refinedMessage. The model is told to give an instant reply only when it can answer with certainty from your business context, and never to guess prices, availability or policies. user lists the agents (id: name (role)) and the visitor's name, subject and message.
  • The reply is parsed even if the model wraps it in code fences or adds prose. An agent id the model invents is dropped. Empty strings are ignored. If the reply is not JSON at all, the call fails and the widget carries on without AI (see Failure behavior).

Option 2: your own functions

Use any SDK and any prompt:

<WhatsAppChat
  phoneNumber="+2348000000000"
  ai={{
    polishMessage: async (draft, context) => {
      const res = await fetch('/api/polish', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ draft, pageTitle: context.title }),
      });
      const { polished } = await res.json();
      return polished;
    },
    routeAndTriage: async ({ message, agents }) => {
      const res = await fetch('/api/triage', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ message, agents }),
      });
      return res.json(); // { suggestedAgentId?: 'sales', instantReply?: '...' }
    },
  }}
/>

Both functions are optional. Provide one or both.

interface WhatsAppAIConfig {
  polishMessage?: (draft: string, context: PageContext) => Promise<string>;
  routeAndTriage?: (payload: {
    name: string; subject: string; message: string;
    agents?: { id: string; name: string; role?: string }[];
  }) => Promise<{ suggestedAgentId?: string; instantReply?: string; refinedMessage?: string }>;
}

Polish with AI

  • When it shows. Once the message box has 10 or more characters. It stays while a request runs, and while an Undo is available.
  • While working. The button reads Polishing… and is disabled.
  • On success. The message box is replaced with the polished text (trimmed, at most 1,000 characters). An Undo button appears and restores the visitor's original words. Screen readers hear "Message polished. Undo is available."
  • On failure (your function throws, or returns nothing usable). The text is left exactly as it was, and a short notice says so.
  • Context. polishMessage receives the draft and a PageContext (title, url without query or hash, utm, text). It is built even when includePageContext is off, so your function can tailor the rewrite to the page. Nothing from it is added to the WhatsApp message unless includePageContext is on.

Smart routing

routeAndTriage runs when the visitor submits, after the form is validated and before anything is sent. The button reads Checking… meanwhile.

It returns The widget does
suggestedAgentId matching an entry in agents Selects that agent, shows a "Routed to Support" badge, and sends to that agent's number (or conversation). An unknown id is ignored.
refinedMessage Sends that text instead of what the visitor typed.
instantReply Shows it in the widget instead of sending. See below.
nothing / {} Continues unchanged.

The agents it receives have only id, name and role. Phone numbers are never sent to your AI.

The widget does not set a time limit on routeAndTriage, so keep your own endpoint fast (a few seconds) or add a timeout. createOpenAICompatibleAI aborts after 20 seconds.

Instant replies (FAQ deflection)

If instantReply is returned, the panel shows it under "This might help" with two buttons:

  • That solved it. Nothing is sent: no WhatsApp, no webhook, no live conversation, and onSend is not called. The visitor sees "Glad that helped!" and can close the panel.
  • Still need a human on WhatsApp. Continues exactly as if there had been no reply: onSend, the lead webhook, then WhatsApp (or the live chat).

Either choice calls onDeflection, so you can measure how many questions the AI answered:

<WhatsAppChat
  ai={ai}
  onDeflection={({ reply, resolved, submission }) => {
    analytics.track(resolved ? 'faq_deflected' : 'faq_escalated', { subject: submission.subject });
  }}
/>

Failure behavior

AI is an extra, never a gate. If polishMessage or routeAndTriage throws, rejects or returns nothing usable, the visitor keeps their text and reaches WhatsApp as normal. Errors are not shown to the visitor, except the short polish notice. Check your server logs for problems.

Privacy and cost

  • The visitor's name, subject and message are sent to your server, and from there to your AI provider. Mention this in your privacy policy, and in the widget's hint if appropriate.
  • Each polish is one request. With routing on, each submission is one more. Choose a small, cheap model.
  • Put a rate limit and a request-size cap in your proxy. See Backend Recipes.

Troubleshooting

  • No "Polish with AI" button. ai.polishMessage must be set, and the message needs at least 10 characters.
  • Button shows but nothing changes. Open the network tab. A CORS error means your endpoint must allow your site's origin. A 4xx or 5xx or a response without choices[0].message.content counts as failure.
  • Routing never picks an agent. The model must return an id that exists in agents. Make sure your systemPrompt describes each agent's area, and give agents a role.
  • Instant replies are wrong or invented. Put the true facts in systemPrompt and keep the default routing instructions, which tell the model to answer only from them.
  • "Checking…" takes too long. Lower your model's latency or set a timeout on your endpoint.

Clone this wiki locally