Polski

Article · AI in Node.js · Tool use (function calling)

AI in Node.js and TypeScript: the Anthropic SDK, Vercel AI SDK and LangChain.js in practice

A map of the AI ecosystem for Node.js – when the provider SDK is enough, when to use the Vercel AI SDK and when LangChain.js – plus streaming to the browser, tools, agents and structured data with Zod, with production notes.

By · · 13 min read

Node.js is a natural home for AI features in web applications: the same language on the front end and back end, excellent support for streams and asynchrony, and a rich library ecosystem on top. The choice is wide, though – from the provider's official SDK, through the Vercel AI SDK, to LangChain.js – and it is easy to add an abstraction layer you do not need. This article shows the same tasks in three approaches so you can choose deliberately.

3
levels of abstraction – provider SDK, Vercel AI SDK, LangChain.js
1
Zod schema – validates tools, outputs and requests from the browser
0
API keys in the browser – model calls always go through your backend

The problem: a chat added "quickly"

The pierogi ordering app is Next.js on the front end and an Express API. The first version of the chat took an afternoon: the front end called the model API directly from the browser (the key in a NEXT_PUBLIC_… variable), waited a dozen seconds for the full answer and pulled order data out of the text with regular expressions. Within a week the key leaked through the browser's developer tools, users closed the tab before anything appeared (while generation kept running – and costing), and the parser fell over on "two ruskie and one with cabbage".

Each of these problems has a ready solution in the Node ecosystem. You just need to know which layer to use.

The ecosystem map

LibraryWhat it gives youWhen to choose it
@anthropic-ai/sdkthe official Claude SDK: Messages API, streaming, tool runner, structured outputs, caching, batches, typesyou want full control and access to all features of one provider
ai + @ai-sdk/anthropic (Vercel AI SDK)one interface for many providers, streamText/generateText, tools, Output, UI hooks (useChat)a web app with streaming to the UI, a need to switch providers
langchain, @langchain/anthropicagents (createAgent), middleware (e.g. human-in-the-loop, summarization), integrations with vector stores and loaderscomplex flows, RAG over many sources, ready-made agent patterns
@modelcontextprotocol/sdkMCP servers and clientsexposing tools to many AI applications
openaithe OpenAI SDK, also for APIs compatible with itOpenAI models or local servers compatible with that API
@huggingface/transformers (Transformers.js)models running locally in Node or the browser (ONNX)embeddings and small models without sending data out
Diagram: A typical architecture: the browser talks to your backend, and only the backend talks to the model and tools

Streaming to the browser

A model's answer is produced token by token, so the user should see it from the first token. In plain Express you stream SSE events from the Anthropic SDK; in Next.js with the Vercel AI SDK one line (toUIMessageStreamResponse()) returns a stream in the format the client-side useChat hook understands.

Chat with streaming: Express + Anthropic SDK and Next.js + AI SDK

server.ts
// npm i @anthropic-ai/sdk express zod
import Anthropic from "@anthropic-ai/sdk";
import express from "express";
import { z } from "zod";

const app = express();
app.use(express.json({ limit: "100kb" }));
const client = new Anthropic(); // the API key stays on the server - never in the browser

const ChatRequest = z.object({
  messages: z
    .array(z.object({ role: z.enum(["user", "assistant"]), content: z.string().max(4000) }))
    .min(1)
    .max(40),
});

app.post("/api/chat", async (req, res) => {
  const parsed = ChatRequest.safeParse(req.body); // untrusted input: validate before paying for tokens
  if (!parsed.success) return void res.status(400).json({ error: "invalid_request" });

  res.setHeader("Content-Type", "text/event-stream");
  res.setHeader("Cache-Control", "no-cache");

  const stream = client.messages.stream({
    model: "claude-opus-5-5",
    max_tokens: 64000,
    system: "You are the ordering assistant of Halina's Pierogi. Answer briefly.",
    messages: parsed.data.messages,
  });
  // Stop generating (and paying) when the browser goes away.
  res.on("close", () => {
    if (!res.writableFinished) stream.abort();
  });
  stream.on("text", (delta) => res.write(`data: ${JSON.stringify({ delta })}\n\n`));

  try {
    const final = await stream.finalMessage();
    res.write(`data: ${JSON.stringify({ done: true, stop: final.stop_reason, usage: final.usage })}\n\n`);
  } catch (err) {
    if (!stream.aborted) res.write(`data: ${JSON.stringify({ error: "generation_failed" })}\n\n`);
  } finally {
    res.end();
  }
});

app.listen(3000, () => console.log("Chat API on http://localhost:3000"));
app/api/chat/route.ts
// Next.js App Router + Vercel AI SDK: npm i ai @ai-sdk/anthropic
import { anthropic } from "@ai-sdk/anthropic";
import { convertToModelMessages, streamText, type UIMessage } from "ai";

export const maxDuration = 60; // seconds - long answers need more than the default serverless limit

export async function POST(req: Request) {
  const { messages }: { messages: UIMessage[] } = await req.json();

  const result = streamText({
    model: anthropic("claude-opus-5-5"),
    system: "You are the ordering assistant of Halina's Pierogi. Answer briefly.",
    messages: await convertToModelMessages(messages),
    abortSignal: req.signal, // client disconnects -> generation stops
    onFinish: ({ usage }) => console.log("tokens", usage.inputTokens, usage.outputTokens),
  });

  // A stream format understood by the useChat() hook from @ai-sdk/react.
  return result.toUIMessageStreamResponse();
}

The rest of this article is for members

Create a free account or sign in to read it all. Still ahead:

  • Tools and agents
  • Structured data with Zod
  • Which library to choose
  • Production: what not to forget
  • Checklist
  • Test yourself
  • What's next

Create a free account · Sign in