Skip to main content
The BuiltInAgent is CopilotKit’s built-in agent implementation powered by the Vercel AI SDK. It provides a flexible, production-ready solution for building AI agents with minimal configuration.

Installation

npm install @copilotkitnext/agent

Quick Start

import { BuiltInAgent } from "@copilotkitnext/agent";

const agent = new BuiltInAgent({
  model: "openai/gpt-4o",
  prompt: "You are a helpful assistant that helps users manage their tasks.",
  maxSteps: 5,
  temperature: 0.7
});

Supported Models

BuiltInAgent supports models from multiple providers:

OpenAI Models

const agent = new BuiltInAgent({
  model: "openai/gpt-5",           // GPT-5
  // model: "openai/gpt-5-mini",   // GPT-5 Mini
  // model: "openai/gpt-4.1",      // GPT-4.1
  // model: "openai/gpt-4.1-mini", // GPT-4.1 Mini
  // model: "openai/gpt-4o",       // GPT-4o
  // model: "openai/gpt-4o-mini",  // GPT-4o Mini
  apiKey: process.env.OPENAI_API_KEY // Optional, defaults to OPENAI_API_KEY env var
});

Reasoning Models

const agent = new BuiltInAgent({
  model: "openai/o3",              // o3
  // model: "openai/o3-mini",      // o3 Mini
  // model: "openai/o4-mini",      // o4 Mini
  providerOptions: {
    openai: {
      reasoningEffort: "high" // Control reasoning depth
    }
  }
});

Anthropic (Claude) Models

const agent = new BuiltInAgent({
  model: "anthropic/claude-sonnet-4.5",
  // model: "anthropic/claude-sonnet-4",
  // model: "anthropic/claude-3.7-sonnet",
  // model: "anthropic/claude-opus-4.1",
  // model: "anthropic/claude-opus-4",
  // model: "anthropic/claude-3.5-haiku",
  apiKey: process.env.ANTHROPIC_API_KEY // Optional, defaults to ANTHROPIC_API_KEY env var
});

Google (Gemini) Models

const agent = new BuiltInAgent({
  model: "google/gemini-2.5-pro",
  // model: "google/gemini-2.5-flash",
  // model: "google/gemini-2.5-flash-lite",
  apiKey: process.env.GOOGLE_API_KEY // Optional, defaults to GOOGLE_API_KEY env var
});

Configuration Options

Basic Configuration

model
BuiltInAgentModel | LanguageModel
required
The LLM model to use. Can be a string like "openai/gpt-4o" or a Vercel AI SDK LanguageModel instance.
apiKey
string
API key for the model provider. Falls back to environment variables:
  • OPENAI_API_KEY for OpenAI models
  • ANTHROPIC_API_KEY for Anthropic models
  • GOOGLE_API_KEY for Google models
prompt
string
System prompt for the agent. Context and state information will be automatically appended.
maxSteps
number
default:1
Maximum number of tool calling iterations. Set higher for multi-step reasoning.

Generation Parameters

toolChoice
ToolChoice
default:"auto"
Control tool selection: "auto", "required", "none", or { type: "tool", toolName: string }
maxOutputTokens
number
Maximum number of tokens to generate in the response.
temperature
number
Controls randomness in generation. Higher values make output more random.
topP
number
Nucleus sampling parameter. Controls diversity via probability mass.
topK
number
Top-K sampling parameter. Limits token selection to top K options.
presencePenalty
number
Penalizes tokens based on whether they appear in the text so far.
frequencyPenalty
number
Penalizes tokens based on their frequency in the text so far.
stopSequences
string[]
Sequences that will stop the generation when encountered.
seed
number
Random seed for deterministic generation (when supported by the model).
maxRetries
number
Maximum number of retries for failed API calls.
providerOptions
Record<string, any>
Provider-specific options. Example: { openai: { reasoningEffort: "high" } }

Advanced Configuration

overridableProperties
OverridableProperty[]
List of properties that can be overridden by client-side forwardedProps. Options include:
  • "model" - Allow client to change model
  • "toolChoice" - Allow client to control tool selection
  • "temperature" - Allow client to adjust temperature
  • And more generation parameters
forwardSystemMessages
boolean
default:false
Whether to forward system-role messages from input to the LLM.
forwardDeveloperMessages
boolean
default:false
Whether to forward developer-role messages from input to the LLM (as system messages).

Defining Tools

Basic Tool Definition

import { BuiltInAgent, defineTool } from "@copilotkitnext/agent";
import { z } from "zod";

const sendEmailTool = defineTool({
  name: "send_email",
  description: "Send an email to a recipient",
  parameters: z.object({
    to: z.string().email().describe("Recipient email address"),
    subject: z.string().describe("Email subject line"),
    body: z.string().describe("Email body content")
  }),
  execute: async (args) => {
    // Your implementation here
    console.log(`Sending email to ${args.to}`);
    console.log(`Subject: ${args.subject}`);
    console.log(`Body: ${args.body}`);
    
    return { success: true, messageId: "msg_123" };
  }
});

const agent = new BuiltInAgent({
  model: "openai/gpt-4o",
  tools: [sendEmailTool]
});

Tool with Complex Parameters

const createTaskTool = defineTool({
  name: "create_task",
  description: "Create a new task in the project management system",
  parameters: z.object({
    title: z.string().describe("Task title"),
    description: z.string().optional().describe("Detailed task description"),
    priority: z.enum(["low", "medium", "high"]).describe("Task priority level"),
    assignee: z.string().email().optional().describe("Email of person to assign"),
    dueDate: z.string().datetime().optional().describe("ISO 8601 due date"),
    tags: z.array(z.string()).optional().describe("Task tags for categorization")
  }),
  execute: async (args) => {
    // Create task in your system
    const task = await createTaskInDatabase(args);
    return { taskId: task.id, url: task.url };
  }
});

MCP Server Integration

BuiltInAgent supports Model Context Protocol (MCP) servers for dynamic tool discovery:

HTTP Transport

const agent = new BuiltInAgent({
  model: "openai/gpt-4o",
  mcpServers: [
    {
      type: "http",
      url: "http://localhost:3000/mcp",
      options: {
        // Optional HTTP-specific options
        headers: {
          "Authorization": "Bearer token"
        }
      }
    }
  ]
});

SSE Transport

const agent = new BuiltInAgent({
  model: "openai/gpt-4o",
  mcpServers: [
    {
      type: "sse",
      url: "http://localhost:3000/mcp/sse",
      headers: {
        "Authorization": "Bearer token"
      }
    }
  ]
});

Multiple MCP Servers

const agent = new BuiltInAgent({
  model: "openai/gpt-4o",
  mcpServers: [
    { type: "http", url: "http://localhost:3001/mcp" },
    { type: "http", url: "http://localhost:3002/mcp" },
    { type: "sse", url: "http://localhost:3003/mcp/sse" }
  ]
});

Using with CopilotRuntime

import { CopilotRuntime } from "@copilotkitnext/runtime";
import { BuiltInAgent } from "@copilotkitnext/agent";

const agent = new BuiltInAgent({
  model: "openai/gpt-4o",
  prompt: "You are a helpful assistant.",
  tools: [sendEmailTool, createTaskTool]
});

const runtime = new CopilotRuntime({
  agents: {
    default: agent
  }
});

Client-Side Property Overrides

Allow clients to override specific properties at runtime:
const agent = new BuiltInAgent({
  model: "openai/gpt-4o",
  temperature: 0.7,
  overridableProperties: ["temperature", "maxOutputTokens"]
});
Client can now send:
useCopilotChat({
  forwardedProps: {
    temperature: 0.9,
    maxOutputTokens: 500
  }
});

State Management

BuiltInAgent automatically provides state management tools:

AGUISendStateSnapshot

Replace the entire application state:
// The agent can call this tool to update state
{
  name: "AGUISendStateSnapshot",
  args: {
    snapshot: { counter: 10, items: ["a", "b", "c"] }
  }
}

AGUISendStateDelta

Apply incremental updates using JSON Patch:
// The agent can call this tool to update state incrementally
{
  name: "AGUISendStateDelta",
  args: {
    delta: [
      { op: "replace", path: "/counter", value: 11 },
      { op: "add", path: "/items/-", value: "d" }
    ]
  }
}

Complete Example

import { BuiltInAgent, defineTool } from "@copilotkitnext/agent";
import { CopilotRuntime } from "@copilotkitnext/runtime";
import { z } from "zod";

// Define tools
const weatherTool = defineTool({
  name: "get_weather",
  description: "Get current weather for a location",
  parameters: z.object({
    location: z.string().describe("City name or zip code")
  }),
  execute: async ({ location }) => {
    // Call weather API
    return { temp: 72, condition: "sunny", location };
  }
});

// Create agent
const agent = new BuiltInAgent({
  model: "openai/gpt-4o",
  prompt: "You are a helpful weather assistant. Provide detailed weather information.",
  temperature: 0.7,
  maxSteps: 3,
  tools: [weatherTool],
  mcpServers: [
    { type: "http", url: "http://localhost:3000/mcp" }
  ],
  overridableProperties: ["temperature"]
});

// Use in runtime
const runtime = new CopilotRuntime({
  agents: {
    weather: agent
  }
});

API Reference

See the BuiltInAgent source code for complete implementation details.

Next Steps

Custom Agents

Build custom agent implementations

LangGraph Integration

Use LangGraph for complex workflows

MCP Servers

Learn about Model Context Protocol

Runtime Configuration

Configure the CopilotRuntime