Grok Chatbot Developer Guide

Technology: grok-chatbot · Category: ai · Last reviewed: 2026-10-18

Source: https://tech-stack.codeamanilabs.org/guide/grok-chatbot

Insight:

A Grok chatbot is not an API call. It is a stateful loop wrapped around a stateless model. The API reference (see xai/) gives you one turn; a bot has to own the other four jobs: persist the transcript, hold a persona steady, execute tools the model asks for, and deliver a reply into a chat surface that has its own rules (WhatsApp's 24-hour window, Telegram's 4096-char cap). The trade-off worth naming up front: Grok's web_search/x_search tools and 500k-1M context make it a strong grounded bot brain, but reasoning latency and per-conversation token growth are what will actually break your build. Cap history, cap steps, meter cost per conversation, and keep a Claude fallback wired behind the same interface.

 ██████╗ ██████╗  ██████╗ ██╗  ██╗     ██████╗██╗  ██╗ █████╗ ████████╗
██╔════╝ ██╔══██╗██╔═══██╗██║ ██╔╝    ██╔════╝██║  ██║██╔══██╗╚══██╔══╝
██║  ███╗██████╔╝██║   ██║█████╔╝     ██║     ███████║███████║   ██║
██║   ██║██╔══██╗██║   ██║██╔═██╗     ██║     ██╔══██║██╔══██║   ██║
╚██████╔╝██║  ██║╚██████╔╝██║  ██╗    ╚██████╗██║  ██║██║  ██║   ██║
 ╚═════╝ ╚═╝  ╚═╝ ╚═════╝ ╚═╝  ╚═╝     ╚═════╝╚═╝  ╚═╝╚═╝  ╚═╝   ╚═╝

Grok Chatbot Developer Guide

Focus: building your own chatbot on the Grok API: the webhook loop, conversation state, persona design, tool calling, streaming into a chat surface, cost guardrails, and a Grok→Claude fallback. Two neighbours, not repeated here:

  • xai/ is the raw API reference (model IDs, SDK setup, image generation).
  • grok-bot/ is xAI's product called Grok Bot: ready-made AI teammates on a cloud computer, used through an app, with no API. If you want a bot you use, read that one. If you want a bot you ship to your customers, you are in the right place.

Overview

The xAI API is stateless by default. Every request is a fresh mind with no memory of the last one. A bot is the machinery you build around that fact:

Job What it means Where it lives
Ingress Receive an inbound message and prove it is real Webhook route + signature verification
Identity Map a phone number / chat ID to a conversation row Your database
State Rebuild the transcript the model needs, and only that History window + summariser
Persona Keep tone, scope, and refusals stable across turns System prompt (instructions)
Action Let the model call your business functions Tool loop
Egress Deliver the reply within the surface's rules Send API + chunking
Economics Know what each conversation cost you Usage logging per turn

Only the middle box is Grok. Six of the seven jobs are yours.

flowchart LR
  A["User in<br/>WhatsApp · Telegram · Discord"] -->|"inbound webhook"| B["Verify signature<br/>+ ACK 200 fast"]
  B --> C["Load conversation<br/>by chat_id"]
  C --> D["Build messages:<br/>persona + summary<br/>+ last N turns"]
  D --> E["Grok<br/>grok-4.7"]
  E -->|"function_call"| F["Execute tools<br/>order lookup · M-Pesa STK<br/>delivery quote"]
  F --> E
  E -->|"final text"| G["Chunk + send<br/>via surface API"]
  E -.->|"on 429 / 5xx / timeout"| H["Claude fallback<br/>same tool schema"]
  H --> G
  G --> I["Persist turn<br/>+ log tokens & cost"]
  I --> C

Which surface?

Surface Transport Streaming to user? The rule that will bite you
WhatsApp Cloud API REST over Graph API, pure HTTP (no SDK) No. One message per send The 24-hour window: outside it, only pre-approved templates go through
Telegram Bot API, grammy Yes, natively, in private chats via sendMessageDraft (Bot API 9.3+, all bots since 9.5) Drafts are ephemeral 30-second previews; you must still sendMessage the final text. 4096-char cap
Discord Gateway + REST, discord.js Simulated via message edits 3s interaction ACK deadline: deferReply() or it fails

Cross-references in this repo: whatsapp-business-api/ for the messaging surface itself, ai-agents/ for the general agent loop across providers, together-ai/ for the cheap open-model tier that can serve as a second fallback.

Official Documentation

Resource URL
xAI quickstart https://docs.x.ai/developers/quickstart
Responses vs Chat Completions (Chat Completions is deprecated) https://docs.x.ai/developers/model-capabilities/text/comparison
Function calling https://docs.x.ai/developers/tools/function-calling
Server-side tools (web_search, x_search) https://docs.x.ai/developers/tools/overview
Models & pricing https://docs.x.ai/developers/models
Tool invocation pricing https://docs.x.ai/developers/pricing
Prompt caching, multi-turn https://docs.x.ai/developers/advanced-api-usage/prompt-caching/multi-turn
Rate limits https://docs.x.ai/developers/rate-limits
AI SDK xAI provider https://ai-sdk.dev/providers/ai-sdk-providers/xai
AI SDK tools & tool calling https://ai-sdk.dev/docs/ai-sdk-core/tools-and-tool-calling
WhatsApp Cloud API https://developers.facebook.com/docs/whatsapp/cloud-api
WhatsApp webhooks https://developers.facebook.com/docs/whatsapp/cloud-api/webhooks
Telegram Bot API (sendMessageDraft) https://core.telegram.org/bots/api#sendmessagedraft

Setup

Install

npm install @ai-sdk/xai ai zod @ai-sdk/anthropic

As of 2026-10-18: @ai-sdk/xai@5.0.24, ai@7.0.143, and @ai-sdk/anthropic@4.0.82 all pin @ai-sdk/provider@4.0.29. Upgrade the three together or the provider types drift. Note the xAI provider is a major version ahead of the Anthropic one (5.x vs 4.x). That is expected, not a mismatch.

Add the messaging client for your surface. WhatsApp Cloud API needs none (plain fetch against the Graph API):

npm install grammy        # Telegram (1.46+ has sendMessageDraft)
npm install discord.js    # Discord
npm install openai        # optional: hand-rolled loop against api.x.ai/v1/responses

Environment variables

# Grok: server-side only, never NEXT_PUBLIC_*
XAI_API_KEY=xai-...

# Fallback provider (codeAmani AI routing policy)
ANTHROPIC_API_KEY=sk-ant-...

# WhatsApp Cloud API
WHATSAPP_ACCESS_TOKEN=<system user token>
WHATSAPP_PHONE_NUMBER_ID=<from Meta app dashboard>
WHATSAPP_VERIFY_TOKEN=<random string you invent, echoed on GET>
WHATSAPP_APP_SECRET=<for X-Hub-Signature-256 verification>

# Telegram
TELEGRAM_BOT_TOKEN=<from @BotFather>
TELEGRAM_WEBHOOK_SECRET=<random; sent as X-Telegram-Bot-Api-Secret-Token>

# Conversation store
DATABASE_URL=<postgres connection string>

The model

Pin an explicit ID. xAI's alias rules: <model> tracks the latest stable version, <model>-latest the latest of any kind, and <model>-<date> never moves. As of 2026-10-18:

Model Context Input / cached / output per 1M (<200k prompt) Use in a bot
grok-4.7 500k $2.00 / $0.50 / $6.00 Flagship. The chat turn
grok-4.6 500k $2.00 / $0.50 / $6.00 Previous flagship, same price. No reason to stay on it
grok-4.3 1M $1.25 / $0.20 / $2.50 Summarisation, classification, long transcripts
grok-build-0.1 256k $1.00 / $0.20 / $2.00 Coding model. Not a chat persona

The 200k cliff: once a request's prompt reaches 200k tokens, every token in that request bills at the higher tier (double the rates above). An uncapped bot transcript drifts across that line. That is why §2 caps history.

grok-4.3 accepts providerOptions.xai.reasoningEffort of 'none' | 'low' | 'medium' | 'high'. 'none' makes it a fast, cheap summariser. The AI SDK docs don't list effort support for grok-4.7 yet, so leave it unset there.

// lib/bot/model.ts
export const GROK_MODEL = "grok-4.7" as const;
export const GROK_CHEAP_MODEL = "grok-4.3" as const;

Retired slugs still resolve, at grok-4.3 prices. grok-4-1-fast-*, grok-4-fast-*, grok-4-0709, and grok-3 were retired on 2026-05-15 and silently redirect to grok-4.3. If an old bot "still works", check which model it is actually billing.

Responses API is the default now

Since AI SDK 7, xai(modelId) calls xAI's Responses API (/v1/responses), not Chat Completions. xAI now marks Chat Completions deprecated ("legacy endpoint, limited updates") and recommends Responses. Two consequences for a bot:

  1. store defaults to true. xAI keeps the input and response for 30 days so you can continue with previous_response_id. For a customer chatbot carrying phone numbers and addresses, that is personal data sitting at a third party. This guide rebuilds history from your own database every turn, so it does not need server-side state: set store: false.
  2. You can still pass the full message history every turn (the AI SDK does), and the Responses API still bills cached prefix tokens at the cached rate.
// Put this on every bot call.
export const XAI_BOT_OPTIONS = { store: false } as const;

1. The bot loop

The shape is always the same, whatever the surface: acknowledge the webhook immediately, then do the work. Meta retries any webhook you do not 200 within seconds, and a retried webhook means a duplicate reply to the user.

// app/api/whatsapp/webhook/route.ts
import { createHmac, timingSafeEqual } from "node:crypto";
import { after } from "next/server";
import { handleTurn } from "@/lib/bot/turn";

// Meta's verification handshake runs once, when you register the callback URL
export async function GET(req: Request) {
  const url = new URL(req.url);
  const mode = url.searchParams.get("hub.mode");
  const token = url.searchParams.get("hub.verify_token");
  const challenge = url.searchParams.get("hub.challenge");

  if (mode === "subscribe" && token === process.env.WHATSAPP_VERIFY_TOKEN) {
    return new Response(challenge, { status: 200 });
  }
  return new Response("forbidden", { status: 403 });
}

export async function POST(req: Request) {
  // Signature is computed over the RAW body. Read text, never req.json() first
  const raw = await req.text();
  if (!verifySignature(raw, req.headers.get("x-hub-signature-256"))) {
    return new Response("invalid signature", { status: 401 });
  }

  const payload = JSON.parse(raw);
  const msg = payload.entry?.[0]?.changes?.[0]?.value?.messages?.[0];

  // ACK first; run the model after the response is sent.
  if (msg?.type === "text") {
    after(() => handleTurn({ chatId: msg.from, text: msg.text.body, messageId: msg.id }));
  }
  return new Response("ok", { status: 200 });
}

function verifySignature(raw: string, header: string | null) {
  if (!header?.startsWith("sha256=")) return false;
  const expected = createHmac("sha256", process.env.WHATSAPP_APP_SECRET as string)
    .update(raw)
    .digest("hex");
  const a = Buffer.from(header.slice(7), "hex");
  const b = Buffer.from(expected, "hex");
  return a.length === b.length && timingSafeEqual(a, b);
}

On a platform without after() (or for work longer than the function timeout), push the turn onto a durable queue instead and let a worker run it. Webhook handlers are the wrong place to wait on a reasoning model.

Idempotency. WhatsApp and Telegram both redeliver. Store the inbound provider message ID with a unique constraint and drop duplicates before you spend a token:

const inserted = await db
  .insertInto("bot_messages")
  .values({ chat_id: chatId, provider_message_id: messageId, role: "user", content: text })
  .onConflict((oc) => oc.column("provider_message_id").doNothing())
  .executeTakeFirst();

if (Number(inserted?.numInsertedOrUpdatedRows ?? 0) === 0) return; // already handled

2. Conversation state

The model is stateless; the transcript is a table. The naive version, appending every turn forever and resending it, works for a week. Then it bills you for a 200k-token prompt (at the doubled tier) on every "asante".

create table bot_conversations (
  id           uuid primary key default gen_random_uuid(),
  chat_id      text not null unique,      -- 254712345678, or Telegram chat.id
  surface      text not null,             -- 'whatsapp' | 'telegram' | 'discord'
  summary      text,                      -- rolling compression of older turns
  locale       text not null default 'en',
  last_user_at timestamptz,               -- drives the WhatsApp 24h window check
  created_at   timestamptz not null default now()
);

create table bot_messages (
  id                  bigserial primary key,
  conversation_id     uuid not null references bot_conversations(id) on delete cascade,
  role                text not null,      -- 'user' | 'assistant' | 'tool'
  content             jsonb not null,
  provider_message_id text unique,        -- idempotency key
  provider            text,               -- 'xai' | 'anthropic' | 'none'
  prompt_tokens       int,
  completion_tokens   int,
  cached_tokens       int,
  cost_usd            numeric(12,6),
  created_at          timestamptz not null default now()
);

create index on bot_messages (conversation_id, created_at desc);

The window + summary pattern

Keep the last N turns verbatim; compress everything older into one paragraph the persona can read.

// lib/bot/history.ts
import type { ModelMessage } from "ai";

const VERBATIM_TURNS = 12;

export async function buildMessages(conversationId: string): Promise<ModelMessage[]> {
  const convo = await getConversation(conversationId);
  const recent = await getRecentMessages(conversationId, VERBATIM_TURNS);

  const messages: ModelMessage[] = [];
  if (convo.summary) {
    messages.push({
      role: "user",
      content: `[Earlier in this conversation]\n${convo.summary}`,
    });
  }
  for (const m of recent) {
    messages.push({ role: m.role, content: m.content } as ModelMessage);
  }
  return messages;
}

Re-summarise on a threshold, not on every turn. A summary call is a full model call, so run it on the cheap model with reasoning off:

import { xai } from "@ai-sdk/xai";
import { generateText } from "ai";

export async function maybeCompress(conversationId: string) {
  const count = await countMessagesSinceSummary(conversationId);
  if (count < 24) return;

  const { text } = await generateText({
    model: xai(GROK_CHEAP_MODEL),
    instructions:
      "Compress this customer conversation into under 150 words. Preserve: names, " +
      "order numbers, amounts, phone numbers, delivery addresses, and any unresolved " +
      "request. Drop pleasantries. Write in the third person.",
    messages: await getAllMessagesSinceSummary(conversationId),
    providerOptions: { xai: { ...XAI_BOT_OPTIONS, reasoningEffort: "none" } },
  });

  await saveSummary(conversationId, text);
}

Prompt caching

A bot's prompt is mostly a stable prefix (persona + summary) with a short tail, which is exactly what xAI's prefix cache rewards. Three rules from xAI's multi-turn caching docs:


3. Persona design

The system prompt is the only thing standing between "helpful shop assistant" and "Grok being Grok at your customer". Treat it as code: version it, test it, and never build it from user input.

// lib/bot/persona.ts
export function buildInstructions(ctx: {
  businessName: string;
  locale: "en" | "sw";
  hoursText: string;
}) {
  return [
    `You are the WhatsApp assistant for ${ctx.businessName}, a shop in Nairobi.`,
    "",
    "## Scope",
    "You handle: product availability, prices in KES, order status, delivery times,",
    "and M-Pesa payment. For anything else, say you'll pass it to a human and stop.",
    "",
    "## Voice",
    "Short. Two or three sentences, then a question or a next step. This is WhatsApp,",
    "not email. No markdown headings, no bullet lists, no emoji unless the customer",
    "used one first.",
    ctx.locale === "sw"
      ? "Reply in the language the customer writes in. Kiswahili and Sheng are both fine; keep numbers and product names in the original."
      : "Reply in English.",
    "",
    "## Hard rules",
    "- Never invent a price, stock level, or order status. Call a tool or say you don't know.",
    "- Never state that a payment succeeded. Only confirm what check_payment_status returns.",
    "- Never ask for an M-Pesa PIN. Nobody legitimate ever does.",
    "- Amounts are whole KES. Phone numbers are 254XXXXXXXXX.",
    `- Shop hours: ${ctx.hoursText}. Outside them, say when you reopen.`,
    "",
    "## Escalation",
    "If the customer is angry, asks for a refund, or repeats a question twice,",
    "call handoff_to_human and say a person will reply shortly. Do not keep trying.",
  ].join("\n");
}

Four things make the difference between a demo and a bot that survives a full shift:

  1. Scope fence before voice. A model that knows what it must not answer degrades gracefully; a model that only knows its tone will confidently answer anything.
  2. "Call a tool or say you don't know." State this explicitly. It is the single highest-leverage line against hallucinated stock levels and invented order numbers.
  3. An escalation tool. Without one, the model's only options are to keep improvising or to refuse. Give it a third door.
  4. Never interpolate user text into the persona. Customer content belongs in a user message, always. Interpolating it is prompt injection with extra steps.

4. Tool calling from a bot loop

This is where a bot stops being a chat toy. The AI SDK runs the loop for you (the model asks, your execute runs, the result goes back, repeat), bounded by stopWhen. Custom tools reach xAI's Responses API as type: "function" tools.

// lib/bot/tools.ts
import { tool } from "ai";
import { z } from "zod";

export const botTools = {
  check_stock: tool({
    description: "Look up whether a product is in stock and its current price in KES.",
    inputSchema: z.object({
      query: z.string().describe("Product name or SKU as the customer said it"),
    }),
    execute: async ({ query }) => {
      const items = await searchInventory(query);
      return items.slice(0, 5).map((i) => ({ sku: i.sku, name: i.name, qty: i.qty, price_kes: i.priceKes }));
    },
  }),

  request_mpesa_payment: tool({
    description:
      "Send an M-Pesa STK Push to the customer's phone for a confirmed order. " +
      "Only call this after the customer has explicitly agreed to the total.",
    inputSchema: z.object({
      order_id: z.string().uuid(),
      amount_kes: z.number().int().positive().describe("Whole KES only. Daraja rejects decimals"),
      phone: z.string().regex(/^254\d{9}$/, "Must be 254XXXXXXXXX"),
    }),
    execute: async ({ order_id, amount_kes, phone }) => {
      // Idempotency: one live STK per order. See MPESA_PATTERNS.md.
      const existing = await getLiveCheckout(order_id);
      if (existing) return { status: "already_pending", checkout_request_id: existing.id };

      const res = await stkPush({ order_id, amount: amount_kes, phone });
      await saveCheckoutRequestId(order_id, res.CheckoutRequestID);
      return { status: "prompt_sent", checkout_request_id: res.CheckoutRequestID };
    },
  }),

  check_payment_status: tool({
    description: "Read the recorded status of an M-Pesa checkout. Never guess payment status.",
    inputSchema: z.object({ checkout_request_id: z.string() }),
    execute: async ({ checkout_request_id }) => getCheckoutStatus(checkout_request_id),
  }),

  handoff_to_human: tool({
    description: "Escalate to a human agent. Use for refunds, complaints, or repeated confusion.",
    inputSchema: z.object({ reason: z.string(), urgency: z.enum(["normal", "high"]) }),
    execute: async ({ reason, urgency }) => {
      await openSupportTicket({ reason, urgency });
      return { escalated: true };
    },
  }),
};
// lib/bot/generate.ts
import { xai } from "@ai-sdk/xai";
import { generateText, isStepCount } from "ai";
import { botTools } from "./tools";
import { buildInstructions } from "./persona";
import { GROK_MODEL, XAI_BOT_OPTIONS } from "./model";

export async function runTurn(conversationId: string, ctx: PersonaCtx) {
  const result = await generateText({
    model: xai(GROK_MODEL),
    instructions: buildInstructions(ctx),
    messages: await buildMessages(conversationId),
    tools: botTools,
    // Default is isStepCount(1). WITHOUT this the loop stops after the first
    // tool call and your user gets an empty reply.
    stopWhen: isStepCount(5),
    maxOutputTokens: 600,               // WhatsApp bubbles are small
    headers: { "x-grok-conv-id": conversationId },
    providerOptions: { xai: { ...XAI_BOT_OPTIONS, promptCacheKey: conversationId } },
  });

  return {
    text: result.text,
    usage: result.usage,               // v7: totals across ALL steps
    steps: result.steps,               // per-step usage, needed for exact costing (§6)
  };
}

Three rules for bot tools

Scoping tools to the caller

A tool that reads customer data must get the caller's identity from your code, never from a model-supplied argument. The model will happily pass someone else's order number. AI SDK v7 does this with typed tool context: the tool declares a contextSchema, execute receives { context }, and each call supplies a toolsContext map keyed by tool name. (experimental_context from older SDKs is gone.)

const callerContext = z.object({ chatId: z.string() });

const check_order = tool({
  description: "Look up an order by reference for the CURRENT customer.",
  inputSchema: z.object({ reference: z.string().min(4) }),
  contextSchema: callerContext,
  execute: async ({ reference }, { context }) => {
    const order = await db.order.findFirst({ where: { reference, chatId: context.chatId } });
    return order ?? { error: "not_found" };
  },
});

await generateText({
  model: xai(GROK_MODEL),
  // ...
  tools: { check_order },
  toolsContext: { check_order: { chatId } }, // required once any tool declares contextSchema
});

"Live Search" (the old search_parameters request field) is gone from xAI's docs. Grounding is now done with server-side tools that xAI runs on its own infrastructure:

Tool AI SDK Price
web_search xai.tools.webSearch() $5 per 1k calls
x_search xai.tools.xSearch() $5 per 1k posts returned + $10 per 1k profiles

Plus the tokens the results add to the prompt.

The sources disagree on mixing these with your function tools. xAI's docs say server-side tools can be combined with client-side functions in one request. The @ai-sdk/xai@5.0.24 docs say the Responses API "cannot mix server-side tools with client-side function tools in the same request." Until you have tested the combination on your exact versions, use the shape that works under either rule: give the bot a function tool that runs search as its own request.

// lib/bot/tools.ts (add to botTools)
import { xai } from "@ai-sdk/xai";
import { generateText } from "ai";

search_web: tool({
  description:
    "Look up current facts on the web (today's prices, schedules, news). " +
    "Only use when the answer depends on information from today.",
  inputSchema: z.object({ query: z.string() }),
  execute: async ({ query }) => {
    const { text, sources } = await generateText({
      model: xai(GROK_MODEL),
      prompt: `Answer briefly and factually: ${query}`,
      tools: { web_search: xai.tools.webSearch() },
      providerOptions: { xai: { ...XAI_BOT_OPTIONS, maxTurns: 3 } }, // caps xAI's internal search loop
    });
    return {
      answer: text.slice(0, 1200),
      sources: sources.flatMap((s) => (s.sourceType === "url" ? [s.url] : [])).slice(0, 3),
    };
  },
}),

This also gives you a natural meter: count search_web calls per conversation and price them at $0.005 each.

Owning the loop by hand (Responses API)

If you would rather not use the AI SDK, write the loop against /v1/responses. Do not write new code against Chat Completions; xAI marks it deprecated. The documented shape: the model returns function_call items; you reply with function_call_output items and chain with previous_response_id.

import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.XAI_API_KEY,
  baseURL: "https://api.x.ai/v1",
  timeout: 360_000, // reasoning models think before they answer
});

// The SDK's FunctionTool type requires `strict`. true needs additionalProperties: false.
const tools: OpenAI.Responses.FunctionTool[] = [
  {
    type: "function",
    name: "check_stock",
    description: "Look up stock and price in KES.",
    strict: false,
    parameters: { type: "object", properties: { query: { type: "string" } }, required: ["query"] },
  },
];

let response = await client.responses.create({ model: "grok-4.7", input: history, tools });

for (let step = 0; step < 5; step++) {
  const calls = response.output.filter((item) => item.type === "function_call");
  if (calls.length === 0) break;

  // Parallel tool calls are ON by default. Resolve ALL of them before continuing.
  const outputs = await Promise.all(
    calls.map(async (call) => ({
      type: "function_call_output" as const,
      call_id: call.call_id,
      output: JSON.stringify(await runTool(call.name, JSON.parse(call.arguments))),
    })),
  );

  response = await client.responses.create({
    model: "grok-4.7",
    previous_response_id: response.id,
    input: outputs,
    tools,
  });
}

const reply = response.output_text;

previous_response_id only works because store defaults to true, so xAI keeps the conversation for 30 days. If that is not acceptable for your data, resend the full input each step instead (what the AI SDK path does with store: false). parallel_tool_calls: false disables multi-call responses if your tools are not safe to run concurrently. With streaming, a function call arrives whole in a single chunk; it is not streamed across deltas.


5. Streaming into a chat surface

Chat surfaces are not terminals, and each one streams differently:

Telegram: sendMessageDraft

Bot API 9.3 added sendMessageDraft ("stream a partial message to a user while the message is being generated"); 9.5 opened it to all bots. The rules, from the Bot API reference:

// lib/bot/stream-telegram.ts
import type { Bot } from "grammy";
import { xai } from "@ai-sdk/xai";
import { streamText, isStepCount } from "ai";

const TG_LIMIT = 4096;

export async function streamToTelegram(
  bot: Bot,
  chat: { id: number; type: string },
  draftId: number,               // e.g. the inbound message_id. Must be non-zero
  opts: TurnOpts,
) {
  const canDraft = chat.type === "private";
  if (canDraft) await bot.api.sendMessageDraft(chat.id, draftId, ""); // "Thinking…"
  else await bot.api.sendChatAction(chat.id, "typing");

  const result = streamText({
    model: xai(GROK_MODEL),
    instructions: opts.instructions,
    messages: opts.messages,
    tools: botTools,
    stopWhen: isStepCount(5),
    abortSignal: opts.abortSignal,  // aborted on stopped_message_generation
    providerOptions: { xai: { ...XAI_BOT_OPTIONS } },
  });

  let buffer = "";
  let lastDraft = 0;
  for await (const part of result.stream) {
    if (part.type !== "text-delta") continue;
    buffer += part.text;
    if (!canDraft) continue;                    // groups: send once at the end
    const now = Date.now();
    if (now - lastDraft < 500) continue;        // no documented draft rate. Throttle anyway
    lastDraft = now;
    await bot.api.sendMessageDraft(chat.id, draftId, buffer.slice(0, TG_LIMIT), { can_stop: true });
  }

  // Drafts vanish. Persist the final answer, split at the 4096-char limit.
  for (const chunk of chunkText(buffer, TG_LIMIT)) {
    await bot.api.sendMessage(chat.id, chunk);
  }
}

function chunkText(text: string, limit: number): string[] {
  const chunks: string[] = [];
  let rest = text.trim();
  while (rest.length > limit) {
    const cut = Math.max(rest.lastIndexOf("\n", limit), rest.lastIndexOf(". ", limit) + 1);
    const at = cut > limit / 2 ? cut : limit;   // prefer a paragraph/sentence break
    chunks.push(rest.slice(0, at).trim());
    rest = rest.slice(at).trim();
  }
  if (rest) chunks.push(rest);
  return chunks;
}

WhatsApp: send once

Drop the drafts and send once. You can still stream server-side, so a stalled generation trips your own timeout instead of the platform's:

const { text } = await runTurn(conversationId, ctx);

await fetch(
  `https://graph.facebook.com/v26.0/${process.env.WHATSAPP_PHONE_NUMBER_ID}/messages`,
  {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.WHATSAPP_ACCESS_TOKEN}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      messaging_product: "whatsapp",
      to: chatId,                                    // 254XXXXXXXXX, no + and no leading 0
      type: "text",
      text: { body: text.slice(0, 4096) },
    }),
  },
);

Graph API v26.0 (released 2026-07-29) is the current version.

The 24-hour window is a bot-architecture problem, not a messaging detail. If the user's last inbound message is older than 24 hours, a free-form text send fails, and you must use an approved template instead. So the bot has to check before it generates:

const stale = Date.now() - convo.last_user_at.getTime() > 24 * 60 * 60 * 1000;
if (stale) {
  await sendTemplate(chatId, "conversation_resume", []); // pre-approved, re-opens the window
  return; // don't burn a Grok call on a message you can't deliver
}

Template creation and approval flow: see whatsapp-business-api/CLAUDE_CODE_INTEGRATION.md.


6. Rate limits and cost guardrails

xAI meters two dimensions per model, both tiered by cumulative API spend since 2026-01-01:

Tier Cumulative spend
0 default
1 $50
2 $250
3 $1,000
4 $5,000

Tiers upgrade automatically and never downgrade. Your exact per-model limits are on the xAI Console's Models page. Over either limit you get HTTP 429. xAI documents no rate-limit response headers, so don't write code that reads x-ratelimit-*.

xAI's documented remedy is exponential backoff: up to 5 tries, waiting 2^attempt seconds, and never retrying non-rate-limit errors. For a bot, that means a queue, not a retry inside the webhook. Note the AI SDK also retries (maxRetries defaults to 2), so set maxRetries: 0 on calls you wrap, or the two retry loops multiply.

// lib/bot/retry.ts
export async function withBackoff<T>(fn: () => Promise<T>, attempts = 5): Promise<T> {
  let lastErr: unknown;
  for (let i = 0; i < attempts; i++) {
    try {
      return await fn();
    } catch (err) {
      lastErr = err;
      const status = (err as { statusCode?: number; status?: number }).statusCode
        ?? (err as { status?: number }).status;
      const retryable = status === 429 || (status !== undefined && status >= 500);
      if (!retryable || i === attempts - 1) throw err;
      const wait = 2 ** i * 1000 + Math.random() * 250; // 1s, 2s, 4s, 8s + jitter
      await new Promise((r) => setTimeout(r, wait));
    }
  }
  throw lastErr;
}

Instrument cost per conversation

You cannot manage what you do not meter, and "tokens per request" is the wrong unit for a bot. The unit is cost per conversation, because that is what scales with users.

Price each step separately. The 200k tier applies per request, and in a multi-step turn each step is its own request, so pricing the summed result.usage would misjudge the tier.

// lib/bot/cost.ts
import type { LanguageModelUsage } from "ai";

// Rates per 1M tokens below a 200k-token prompt. At or above it, ALL tokens in
// that request bill at 2x. Verify against https://docs.x.ai/developers/models.
const RATES = {
  "grok-4.7": { input: 2.0, cachedInput: 0.5, output: 6.0 },
  "grok-4.3": { input: 1.25, cachedInput: 0.2, output: 2.5 },
} as const;
const LONG_PROMPT = 200_000;

export type PricedModel = keyof typeof RATES;

export function requestCostUsd(model: PricedModel, u: LanguageModelUsage) {
  const r = RATES[model];
  const input = u.inputTokens ?? 0;
  const cached = u.inputTokenDetails.cacheReadTokens ?? 0;   // v7 field name
  const fresh = Math.max(0, input - cached);
  const tier = input >= LONG_PROMPT ? 2 : 1;
  return (tier * (fresh * r.input + cached * r.cachedInput + (u.outputTokens ?? 0) * r.output)) / 1_000_000;
}

export function turnCostUsd(model: PricedModel, steps: { usage: LanguageModelUsage }[]) {
  return steps.reduce((sum, s) => sum + requestCostUsd(model, s.usage), 0);
}
const { text, usage, steps } = await runTurn(conversationId, ctx);

await db.insertInto("bot_messages").values({
  conversation_id: conversationId,
  role: "assistant",
  content: text,
  provider: "xai",
  prompt_tokens: usage.inputTokens ?? 0,
  completion_tokens: usage.outputTokens ?? 0,
  cached_tokens: usage.inputTokenDetails.cacheReadTokens ?? 0,
  cost_usd: turnCostUsd(GROK_MODEL, steps) + searchCallsThisTurn * 0.005,
}).execute();

Then add the guardrails that keep one user from becoming the whole bill:

Guardrail Implementation Why
Per-conversation budget Sum cost_usd for the conversation; over ceiling → handoff_to_human One looping user can outspend a hundred normal ones
Per-user message rate Token bucket keyed on chat_id in Redis/Upstash Bots get spammed; each spam message is a paid inference
Step cap stopWhen: isStepCount(5) Every step is a full prompt resend
History cap VERBATIM_TURNS + summarisation Keeps prompts far below the 200k double-price cliff
Output cap maxOutputTokens sized to the surface Output tokens cost 3× input on grok-4.7
Search cap maxTurns on the search call + a per-conversation count web_search is $5 per 1k calls on top of tokens
Global kill switch Feature flag checked before every generate The only thing that stops a runaway at 2am

Priority processing (providerOptions.xai.serviceTier: 'priority') buys lower latency at 2× token rates, and only when the response confirms the tier. Read providerMetadata.xai.serviceTier back before you double your cost model.


7. Grok → Claude fallback

codeAmani's routing policy makes Anthropic Claude primary for complex reasoning and code gen; Grok earns its slot for live grounding and conversational speed. For a bot, the practical framing is different. Grok is the default brain, and Claude keeps the bot answering when xAI returns 429, times out, or ships a bad deploy.

Make the fallback a boundary, not a branch scattered through the code: one interface, two adapters, the same tool schemas on both sides.

flowchart TD
  A["Turn"] --> B["Grok · grok-4.7"]
  B -->|"ok"| Z["Reply"]
  B -->|"429 / 5xx / timeout"| C{"Retries<br/>exhausted?"}
  C -->|"no"| B
  C -->|"yes"| D["Claude · same tools"]
  D -->|"ok"| Z
  D -->|"fails too"| E["Canned holding reply<br/>+ handoff_to_human"]
  E --> Z
// lib/bot/brain.ts
import { xai } from "@ai-sdk/xai";
import { anthropic } from "@ai-sdk/anthropic";
import { generateText, isStepCount, type ModelMessage } from "ai";

type TurnInput = { instructions: string; messages: ModelMessage[]; conversationId: string };

async function grokTurn({ conversationId, ...input }: TurnInput) {
  return generateText({
    model: xai(GROK_MODEL),
    ...input,
    tools: botTools,
    stopWhen: isStepCount(5),
    maxRetries: 0,                                    // withBackoff owns retries
    headers: { "x-grok-conv-id": conversationId },
    providerOptions: { xai: { ...XAI_BOT_OPTIONS, promptCacheKey: conversationId } },
  });
}

async function claudeTurn({ conversationId: _id, ...input }: TurnInput) {
  return generateText({
    model: anthropic("claude-opus-5-5"), // see anthropic/; claude-sonnet-5-5 is the cheaper option
    ...input,
    tools: botTools,                     // identical schemas: this is the whole point
    stopWhen: isStepCount(5),
    // No temperature, no xai providerOptions: current Claude models reject sampling params.
  });
}

export async function think(input: TurnInput) {
  try {
    const r = await withBackoff(() => grokTurn(input));
    return { ...r, provider: "xai" as const };
  } catch (err) {
    logProviderFailure("xai", err);
    try {
      const r = await claudeTurn(input);
      return { ...r, provider: "anthropic" as const };
    } catch (err2) {
      logProviderFailure("anthropic", err2);
      return {
        text: "Sorry, I'm having trouble right now. A colleague will reply shortly.",
        provider: "none" as const,
        steps: [],
      };
    }
  }
}

Three things make a fallback real rather than decorative:


codeAmani notes

Security

AI routing

Grok is the bot brain when the value is conversational latency plus live grounding: a shop assistant that can answer "what's the fuel price today" or "is that team playing tonight" through search_web without you building a scraper. Claude stays primary for the harder offline work around the bot: writing the tool layer, reviewing prompts, and any multi-step reasoning that runs outside the chat turn. grok-4.3 with reasoningEffort: 'none' or Together AI covers high-volume, low-stakes classification (intent tagging, language detection), where a flagship model is waste.

Kenya-targeted projects


Troubleshooting

Symptom Cause Fix
Bot replies with an empty message after using a tool stopWhen left at the v7 default isStepCount(1) Set stopWhen: isStepCount(5)
User gets the same reply twice Webhook redelivered after a slow/failed ACK 200 immediately, run the turn after; dedupe on provider_message_id
WhatsApp send returns an error on a free-form text Outside the 24-hour window Check last_user_at first; re-open with an approved template
401 on the webhook you just deployed Signature computed over parsed JSON HMAC the raw body string, before JSON.parse
429 from api.x.ai under load RPS (RPM÷48) or TPM tier limit Backoff + queue; raise tier by spend, or fall back to Claude
Retries take far longer than expected AI SDK maxRetries (default 2) stacked under your own backoff maxRetries: 0 on wrapped calls
Cached tokens always log as 0 Reading usage.cachedInputTokens (not a v7 field) Read usage.inputTokenDetails.cacheReadTokens
Costs climb every day with the same user count Unbounded history, or prompts crossing 200k (2× tier) Cap verbatim turns, summarise, send x-grok-conv-id / promptCacheKey
Old bot "works" but quality/cost changed Retired slug (grok-4-1-fast-*, grok-3, …) silently redirected to grok-4.3 Pin grok-4.7 / grok-4.3 explicitly
Telegram draft appears, then the answer vanishes Drafts are 30-second ephemeral previews Always sendMessage the final text after the stream ends
sendMessageDraft fails in a group Drafts are private-chat only Use sendChatAction("typing") + one sendMessage in groups
web_search + function tools in one request misbehaves Provider docs say server-side and function tools can't mix Wrap search in its own search_web function tool (§4)
Replies take 40s+ and users repeat themselves Reasoning latency Show a draft/typing indicator immediately, stream, raise SDK timeout (~360s)
Bot invents an order status Persona lacks an explicit "call a tool or say you don't know" rule Add the rule and make the tool the only source of that fact

Official docs: