# TypeScript SDK

> Use the official FastGPT TypeScript SDK (@fastgpt/sdk) with zero runtime dependencies for chat, SSE streaming, interactive Workflows, and Datasets.

Source: https://doc.fastgpt.io/openapi/sdk/typescript
Last Updated: 2026-12-02

> **Online API Reference**: Refer to the official API reference and deployment interactive pages for complete request/response schemas and endpoint availability:
>
> * Official API Reference (Global): [System OpenAPI](https://doc.fastgpt.io/openapi/api-reference)
> * Official API Reference (China): [System OpenAPI](https://doc.fastgpt.cn/openapi/api-reference)
> * International Cloud (Try it out): [System OpenAPI](https://cloud.fastgpt.io/apidoc/systemopenapi)
> * Mainland China Cloud (Try it out): [System OpenAPI](https://cloud.fastgpt.cn/apidoc/systemopenapi)
> * Self-Hosted Instance (Try it out): `<instance>/apidoc/systemopenapi`

**Compatibility: Node.js 20.0.0 or later (also supports Bun, Deno, and Edge Runtimes) for FastGPT System OpenAPI.**

`@fastgpt/sdk` is the official TypeScript / JavaScript SDK for FastGPT System OpenAPI. Built with **zero runtime dependencies** on standard Web `fetch`, `FormData`, `Blob`, and `ReadableStream`, it ships dual ESM/CJS bundles with full `.d.mts` / `.d.cts` type declarations. All resource methods and contracts are deterministically generated from the System OpenAPI IR across 47 endpoints covering chat completions, SSE streaming, interactive Workflow resumption, Datasets, App logs, and model catalogs.

> If you only need basic OpenAI-compatible chat completions, see the [API Quick Start](https://doc.fastgpt.io/openapi/intro). Use `@fastgpt/sdk` when integrating interactive Workflow resumption, chat history management, Dataset uploads, batch archive downloads, cursor-based App log search, or structured error handling in TypeScript or JavaScript services.

## Installation and Requirements

* Runtime: **Node.js >= 20.0.0**, Bun, Deno, or Edge Runtimes (standard Web `fetch`, `FormData`, `Blob`, and `ReadableStream`)
* Runtime dependencies: None (zero runtime dependencies)
* Package name and target version: `@fastgpt/sdk` (`0.1.0-beta.2` aligned with System OpenAPI)

```bash
# In the dependency-installed FastGPT repository root, build and pack 0.1.0-beta.2
pnpm --filter @fastgpt/sdk build
npm pack ./sdk/client --pack-destination /tmp

# In your application project, install the generated tarball
npm install /tmp/fastgpt-sdk-0.1.0-beta.2.tgz
# or with pnpm
pnpm add /tmp/fastgpt-sdk-0.1.0-beta.2.tgz
```

> This guide documents the System OpenAPI-aligned **`0.1.0-beta.2`** surface (47 operations plus subpath exports `./errors`, `./sse`, `./options`, `./interactive`, `./pagination`, and `./types`). On npm, the default tag currently resolves to the earlier `0.1.0-beta.1` preview (which exported `.`, `./errors`, and `./server` only and lacks `./options`, `./types`, and related subpaths). Use the local build-and-pack commands above until `0.1.0-beta.2` is published to npm, after which you can install `@fastgpt/sdk@0.1.0-beta.2` (or `pnpm add @fastgpt/sdk@0.1.0-beta.2`) directly.

### Subpath Exports

`@fastgpt/sdk` exports only the `FastGPT` client class from the package root; errors, streaming helpers, client options, interactive helpers, pagination utilities, and contract types are organized under dedicated subpaths:

| Subpath                    | Exported Symbols                                                                                                                                                                     |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `@fastgpt/sdk`             | `FastGPT`                                                                                                                                                                            |
| `@fastgpt/sdk/errors`      | `FastGptError` and 8 typed subclasses, `redactSecrets`, `createMappedApiError`, `FastGptErrorDetails`                                                                                |
| `@fastgpt/sdk/sse`         | `ChatStream`, `parseChatSseFrame`, `iterateRawSseFrames`, `ChatSseEvent`, `ChatStreamFinalResult`, `ChatStreamTerminalState`, `RawSseFrame`                                          |
| `@fastgpt/sdk/options`     | `FastGptClientOptions`, `RequestOptions`, `CredentialProvider`, `FastGptIdentity`, `AuthProxyIdentity`, `FastGptHooks`, `FastGptLogger`, `Uploadable`, `WithRawResponseResult`, etc. |
| `@fastgpt/sdk/interactive` | `ChatInteractiveHelper`, `extractInteractive`, `isInteractivePending`, `unwrapInteractive`, `buildUserSelectMessage`, `buildUserFormMessage`, `InteractivePayload`, etc.             |
| `@fastgpt/sdk/pagination`  | `createOffsetPaginator`, `createPageNumPaginator`, `createCursorPaginator`, `AsyncPageIterable`, `AutoPagingOptions`, `CursorAutoPagingOptions`                                      |
| `@fastgpt/sdk/types`       | Generated System OpenAPI `*Req` / `*Res` contract types                                                                                                                              |

### Environment Variables

| Variable           | Description                                                          | Default / Behavior                                                                     |
| ------------------ | -------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
| `FASTGPT_BASE_URL` | FastGPT server base URL (trailing `/api` is optional and normalized) | Read automatically when `baseUrl` is omitted; falls back to `https://cloud.fastgpt.cn` |
| `FASTGPT_API_KEY`  | Personal API key or App API key                                      | Read automatically when omitted in `FastGPT` options and `RequestOptions`              |
| `FASTGPT_APP_ID`   | Default App ID                                                       | Not read automatically; pass `process.env.FASTGPT_APP_ID` to `defaultAppId` as needed  |

## Quick Start and Authentication

### Basic Chat Completion

When `baseUrl` and `apiKey` are omitted, `FastGPT` automatically reads `FASTGPT_BASE_URL` and `FASTGPT_API_KEY` from environment variables (set `FASTGPT_BASE_URL` for self-hosted deployments):

```ts
import { FastGPT } from '@fastgpt/sdk';

const client = new FastGPT({
  defaultAppId: process.env.FASTGPT_APP_ID // Optional when using an App API key
});

const completion = await client.chat.completionsV2({
  chatId: 'chat_quickstart_001',
  messages: [{ role: 'user', content: 'Summarize today’s release notes.' }]
});

console.log(completion.choices[0]?.message.content);
```

> To prevent leaking API keys into frontend bundles, instantiating `new FastGPT(...)` in a browser environment (where `window.document` exists) is blocked by default and throws `FastGptError`. Pass `{ dangerouslyAllowBrowser: true }` only if you explicitly understand and accept the risk.

### Personal API Keys vs. App API Keys

* **App API key (v4.18.0+)**: Bound server-side to a single App. You can omit `defaultAppId` when calling chat, chat management, and `apps.logs` endpoints. `datasets` and `models.catalog` accept Personal API keys only.
* **Personal API key**: Accesses all permitted System OpenAPI resources (including `datasets`, `apps.logs`, and `models.catalog`). Configure `defaultAppId`, pass `appId` in the request params object, or derive a client with `client.withOptions({ defaultAppId })` when targeting an App. `models.list()` queries public system models without requiring an API key.
* **Dynamic credential rotation**: `apiKey` accepts a sync or async callback `() => string | Promise<string>`, evaluated on each request.

```ts
import { FastGPT } from '@fastgpt/sdk';

const rotatingClient = new FastGPT({
  apiKey: async () => await tokenStore.getLatestApiKey()
});
```

### Client Configuration (`FastGptClientOptions`)

| Option                    | Type                                        | Default                                          | Description                                                                                             |
| ------------------------- | ------------------------------------------- | ------------------------------------------------ | ------------------------------------------------------------------------------------------------------- |
| `baseUrl`                 | `string`                                    | `FASTGPT_BASE_URL` or `https://cloud.fastgpt.cn` | FastGPT base URL (trailing slashes and `/api` normalized automatically)                                 |
| `apiKey`                  | `string \| () => string \| Promise<string>` | `FASTGPT_API_KEY`                                | Static API key or dynamic async provider                                                                |
| `defaultAppId`            | `string`                                    | `undefined`                                      | Default `appId` automatically injected into app-scoped endpoints for Personal API keys                  |
| `identity`                | `FastGptIdentity`                           | `undefined`                                      | Default caller identity (`{ customUid }` or `{ authProxy }`; mutually exclusive)                        |
| `timeoutMs`               | `number`                                    | `60_000`                                         | Per-request timeout in ms (full body for regular/binary calls, handshake-only for SSE; `0` disables)    |
| `maxRetries`              | `number`                                    | `2` for idempotent `GET`, `0` otherwise          | Exponential-backoff retries for `GET` (except `batchDownload`) on `408`/`429`/`502`/`503`/`504`/network |
| `defaultHeaders`          | `Record<string, string>`                    | `undefined`                                      | Default HTTP headers added to every request                                                             |
| `fetch`                   | `typeof globalThis.fetch`                   | `globalThis.fetch`                               | Custom `fetch` implementation for proxies or test stubs                                                 |
| `dangerouslyAllowBrowser` | `boolean`                                   | `false`                                          | Explicitly allow client instantiation inside browser environments                                       |
| `hooks`                   | `FastGptHooks`                              | `undefined`                                      | Request/response/error observability hooks with automatic secret redaction                              |
| `logger`                  | `FastGptLogger \| FastGptLogLevel`          | `undefined` (silent)                             | Built-in log level (`debug` / `info` / `warn` / `error` / `silent`) or custom logger                    |

## Identity Isolation, Derived Clients, and Per-Request Overrides

### Derived Clients (`withIdentity` / `withOptions`)

Keep a shared `FastGPT` singleton and use `withIdentity(...)` or `withOptions(...)` to derive lightweight scoped instances without mutating the parent client. `customUid` (end-user isolation) and `authProxy` (proxy-enabled Personal API keys only) are mutually exclusive; setting both throws `FastGptBadRequestError`.

> The SDK injects `customUid` or `authProxy` into the exact contract carrier (`query` or `body`) only on operations that declare an identity carrier (`chat.*` chat and chat-management endpoints, excluding `chat.histories.batchDelete`). Calls under `datasets.*` and `apps.logs.*` never inject identity parameters.

```ts
// End-user isolation
const userClient = client.withIdentity({ customUid: 'customer_42' });
const histories = await userClient.chat.histories.list({ pageSize: 20 });

// Team member proxy (Personal API key with proxy permission enabled)
const proxyClient = client.withIdentity({ authProxy: { username: 'alice' } });

// Derived client with overridden options (such as another defaultAppId or timeout)
const appBClient = client.withOptions({
  defaultAppId: '68ad85a7463006c963799a09',
  timeoutMs: 30_000
});
```

### Per-Request Overrides (`RequestOptions`)

Operations that take business parameters accept `options?: RequestOptions` as their **2nd argument** to override the API key, identity, timeout, retry count, headers, or `AbortSignal` per call. Parameterless operations (currently `client.models.list(options?)`) accept `RequestOptions` directly as their **1st argument** (passing options as a 2nd argument fails TypeScript typechecking and is silently ignored in JavaScript). Because the server validates session ownership per `chatId`, use distinct session IDs for different `customUid` values and the default identity:

```ts
// Override Personal API key and timeout on an endpoint without an identity carrier
const detail = await client.datasets.detail(
  { id: '68ad85a7463006c963799a05' },
  {
    apiKey: process.env.FASTGPT_PERSONAL_KEY,
    timeoutMs: 10_000,
    maxRetries: 0,
    signal: AbortSignal.timeout(10_000),
    headers: { 'x-trace-id': 'req_001' }
  }
);
console.log(detail.name);

// Parameterless operations (such as models.list) take RequestOptions as the 1st argument
const publicModels = await client.models.list({
  signal: AbortSignal.timeout(5_000),
  headers: { 'x-trace-id': 'req_002' }
});
console.log(publicModels.models.length);

// Override customUid per request on an identity-enabled chat endpoint (using a separate chatId);
// Personal API keys can also override appId in the request payload
const reply = await client.chat.completionsV2(
  {
    appId: '68ad85a7463006c963799a01', // Personal API key only; omit for App API keys
    chatId: 'chat_override_001',
    messages: [{ role: 'user', content: 'Hello' }]
  },
  {
    customUid: 'tenant-01:user-42'
  }
);
```

* `signal` governs both full body reads on standard requests and the **entire stream lifecycle** on SSE requests, immediately canceling the underlying stream when aborted.

## Serialization Semantics and Resource Catalog

### Omitted (`undefined`) vs. Explicit `null`

Request serialization treats `undefined` and explicit `null` distinctly:

* **JSON body and multipart `data` JSON**: Keys set to `undefined` are stripped during serialization, while explicit `null` (such as `{ parentId: null }`) and falsy values (`false`, `0`, `""`) are preserved.
* **Query parameters and flat multipart fields**: Both `undefined` and `null` are skipped. Nested query objects are JSON-encoded, and arrays are appended as repeated query parameters.

### Resource Catalog

| Resource Entry    | Capabilities                                                                                                               |
| ----------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `client.chat`     | `completionsV2`, `completionsV2Stream`, `init`, `stop`, `interactive` helper, plus `histories`, `records`, and `feedbacks` |
| `client.datasets` | Dataset management, `search`, `collections` (local file, link, text, batch archive downloads), and `data` Chunk operations |
| `client.apps`     | `apps.logs` cursor search (`search` / `searchAutoPaging`), chart analytics, totals, and user pagination                    |
| `client.models`   | Public system models `list` (no key required), team/system `catalog` (Personal API key required), and `summary`            |

## Chat Completions and SSE Streaming

`/v2/chat/completions` is split into non-streaming `completionsV2` and streaming `completionsV2Stream`. Streaming calls return `ChatStream` (implementing `AsyncIterable<ChatSseEvent>`), emitting strongly typed discriminated union events keyed by `event.type`:

```ts
const stream = await userClient.chat.completionsV2Stream({
  chatId: 'chat_stream_001',
  messages: [{ role: 'user', content: 'Summarize today’s workflow run.' }],
  detail: true
});

for await (const event of stream) {
  switch (event.type) {
    case 'answer':
      process.stdout.write(event.textDelta);
      break;
    case 'flowNodeStatus':
      console.log(`\n[Node] ${event.name} (${event.status})`);
      break;
    case 'interactive':
      console.log('\n[Interactive Pause]', event.interactive);
      break;
  }
}

// Safely callable after `for await` or standalone without iterating manually
const summary = await stream.finalResult();
console.log('\nTitle:', summary.chatTitle, 'Quotes:', summary.quotes.length);
// Or call `await stream.finalText()` when you only need the concatenated answer text
```

### Stream Lifecycle and Terminal Guarantees

* **Single consumption**: Each `ChatStream` instance can be iterated only once; calling `for await` a second time throws `FastGptError`.
* **Aggregated result**: `ChatStreamFinalResult` contains `text`, `reasoningText`, `chatTitle`, `durationSeconds`, `interactive`, `variables`, `nodeResponses`, and `quotes`.
* **Terminal state machine (`stream.state`)**: Tracks `pending`, `completed`, `closed`, `aborted`, and `failed`. A stream transitions to `completed` only when `[DONE]` / `event: done` is received; unexpected EOF throws `FastGptNetworkError`; breaking out of `for await` early cancels the underlying `ReadableStream`, transitions to `closed`, and still lets `finalResult()` return the partial snapshot collected so far; calling `stream.abort(reason?)` or triggering an external `AbortSignal` transitions immediately to `aborted`.

## Resuming Interactive Workflows

When a Workflow pauses at a human-in-the-loop Node (`userSelect` or `userInput`), `client.chat.interactive` inspects and resumes both non-streaming `completionsV2` responses and streaming `stream.finalResult()` outputs:

```ts
const interactiveChatId = 'chat_interactive_001';

const reply = await userClient.chat.completionsV2({
  chatId: interactiveChatId,
  messages: [{ role: 'user', content: 'Request temporary release approval' }],
  detail: true
});

const rawInteractive = userClient.chat.interactive.extract(reply);
if (rawInteractive !== null) {
  // Recursively unwraps nested sub-workflow or loop wrappers to the innermost prompt
  const prompt = userClient.chat.interactive.unwrap(rawInteractive);

  if (prompt.type === 'userSelect') {
    const selected = prompt.params.userSelectOptions[0]?.value;
    if (selected !== undefined) {
      const next = await userClient.chat.interactive.replyUserSelect({
        chatId: interactiveChatId,
        value: selected
      });
      console.log('Selection submitted:', next.choices[0]?.message.content);
    }
  } else if (prompt.type === 'userInput') {
    const nextStream = await userClient.chat.interactive.replyUserFormStream({
      chatId: interactiveChatId,
      values: { env: 'staging', reason: 'Pre-release regression check' }
    });
    console.log('Form reply:', await nextStream.finalText());
  }
}
```

## Dataset Uploads, Archive Downloads, and Auto-Pagination

### Local File Upload (Multipart)

`datasets.collections.createByLocalFile` automatically builds the `file` binary part and JSON `data` form part. The `file` parameter (`Uploadable`) accepts Web `File`, `Blob`, `ArrayBuffer`, `Uint8Array` (including Node.js `Buffer`), or `{ data, filename, contentType }`:

```ts
import { readFileSync } from 'node:fs';

// Requires Personal API key permission
const uploadRes = await client.datasets.collections.createByLocalFile({
  datasetId: '68ad85a7463006c963799a05',
  trainingType: 'chunk',
  file: {
    data: readFileSync('./docs/release-notes.pdf'),
    filename: 'release-notes.pdf',
    contentType: 'application/pdf'
  }
});

console.log('Collection ID:', uploadRes.collectionId, 'Inserted:', uploadRes.results.insertLen);
```

### Batch Archive Download

Downloading Collection archives uses a two-step ticket flow:

```ts
import { writeFileSync } from 'node:fs';

// 1. Request a short-lived one-time download ticket
const ticketRes = await client.datasets.collections.getDownloadTicket({
  datasetId: '68ad85a7463006c963799a05',
  collectionIds: ['68ad85a7463006c963799a10']
});

// 2. Download the archive binary (retries are disabled on batchDownload because tickets are single-use)
const archiveBuffer = await client.datasets.collections.batchDownload({
  ticket: ticketRes.ticket
});

writeFileSync('./collections-archive.zip', Buffer.from(archiveBuffer));
```

### Auto-Pagination (`*AutoPaging`)

The SDK provides async iterables across all paginated list operations, covering six offset-based endpoints and one cursor-based endpoint:

* **Offset pagination (`AutoPagingOptions`: `pageSize`, `maxItems`, `maxPages`, plus `RequestOptions`)**:
  * `client.chat.histories.listAutoPaging`
  * `client.chat.records.listAutoPaging`
  * `client.datasets.listAutoPaging`
  * `client.datasets.collections.listAutoPaging`
  * `client.datasets.data.listAutoPaging`
  * `client.apps.logs.listUsersAutoPaging`
* **Cursor pagination (`CursorAutoPagingOptions`: `maxItems`, `maxPages`, plus `RequestOptions`)**:
  * `client.apps.logs.searchAutoPaging`

```ts
// 1. Iterate item by item
for await (const item of client.datasets.listAutoPaging({}, { pageSize: 20, maxItems: 100 })) {
  console.log(item._id, item.name);
}

// 2. Iterate page by page
for await (const page of client.apps.logs.searchAutoPaging(
  {
    appId: '68ad85a7463006c963799a05',
    dateStart: '2026-01-01T00:00:00.000Z',
    dateEnd: '2026-01-31T23:59:59.999Z'
  },
  { maxPages: 5 }
).pages()) {
  console.log('Logs in page:', page.length);
}

// 3. Collect all items (use maxItems to bound memory)
const chunks = await client.datasets.data
  .listAutoPaging({ collectionId: '68ad85a7463006c963799a10' }, { maxItems: 200 })
  .toArray();
console.log('Total chunks:', chunks.length);
```

## Raw Responses, Observability, and Error Hierarchy

### Reading Raw HTTP Metadata (`.withRawResponse()`)

Standard API methods return an enhanced promise that resolves to the unwrapped data `T` when `await`ed directly, or `{ data, response }` (`WithRawResponseResult<T>` from `@fastgpt/sdk/options`) when `.withRawResponse()` is called:

```ts
import type { WithRawResponseResult } from '@fastgpt/sdk/options';
import type { DatasetsListRes } from '@fastgpt/sdk/types';

const rawResult: WithRawResponseResult<DatasetsListRes> = await client.datasets
  .list({ pageSize: 10 })
  .withRawResponse();

console.log(
  'HTTP Status:',
  rawResult.response.status,
  'Request ID:',
  rawResult.response.requestId,
  'Total:',
  rawResult.data.total
);
```

### Hooks, Logging, and Secret Redaction

Use `FastGptClientOptions.hooks` and `logger` to observe SDK requests. Hook errors are caught and logged without aborting the underlying HTTP call. The SDK automatically redacts `authorization`, `proxy-authorization`, `x-api-key`, `cookie`, `set-cookie`, query credential parameters, and the active `apiKey` (including custom OEM prefixes) before passing contexts or errors to hooks, loggers, or error messages.

```ts
import { FastGPT } from '@fastgpt/sdk';

const observedClient = new FastGPT({
  logger: 'info',
  hooks: {
    onRequest: (ctx) => {
      console.log('-> Request', ctx.operationId, ctx.method, ctx.url, 'attempt=', ctx.attempt);
    },
    onResponse: (ctx) => {
      console.log('<- Response', ctx.operationId, ctx.status, `${ctx.durationMs}ms`, ctx.requestId);
    },
    onError: (ctx) => {
      console.error('!! Error', ctx.operationId, ctx.error.name, ctx.error.message);
    }
  }
});
```

### Error Hierarchy (`@fastgpt/sdk/errors`)

All errors extend `FastGptError`, exposing `httpStatus`, `serverCode`, `statusText`, `requestId`, `url`, and `cause`:

| Error Class              | Trigger Condition (HTTP / Business Code)                               |
| ------------------------ | ---------------------------------------------------------------------- |
| `FastGptError`           | Base class for all SDK errors                                          |
| `FastGptAuthError`       | Missing key, `HTTP 401/403`, or `serverCode 401/403/514` / `unAuth`    |
| `FastGptBadRequestError` | Other `HTTP 4xx`, client-side validation failure, or parameter error   |
| `FastGptNotFoundError`   | `HTTP 404/410` or resource-not-found business error                    |
| `FastGptConflictError`   | `HTTP 409` or concurrent generation conflict (`chatIsGenerating`)      |
| `FastGptRateLimitError`  | `HTTP 429` or rate limit (`tooManyRequest`, `uploadFileIntervalLimit`) |
| `FastGptServerError`     | `HTTP 5xx` or internal server failure                                  |
| `FastGptTimeoutError`    | Request or body read timeout                                           |
| `FastGptNetworkError`    | Network failure or premature SSE EOF before `[DONE]`                   |

```ts
import { FastGptAuthError, FastGptError, FastGptRateLimitError } from '@fastgpt/sdk/errors';

try {
  await client.models.catalog();
} catch (err) {
  if (err instanceof FastGptAuthError) {
    console.error('Authentication failed (verify Personal API key):', err.requestId);
  } else if (err instanceof FastGptRateLimitError) {
    console.warn('Rate limited, retry later:', err.httpStatus, err.message);
  } else if (err instanceof FastGptError) {
    console.error('API error:', err.httpStatus, err.serverCode, err.requestId, err.message);
  }
}
```
