Build a Customer Chatbot with the Claude API
Building a customer chatbot with the Claude API means writing a backend service that sends user messages to Claude's Messages endpoint, keeps track of conversation history, and streams the response back to your frontend. The actual integration is a handful of HTTP calls — the real work is in prompt design, state management, and handling the edge cases that come up once real customers start typing at it.
This guide walks through the full process: designing a system prompt that keeps the bot on-topic, managing conversation memory across turns, streaming responses so users aren't staring at a blank screen, and optionally giving the bot tools so it can look up orders or check account status instead of just talking about them.
Step 1: Design the system prompt
Everything about how your chatbot behaves — tone, scope, what it refuses to answer — lives in the system prompt. For a customer-facing bot, be explicit about boundaries:
You are the support assistant for Acme Shipping.
- Answer questions about orders, tracking, returns, and billing.
- If asked about anything unrelated to Acme, politely redirect.
- Never invent tracking numbers or order statuses — use the lookup_order tool.
- Keep responses under 4 sentences unless the user asks for detail.
Vague system prompts produce chatbots that wander off-topic or make up answers. Specific, constrained prompts produce chatbots that feel reliable. Iterate on this prompt against real transcripts before shipping it.
Step 2: Send the first request
A basic call to the Claude API looks like this:
curl https://api.anthropic.com/v1/messages \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{
"model": "claude-sonnet-4-5",
"max_tokens": 500,
"system": "You are the support assistant for Acme Shipping...",
"messages": [
{"role": "user", "content": "Where is my order #4821?"}
]
}'
If you'd rather skip the key management, rate-limit handling, and header plumbing, SubToAPI exposes the same Messages API over a stable endpoint with an application key you generate once:
curl https://api.subtoapi.app/v1/messages \
-H "Authorization: Bearer $SUBTOAPI_KEY" \
-H "content-type: application/json" \
-d '{
"model": "claude-sonnet-4-5",
"max_tokens": 500,
"system": "You are the support assistant for Acme Shipping...",
"messages": [
{"role": "user", "content": "Where is my order #4821?"}
]
}'
See /docs/quickstart for the full setup and /docs/messages for the request/response shape.
Step 3: Manage conversation history
Claude's API is stateless — every request needs the full conversation history, not just the latest message. Your backend is responsible for storing turns (user ID, session ID, role, content) and reassembling them into the messages array on each call:
const history = await getSession(sessionId); // [{role, content}, ...]
history.push({ role: "user", content: userMessage });
const response = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
"content-type": "application/json",
},
body: JSON.stringify({
model: "claude-sonnet-4-5",
max_tokens: 500,
system: SYSTEM_PROMPT,
messages: history,
}),
});
const data = await response.json();
history.push({ role: "assistant", content: data.content[0].text });
await saveSession(sessionId, history);
For long-running support conversations, trim or summarize older turns once you approach your context budget — don't just let the array grow unbounded, since that increases both latency and cost per request.
Step 4: Stream responses for a better UX
Customers notice the difference between a chatbot that replies instantly token-by-token and one that goes silent for three seconds. Use streaming so the UI can render text as it arrives:
const response = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
"content-type": "application/json",
},
body: JSON.stringify({
model: "claude-sonnet-4-5",
max_tokens: 500,
system: SYSTEM_PROMPT,
messages: history,
stream: true,
}),
});
for await (const chunk of response.body) {
// parse server-sent event chunks and append to the UI
}
See /docs/streaming for the event format. Streaming is table stakes for any customer-facing chat UI at this point — don't ship without it.
Step 5: Give the bot tools instead of guesses
A chatbot that can only talk is limited. One that can call lookup_order(order_id) or check_refund_status(email) is actually useful. Define tools in your request and let Claude decide when to call them:
{
"name": "lookup_order",
"description": "Look up order status by order ID",
"input_schema": {
"type": "object",
"properties": { "order_id": { "type": "string" } },
"required": ["order_id"]
}
}
When Claude returns a tool_use block, your backend executes the real lookup against your order database, sends the result back as a tool_result, and Claude incorporates it into its next reply. This is what stops the bot from hallucinating tracking numbers. Details are in /docs/tools.
Step 6: Deploy, monitor, and iterate
Once the core loop works, the remaining effort is operational: rate limiting per user, logging transcripts for review, tracking token usage per customer or team, and rotating API keys without downtime. If you're building this as a product with multiple team members or clients, SubToAPI adds usage metadata per key and team seats on top of the raw API, so you're not building that dashboard yourself. Plans start at €9/month for solo use, with Team and Scale tiers for per-seat billing — see /pricing. You can try it with a free trial at /signup.
Whether you call Claude directly or through a wrapper like SubToAPI, the chatbot logic itself — system prompt, history management, streaming, tools — stays the same. The choice is mostly about how much infrastructure you want to own.
Frequently asked questions
Do I need a backend, or can I call the Claude API directly from the browser? Always use a backend. Calling the API from client-side JavaScript exposes your API key to anyone who opens dev tools. Route requests through your own server or a proxy like SubToAPI, and only expose a session token to the frontend.
How do I stop the chatbot from answering off-topic questions? Constrain it in the system prompt with explicit scope and refusal instructions, and test against adversarial prompts. For stricter control, add a lightweight classification step before the main call that routes clearly off-topic messages to a canned response.
How much does it cost to run a customer chatbot on the Claude API? Cost scales with tokens per conversation (system prompt + history + response) multiplied by conversation volume. Trimming conversation history, using shorter system prompts, and choosing an appropriately sized model all reduce per-conversation cost meaningfully.