08. Programming & Technologies
JavaScript and TypeScript for Agentic AI
JavaScript and TypeScript power agent UIs and many Node runtimes: strict TypeScript plus Zod validate tool args at runtime; async/await and streaming (SSE) deliver chat UX; route handlers own secrets, auth, and budgets. Prefer TypeScript for agents β types catch tool bugs before production.
What you will learn
- Explain why TS is preferred over plain JS for agents
- Use Zod schemas for tools and structured outputs
- Design streaming route-handler agent endpoints
- Bound concurrency and cancel streams with AbortSignal
- Answer interview questions with short, solid answers
Definition
JS/TS for Agentic AI means building the product edge and often the agent runtime in the JavaScript ecosystem: typed tools, validated I/O, async fetch to models, and streamed responses to the browser β with secrets only on the server.
Plain JavaScript can prototype. TypeScript plus runtime schemas (Zod) is what you ship when tools can spend money or change data.
Introduction
This lesson (#2 in Programming & Technologies) follows Python for Agentic AI. Same principles β contracts, async I/O, edge ownership β different language and UX strengths (browser streaming, Next.js, Mastra, Vercel AI SDK).
Next: LLM Providers for Agents (OpenAI, Gemini, Claude, Llama).
Why JavaScript / TypeScript
- Native home for chat UIs and real-time streaming
- One language across Next.js / Node agent backends
- Strong TS agent kits: Vercel AI SDK, Mastra, OpenAI Agents SDK (TS)
- fetch + Streams + AbortController are built-in
- Huge web hiring pool for product agent features
TypeScript essentials
- Enable strict mode β agents amplify any any
- Type tool results and API payloads; avoid unknown dumps
- Discriminated unions for agent events / stream parts
- eslint + tsc in CI before deploy
- Prefer unknown + narrowing over any when parsing JSON
Zod contracts
TypeScript types erase at runtime. LLM tool calls are JSON strings. Zod (or similar) parses and validates before execute β the TS analog of Pydantic.
- z.object for tool argument schemas
- z.infer for TypeScript types derived from the same schema
- parse / safeParse β fail closed on bad args
- Structured outputs via schema-backed object generation
- Same Module 05 rule: least privilege + validated args
Async, concurrency, cancellation
- async/await for model and tool I/O
- Promise.all / allSettled for independent fan-out
- Limit parallelism (p-limit or a simple semaphore) for quotas
- AbortController / AbortSignal to cancel fetches and streams
- Never put provider API keys in client bundles
Streaming to the UI
Chat agents feel broken without streaming. Server runs streamText (or equivalent), returns SSE/UI message streams; the browser renders tokens as they arrive.
- streamText / createUIMessageStreamResponse patterns (AI SDK)
- Bound tool loops β stopWhen / max steps
- User Stop β abort the in-flight request
- Log tokens and tool calls server-side
- Fallbacks / gateway models for resilience when useful
Tools in TS
- description + inputSchema + async execute
- AuthZ inside execute β model cannot bypass your checks
- Return JSON-serializable, schema-friendly results
- Idempotent writes where possible
- Unit-test execute with mocked deps β no live model required
Frameworks in this ecosystem
- Vercel AI SDK - streaming UX + tools + structured output
- Mastra - TS agents, workflows, RAG, evals
- OpenAI Agents SDK (TS) - handoffs, guardrails, tracing
- LangGraph.js / LlamaIndex.TS when you need those graphs/data layers
- Pick by UI streaming needs vs multi-agent depth (Module 07)
Map to Python lesson
- Zod β Pydantic at boundaries
- Promise.all + limiter β asyncio.gather + Semaphore
- Route handlers β FastAPI edge (auth/budgets/secrets)
- Streaming is often stronger out of the box in TS web stacks
- Heavy RAG/ML research still often lives in Python services
Failure modes
- API keys in NEXT_PUBLIC_* or client components
- Trusting types without Zod.parse on LLM JSON
- Unbounded tool loops with no stopWhen / max steps
- Blocking CPU work on the request thread without offload
- Streaming without auth β anyone can burn your quota
Program / implementation notes
Ship a minimal route handler: Zod tool schema, streamText with a step cap, AbortSignal wiring, and env-based secrets. Add Mastra or Agents SDK only when the product needs their orchestration.
- Prefer TypeScript strict for all new agent code
- Next: LLM Providers for Agents (OpenAI, Gemini, Claude, Llama)
Advantages and limitations
- Advantage: best path for streamed chat product UX
- Advantage: shared language with modern web apps
- Advantage: mature TS SDKs for tools and agents
- Limitation: scientific/ML ecosystem still thinner than Python
- Limitation: easy to leak secrets into the browser
- Limitation: any and unvalidated JSON still sneak into JS codebases
Key points
- Prefer TypeScript strict for agent code.
- Zod validates runtime LLM/tool JSON β types alone are not enough.
- Stream from secured route handlers; keep keys server-side.
- Bound tool loops and cancel with AbortSignal.
- AI SDK / Mastra / Agents SDK TS cover common product needs.
- Same edge rules as Python: auth, budgets, logs, fail closed.
FAQs
JS or TS for agents?
TypeScript. Agents call tools with money and data on the line β compile-time types plus Zod runtime checks reduce costly mistakes.
Zod vs TypeScript interfaces?
Interfaces disappear at runtime. Zod parses real JSON and can infer the TypeScript type from one schema.
Where should the agent run?
On the server (route handler, Node service, or edge runtime with care). The browser streams the UI; it must not hold provider secrets.
AI SDK or Mastra?
AI SDK excels at model I/O and streaming UX. Mastra adds more agent/workflow/RAG opinion. Many apps use AI SDK primitives inside a larger TS app.
Interview questions
- Why TypeScript for Agentic AI?
Answer Strict types catch tool and API contract bugs early, fit Next.js/Node product stacks, and pair with Zod for validating untrusted LLM JSON at runtime.
- How do you validate tool arguments in TS?
Answer Define a Zod (or JSON Schema) inputSchema, parse/safeParse before execute, and fail closed on validation errors β never trust raw model JSON.
- How do you stream an agent reply to the browser?
Answer Run the model/tool loop on the server (e.g. streamText), return an SSE/UI message stream from a secured route handler, and render tokens on the client.
- How do you stop runaway tool loops?
Answer Set max steps / stopWhen conditions, enforce time and token budgets, and allow the client to abort via AbortSignal.
- Name a critical JS agent security mistake.
Answer Exposing provider API keys in client-side code or NEXT_PUBLIC env vars so anyone can drain the account.
- When keep Python alongside a TS agent UI?
Answer When heavy RAG, ML, or Python-only agent frameworks are the bottleneck β TS owns UX/edge; Python owns data/science services behind an API.
Related topics
Practice task
Complete each numbered practice step in a notebook or doc before opening the next lesson.
- Write a Zod schema for a βcreate_ticketβ tool (3β5 fields) and the z.infer type.
- Sketch a POST route handler: auth check β streamText β step cap β env secret.
- List how AbortSignal is passed from UI Stop button to the fetch.
- Write 3 unit tests for tool execute: valid, invalid Zod, unauthorized.
- Answer interview questions 1, 2, and 3 in two sentences each.