> ## Documentation Index
> Fetch the complete documentation index at: https://docs.agentbase.sh/llms.txt
> Use this file to discover all available pages before exploring further.

# TypeScript SDK

> Official TypeScript/JavaScript SDK for the Agentbase API

> The official TypeScript SDK for seamless integration with Agentbase agents.

## Installation

```bash theme={null}
npm install agentbase-sdk
# or
yarn add agentbase-sdk
```

## Quick Start

```typescript theme={null}
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

```typescript theme={null}
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:

```typescript theme={null}
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()`):

```typescript theme={null}
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:

```typescript theme={null}
const messages = await client.messages.get({
  session: "session-id",
});
```

#### client.messages.clear()

Clear all messages from an agent session:

```typescript theme={null}
const result = await client.messages.clear({
  session: "session-id",
});
```

## Error Handling

```typescript theme={null}
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

```typescript theme={null}
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

```typescript theme={null}
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

```typescript theme={null}
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

```typescript theme={null}
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

* **GitHub Repository**: [agentbase-sdk](https://github.com/AgentbaseHQ/agentbase-sdk)
* **NPM Package**: [agentbase-sdk](https://www.npmjs.com/package/agentbase-sdk)
* **Issues & Support**: [GitHub Issues](https://github.com/AgentbaseHQ/agentbase-sdk/issues)

## What's Next?

<CardGroup cols={3}>
  <Card title="Python SDK" icon="python" href="/sdk/python-sdk">
    Use Agentbase with Python
  </Card>

  <Card title="API Reference" icon="code" href="/api/run-agent">
    Complete API documentation
  </Card>

  <Card title="Examples" icon="lightbulb" href="/api/example">
    See more integration examples
  </Card>
</CardGroup>
