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

# TypeScript SDK

> Avala TypeScript SDK 完整指南

## 安装

<CodeGroup>
  ```bash npm theme={null}
  npm install @avala-ai/sdk
  ```

  ```bash yarn theme={null}
  yarn add @avala-ai/sdk
  ```

  ```bash pnpm theme={null}
  pnpm add @avala-ai/sdk
  ```
</CodeGroup>

## 快速开始

```typescript theme={null}
import Avala from "@avala-ai/sdk";

const avala = new Avala({ apiKey: "your-api-key" });

const datasets = await avala.datasets.list();
for (const dataset of datasets.items) {
  console.log(dataset.name, dataset.uid);
}
```

## 创建账户

`signup` 函数创建新的 Avala 账户并返回 API 密钥。不需要认证。

```typescript theme={null}
import { signup } from "@avala-ai/sdk";

const result = await signup({
  email: "dev@acme.com",
  password: "SecurePass123!",
  firstName: "Jane",       // optional
  lastName: "Doe",         // optional
});

console.log(`User: ${result.user.email}`);
console.log(`API Key: ${result.apiKey}`);
```

使用返回的 API 密钥初始化客户端：

```typescript theme={null}
import Avala, { signup } from "@avala-ai/sdk";

const { apiKey } = await signup({ email: "dev@acme.com", password: "SecurePass123!" });
const avala = new Avala({ apiKey });
```

## 认证

SDK 使用 Avala API 密钥进行认证，通过 `X-Avala-Api-Key` 头在每个请求中发送。

您可以直接提供密钥或让 SDK 从环境变量读取。

**方式 1：直接传递密钥**

```typescript theme={null}
import Avala from "@avala-ai/sdk";

const avala = new Avala({ apiKey: "your-api-key" });
```

**方式 2：使用环境变量**

```bash theme={null}
export AVALA_API_KEY="your-api-key"
```

```typescript theme={null}
import Avala from "@avala-ai/sdk";

// 自动从环境变量读取 AVALA_API_KEY
const avala = new Avala();
```

## 使用数据集

<Note>
  TypeScript SDK 目前对数据集是**只读的**——您可以列出和检索数据集，但不能创建、更新或删除。上传和修改操作请使用 [REST API](/docs/sdks/rest-api#file-uploads)。
</Note>

### 列出数据集

```typescript theme={null}
const datasets = await avala.datasets.list();

for (const dataset of datasets.items) {
  console.log(`${dataset.name} (${dataset.uid})`);
  console.log(`  Items: ${dataset.itemCount}`);
  console.log(`  Created: ${dataset.createdAt}`);
}
```

### 获取数据集

```typescript theme={null}
const dataset = await avala.datasets.get("550e8400-e29b-41d4-a716-446655440000");

console.log(dataset.name);
console.log(dataset.slug);
console.log(dataset.itemCount);
```

## 使用项目

### 列出项目

```typescript theme={null}
const projects = await avala.projects.list();

for (const project of projects.items) {
  console.log(`${project.name} (${project.uid})`);
  console.log(`  Status: ${project.status}`);
  console.log(`  Created: ${project.createdAt}`);
}
```

### 获取项目

```typescript theme={null}
const project = await avala.projects.get("770a9600-a40d-63f6-c938-668877660000");

console.log(project.name);
console.log(project.status);
```

## 使用任务

### 列出任务

```typescript theme={null}
const tasks = await avala.tasks.list({
  project: "770a9600-a40d-63f6-c938-668877660000",
  status: "pending",
});

for (const task of tasks.items) {
  console.log(`${task.uid} — ${task.name} (${task.status})`);
}
```

### 获取任务

```typescript theme={null}
const task = await avala.tasks.get("990c1800-b62f-85a8-e150-880099880000");

console.log(task.name);
console.log(task.status);
```

## 使用导出

### 创建导出

```typescript theme={null}
const exportJob = await avala.exports.create({
  project: "770a9600-a40d-63f6-c938-668877660000",
});

console.log(`Export started: ${exportJob.uid}`);
console.log(`Status: ${exportJob.status}`);
```

### 轮询完成状态

```typescript theme={null}
let exportJob = await avala.exports.create({
  project: "770a9600-a40d-63f6-c938-668877660000",
});

while (exportJob.status !== "completed") {
  await new Promise((resolve) => setTimeout(resolve, 2000));
  exportJob = await avala.exports.get(exportJob.uid);
  console.log(`Status: ${exportJob.status}`);
}

console.log(`Download: ${exportJob.downloadUrl}`);
```

## TypeScript 类型

SDK 导出所有 API 对象的完整 TypeScript 接口。使用它们为您的函数和变量添加类型。

```typescript theme={null}
import Avala from "@avala-ai/sdk";
import type { Dataset, Project, Export, Task, CursorPage } from "@avala-ai/sdk";

function processDataset(dataset: Dataset): void {
  console.log(dataset.name);       // string
  console.log(dataset.uid);        // string
  console.log(dataset.itemCount);  // number
  console.log(dataset.createdAt);  // string | null
}

function processTask(task: Task): void {
  console.log(task.uid);           // string
  console.log(task.name);          // string | null
  console.log(task.status);        // string | null
  console.log(task.project);       // string | null
}
```

## 错误处理

SDK 抛出类型化错误，让您精确处理不同的失败模式。

```typescript theme={null}
import Avala, { AvalaError, NotFoundError, RateLimitError } from "@avala-ai/sdk";

const avala = new Avala();

try {
  const dataset = await avala.datasets.get("nonexistent");
} catch (error) {
  if (error instanceof NotFoundError) {
    console.log(`Dataset not found: ${error.message}`);
  } else if (error instanceof RateLimitError) {
    console.log(`Rate limited. Retry after ${error.retryAfter} seconds.`);
  } else if (error instanceof AvalaError) {
    console.log(`API error (${error.statusCode}): ${error.message}`);
  } else {
    throw error;
  }
}
```

| 异常                    | 描述                                         |
| --------------------- | ------------------------------------------ |
| `AvalaError`          | 所有 Avala API 错误的基础错误类。                     |
| `AuthenticationError` | API 密钥无效或缺失（HTTP 401）。                     |
| `NotFoundError`       | 请求的资源不存在（HTTP 404）。                        |
| `RateLimitError`      | 已超过 API 速率限制（HTTP 429）。包含 `retryAfter` 属性。 |
| `ValidationError`     | 请求载荷验证失败（HTTP 400/422）。                    |
| `ServerError`         | 服务器返回内部错误（HTTP 5xx）。                       |

## 分页

列表方法返回 `CursorPage<T>` 对象，使用基于游标的分页。

```typescript theme={null}
// Access items on the current page
const page = await avala.datasets.list({ limit: 10 });
for (const dataset of page.items) {
  console.log(dataset.name);
}

// Fetch the next page
if (page.hasMore) {
  const nextPage = await avala.datasets.list({
    limit: 10,
    cursor: page.nextCursor!,
  });
}
```

## 使用代理

### 创建代理

```typescript theme={null}
const agent = await avala.agents.create({
  name: "QA Bot",
  events: ["task.completed"],
  callbackUrl: "https://example.com/webhook",
  taskTypes: ["annotation"],
});
```

### 列出代理执行

```typescript theme={null}
const executions = await avala.agents.listExecutions(agent.uid);
for (const exec of executions.items) {
  console.log(`${exec.eventType} — ${exec.status}`);
}
```

## 使用 Webhook

### 创建 Webhook

```typescript theme={null}
const webhook = await avala.webhooks.create({
  targetUrl: "https://example.com/webhook",
  events: ["task.completed", "export.ready"],
});
```

### 检查投递

```typescript theme={null}
const deliveries = await avala.webhookDeliveries.list();
for (const d of deliveries.items) {
  console.log(`${d.eventType} — ${d.status} (attempts: ${d.attempts})`);
}
```

## 使用质量和共识

### 创建质量目标

```typescript theme={null}
const target = await avala.qualityTargets.create("proj_uid", {
  name: "Accuracy",
  metric: "accuracy",
  operator: "gte",
  threshold: 0.95,
  notifyEmails: ["alerts@example.com"],
});
```

### 检查共识

```typescript theme={null}
const summary = await avala.consensus.getSummary("proj_uid");
console.log(`Mean score: ${summary.meanScore}`);
console.log(`Coverage: ${summary.itemsWithConsensus}/${summary.totalItems}`);
```

## 车队管理

<Info>
  车队管理处于预览阶段。此处描述的 API 可能会更改。
</Info>

`fleet` 命名空间提供对设备注册、录制、事件、规则和警报的访问。

```typescript theme={null}
// List online devices
const devices = await avala.fleet.devices.list({ status: "online" });

// Create a timeline event on a recording
const event = await avala.fleet.events.create({
  recordingId: "rec_abc123",
  timestamp: "2026-01-15T10:30:00Z",
  type: "anomaly",
  label: "Gripper force spike",
  metadata: { force_n: 45.2 },
});

// Create a recording rule
const rule = await avala.fleet.rules.create({
  name: "High Latency Alert",
  condition: { type: "threshold", topic: "/diagnostics/latency", field: "data.value", operator: "gt", value: 100 },
  actions: [{ type: "tag", value: "high-latency" }, { type: "notify", channelId: "ch_your_channel_id" }],
});
```

完整示例请参阅[车队仪表板](/docs/visualization/fleet/fleet-dashboard)指南。

## 配置

您可以在初始化时自定义客户端行为。

```typescript theme={null}
import Avala from "@avala-ai/sdk";

const avala = new Avala({
  apiKey: "your-api-key",
  baseUrl: "https://api.avala.ai/api/v1", // Default
  timeout: 60_000,    // Request timeout in ms (default: 30000)
});
```

| 参数        | 类型       | 默认值                           | 描述               |
| --------- | -------- | ----------------------------- | ---------------- |
| `apiKey`  | `string` | `AVALA_API_KEY` 环境变量          | 您的 Avala API 密钥。 |
| `baseUrl` | `string` | `https://api.avala.ai/api/v1` | API 基础 URL。      |
| `timeout` | `number` | `30000`                       | 请求超时时间（毫秒）。      |

## 零依赖

`@avala-ai/sdk` 包没有运行时依赖。它使用 Node.js 18+、Deno 和 Bun 中可用的原生 `fetch` API。

## 框架示例

### Next.js (App Router)

```typescript theme={null}
// app/api/datasets/route.ts
import Avala from "@avala-ai/sdk";
import { NextResponse } from "next/server";

const avala = new Avala({ apiKey: process.env.AVALA_API_KEY! });

export async function GET() {
  const datasets = await avala.datasets.list();
  return NextResponse.json(datasets);
}
```

### Express

```typescript theme={null}
import express from "express";
import Avala from "@avala-ai/sdk";

const app = express();
const avala = new Avala(); // Reads AVALA_API_KEY from env

app.get("/datasets", async (req, res) => {
  try {
    const datasets = await avala.datasets.list();
    res.json(datasets);
  } catch (error) {
    res.status(500).json({ error: "Failed to fetch datasets" });
  }
});

app.listen(3000, () => {
  console.log("Server running on port 3000");
});
```
