{"id":"6b08c24c38c84264c202746e","slug":"ai-in-node","title":"AI w Node.js i TypeScript: Anthropic SDK, Vercel AI SDK i LangChain.js w praktyce","summary":"Mapa ekosystemu AI dla Node.js – kiedy wystarczy SDK dostawcy, kiedy Vercel AI SDK, a kiedy LangChain.js – oraz strumieniowanie do przeglądarki, narzędzia, agenci i ustrukturyzowane dane z Zod, z uwagami produkcyjnymi.","servedLang":"pl","availableLangs":["pl","en"],"topics":["ai-in-node","tool-use","ai-agents","mcp"],"techs":["typescript","node","javascript"],"tags":["nodejs","typescript","vercel-ai-sdk","langchainjs","anthropic-sdk","streaming","zod","claude"],"level":"intermediate","kind":"article","access":"members","status":"published","cover":null,"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"readingMinutes":12,"stats":{"views":1,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-26T23:35:40.570Z","updatedAt":"2026-11-27T10:04:38.823Z","requestedLang":"pl","theme":{"hero":"classic","heroMedia":null,"accent":"rose","background":"hex","weaveResources":true,"toc":"right"},"seoDescription":"AI w Node.js i TypeScript: Anthropic SDK, Vercel AI SDK (streamText, tools, Output), LangChain.js (createAgent), MCP, streaming SSE w Express i Next.js, Zod, przerywanie generowania, limity, koszty i testy.","wordCount":2208,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Node.js to naturalne miejsce dla funkcji AI w aplikacjach webowych: ten sam język na froncie i backendzie, świetna obsługa strumieni i asynchroniczności, a do tego bogaty ekosystem bibliotek. Wybór jest jednak szeroki – od oficjalnego SDK dostawcy, przez "},{"type":"text","text":"Vercel AI SDK","marks":[{"type":"bold"}]},{"type":"text","text":", po "},{"type":"text","text":"LangChain.js","marks":[{"type":"bold"}]},{"type":"text","text":" – i łatwo dołożyć warstwę abstrakcji, której nie potrzebujesz. Ten artykuł pokazuje te same zadania w trzech podejściach, żebyś mógł wybrać świadomie."}]},{"type":"stats","attrs":{"items":[{"value":"3","label":"poziomy abstrakcji","hint":"SDK dostawcy, Vercel AI SDK, LangChain.js"},{"value":"1","label":"schemat Zod","hint":"waliduje narzędzia, dane wyjściowe i żądania z przeglądarki"},{"value":"0","label":"kluczy API w przeglądarce","hint":"wywołania modelu zawsze idą przez Twój backend"}]}},{"type":"callout","attrs":{"variant":"info","title":"W skrócie"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"SDK dostawcy","marks":[{"type":"bold"}]},{"type":"text","text":" ("},{"type":"text","text":"@anthropic-ai/sdk","marks":[{"type":"code"}]},{"type":"text","text":") daje pełny dostęp do funkcji modelu i najmniej magii; "},{"type":"text","text":"Vercel AI SDK","marks":[{"type":"bold"}]},{"type":"text","text":" ujednolica dostawców i świetnie integruje strumieniowanie z UI; "},{"type":"text","text":"LangChain.js","marks":[{"type":"bold"}]},{"type":"text","text":" dorzuca gotowe agenty, middleware i integracje."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Strumieniuj odpowiedzi (SSE), przerywaj generowanie, gdy klient się rozłączy, i waliduj wejście z przeglądarki, zanim zapłacisz za tokeny."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Zod to wspólny język: opisuje argumenty "},{"type":"text","text":"narzędzi","marks":[{"type":"link","attrs":{"href":"/pl/topics/tool-use"}}]},{"type":"text","text":", ustrukturyzowane odpowiedzi i kontrakty API – z pełnym typowaniem w TypeScript."}]}]}]}]},{"type":"heading","attrs":{"level":2,"id":"problem-czat-dodany-na-szybko"},"content":[{"type":"text","text":"Problem: czat dodany „na szybko”"}]},{"type":"paragraph","content":[{"type":"text","text":"Aplikacja zamówień pierogarni to Next.js na froncie i API w Expressie. Pierwsza wersja czatu powstała w jedno popołudnie: frontend wołał API modelu bezpośrednio z przeglądarki (klucz w zmiennej "},{"type":"text","text":"NEXT_PUBLIC_…","marks":[{"type":"code"}]},{"type":"text","text":"), czekał kilkanaście sekund na całą odpowiedź, a dane zamówienia wyciągał z tekstu wyrażeniami regularnymi. Po tygodniu klucz wyciekł w narzędziach deweloperskich przeglądarki, użytkownicy zamykali kartę, zanim cokolwiek się pojawiło (a generowanie i tak trwało – i kosztowało), a parser wywracał się na „dwie ruskie i jedne z kapustą”."}]},{"type":"paragraph","content":[{"type":"text","text":"Każdy z tych problemów ma w ekosystemie Node gotowe rozwiązanie. Trzeba tylko wiedzieć, której warstwy użyć."}]},{"type":"heading","attrs":{"level":2,"id":"mapa-ekosystemu"},"content":[{"type":"text","text":"Mapa ekosystemu"}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Biblioteka"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Co daje"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Kiedy wybrać"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"@anthropic-ai/sdk","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"oficjalne SDK Claude: Messages API, streaming, tool runner, structured outputs, cache, batch, typy"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"chcesz pełnej kontroli i dostępu do wszystkich funkcji jednego dostawcy"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"ai","marks":[{"type":"code"}]},{"type":"text","text":" + "},{"type":"text","text":"@ai-sdk/anthropic","marks":[{"type":"code"}]},{"type":"text","text":" (Vercel AI SDK)"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"jeden interfejs dla wielu dostawców, "},{"type":"text","text":"streamText","marks":[{"type":"code"}]},{"type":"text","text":"/"},{"type":"text","text":"generateText","marks":[{"type":"code"}]},{"type":"text","text":", narzędzia, "},{"type":"text","text":"Output","marks":[{"type":"code"}]},{"type":"text","text":", hooki UI ("},{"type":"text","text":"useChat","marks":[{"type":"code"}]},{"type":"text","text":")"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"aplikacja webowa ze strumieniowaniem do UI, potrzeba przełączania dostawców"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"langchain","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"@langchain/anthropic","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"agenci ("},{"type":"text","text":"createAgent","marks":[{"type":"code"}]},{"type":"text","text":"), middleware (np. human-in-the-loop, podsumowania), integracje z bazami wektorowymi i loaderami"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"złożone przepływy, RAG z wieloma źródłami, gotowe wzorce agentów"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"@modelcontextprotocol/sdk","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"serwery i klienci "},{"type":"text","text":"MCP","marks":[{"type":"link","attrs":{"href":"/pl/topics/mcp"}}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"udostępnianie narzędzi wielu aplikacjom AI"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"openai","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"SDK OpenAI, także dla API z nim zgodnych"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"modele OpenAI lub lokalne serwery zgodne z tym API"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"@huggingface/transformers","marks":[{"type":"code"}]},{"type":"text","text":" (Transformers.js)"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"modele uruchamiane lokalnie w Node lub przeglądarce (ONNX)"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"embeddingi i małe modele bez wysyłania danych na zewnątrz"}]}]}]}]},{"type":"diagram","attrs":{"kind":"mermaid","code":"flowchart TB\n  B[\"Przeglądarka<br/>useChat() / EventSource\"] -->|\"POST /api/chat\"| R[\"Backend Node<br/>Next.js route lub Express\"]\n  R -->|\"walidacja Zod, limity, sesja\"| S[\"SDK: Anthropic / AI SDK / LangChain.js\"]\n  S -->|\"HTTPS, klucz z sekretów\"| M[\"Claude API\"]\n  S -->|\"wywołania narzędzi\"| T[\"Serwis zamówień<br/>(autoryzacja z sesji)\"]\n  S -->|\"MCP\"| P[\"Serwery MCP\"]\n  M -->|\"strumień tokenów\"| R\n  R -->|\"SSE\"| B","caption":"Typowa architektura: przeglądarka rozmawia z Twoim backendem, a dopiero on z modelem i narzędziami"}},{"type":"heading","attrs":{"level":2,"id":"strumieniowanie-do-przegladarki"},"content":[{"type":"text","text":"Strumieniowanie do przeglądarki"}]},{"type":"paragraph","content":[{"type":"text","text":"Odpowiedź modelu powstaje token po tokenie, więc użytkownik powinien widzieć ją od pierwszego tokenu. W czystym Expressie strumieniujesz zdarzenia SSE z SDK Anthropic; w Next.js z Vercel AI SDK jedna linia ("},{"type":"text","text":"toUIMessageStreamResponse()","marks":[{"type":"code"}]},{"type":"text","text":") zwraca strumień w formacie, który rozumie hook "},{"type":"text","text":"useChat","marks":[{"type":"code"}]},{"type":"text","text":" po stronie klienta."}]},{"type":"codeGroup","attrs":{"title":"Czat ze strumieniowaniem: Express + Anthropic SDK i Next.js + AI SDK"},"content":[{"type":"codeBlock","attrs":{"language":"typescript","filename":"server.ts"},"content":[{"type":"text","text":"// npm i @anthropic-ai/sdk express zod\nimport Anthropic from \"@anthropic-ai/sdk\";\nimport express from \"express\";\nimport { z } from \"zod\";\n\nconst app = express();\napp.use(express.json({ limit: \"100kb\" }));\nconst client = new Anthropic(); // the API key stays on the server - never in the browser\n\nconst ChatRequest = z.object({\n  messages: z\n    .array(z.object({ role: z.enum([\"user\", \"assistant\"]), content: z.string().max(4000) }))\n    .min(1)\n    .max(40),\n});\n\napp.post(\"/api/chat\", async (req, res) => {\n  const parsed = ChatRequest.safeParse(req.body); // untrusted input: validate before paying for tokens\n  if (!parsed.success) return void res.status(400).json({ error: \"invalid_request\" });\n\n  res.setHeader(\"Content-Type\", \"text/event-stream\");\n  res.setHeader(\"Cache-Control\", \"no-cache\");\n\n  const stream = client.messages.stream({\n    model: \"claude-opus-5-5\",\n    max_tokens: 64000,\n    system: \"You are the ordering assistant of Halina's Pierogi. Answer briefly.\",\n    messages: parsed.data.messages,\n  });\n  // Stop generating (and paying) when the browser goes away.\n  res.on(\"close\", () => {\n    if (!res.writableFinished) stream.abort();\n  });\n  stream.on(\"text\", (delta) => res.write(`data: ${JSON.stringify({ delta })}\\n\\n`));\n\n  try {\n    const final = await stream.finalMessage();\n    res.write(`data: ${JSON.stringify({ done: true, stop: final.stop_reason, usage: final.usage })}\\n\\n`);\n  } catch (err) {\n    if (!stream.aborted) res.write(`data: ${JSON.stringify({ error: \"generation_failed\" })}\\n\\n`);\n  } finally {\n    res.end();\n  }\n});\n\napp.listen(3000, () => console.log(\"Chat API on http://localhost:3000\"));"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"app/api/chat/route.ts"},"content":[{"type":"text","text":"// Next.js App Router + Vercel AI SDK: npm i ai @ai-sdk/anthropic\nimport { anthropic } from \"@ai-sdk/anthropic\";\nimport { convertToModelMessages, streamText, type UIMessage } from \"ai\";\n\nexport const maxDuration = 60; // seconds - long answers need more than the default serverless limit\n\nexport async function POST(req: Request) {\n  const { messages }: { messages: UIMessage[] } = await req.json();\n\n  const result = streamText({\n    model: anthropic(\"claude-opus-5-5\"),\n    system: \"You are the ordering assistant of Halina's Pierogi. Answer briefly.\",\n    messages: await convertToModelMessages(messages),\n    abortSignal: req.signal, // client disconnects -> generation stops\n    onFinish: ({ usage }) => console.log(\"tokens\", usage.inputTokens, usage.outputTokens),\n  });\n\n  // A stream format understood by the useChat() hook from @ai-sdk/react.\n  return result.toUIMessageStreamResponse();\n}"}]}]}]},"toc":[{"id":"problem-czat-dodany-na-szybko","text":"Problem: czat dodany „na szybko”","level":2,"locked":false},{"id":"mapa-ekosystemu","text":"Mapa ekosystemu","level":2,"locked":false},{"id":"strumieniowanie-do-przegladarki","text":"Strumieniowanie do przeglądarki","level":2,"locked":false},{"id":"narzedzia-i-agenci","text":"Narzędzia i agenci","level":2,"locked":true},{"id":"ustrukturyzowane-dane-z-zod","text":"Ustrukturyzowane dane z Zod","level":2,"locked":true},{"id":"ktora-biblioteke-wybrac","text":"Którą bibliotekę wybrać","level":2,"locked":true},{"id":"produkcja-o-czym-nie-zapomniec","text":"Produkcja: o czym nie zapomnieć","level":2,"locked":true},{"id":"lista-kontrolna","text":"Lista kontrolna","level":2,"locked":true},{"id":"sprawdz-sie","text":"Sprawdź się","level":2,"locked":true},{"id":"co-dalej","text":"Co dalej","level":2,"locked":true}],"locked":true,"paywall":null,"previewRatio":0.3,"totalBlocks":43,"visibleBlocks":12,"resources":[{"id":"6b0857bf3c96f2d34d0b425d","type":"article","provider":"web","url":"https://ai-sdk.dev/docs/introduction","embedUrl":null,"title":"AI SDK by Vercel | AI SDK","description":"The AI SDK is the TypeScript toolkit for building AI applications and agents with React, Next.js, Vue, Svelte, Node.js, and more.","author":"Vercel","thumbnailUrl":"https://ai-sdk.dev/og/introduction/image.png","durationSec":null,"lang":"en","topics":["ai-in-node"],"techs":["node","javascript","typescript"],"tags":["ai"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":null,"popularity":65,"verifiedAt":"2026-11-26T11:25:52.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:02.417Z","updatedAt":"2026-11-26T16:01:02.417Z"},{"id":"6b0857a93c96f2d34d0b324f","type":"repo","provider":"github","url":"https://github.com/vercel/ai","embedUrl":null,"title":"vercel/ai","description":"The AI Toolkit for TypeScript, from the creators of Next.js.","author":"vercel","thumbnailUrl":"https://opengraph.githubassets.com/1/vercel/ai","durationSec":null,"lang":"en","topics":["ai-in-node"],"techs":["typescript"],"tags":[],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"seed","publishedAt":null,"popularity":89,"verifiedAt":"2026-11-26T00:00:00.000Z","curated":true,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:41.718Z","updatedAt":"2026-11-26T16:00:41.718Z"},{"id":"6b0857b23c96f2d34d0b344d","type":"repo","provider":"github","url":"https://github.com/langchain-ai/langchainjs","embedUrl":null,"title":"langchain-ai/langchainjs","description":"The agent engineering platform","author":"langchain-ai","thumbnailUrl":"https://opengraph.githubassets.com/1/langchain-ai/langchainjs","durationSec":null,"lang":"en","topics":["ai-in-node"],"techs":["node","typescript"],"tags":["ai"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"github","publishedAt":"2023-02-06T22:50:27.000Z","popularity":82,"verifiedAt":"2026-11-26T10:55:56.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:49.541Z","updatedAt":"2026-11-26T16:00:49.541Z"},{"id":"6b0857ca3c96f2d34d0b4b7a","type":"video","provider":"youtube","url":"https://www.youtube.com/watch?v=WLBrpwYSCjQ","embedUrl":"https://www.youtube-nocookie.com/embed/WLBrpwYSCjQ","title":"AI Dev 25 x NYC | Aayush Kapoor: Vercel AI SDK: From Fundamentals to Deep Research","description":"Aayush Kapoor, Software Engineer on the AI SDK team at Vercel, shared during AI Dev 25 x NYC how to build production-ready agents with the Vercel AI SDK. He covered fundamentals like text generation, tool and function calling, structured outputs, and swapping models with a single line, then code a…","author":"DeepLearningAI","thumbnailUrl":"https://i.ytimg.com/vi/WLBrpwYSCjQ/hqdefault.jpg","durationSec":null,"lang":"en","topics":["ai-in-node"],"techs":["node","javascript"],"tags":["ai"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"youtube-rss","publishedAt":"2025-12-02T21:51:13.000Z","popularity":49,"verifiedAt":"2026-11-26T10:58:13.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:12.872Z","updatedAt":"2026-11-26T16:01:12.872Z"},{"id":"6b0857b23c96f2d34d0b345f","type":"repo","provider":"github","url":"https://github.com/huggingface/transformers.js","embedUrl":null,"title":"huggingface/transformers.js","description":"State-of-the-art Machine Learning for the web. Run 🤗 Transformers directly in your browser, with no need for a server!","author":"huggingface","thumbnailUrl":"https://opengraph.githubassets.com/1/huggingface/transformers.js","durationSec":null,"lang":"en","topics":["llm-fundamentals","ai-in-node"],"techs":["javascript"],"tags":["browser","javascript","transformers","webml","machine-learning","ai"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"github","publishedAt":"2023-02-13T13:51:45.000Z","popularity":81,"verifiedAt":"2026-11-26T11:01:30.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:49.541Z","updatedAt":"2026-11-26T16:00:49.541Z"},{"id":"6b0857b23c96f2d34d0b3415","type":"repo","provider":"github","url":"https://github.com/mastra-ai/mastra","embedUrl":null,"title":"mastra-ai/mastra","description":"Mastra is the modern TypeScript framework for AI-powered applications and agents.","author":"mastra-ai","thumbnailUrl":"https://opengraph.githubassets.com/1/mastra-ai/mastra","durationSec":null,"lang":"en","topics":["evals","ai-agents","ai-in-node","mcp"],"techs":["node","javascript","typescript"],"tags":["agents","ai","chatbots","evals","javascript","llm","mcp","nextjs","nodejs","reactjs"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"github","publishedAt":"2024-08-06T20:44:31.000Z","popularity":86,"verifiedAt":"2026-11-26T11:00:38.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:49.541Z","updatedAt":"2026-11-26T16:00:49.541Z"}],"challenges":[],"attachments":[],"hasCode":true,"repoUrl":null,"series":[],"prev":null,"next":null,"featured":false,"authorCard":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","headline":"Wzorce projektowe · Architektura · AI i LLM","community":false,"reputation":{"points":3900,"level":{"key":"mentor","label":"Mentor"}},"articles":68,"skills":[{"key":"typescript","title":"TypeScript","level":5,"levelLabel":"Autorytet","articles":63},{"key":"dotnet","title":".NET","level":5,"levelLabel":"Autorytet","articles":53},{"key":"python","title":"Python","level":5,"levelLabel":"Autorytet","articles":52},{"key":"java","title":"Java","level":5,"levelLabel":"Autorytet","articles":38}]}}