Skip to main content

Building AI Features in Web Apps: Streaming, Tool Calling, and Structured Output

A practical guide to adding LLM-powered features to web applications. Learn how to stream responses into React, get typed JSON back with structured output, let the model call your functions, and keep cost, latency, and security under control.

Table of Contents

Introduction

Adding an AI feature to a web app looks deceptively simple: send some text to an API, get some text back. The first demo takes ten minutes. The production version — the one that streams smoothly, never leaks your API key, returns data your code can actually rely on, handles a user hitting “Stop” halfway through, and doesn’t produce a surprise invoice — takes considerably more thought.

The good news is that almost none of that extra work is “AI” work. It’s the same web engineering you already know: server routes, streams, validation, error handling, caching, and testing. Large language models (LLMs) just put new pressure on each of those layers. Responses take seconds instead of milliseconds, output is non-deterministic, and every request has a real per-token cost.

This guide walks through the four building blocks behind nearly every LLM-powered feature:

  1. A server-side integration that keeps credentials and control on your side
  2. Streaming so users see output as it’s generated
  3. Structured output so your code receives typed, validated JSON instead of prose
  4. Tool calling so the model can query your data and trigger actions in your app

The examples use TypeScript, React, and the Anthropic SDK (@anthropic-ai/sdk) with Claude models, but the architecture and patterns transfer directly to any provider. The server code uses the standard Request/Response Web APIs, so it runs as-is in Next.js route handlers, Astro endpoints, Cloudflare Workers, Remix, Hono, and similar runtimes.


Architecture: Why AI Calls Belong on the Server

The single most important architectural decision is also the easiest: never call an LLM API directly from the browser.

┌──────────┐ POST /api/chat ┌──────────────┐ HTTPS + API key ┌──────────┐
│ Browser │ ──────────────────▶ │ Your server │ ──────────────────▶ │ LLM API │
│ (React) │ ◀────────────────── │ (route/edge) │ ◀────────────────── │ │
└──────────┘ streamed chunks └──────────────┘ streamed events └──────────┘

Your server sits in the middle for several reasons:

  • Secrets: API keys shipped to the browser are public keys. Anyone can open DevTools, copy the key, and run up your bill.
  • Control: The server owns the system prompt, model choice, max_tokens, and which tools exist. The client sends only what the user typed.
  • Authorization: Tools that read your database must run with the user’s permissions, which only your server can enforce.
  • Rate limiting and quotas: Per-user limits only work if requests flow through something you control.
  • Observability: You’ll want to log token usage, latency, and errors per feature.

💡 Tip: Treat your AI route like any other API endpoint that costs money per call — think “payment endpoint”, not “static content”. Authenticate it, rate-limit it, and validate its input. See Web Security Best Practices for the fundamentals.

Setup

Terminal window
npm install @anthropic-ai/sdk zod

Store the key in your server environment (.env, your hosting provider’s secrets, or wrangler secret put on Cloudflare) as ANTHROPIC_API_KEY. The SDK picks it up automatically.

src/lib/ai.ts
import Anthropic from "@anthropic-ai/sdk";
// Reads ANTHROPIC_API_KEY from the environment.
export const client = new Anthropic();
export const MODEL = "claude-opus-5-5";

Centralizing the client and model ID in one module makes it trivial to swap models later or point tests at a mock.


Your First Request

Before streaming anything, here’s the simplest possible non-streaming call — useful for background jobs, summaries, and anything the user isn’t watching in real time:

import { client, MODEL } from "./ai";
export async function summarize(article: string): Promise<string> {
const response = await client.messages.create({
model: MODEL,
max_tokens: 16000,
system:
"You summarize technical articles in three sentences for busy developers.",
messages: [{ role: "user", content: article }],
});
if (response.stop_reason === "refusal") {
throw new Error("The model declined to summarize this content.");
}
// response.content is an array of typed blocks; narrow before reading .text
return response.content
.filter((block) => block.type === "text")
.map((block) => block.text)
.join("");
}

A few things worth noticing:

  • system carries your instructions; messages carries the conversation. Keep them separate — the user should never be able to edit your system prompt.
  • content is an array of blocks, not a string. A single response can contain text, tool calls, and reasoning blocks. TypeScript’s discriminated unions make you narrow by type, which is exactly what you want.
  • stop_reason tells you why generation ended: end_turn (finished normally), max_tokens (cut off), tool_use (wants to call a tool), or refusal. Always check it before trusting the output.

Multi-turn Conversations

LLM APIs are stateless. To continue a conversation, you resend the full history every time:

import type Anthropic from "@anthropic-ai/sdk";
const messages: Anthropic.MessageParam[] = [
{ role: "user", content: "What's a closure in JavaScript?" },
{ role: "assistant", content: "A closure is a function that remembers..." },
{ role: "user", content: "Show me a practical example." },
];
const response = await client.messages.create({
model: MODEL,
max_tokens: 16000,
messages,
});

Use the SDK’s exported types (Anthropic.MessageParam, Anthropic.Message, Anthropic.Tool) rather than redefining your own interfaces — they track the API exactly and catch mistakes at compile time.


Streaming Responses: From API to UI

An LLM response can take anywhere from one to thirty-plus seconds to complete. Showing a spinner for that long feels broken. Streaming shows the first words in well under a second and keeps users engaged while the rest arrives.

Streaming has three hops, and each one needs to stream for the whole thing to work:

  1. LLM API → your server: the SDK exposes the response as an async iterable of events
  2. Your server → browser: you forward chunks in a ReadableStream response
  3. Browser → DOM: React appends each chunk to state

Step 1: Consuming the Stream on the Server

The SDK’s messages.stream() returns an object you can iterate with for await:

const stream = client.messages.stream({
model: MODEL,
max_tokens: 64000,
messages: [{ role: "user", content: "Explain the event loop" }],
});
for await (const event of stream) {
if (
event.type === "content_block_delta" &&
event.delta.type === "text_delta"
) {
process.stdout.write(event.delta.text);
}
}
// After iteration, get the complete message (usage, stop_reason, etc.)
const finalMessage = await stream.finalMessage();
console.log(finalMessage.usage.output_tokens);

The event sequence is always the same: message_start → one or more content blocks (content_block_start → many content_block_delta → content_block_stop) → message_delta (carries stop_reason and usage) → message_stop. For a chat UI, you mostly care about text_delta.

💡 Tip: Use streaming for any request that might produce long output or use a large max_tokens. Besides better UX, it avoids HTTP timeouts on long generations.

Step 2: Forwarding the Stream to the Browser

You need a wire format between your server and the browser. You have three common options:

FormatProsCons
Raw text chunksSimplest possibleNo way to signal errors, metadata, or end-of-stream reasons
Server-Sent Events (SSE)Standard format, EventSource reconnects automaticallyEventSource only supports GET — awkward for sending chat history
Newline-delimited JSON (NDJSON)Typed events, works with POST + fetchYou write a tiny parser

EventSource is great for server-pushed notifications (covered in WebSockets vs Server-Sent Events), but chat requests need a POST body. The pragmatic choice is fetch with a streamed body using NDJSON: one JSON object per line.

First, define the events your UI understands. This type is shared between server and client:

src/lib/chat-events.ts
export type ChatStreamEvent =
| { type: "text"; text: string }
| { type: "done"; stopReason: string | null }
| { type: "error"; message: string };

Now the route handler:

// src/app/api/chat/route.ts (Next.js) — or src/pages/api/chat.ts (Astro), etc.
import Anthropic from "@anthropic-ai/sdk";
import { z } from "zod";
import { client, MODEL } from "@/lib/ai";
import type { ChatStreamEvent } from "@/lib/chat-events";
const SYSTEM_PROMPT =
"You are a friendly assistant for codingjournal.dev. Answer questions about web development concisely, with code examples when helpful.";
// Never trust the client's message history blindly — validate shape and size.
const RequestSchema = z.object({
messages: z
.array(
z.object({
role: z.enum(["user", "assistant"]),
content: z.string().min(1).max(8000),
}),
)
.min(1)
.max(40),
});
export async function POST(request: Request): Promise<Response> {
const parsed = RequestSchema.safeParse(await request.json());
if (!parsed.success) {
return Response.json({ error: "Invalid request" }, { status: 400 });
}
const stream = client.messages.stream(
{
model: MODEL,
max_tokens: 64000,
output_config: { effort: "low" }, // chat rarely needs deep reasoning
system: SYSTEM_PROMPT,
messages: parsed.data.messages,
},
{ signal: request.signal }, // stop paying for tokens if the user disconnects
);
const encoder = new TextEncoder();
const send = (
controller: ReadableStreamDefaultController<Uint8Array>,
event: ChatStreamEvent,
) => controller.enqueue(encoder.encode(JSON.stringify(event) + "\n"));
const body = new ReadableStream<Uint8Array>({
async start(controller) {
try {
for await (const event of stream) {
if (
event.type === "content_block_delta" &&
event.delta.type === "text_delta"
) {
send(controller, { type: "text", text: event.delta.text });
}
}
const final = await stream.finalMessage();
send(controller, { type: "done", stopReason: final.stop_reason });
} catch (error) {
send(controller, { type: "error", message: toUserMessage(error) });
} finally {
controller.close();
}
},
cancel() {
stream.abort();
},
});
return new Response(body, {
headers: {
"Content-Type": "application/x-ndjson; charset=utf-8",
"Cache-Control": "no-cache, no-transform",
},
});
}
function toUserMessage(error: unknown): string {
if (error instanceof Anthropic.RateLimitError) {
return "We're getting a lot of requests right now. Please try again in a moment.";
}
if (error instanceof Anthropic.APIError) {
return "The AI service returned an error. Please try again.";
}
return "Something went wrong while generating a response.";
}

Key details in this handler:

  • Errors travel in-band. Once you’ve sent a 200 and started streaming, you can’t change the status code. An error event lets the UI show a proper message instead of silently stopping.
  • Cancellation propagates. Passing request.signal and calling stream.abort() in cancel() means a closed tab or a “Stop” click stops generation upstream — you stop paying for tokens nobody will read.
  • no-transform tells proxies and CDNs not to buffer or compress the response, which would defeat streaming.
  • Typed SDK errors (Anthropic.RateLimitError, Anthropic.APIError) instead of string-matching error messages. Raw API errors stay in your server logs; users get friendly copy.

⚠️ Warning: Some hosting platforms and reverse proxies buffer responses by default. If your stream arrives all at once in production but works locally, check for response buffering in your proxy (e.g., X-Accel-Buffering: no for nginx) and make sure the route isn’t being statically rendered or cached.

Step 3: Rendering the Stream in React

On the client, fetch exposes response.body as a ReadableStream. Pipe it through TextDecoderStream, split on newlines, and parse each complete line:

src/hooks/useChat.ts
import { useCallback, useRef, useState } from "react";
import type { ChatStreamEvent } from "@/lib/chat-events";
export type ChatMessage = { role: "user" | "assistant"; content: string };
type Status = "idle" | "streaming" | "error";
export function useChat() {
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [status, setStatus] = useState<Status>("idle");
const [error, setError] = useState<string | null>(null);
const abortRef = useRef<AbortController | null>(null);
const appendToAssistant = useCallback((text: string) => {
setMessages((prev) => {
const last = prev[prev.length - 1];
return [...prev.slice(0, -1), { ...last, content: last.content + text }];
});
}, []);
const send = useCallback(
async (text: string) => {
const history: ChatMessage[] = [
...messages,
{ role: "user", content: text },
];
// Optimistically show the user message and an empty assistant bubble
setMessages([...history, { role: "assistant", content: "" }]);
setStatus("streaming");
setError(null);
const controller = new AbortController();
abortRef.current = controller;
try {
const res = await fetch("/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ messages: history }),
signal: controller.signal,
});
if (!res.ok || !res.body)
throw new Error(`Request failed (${res.status})`);
for await (const event of readNdjson<ChatStreamEvent>(res.body)) {
if (event.type === "text") appendToAssistant(event.text);
if (event.type === "error") throw new Error(event.message);
}
setStatus("idle");
} catch (err) {
if (controller.signal.aborted) {
setStatus("idle"); // user pressed Stop — keep the partial answer
return;
}
setError(err instanceof Error ? err.message : "Unknown error");
setStatus("error");
} finally {
abortRef.current = null;
}
},
[messages, appendToAssistant],
);
const stop = useCallback(() => abortRef.current?.abort(), []);
return { messages, status, error, send, stop };
}
// Parses a byte stream of newline-delimited JSON into typed events.
export async function* readNdjson<T>(
body: ReadableStream<Uint8Array>,
): AsyncGenerator<T> {
const reader = body.pipeThrough(new TextDecoderStream()).getReader();
let buffer = "";
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += value;
const lines = buffer.split("\n");
buffer = lines.pop() ?? ""; // last element may be an incomplete line
for (const line of lines) {
if (line.trim()) yield JSON.parse(line) as T;
}
}
if (buffer.trim()) yield JSON.parse(buffer) as T;
}

The buffering in readNdjson matters: network chunks don’t align with your JSON lines. A single read() can return half a line or three and a half lines, so you keep the trailing fragment until the next chunk completes it.

A minimal component using the hook:

src/components/Chat.tsx
import { useState } from "react";
import { useChat } from "@/hooks/useChat";
export function Chat() {
const { messages, status, error, send, stop } = useChat();
const [input, setInput] = useState("");
return (
<div className="chat">
<ul aria-live="polite">
{messages.map((m, i) => (
<li key={i} className={m.role}>
{m.content || (status === "streaming" ? "…" : "")}
</li>
))}
</ul>
{error && <p role="alert">{error}</p>}
<form
onSubmit={(e) => {
e.preventDefault();
if (!input.trim() || status === "streaming") return;
send(input.trim());
setInput("");
}}
>
<label htmlFor="chat-input">Ask a question</label>
<input
id="chat-input"
value={input}
onChange={(e) => setInput(e.target.value)}
/>
{status === "streaming" ? (
<button type="button" onClick={stop}>
Stop
</button>
) : (
<button type="submit">Send</button>
)}
</form>
</div>
);
}

aria-live="polite" lets screen readers announce new content without interrupting the user — see Web Accessibility for more on live regions.


Structured Output: Typed JSON You Can Trust

Chat is only one use case. Many of the most valuable AI features never show raw model text to the user at all: classifying support tickets, extracting fields from documents, generating tags and metadata, or filling in a form from a paragraph of text. For these, you need data, not prose.

The Fragile Way

The classic approach is to ask nicely and hope:

// ❌ Fragile: the model may wrap JSON in markdown fences, add commentary,
// omit fields, or invent new ones.
const response = await client.messages.create({
model: MODEL,
max_tokens: 16000,
messages: [
{
role: "user",
content: `Return JSON with title, tags, and summary for:\n${post}`,
},
],
});
const data = JSON.parse(text); // 💥 SyntaxError: Unexpected token '`'

Even when it works 99% of the time, the 1% becomes a production incident.

The Reliable Way: Schema-Constrained Output

Modern LLM APIs can constrain generation to a JSON schema, so the response is guaranteed to parse and match the shape you defined. With the Anthropic SDK, you define the schema with Zod and call messages.parse():

src/lib/post-metadata.ts
import { z } from "zod";
import { zodOutputFormat } from "@anthropic-ai/sdk/helpers/zod";
import { client, MODEL } from "./ai";
const PostMetadataSchema = z.object({
description: z
.string()
.describe("SEO meta description, 140-160 characters, no marketing fluff"),
tags: z.array(z.string()).describe("3 to 6 topic tags in Title Case"),
difficulty: z.enum(["beginner", "intermediate", "advanced"]),
readingTimeMinutes: z.number().int(),
});
export type PostMetadata = z.infer<typeof PostMetadataSchema>;
export async function generatePostMetadata(
markdown: string,
): Promise<PostMetadata> {
const response = await client.messages.parse({
model: MODEL,
max_tokens: 16000,
system: "You write accurate metadata for technical blog posts.",
messages: [{ role: "user", content: markdown }],
output_config: { format: zodOutputFormat(PostMetadataSchema) },
});
if (response.stop_reason !== "end_turn" || !response.parsed_output) {
throw new Error(
`Metadata generation failed (stop_reason: ${response.stop_reason})`,
);
}
return response.parsed_output; // fully typed as PostMetadata
}

What you get:

  • response.parsed_output is typed as PostMetadata — autocomplete and compile-time checks all the way through your app.
  • .describe() doubles as prompt engineering. Field descriptions are sent with the schema, so constraints like “140-160 characters” live next to the field they apply to.
  • Enums constrain choices. difficulty can only be one of three values, so downstream code can switch on it exhaustively.

💡 Tip: Schema constraints guarantee shape, not truth. The model can still return a well-formed description that’s inaccurate. Validate business rules (lengths, allowed tags, cross-field consistency) in your own code, exactly as you would with any user input.

When to Use Structured Output

Use structured output when…Use free text when…
Your code consumes the resultA human reads the result
You need specific fields or enumsFormatting is flexible (markdown is fine)
Results are stored in a databaseResults are displayed once and discarded
You’re classifying, extracting, or routingYou’re explaining, drafting, or chatting

Tool Calling: Letting the Model Use Your Code

An LLM on its own only knows what was in its training data and your prompt. Tool calling (also called function calling) lets the model request that your code run a function and hand back the result. That’s how an assistant answers “What did I order last week?” or “Find articles about React performance on this site.”

How Tool Calling Works

The model never executes anything itself. The flow is a loop:

1. You send: user message + tool definitions (name, description, JSON schema)
2. Model replies: stop_reason "tool_use" + { name: "search_posts", input: { query: "react perf" } }
3. Your code runs searchPosts("react perf") and sends the result back as a tool_result
4. Model replies: either another tool call (go to 3) or a final answer (stop_reason "end_turn")

Your server decides which tools exist, validates every input, and runs every call. The model only chooses among the options you exposed.

The Manual Loop

It’s worth writing the loop by hand once to understand it:

import Anthropic from "@anthropic-ai/sdk";
import { client, MODEL } from "./ai";
import { searchPosts, getPost } from "./posts"; // your existing data layer
const tools: Anthropic.Tool[] = [
{
name: "search_posts",
description:
"Search blog posts by keyword. Returns titles, slugs, and descriptions.",
input_schema: {
type: "object",
properties: {
query: { type: "string", description: "Search keywords" },
limit: { type: "integer", description: "Max results (1-10)" },
},
required: ["query"],
},
},
{
name: "get_post",
description: "Get the full markdown content of a blog post by its slug.",
input_schema: {
type: "object",
properties: { slug: { type: "string" } },
required: ["slug"],
},
},
];
async function executeTool(name: string, input: unknown): Promise<string> {
switch (name) {
case "search_posts": {
const { query, limit = 5 } = input as { query: string; limit?: number };
return JSON.stringify(await searchPosts(query, Math.min(limit, 10)));
}
case "get_post": {
const { slug } = input as { slug: string };
const post = await getPost(slug);
if (!post) throw new Error(`No post found with slug "${slug}"`);
return post.body;
}
default:
throw new Error(`Unknown tool: ${name}`);
}
}
export async function askAboutBlog(
question: string,
): Promise<Anthropic.Message> {
const messages: Anthropic.MessageParam[] = [
{ role: "user", content: question },
];
for (let turn = 0; turn < 10; turn++) {
const response = await client.messages.create({
model: MODEL,
max_tokens: 16000,
tools,
messages,
});
if (response.stop_reason !== "tool_use") return response;
// Append the assistant turn *including* its tool_use blocks
messages.push({ role: "assistant", content: response.content });
const toolUses = response.content.filter(
(block): block is Anthropic.ToolUseBlock => block.type === "tool_use",
);
// Run tool calls in parallel; report failures instead of crashing the loop
const results = await Promise.all(
toolUses.map(async (toolUse): Promise<Anthropic.ToolResultBlockParam> => {
try {
return {
type: "tool_result",
tool_use_id: toolUse.id,
content: await executeTool(toolUse.name, toolUse.input),
};
} catch (error) {
return {
type: "tool_result",
tool_use_id: toolUse.id,
content: error instanceof Error ? error.message : "Tool failed",
is_error: true,
};
}
}),
);
// All results go back in a single user message
messages.push({ role: "user", content: results });
}
throw new Error("Tool loop exceeded 10 turns");
}

Three rules that trip people up:

  1. Append the full response.content, not just the text. The next request must include the tool_use blocks so each tool_result can reference its tool_use_id.
  2. Return all tool results in one message. The model can request several tools at once; answer them together (run them concurrently with Promise.all, as above).
  3. Report errors as results, don’t throw. is_error: true tells the model the call failed, and it will often recover — trying a different query or explaining the problem to the user.

And always cap the number of turns. A loop with no upper bound is a loop that can run up your bill.

The Tool Runner: Less Boilerplate, Built-in Validation

Once you understand the loop, you rarely need to write it. The SDK’s tool runner handles it for you, and with Zod you get typed, validated inputs instead of input as { ... } casts:

import { betaZodTool } from "@anthropic-ai/sdk/helpers/beta/zod";
import { z } from "zod";
import { client, MODEL } from "./ai";
import { searchPosts, getPost } from "./posts";
const searchPostsTool = betaZodTool({
name: "search_posts",
description:
"Search blog posts by keyword. Returns titles, slugs, and descriptions.",
inputSchema: z.object({
query: z.string().describe("Search keywords"),
limit: z.number().int().min(1).max(10).optional(),
}),
run: async ({ query, limit = 5 }) =>
JSON.stringify(await searchPosts(query, limit)),
});
const getPostTool = betaZodTool({
name: "get_post",
description: "Get the full markdown content of a blog post by its slug.",
inputSchema: z.object({ slug: z.string() }),
run: async ({ slug }) => {
const post = await getPost(slug);
if (!post) throw new Error(`No post found with slug "${slug}"`);
return post.body;
},
});
export async function askAboutBlog(question: string) {
const finalMessage = await client.beta.messages.toolRunner({
model: MODEL,
max_tokens: 16000,
tools: [searchPostsTool, getPostTool],
messages: [{ role: "user", content: question }],
});
return finalMessage;
}

The runner validates each tool input against its Zod schema before calling run, feeds results back, and returns once the model produces a final answer. It also supports stream: true when you want to stream the final answer to the UI using the same NDJSON route shown earlier.

Writing Good Tool Definitions

The model chooses tools based almost entirely on their names and descriptions. Treat them like documentation for a new teammate:

// ❌ Vague: when should the model use this? What does it return?
{ name: "search", description: "Searches stuff" }
// ✅ Specific: purpose, return value, and when *not* to use it
{
name: "search_posts",
description:
"Full-text search over published blog posts. Returns up to `limit` results " +
"with title, slug, and description. Use get_post to read a result in full. " +
"Does not search cheatsheets.",
}

Other guidelines:

  • Prefer a few well-designed tools over dozens of granular ones.
  • Return concise, structured results. Dumping a 50KB JSON blob into the conversation wastes tokens and attention; return the fields the model actually needs.
  • Make errors actionable. "No post found with slug 'react-hooks'. Try search_posts first." helps the model recover; "Error 404" doesn’t.

UX Patterns for AI Features

AI features have a different “shape” from typical CRUD interactions: they’re slow, incremental, and occasionally wrong. Good UX acknowledges all three.

Show Progress Immediately

  • Optimistic user messages: Append the user’s message to the list before the request completes (the useChat hook does this).
  • A visible “thinking” state: Modern models may reason before emitting their first visible token. A subtle indicator (“Thinking…”) in the empty assistant bubble prevents the UI from looking frozen.
  • Tool activity: When the model calls a tool, send a status event ({ type: "status", text: "Searching posts…" }) so users understand the pause.

Always Offer a Way Out

Long generations need a Stop button. Wire it to an AbortController (as in the hook above) and keep the partial answer — users often have what they need halfway through.

Keep Rendering Cheap

Streaming can trigger dozens of state updates per second, and rendering markdown with syntax highlighting on every update gets expensive as answers grow. Options, from simplest to most involved:

import { useDeferredValue, memo } from "react";
// 1. Let React deprioritize the expensive markdown render during streaming
function AssistantMessage({ content }: { content: string }) {
const deferredContent = useDeferredValue(content);
return <Markdown source={deferredContent} />;
}
// 2. Memoize completed messages so only the streaming one re-renders
const CompletedMessage = memo(function CompletedMessage({
content,
}: {
content: string;
}) {
return <Markdown source={content} />;
});

You can also batch incoming chunks and flush them to state on a requestAnimationFrame or short interval — the same idea as throttling. See React Concurrent Features for how useDeferredValue keeps input responsive during heavy renders.

Handle Failure Gracefully

SituationGood UX
Rate limit (429)“Busy right now — try again in a moment” with a retry button
Error mid-streamKeep the partial text, mark it as incomplete, offer “Regenerate”
Network dropDetect with the aborted fetch, offer retry with the same input
stop_reason: "max_tokens"Show “Response was cut off” with a “Continue” action
stop_reason: "refusal"A neutral message explaining the request couldn’t be completed

For broader patterns, see Error Handling Strategies in JavaScript.

Set Expectations

Label AI-generated content, make it easy to copy or edit, and avoid presenting generated output as authoritative when it isn’t. For anything with consequences — sending an email, deleting data, making a purchase — show the user what will happen and require explicit confirmation.


Cost and Performance

LLM APIs bill per token, separately for input (what you send) and output (what the model generates). Output tokens are typically several times more expensive than input tokens. A few decisions dominate your bill.

Choose the Right Model per Feature

Different features have different needs. A rough guide using Claude’s current lineup (prices per million tokens, input / output):

ModelPrice (in / out)Good fit
claude-opus-5-5$4 / $20Complex reasoning, coding agents, multi-step tool use
claude-sonnet-5-5$2 / $10Everyday chat, content generation, most product features
claude-haiku-5-5$0.10 / $0.50High-volume classification, extraction, routing

Start with the most capable model to establish what “good” looks like, then measure whether a cheaper model holds up on real inputs for each specific feature. Pricing changes over time, so check your provider’s current pricing page.

Tune Effort Before Switching Models

Modern models let you trade reasoning depth for speed and cost within the same model. With Claude, that’s the effort setting:

await client.messages.create({
model: MODEL,
max_tokens: 16000,
output_config: { effort: "low" }, // low | medium | high | xhigh | max
messages,
});

Chat and simple extraction often do well at low; complex coding or multi-step agent work benefits from high. Often a capable model at lower effort beats a smaller model at high effort — measure both before committing.

Use Prompt Caching

If every request starts with the same large prefix — a long system prompt, tool definitions, or a reference document — prompt caching lets the provider reuse that processed prefix. Cached reads cost a fraction of normal input tokens and reduce latency.

const response = await client.messages.create({
model: MODEL,
max_tokens: 16000,
cache_control: { type: "ephemeral" }, // cache the stable prefix automatically
system: LARGE_STABLE_SYSTEM_PROMPT,
messages,
});
console.log(response.usage.cache_read_input_tokens); // > 0 on cache hits

Caching is a prefix match: any change early in the request invalidates everything after it. To get hits:

  • Keep the system prompt byte-for-byte stable. Don’t interpolate new Date(), request IDs, or user names into it.
  • Keep tool definitions in a fixed order.
  • Put volatile content last (the user’s latest message, per-request context).
  • Verify with usage.cache_read_input_tokens. If it’s always zero, something in your prefix is changing.

Protect Your Budget

// Simple per-user limit — use Redis, Cloudflare KV/Rate Limiting, or your DB in production
const WINDOW_MS = 60_000;
const MAX_REQUESTS = 10;
const hits = new Map<string, number[]>();
export function isRateLimited(userId: string): boolean {
const now = Date.now();
const recent = (hits.get(userId) ?? []).filter((t) => now - t < WINDOW_MS);
recent.push(now);
hits.set(userId, recent);
return recent.length > MAX_REQUESTS;
}

Beyond rate limiting:

  • Cap input size (the Zod schema in the chat route limits message length and count).
  • Cap tool loops (the manual loop above stops after 10 turns).
  • Log usage on every request with the user and feature, so you know which feature costs what.
  • Set spend alerts and limits in your provider’s console.

Security Considerations

AI features introduce a new class of vulnerability: prompt injection. Any text the model reads — a user message, a fetched web page, a document, a tool result — might contain instructions like “ignore your previous instructions and…”. You cannot fully prevent a model from being influenced by text it reads, so design so that it doesn’t matter.

Principle of Least Privilege for Tools

// ❌ Dangerous: model-controlled SQL with full database access
const runSql = betaZodTool({
name: "run_sql",
description: "Run any SQL query",
inputSchema: z.object({ sql: z.string() }),
run: async ({ sql }) => JSON.stringify(await db.query(sql)),
});
// ✅ Safe: narrow, parameterized, scoped to the current user
function makeOrderTools(userId: string) {
return [
betaZodTool({
name: "list_recent_orders",
description: "List the current user's orders from the last N days.",
inputSchema: z.object({ days: z.number().int().min(1).max(90) }),
run: async ({ days }) =>
JSON.stringify(await orders.listForUser(userId, { days })),
}),
];
}

The model can only ever do what your tools allow. Bind tools to the authenticated user on the server — never accept a userId from the model’s tool input.

Security Checklist 🔒

  • Keep keys server-side and out of client bundles and logs.
  • Authenticate and rate-limit AI endpoints like any paid API.
  • Validate everything: request bodies, tool inputs (the tool runner does this with Zod), and model output before you act on it.
  • Treat model output as untrusted when rendering. If you render markdown to HTML, sanitize it — a model can be tricked into emitting <img onerror=...> just like any user input. See XSS prevention.
  • Require human confirmation for irreversible or outward-facing actions (sending messages, payments, deletions).
  • Don’t put secrets in prompts. Assume anything in the system prompt can be extracted by a determined user.
  • Separate trust levels. Instructions belong in system; untrusted content (documents, web pages, user uploads) belongs in messages, clearly delimited.

Testing AI Features

Non-deterministic output makes “assert the response equals X” useless. Instead, split testing into layers.

1. Unit-test the Deterministic Parts

Most of your AI integration is ordinary code: parsers, validators, tool implementations, and prompt builders. Test them as usual. For example, the NDJSON parser from the streaming section, with Vitest:

import { describe, expect, it } from "vitest";
import { readNdjson } from "@/hooks/useChat";
function streamFrom(chunks: string[]): ReadableStream<Uint8Array> {
const encoder = new TextEncoder();
return new ReadableStream({
start(controller) {
for (const chunk of chunks) controller.enqueue(encoder.encode(chunk));
controller.close();
},
});
}
describe("readNdjson", () => {
it("reassembles events split across network chunks", async () => {
const body = streamFrom([
'{"type":"text","te',
'xt":"Hel"}\n{"type":"text",',
'"text":"lo"}\n',
]);
const events = [];
for await (const event of readNdjson(body)) events.push(event);
expect(events).toEqual([
{ type: "text", text: "Hel" },
{ type: "text", text: "lo" },
]);
});
});

Tool run functions are just async functions — call them directly with valid and invalid inputs and assert on the results.

2. Mock the Model at the Boundary

For integration tests of your route or hook, don’t call the real API — it’s slow, costs money, and is non-deterministic. Mock at the network boundary instead:

import { vi } from "vitest";
vi.mock("@/lib/ai", () => ({
MODEL: "test-model",
client: {
messages: {
parse: vi.fn().mockResolvedValue({
stop_reason: "end_turn",
parsed_output: {
description: "A practical guide to closures in JavaScript.",
tags: ["JavaScript", "Closures"],
difficulty: "intermediate",
readingTimeMinutes: 12,
},
}),
},
},
}));

This is where centralizing the client in src/lib/ai.ts pays off. For end-to-end tests, Playwright’s page.route() can intercept /api/chat and replay a recorded NDJSON stream — see Playwright vs Cypress.

3. Evaluate Output Quality Separately

Whether the model’s answers are good is a different question from whether your code works. Build a small evaluation set: 20–50 realistic inputs with criteria for a good output (required facts, schema rules, tone). Run it whenever you change prompts, models, or effort settings, and compare scores. Keep it out of your regular CI run since it calls the real API and costs money.


Best Practices and Common Pitfalls

Best Practices ✅

  • Stream anything a user waits for, and propagate cancellation end to end.
  • Use structured output whenever code consumes the result.
  • Keep prompts and tool definitions in version control and review changes to them like code changes — they are code.
  • Start with the most capable model, then optimize with effort settings, caching, and cheaper models where measurements allow.
  • Log usage and latency per feature from day one.
  • Design for failure: errors, refusals, truncation, and slow responses are normal operating conditions, not edge cases.

Common Pitfalls ❌

Calling the API from the browser

// ❌ Ships your API key to every visitor
const client = new Anthropic({ apiKey: import.meta.env.PUBLIC_ANTHROPIC_KEY });

Treating content as a string

// ❌ content is an array of typed blocks
const text = response.content[0].text;
// ✅ Narrow by type
const text = response.content
.filter((block) => block.type === "text")
.map((block) => block.text)
.join("");

Ignoring stop_reason

A response that hit max_tokens is truncated mid-sentence (or mid-JSON). A refusal has no useful content. Check stop_reason before using output.

Breaking the prompt cache with dynamic system prompts

// ❌ Different system prompt every request → zero cache hits
system: `You are a helpful assistant. Current time: ${new Date().toISOString()}`;
// ✅ Stable system prompt; put dynamic context in the latest user message
system: "You are a helpful assistant.";

Unbounded loops and inputs

No turn cap on tool loops, no length limits on input, no per-user rate limits. Each one is a way for a bug, an abusive user, or a prompt injection to run up your bill.

Hardcoding model IDs throughout the codebase

Models are released and deprecated regularly. Keep the model ID in one module (or config) so upgrading is a one-line change followed by an evaluation run.


Conclusion

Building AI features is mostly web engineering with a few new constraints. Put the model behind your own server route, stream its output through to a React UI that can be stopped mid-answer, constrain output to schemas whenever code consumes it, and expose narrowly scoped tools so the model can work with your data without being able to do damage.

Key Takeaways:

  • Server-side only: Keep API keys, system prompts, and tool execution on your server
  • Stream end to end: SDK stream → ReadableStream response → fetch reader → React state, with cancellation at every hop
  • Structured output: Use schema-constrained JSON (messages.parse() with Zod) instead of parsing free text
  • Tool calling: The model requests, your code executes; validate inputs, return errors as results, and cap the loop
  • Cost control: Pick models per feature, tune effort, cache stable prefixes, and rate-limit users
  • Security: Assume prompt injection; scope tools with least privilege and confirm consequential actions

Next Steps:

Start with one small, well-scoped feature: a summary, a smart search, or an auto-generated set of tags. Get the plumbing right — streaming, validation, error handling, and logging — and every AI feature you add after that becomes far easier.