Skip to main content

Basic Agent

The simplest agent consists of a name, model, and instructions (prompt):
import { openai } from '@ai-sdk/openai';
import { agent, execute } from '@deepagents/agent';

const assistant = agent({
  name: 'assistant',
  model: openai('gpt-4o'),
  prompt: 'You are a helpful assistant.',
});

const stream = await execute(assistant, 'What is TypeScript?', {});
const text = await stream.text;

console.log(text);

Agent Configuration

Required Fields

name
string
required
Unique identifier for the agent. Used in handoff tools and logging.
model
LanguageModel
required
AI model from any Vercel AI SDK provider (OpenAI, Anthropic, Google, etc.).
prompt
string | string[] | ((ctx?) => string)
required
Instructions for the agent. Can be a string, array of strings, or function that returns instructions based on context.

Optional Fields

tools
ToolSet
Tools available to the agent (see Tools).
handoffs
Agent[]
Specialized agents this agent can delegate to (see Multi-Agent).
output
z.Schema<T>
Zod schema for structured output (see Structured Output).
handoffDescription
string
Description of what this agent does, used when it’s added as a handoff target.
toolChoice
'auto' | 'none' | 'required'
default:"auto"
Controls when the agent should use tools.

Execution Methods

There are three ways to execute an agent:

Streaming Execution

Use execute() (or stream()) for real-time streaming responses:
import { execute } from '@deepagents/agent';

const stream = await execute(assistant, 'Tell me a story', {});

// Stream text chunks
for await (const chunk of stream.textStream) {
  process.stdout.write(chunk);
}

// Or get the full text
const text = await stream.text;

Non-Streaming Execution

Use generate() for a single response:
import { generate } from '@deepagents/agent';

const result = await generate(assistant, 'What is 2+2?', {});
console.log(result.text);

Multi-Agent Streaming

Use swarm() for agents with handoffs (see Multi-Agent):
import { swarm } from '@deepagents/agent';

const stream = swarm(coordinator, 'Complete this task', {});

for await (const chunk of stream) {
  if (chunk.type === 'text-delta') {
    process.stdout.write(chunk.delta);
  }
}

Dynamic Instructions

Instructions can be dynamic based on context variables:
interface UserContext {
  userId: string;
  userName: string;
  preferences: Record<string, string>;
}

const personalizedAgent = agent<unknown, UserContext>({
  name: 'personal_assistant',
  model: openai('gpt-4o'),
  prompt: (ctx) => `
    You are a helpful assistant for ${ctx?.userName || 'the user'}.
    User preferences: ${JSON.stringify(ctx?.preferences || {})}
  `,
});

const context: UserContext = {
  userId: 'user123',
  userName: 'Alice',
  preferences: { theme: 'dark', language: 'en' },
};

const stream = await execute(personalizedAgent, 'Hello!', context);

Structured Instructions

Use the instructions() helper for well-structured prompts:
import { agent, instructions } from '@deepagents/agent';

const analyst = agent({
  name: 'data_analyst',
  model: openai('gpt-4o'),
  prompt: instructions({
    purpose: [
      'You are a data analyst specializing in financial data.',
      'Analyze datasets and provide actionable insights.',
    ],
    routine: [
      'Examine the data for patterns and anomalies',
      'Calculate relevant statistics',
      'Provide clear recommendations',
    ],
  }),
});
The instructions() helper formats prompts consistently:
# Agent Context
You are a data analyst specializing in financial data.
Analyze datasets and provide actionable insights.


Use the following routine to fulfill the task.
# Routine
1. Examine the data for patterns and anomalies
2. Calculate relevant statistics
3. Provide clear recommendations

Message Formats

Execute agents with different message formats:

Simple String

const stream = await execute(assistant, 'What is AI?', {});

UI Messages

import { user } from '@deepagents/agent';

const messages = [
  user('What is TypeScript?'),
];

const stream = await execute(assistant, messages, {});

Multi-Turn Conversation

const messages = [
  user('What is TypeScript?'),
  // Previous assistant response would be here
  user('Can you give me an example?'),
];

const stream = await execute(assistant, messages, {});

Error Handling

try {
  const stream = await execute(assistant, 'Hello!', {});
  const text = await stream.text;
  console.log(text);
} catch (error) {
  if (error.name === 'AbortError') {
    console.log('Request was aborted');
  } else {
    console.error('Error:', error.message);
  }
}

Abort Signal

Cancel long-running executions:
const controller = new AbortController();

const stream = await execute(assistant, 'Write a long story', {}, {
  abortSignal: controller.signal,
});

// Cancel after 5 seconds
setTimeout(() => controller.abort(), 5000);

try {
  const text = await stream.text;
} catch (error) {
  if (error.name === 'AbortError') {
    console.log('Execution aborted');
  }
}

Next Steps

Add Tools

Extend agent capabilities with tools

Multi-Agent Systems

Coordinate multiple agents with handoffs

Structured Output

Get type-safe structured responses

Context Variables

Share state between agents

Build docs developers (and LLMs) love