npm package: @rightbrain/sdk
Description: RightBrain AI client for running tasks with full TypeScript support
Latest version: 0.3.0

# @rightbrain/sdk

TypeScript SDK for running RightBrain AI tasks.

---

## Installation

```bash
npm install @rightbrain/sdk
```

```bash
pnpm add @rightbrain/sdk
```

```bash
yarn add @rightbrain/sdk
```

---

## Quick Start

```bash
# Login and initialize (generates types)
npx rightbrain@latest login
npx rightbrain@latest init
```

```typescript
import type { Tasks } from "./generated"

import { Client, DirectTransport } from "@rightbrain/sdk"

const rb = new Client<Tasks>({
  transport: new DirectTransport({
    apiKey: process.env.RB_API_KEY,
    orgId: process.env.RB_ORG_ID,
    projectId: process.env.RB_PROJECT_ID,
  }),
})

const result = await rb["<task-id>"].run({
  inputs: { prompt: "Hello" },
})

console.log(result.response)
```

For a complete Next.js integration example, see [rightbrain-sdk-demo](https://github.com/RightbrainAI/rightbrain-sdk-demo).

---

## Transports

The SDK uses transports to communicate with the RightBrain API.

### DirectTransport

For server-side environments where API keys can be stored securely.

```typescript
import { Client, DirectTransport } from "@rightbrain/sdk"

const client = new Client({
  transport: new DirectTransport({
    apiKey: process.env.RB_API_KEY,
    orgId: process.env.RB_ORG_ID,
    projectId: process.env.RB_PROJECT_ID,
  }),
})
```

| Option      | Required | Default                            | Description              |
| ----------- | -------- | ---------------------------------- | ------------------------ |
| `apiKey`    | Yes      | -                                  | RightBrain API key       |
| `orgId`     | Yes      | -                                  | Organization ID          |
| `projectId` | Yes      | -                                  | Project ID               |
| `baseUrl`   | No       | `https://app.rightbrain.ai/api/v1` | API base URL             |
| `config`    | No       | -                                  | Additional fetch options |

### PublicTransport

For client-side environments. Routes requests through a server-side proxy.

```typescript
import { Client, PublicTransport } from "@rightbrain/sdk"

const client = new Client({
  transport: new PublicTransport({
    baseUrl: "/api/tasks",
  }),
})
```

| Option    | Required | Description                |
| --------- | -------- | -------------------------- |
| `baseUrl` | Yes      | URL of your proxy endpoint |

---

## Running Tasks

### Basic Usage

```typescript
const result = await client.runTask({
  taskId: "019bb0de-9b73-7d52-650d-2ca7287630da",
  inputs: { prompt: "Summarize this text" },
})

console.log(result.response)
```

### With Generated Types

After running `npx rightbrain@latest generate`:

```typescript
import type { Tasks } from "./generated"

const rb = new Client<Tasks>({ transport })

// Run active revision
const result = await rb["<task-id>"].run({
  inputs: { prompt: "Hello" },
})

// Run specific revision
const result = await rb["<task-id>"]["<revision-id>"].run({
  inputs: { prompt: "Hello" },
})
```

### RunTaskParams

| Property           | Type      | Required | Description                         |
| ------------------ | --------- | -------- | ----------------------------------- |
| `taskId`           | `string`  | Yes      | Task UUID                           |
| `inputs`           | `object`  | No       | Input data for the task             |
| `files`            | `File[]`  | No       | Files to upload                     |
| `revisionId`       | `string`  | No       | Run a specific revision             |
| `useFallbackModel` | `boolean` | No       | Use fallback model if primary fails |
| `accept`           | `string`  | No       | Request specific response type      |

---

## File Inputs

```typescript
const result = await client.runTask({
  taskId: "<task-id>",
  inputs: { product_name: "Widget" },
  files: [imageFile],
})
```

---

## File Responses

Request non-JSON outputs with the `accept` parameter:

```typescript
const result = await client.runTask({
  taskId: "<image-generator-task>",
  inputs: { prompt: "A sunset" },
  accept: "image/png",
})

if (result instanceof File) {
  // Handle file
  console.log(result.name, result.type)
}
```

Supported types: `image/*`, `audio/*`, `application/pdf`, `text/csv`.

---

## Server-Side Proxy

Use `handleRunTaskRequest` to create a proxy endpoint for `PublicTransport`.

**Next.js App Router:**

```typescript
import { TaskRunError, handleRunTaskRequest } from "@rightbrain/sdk"

export async function POST(request: Request) {
  try {
    const result = await handleRunTaskRequest(
      {
        orgId: process.env.RB_ORG_ID,
        projectId: process.env.RB_PROJECT_ID,
        apiKey: process.env.RB_API_KEY,
      },
      await request.formData()
    )

    if (result instanceof File) {
      return new Response(result, {
        headers: {
          "Content-Type": result.type,
          "Content-Disposition": `attachment; filename="${result.name}"`,
        },
      })
    }

    return Response.json(result)
  } catch (error) {
    if (error instanceof TaskRunError) {
      return Response.json({ error: error.message, detail: error.response }, { status: error.status })
    }
    throw error
  }
}
```

---

## TaskRun Response

```typescript
interface TaskRun<Response> {
  id: string
  task_id: string
  task_revision_id: string
  response: Response
  run_data: { submitted: unknown }
  input_tokens: number
  output_tokens: number
  total_tokens: number
  created: string
  files?: TaskRunFileMetadata[]
  is_error?: boolean
  used_fallback_model?: boolean
  primary_failure_reason?: string | null
  fallback_llm_model_id?: string | null
}
```

---

## Error Handling

```typescript
import { TaskRunError } from "@rightbrain/sdk"

try {
  await client.runTask({ taskId: "...", inputs: {} })
} catch (error) {
  if (error instanceof TaskRunError) {
    console.error(`Status: ${error.status}`)
    console.error(`Message: ${error.message}`)
    console.error(`Response:`, error.response)
  }
}
```

### TaskRunError

| Property   | Type      | Description       |
| ---------- | --------- | ----------------- |
| `message`  | `string`  | Error description |
| `status`   | `number`  | HTTP status code  |
| `response` | `unknown` | Raw API response  |

---

## Type Generation

Types are generated by the CLI into your configured `generatedTaskTypePath`
(default: `./src/generated` if `src` exists, otherwise `./generated`).

```bash
npx rightbrain@latest generate
```

Configure tasks in `rightbrain.json`:

```json
{
  "taskIds": ["019bb0de-9b73-7d52-650d-2ca7287630da"]
}
```

Generated types provide:

- `TaskIds` - Mapping of task names to UUIDs
- `Tasks` - Typed task runners
- Input/output types for each task

---

## License

MIT