Skip to main content
The official TypeScript SDK for seamless integration with Agentbase agents.

Installation

npm install agentbase-sdk
# or
yarn add agentbase-sdk

Quick Start

import { Agentbase } from "agentbase-sdk";

const client = new Agentbase({
  apiKey: "your-api-key",
});

// Run an agent (root-level method)
const response = await client.runAgent({
  message: "Hello, analyze this data for me",
});

// Or use the agent resource
const response2 = await client.agent.run({
  message: "Hello, analyze this data for me",
});

// Handle streaming response
for await (const event of response) {
  console.log(event);
}

Configuration

const client = new Agentbase({
  apiKey: "your-api-key",
  baseURL: "https://api.agentbase.sh", // optional
  timeout: 30000, // optional, in milliseconds
});

API Methods

Root-Level Methods

client.runAgent()

Run an agent directly from the root client:
const stream = await client.runAgent({
  message: "Your task here", // required
  session: "session-id", // optional: continue conversation
  mode: "fast", // optional: "fast" | "flash" | "max", defaults to "fast"
  system: "You are a helpful assistant", // optional: system prompt
  rules: ["Be concise", "Show examples"], // optional: array of constraints
  workflows: [
    // optional: declarative workflows
    {
      id: "workflow_1",
      name: "example_workflow",
      description: "Example workflow description",
      steps: [
        {
          id: "step_1",
          name: "first_step",
          description: "What this step should accomplish",
          depends_on: [],
          optional: false, // optional
          retry_policy: {
            // optional
            max_attempts: 3,
            backoff: "exponential",
          },
          output_schema: {
            // optional
            type: "object",
            properties: {
              result: { type: "string" },
            },
          },
        },
      ],
    },
  ],
  mcp_servers: [
    // optional: MCP server configs
    {
      serverName: "my-api",
      serverUrl: "https://api.example.com/mcp",
    },
  ],
  background: false, // optional: run agent asynchronously, defaults to false
  callback: {
    // optional: use with background: true
    url: "https://your-server.com/webhook",
    headers: {
      Authorization: "Bearer your-token",
    },
  },
  datastores: [
    // optional: data sources for the agent
    {
      id: "ds_1234567890abcdef",
      name: "my-datastore",
    },
  ],
  queries: [
    // optional: custom datastore queries
    {
      name: "getUserById",
      description: "Fetch user details by their ID",
      query: "SELECT * FROM users WHERE id = ?",
    },
  ],
  streaming_tokens: false, // optional: stream tokens, defaults to false
  final_output: {
    // optional: structured final output
    name: "task_summary",
    strict: true,
    schema: {
      type: "object",
      properties: {
        summary: { type: "string" },
        outcome: {
          type: "string",
          enum: ["success", "partial_success", "failure"],
        },
      },
      required: ["summary", "outcome"],
    },
  },
});

Agent Resource

client.agent.run()

Run an agent using the agent resource (accepts same parameters as client.runAgent()):
const stream = await client.agent.run({
  message: "Your task here", // required
  session: "session-id", // optional
  mode: "fast", // optional
  system: "You are a helpful assistant", // optional
  rules: ["Be concise", "Show examples"], // optional
  workflows: [...], // optional
  mcp_servers: [...], // optional
  background: false, // optional
  callback: {...}, // optional
  datastores: [...], // optional
  queries: [...], // optional
  streaming_tokens: false, // optional
  final_output: {...} // optional
});

Messages Resource

client.messages.get()

Retrieve messages from an agent session:
const messages = await client.messages.get({
  session: "session-id",
});

client.messages.clear()

Clear all messages from an agent session:
const result = await client.messages.clear({
  session: "session-id",
});

Error Handling

try {
  const response = await client.runAgent({
    message: "Your task",
  });
} catch (error) {
  if (error instanceof AgentbaseError) {
    console.error("API Error:", error.message);
    console.error("Status:", error.status);
  } else {
    console.error("Unexpected error:", error);
  }
}

TypeScript Types

interface RunAgentParams {
  message: string;
  session?: string;
  mode?: "fast" | "flash" | "max";
  system?: string;
  rules?: string[];
  workflows?: Workflow[];
  mcp_servers?: MCPServer[];
  background?: boolean;
  callback?: CallbackConfig;
  datastores?: Datastore[];
  queries?: Query[];
  streaming_tokens?: boolean;
  final_output?: FinalOutputConfig;
}

interface Workflow {
  id: string;
  name: string;
  description: string;
  steps: WorkflowStep[];
}

interface WorkflowStep {
  id: string;
  name: string;
  description: string;
  depends_on: string[];
  optional?: boolean;
  retry_policy?: {
    max_attempts: number;
    backoff: "linear" | "exponential";
  };
  output_schema?: Record<string, any>;
}

interface MCPServer {
  serverName: string;
  serverUrl: string;
}

interface CallbackConfig {
  url: string;
  headers?: Record<string, string>;
}

interface Datastore {
  id: string;
  name: string;
}

interface Query {
  name: string;
  description: string;
  query: string;
}

interface FinalOutputConfig {
  name: string;
  strict: boolean;
  schema: Record<string, any>;
}

interface AgentEvent {
  type: string;
  content?: string;
  session?: string;
  cost?: string;
  balance?: number;
}

Examples

Basic Chat

const chat = await client.runAgent({
  message: "What's the weather like today?",
});

for await (const event of chat) {
  if (event.type === "agent_message") {
    console.log("Agent:", event.content);
  }
}

With Session Continuity

let sessionId: string | undefined;

// First message
const response1 = await client.runAgent({
  message: "Hello, I'm working on a React project",
});

for await (const event of response1) {
  if (event.session) sessionId = event.session;
}

// Continue conversation
const response2 = await client.agent.run({
  message: "Can you help me with state management?",
  session: sessionId,
});

Cost Tracking

let totalCost = 0;

const response = await client.runAgent({
  message: "Analyze this dataset",
});

for await (const event of response) {
  if (event.type === "agent_cost") {
    totalCost += parseFloat(event.cost || "0");
    console.log(`Current cost: $${event.cost}`);
    console.log(`Total spent: $${totalCost}`);
  }
}

Resources

What’s Next?