AI and tools

The AI provider is a deployment decision, not a code decision. The same bot binary runs on Workers AI in one account and against a self-hosted OpenAI-compatible endpoint in another.

Configuration

Variable Meaning
AI_SERVICE Which provider. One of the four below. Unset ⇒ AI is off.
AI_MODEL Model id, transport-specific.
AI_MAX_TOKENS Output-token ceiling.
AI_BASE_URL OpenAI-compatible endpoint, for ollama.
AI_GATEWAY_ID AI Gateway id, for gateway.
AI_EMBEDDING_MODEL Embedding model, for a knowledge base searched with Vectorize. Unset ⇒ the default. See The knowledge base.
AI_SETUP_INSTRUCTIONS What the "AI is not configured" notice says, in your own words. Unset ⇒ the standard explanation.
AI_SETUP_URL The link under that standard explanation. Unset ⇒ this page, on the bot's own website. Ignored once AI_SETUP_INSTRUCTIONS is set.
AI_PRICE_INPUT, AI_PRICE_OUTPUT What the model costs, in US dollars per million input and output tokens — both or neither. Unset ⇒ the model's list price where the SDK knows it, and no cost where it does not. Used for each conversation's cost in the operator console and for a cost cap.

Every value AI_SERVICE takes

Value What it is What it needs Runs in a Worker?
unset AI is off. A supported state, not a fault: the bot answers by keyword search over this knowledge base and says why. Nothing. —
workers-ai Cloudflare Workers AI — a model running in the same account as the bot, billed there, with no third-party key. The one to pick if you have no reason to pick another. The AI binding in wrangler.jsonc, and AI_MODEL — e.g. @cf/meta/llama-3.3-70b-instruct-fp8-fast. Yes
gateway The same models behind an AI Gateway, for caching, rate limiting and a log of what was asked. The AI binding, AI_GATEWAY_ID, and AI_MODEL. Yes
ollama Any OpenAI-compatible endpoint — a self-hosted model, an internal proxy, a vendor. The escape hatch: if it speaks that protocol, this is the value. AI_BASE_URL pointing at it, and AI_MODEL. Yes
claude-cli The local Claude command-line tool, for development on a personal plan. A Node runtime and the tool on the path. No — see below.

Anything else — a typo, a provider that does not exist — switches AI off rather than failing a request, and logs a warning naming the value. A bot whose brain silently stopped because somebody wrote wrokers-ai is worth one log line.

claude-cli can never work in a deployed bot

It shells out to a binary. A Worker has no subprocesses, and wrangler dev is the same runtime rather than Node, so "local" does not rescue it either. Setting it is treated exactly as not configured: llmClientFromEnv returns null, isAiConfigured agrees, the user gets the standard notice, and the log says what to do instead — so it degrades rather than 500s.

To develop against a local Claude plan, run the bridge and point the bot at it as an ordinary OpenAI-compatible endpoint:

pnpm bridge                       # from the SDK repository
AI_SERVICE  = "ollama"
AI_BASE_URL = "http://127.0.0.1:8788/v1"

This is why the Settings screen's provider menu offers three values and not four: the one that cannot work is not offered.

AI_SERVICE, AI_MODEL and AI_SETUP_INSTRUCTIONS are on the bot's own Settings screen, so switching provider is a page rather than a deploy. The provider is picked from a menu of the ones that work in a Worker; the model is a suggestion list you can type past.

llmClientFromEnv(env, logger) returns null when AI is switched off — a recognised, non-throwing state. Design the bot so it still works: fall back to a keyword search over the knowledge base, or to a scripted menu.

const client = llmClientFromEnv(conversation.env, conversation.logger);
if (!client) return conversation.reply(searchFallback(question));

When no provider is configured

Silence is the wrong answer: the user thinks the bot is broken, and whoever could switch AI on never finds out. The SDK ships the reply.

const client = await llmClientOrExplain(conversation);
if (!client) return;              // the user has been told, and told how to fix it

That tells whoever addressed the bot that no AI provider is configured, which variables to set, and where the instructions are — privately where the platform allows it (replyPrivately: ephemeral, else a direct message, else the conversation), because setup instructions are noise to everybody else in the channel.

A bot with a fallback of its own keeps answering and adds the notice as a footnote instead:

await conversation.replyInThread(await searchFallback(question));
await reportAiNotConfigured(conversation, {
  once: true,                     // it did answer — repeating this would nag
  intro: "That was a keyword match: this bot has no AI provider configured.",
});

The link under the standard explanation is this page. The bot works out its own address (KNOWLEDGE_SITE_URL, or the address the request arrived at) and links the article on the website it is already serving, so the reader is sent somewhere that exists on that deployment. A bot serving no website links to nothing at all — the notice still names the variables — because a dead link costs a click and tells the reader the bot is neglected.

AI_SETUP_INSTRUCTIONS replaces the whole explanation with a deployment's own — "ask #platform-help", an internal runbook — and AI_SETUP_URL overrides only the link under the standard one. defaultAiSetupInstructions(settingsUrl) is the standard wording, which is what the settings screen seeds its field with — with that deployment's own address written into it — so a customer edits a sentence instead of inventing one. DEFAULT_AI_SETUP_INSTRUCTIONS is the same wording with no address in it. aiNotConfiguredNotice(env) returns whichever of the two applies, for a bot that wants the words inside a message of its own.

Answering a question

import { createResponder } from "@wingman/ai";
import { knowledgeBaseTools } from "@wingman/knowledge-base";

const responder = createResponder({
  client,
  instructions: "You are Acme's support bot. Answer only from the knowledge base.",
  tools: knowledgeBaseTools(kb),
});

const answer = await responder.answer({ question, history }, conversation);

The responder assembles the prompt (persona, recent transcript, retrieved context, question), runs the tool-calling loop, and returns the answer: answer.text, what the model wrote, and answer.sources, the documents its tools searched, read and the answer cites. Hand the whole answer to plan.finish(answer) (see questions) and the documents are counted with nothing else to wire.

The chat panel on this page is such a responder. Try it: Which events can a bot handle? — the answer is written as it arrives, from these pages.

Writing a tool

A tool is a name, a description the model reads, a JSON Schema, and an execute. The context is whatever you pass to the responder — usually the Conversation:

import { defineTool, objectSchema, stringProperty } from "@wingman/ai";

const askAPerson = defineTool<Conversation>({
  name: "hand_over_to_human",
  description: "Ask a person to take over. Call this when the "
    + "knowledge base does not answer the question, or the user asks for a person.",
  inputSchema: objectSchema({ reason: stringProperty("Why the bot could not help") }, ["reason"]),
  async execute({ reason }, conversation) {
    const asked = await askForHelp(conversation, String(reason));
    // What the tool returns is what the model bases its closing sentence on, so
    // it has to say what actually happened. See mentions.md.
    return asked
      ? "Asked. Tell the user a person will follow up shortly."
      : "Nobody could be reached. The user has been told; do not promise a person.";
  },
});

A tool that throws is reported to the model rather than failing the answer, so the bot can apologise or try another route.

The return string is the tool's only channel back to the model, and the model writes the sentence the user reads. A tool that reports success unconditionally teaches the model to promise things that did not happen — see Mentions and direct messages.

The loop

runAgent prompts, executes any requested tools, feeds the results back, and repeats — up to maxSteps (default 4). On the final step the tool declarations are withheld, so a model that keeps calling tools still produces an answer for the waiting user.

Related: The knowledge base, The bot-scaffolding skill.

← Mentions and direct messagesThe knowledge base →