TypeScript / JavaScript Agent Guide

Building Agents with Vercel AI SDK

Learn how to construct multi-step agent loops, define Zod-validated tool schemas, and stream real-time tool execution results to modern web interfaces.

01

Multi-Step Agent Loops

Set maxSteps: 10 to let the agent continuously invoke tools, parse observations, and iterate until the task reaches completion.

02

Zod Schema Validation

Define type-safe tool input schemas with Zod to guarantee strict parameter validation before functions execute.

03

React & Next.js Streaming

Use useChat or Server Actions to stream tool invocation states and model tokens directly to React UI components.

TypeScript Multi-Step Agent Implementation

Here is a complete Node.js / TypeScript agent using generateText with automated multi-step tool execution.

import { generateText, tool } from 'ai';
import { openai } from '@ai-sdk/openai';
import { z } from 'zod';

// 1. Define Validated Tools
const weatherTool = tool({
  description: 'Get current weather conditions for a location',
  parameters: z.object({
    location: z.string().describe('City name or coordinates'),
  }),
  execute: async ({ location }) => {
    return { location, temperature: '72°F', condition: 'Sunny' };
  },
});

const databaseTool = tool({
  description: 'Query database for user account status',
  parameters: z.object({
    userId: z.string().describe('Target user ID'),
  }),
  execute: async ({ userId }) => {
    return { userId, status: 'Active', plan: 'Enterprise' };
  },
});

// 2. Execute Multi-Step Agent Loop
async function runAgent() {
  const { text, steps } = await generateText({
    model: openai('gpt-4o'),
    maxSteps: 5, // Enables recursive tool loop
    system: 'You are an autonomous operations assistant. Use tools when needed.',
    prompt: 'Check weather in San Francisco and verify account status for user US_9021.',
    tools: {
      getWeather: weatherTool,
      getUserStatus: databaseTool,
    },
  });

  console.log('Final Agent Response:', text);
  console.log('Total Steps Executed:', steps.length);
}

runAgent();