# Java SDK

> Use the official FastGPT Java 17 SDK for sync and async chat, SSE streaming, interactive Workflows, and Datasets.

Source: https://doc.fastgpt.io/openapi/sdk/java
Last Updated: 2026-12-01

> **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: Java 17 LTS or later for FastGPT System OpenAPI.**

`io.github.fastgpt-apps:fastgpt-sdk` (Java packages under `cn.fastgpt.sdk.*`) is the official Java SDK for FastGPT System OpenAPI. Built on JDK 17's `java.net.http.HttpClient` with a single compile dependency (`com.fasterxml.jackson.core:jackson-databind:2.18.3`), it provides matching synchronous (`FastGPTClient`) and `CompletableFuture`-based asynchronous (`FastGPTAsyncClient`) clients deterministically generated from the System OpenAPI IR across 47 endpoints.

> If you only need basic OpenAI-compatible chat calls, see the [API Quick Start](https://doc.fastgpt.io/openapi/intro). Use the official Java SDK when integrating typed Datasets, interactive Workflows, streaming chat, batch archive downloads, or App logs in Java services.

## Installation and Requirements

* Runtime: **Java 17 (LTS) or later**
* Runtime dependency: `com.fasterxml.jackson.core:jackson-databind:2.18.3` (no mandatory logging facade dependency)
* Maven Central coordinate: `io.github.fastgpt-apps:fastgpt-sdk:0.1.0-beta.1` (Java package `cn.fastgpt.sdk.*`)

Install the published beta artifact directly from Maven Central via Gradle (Kotlin DSL) or Maven:

```kotlin
// build.gradle.kts
dependencies {
  implementation("io.github.fastgpt-apps:fastgpt-sdk:0.1.0-beta.1")
}
```

```xml
<!-- pom.xml -->
<dependency>
  <groupId>io.github.fastgpt-apps</groupId>
  <artifactId>fastgpt-sdk</artifactId>
  <version>0.1.0-beta.1</version>
</dependency>
```

Optional environment variable fallbacks:

| Variable           | Purpose                                                                  | Default / Fallback                                                                            |
| ------------------ | ------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------- |
| `FASTGPT_BASE_URL` | FastGPT server origin (with or without `/api`, normalized automatically) | Read when `baseUrl` is omitted; falls back to `https://cloud.fastgpt.cn`                      |
| `FASTGPT_API_KEY`  | Personal API key or App API key                                          | Read when `apiKey`, `apiKeyProvider`, and `RequestOptions.apiKey()` are unset                 |
| `FASTGPT_APP_ID`   | Default App ID                                                           | Passed explicitly by your code via `System.getenv("FASTGPT_APP_ID")` into `defaultAppId(...)` |

## Quick Start and Authentication

### Synchronous client (`FastGPTClient`)

`FastGPTClient` implements `AutoCloseable`; wrap it in `try-with-resources` so its internal async executor and timeout scheduler close cleanly on exit:

```java
import cn.fastgpt.sdk.FastGPTClient;
import cn.fastgpt.sdk.generated.models.ChatCompletionsV2Params;
import cn.fastgpt.sdk.generated.models.ChatMessage;
import java.util.List;

try (FastGPTClient client = FastGPTClient.builder()
    .apiKey(System.getenv("FASTGPT_API_KEY"))
    .defaultAppId(System.getenv("FASTGPT_APP_ID")) // optional for App API keys
    .build()) {
  var completion = client.chat().completionsV2(
      ChatCompletionsV2Params.builder()
          .chatId("chat_001")
          .messages(List.of(ChatMessage.user("Summarize today's release notes.")))
          .build());
  System.out.println(completion.choices().get(0).message().content().text());
}
```

### Asynchronous client (`FastGPTAsyncClient`)

`FastGPTAsyncClient` also implements `AutoCloseable` and returns `CompletableFuture<T>` for all operations (or derive one sharing configuration from an existing client via `client.async()`):

```java
import cn.fastgpt.sdk.FastGPTAsyncClient;
import cn.fastgpt.sdk.generated.models.ChatCompletionsV2Params;
import cn.fastgpt.sdk.generated.models.ChatMessage;
import java.util.List;

try (FastGPTAsyncClient asyncClient = FastGPTAsyncClient.builder()
    .apiKey(System.getenv("FASTGPT_API_KEY"))
    .defaultAppId(System.getenv("FASTGPT_APP_ID"))
    .build()) {
  var completion = asyncClient.chat().completionsV2(
      ChatCompletionsV2Params.builder()
          .chatId("chat_001")
          .messages(List.of(ChatMessage.user("Summarize today's release notes.")))
          .build()).join();
  System.out.println(completion.choices().get(0).message().content().text());
}
```

### Personal API keys vs. App API keys

* **App API key (v4.18.0+)**: Bound to a single App on the server, so `defaultAppId` can be omitted on chat, chat-management, and App log (`apps().logs()`) calls; `datasets()` and `models().catalog()` require a Personal API key.
* **Personal API key**: Accesses any permitted System OpenAPI resource in the team (including `datasets()`, `apps().logs()`, and `models().catalog()`). Set `defaultAppId(...)` or pass `appId` in params / `RequestOptions` to target a specific App. `models().list()` queries public system models without requiring a key.
* **Credential rotation**: Supply `.apiKeyProvider(() -> tokenStore.getToken())` to resolve fresh tokens on every request.

### Common client options (`FastGPTClientOptions.Builder`)

| Builder Method             | Type               | Default                                          | Description                                                                                           |
| -------------------------- | ------------------ | ------------------------------------------------ | ----------------------------------------------------------------------------------------------------- |
| `baseUrl(url)`             | `String`           | `FASTGPT_BASE_URL` or `https://cloud.fastgpt.cn` | FastGPT instance origin, normalized to end with `/api`                                                |
| `apiKey(key)`              | `String`           | `FASTGPT_API_KEY`                                | Static API key                                                                                        |
| `apiKeyProvider(supplier)` | `Supplier<String>` | `null`                                           | Dynamic per-request credential supplier                                                               |
| `defaultAppId(appId)`      | `String`           | `null`                                           | Default `appId` injected on App-scoped calls                                                          |
| `identity(identity)`       | `Identity`         | `null`                                           | Default caller identity (`Identity.customUid` or `Identity.authProxy`)                                |
| `timeout(duration)`        | `Duration`         | `Duration.ofSeconds(60)`                         | Full-body timeout for JSON calls; handshake-only for SSE and binary downloads (`ZERO` disables limit) |
| `maxRetries(n)`            | `int`              | `2`                                              | Retry limit for idempotent `GET` requests on `408`/`429`/`502`/`503`/`504` or transport errors        |
| `defaultHeader(k, v)`      | `String, String`   | None                                             | Default HTTP header sent with every request                                                           |
| `httpClient(client)`       | `HttpClient`       | Managed `HttpClient`                             | Custom shared `java.net.http.HttpClient`                                                              |
| `hooks(hooks)`             | `FastGPTHooks`     | `FastGPTHooks.empty()`                           | Request, response, and error observability hooks                                                      |

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

### End-user identity isolation and `withOptions`

Keep a single long-lived `FastGPTClient` in your service and attach per-user identity via `RequestOptions.builder().identity(...)`. When deriving an instance with `withOptions(...)` to adjust defaults, always wrap the derived client in `try-with-resources` so its own internal executor and timeout scheduler close properly—even if you pass a shared custom `HttpClient`:

```java
import cn.fastgpt.sdk.AuthProxy;
import cn.fastgpt.sdk.Identity;
import cn.fastgpt.sdk.RequestOptions;
import cn.fastgpt.sdk.generated.models.ChatHistoriesListParams;

// 1. Track external end users per request (App API key or Personal API key)
var histories = client.chat().histories().list(
    ChatHistoriesListParams.builder().pageSize(20L).build(),
    RequestOptions.builder()
        .identity(Identity.customUid("tenant-01:user-42"))
        .build());

// 2. Act as a team member using a derived client with a Personal API key and AuthProxy enabled
try (var memberClient = client.withOptions(opts ->
    opts.identity(Identity.authProxy(AuthProxy.byUsername("alice"))))) {
  var memberHistories = memberClient.chat().histories().list(
      ChatHistoriesListParams.builder().pageSize(20L).build());
}
```

`Identity.customUid(...)` and `Identity.authProxy(...)` are strictly mutually exclusive; see [Identity Proxy](https://doc.fastgpt.io/openapi/identity-proxy) for server-side rules.

### Per-call overrides (`RequestOptions`)

Every sync and async method accepts an optional `RequestOptions` to override `apiKey`, `timeout`, `maxRetries`, `headers`, `appId`, `identity`, or register `onRawResponse(...)` to inspect response status and headers:

```java
import cn.fastgpt.sdk.RawResponse;
import cn.fastgpt.sdk.RequestOptions;
import cn.fastgpt.sdk.generated.models.ChatCompletionsV2Params;
import cn.fastgpt.sdk.generated.models.ChatMessage;
import cn.fastgpt.sdk.generated.models.DatasetsDetailParams;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

AtomicReference<RawResponse> rawRef = new AtomicReference<>();

// Do not pass identity on endpoints without caller identity support (such as datasets().detail())
var detail = client.datasets().detail(
    DatasetsDetailParams.builder().id("68ad85a7463006c963799a05").build(),
    RequestOptions.builder()
        .apiKey(System.getenv("FASTGPT_PERSONAL_KEY"))
        .timeout(Duration.ofSeconds(10))
        .maxRetries(0)
        .onRawResponse(rawRef::set)
        .build());
System.out.println(detail.name() + " status=" + rawRef.get().statusCode());

// Override identity on supported chat endpoints; Personal API keys can also switch appId per call
var reply = client.chat().completionsV2(
    ChatCompletionsV2Params.builder()
        .chatId("chat_001")
        .messages(List.of(ChatMessage.user("Hello")))
        .build(),
    RequestOptions.builder()
        .appId("68ad85a7463006c963799a01") // Personal API key only; omit for App API keys
        .identity(Identity.customUid("tenant-01:user-42"))
        .build());
```

## Tri-State Optional Fields (`JsonField<T>`) and Resource Tree

### Tri-state `JsonField<T>`

Request parameter builders use `JsonField<T>` to distinguish omitted keys (`JsonField.ofMissing()`), explicit JSON `null` (`*Null()` / `JsonField.ofNull()`), and explicit zero values (`false`, `0`, `""`). Workflow `variables` and JSON `Map<String, Object>` values preserve explicit `null` entries in both outgoing requests and incoming SSE `UpdateVariables` events.

### Resource tree

| Resource Accessor   | Capabilities                                                                                                                         |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| `client.chat()`     | `completionsV2`, `completionsV2Stream`, `stop`, Workflow `interactive()` helpers, plus `histories()`, `records()`, and `feedbacks()` |
| `client.datasets()` | Dataset lifecycle, hybrid `search`, `collections()` (local file, link, text, batch download), and `data()` Chunk management          |
| `client.apps()`     | `apps().logs()` cursor search (`search` / `searchAutoPaging`), chart analytics, and user lists                                       |
| `client.models()`   | Public system model `list()`, model `catalog()` (Personal API key), and `summary()`                                                  |

## Chat Completions and SSE Streaming

`/v2/chat/completions` splits into non-streaming `completionsV2` and streaming `completionsV2Stream`. `ChatStream` implements `Iterable<ChatSseEvent>` and `AutoCloseable`, allowing type-safe pattern matching inside `try-with-resources`:

```java
import cn.fastgpt.sdk.generated.models.ChatCompletionsV2Params;
import cn.fastgpt.sdk.generated.models.ChatMessage;
import cn.fastgpt.sdk.sse.ChatSseEvent;
import cn.fastgpt.sdk.sse.ChatStream;
import cn.fastgpt.sdk.sse.ChatStreamFinalResult;
import java.util.List;

var params = ChatCompletionsV2Params.builder()
    .chatId("chat_001")
    .messages(List.of(ChatMessage.user("Summarize today's Workflow logs.")))
    .detail(true)
    .build();

try (ChatStream stream = client.chat().completionsV2Stream(params)) {
  for (ChatSseEvent event : stream) {
    if (event instanceof ChatSseEvent.Answer ans) {
      System.out.print(ans.textDelta());
    } else if (event instanceof ChatSseEvent.FlowNodeStatus node) {
      System.out.printf("%n[Node] %s (%s)%n", node.name(), node.status());
    }
  }
  ChatStreamFinalResult summary = stream.finalResult();
  System.out.printf("%nTitle=%s Quotes=%d%n", summary.chatTitle(), summary.quotes().size());
}
```

* Canceling an async `CompletableFuture<ChatStream>` via `.cancel(true)` aborts the underlying HTTP request immediately and closes any unclaimed stream before delivering it to callers.
* Streams ending before `[DONE]` raise `FastGPTNetworkException`, while HTTP 200 JSON error envelopes (such as `chatIsGenerating`) are mapped to `FastGPTConflictException` before handoff.

## Resuming Interactive Workflows

`client.chat().interactive()` detects, unwraps, and resumes interactive Workflow pauses—see [Interactive Nodes & Variables](https://doc.fastgpt.io/openapi/interactive-and-variables) for full protocol details:

```java
import cn.fastgpt.sdk.interactive.InteractivePayload;
import cn.fastgpt.sdk.interactive.ReplyUserFormParams;
import cn.fastgpt.sdk.interactive.ReplyUserSelectParams;
import java.util.Map;

if (client.chat().interactive().isInteractivePending(summary)) {
  InteractivePayload outer = client.chat().interactive().extractInteractive(summary);
  InteractivePayload prompt = client.chat().interactive().unwrapInteractive(outer);

  if (prompt.isUserSelect()) {
    var resumed = client.chat().interactive().replyUserSelect(
        ReplyUserSelectParams.builder()
            .chatId("chat_001")
            .value(prompt.userSelect().userSelectOptions().get(0).value())
            .build());
    System.out.println(resumed.choices().get(0).message().content().text());
  } else if (prompt.isUserInput()) {
    var resumed = client.chat().interactive().replyUserForm(
        ReplyUserFormParams.builder()
            .chatId("chat_001")
            .values(Map.of("project", "FastGPT", "priority", "P0"))
            .build());
    System.out.println(resumed.choices().get(0).message().content().text());
  }
}
```

Use `asyncClient.chat().interactive()` for `CompletableFuture`-based resumption on `FastGPTAsyncClient`.

## Datasets, Streaming Downloads, and Auto-Pagination

### Streaming multipart uploads

`FileUpload.ofPath(...)` and `FileUpload.ofStream(...)` stream multipart bodies without buffering large files into the JVM heap, and non-replayable `InputStream` uploads force `0` retries automatically:

```java
import cn.fastgpt.sdk.FileUpload;
import cn.fastgpt.sdk.generated.models.DatasetsCollectionsCreateByLocalFileParams;
import java.nio.file.Path;

var created = client.datasets().collections().createByLocalFile(
    DatasetsCollectionsCreateByLocalFileParams.builder()
        .datasetId("68ad85a7463006c963799a05")
        .trainingType("chunk")
        .file(FileUpload.ofPath(Path.of("handbook.md")))
        .parentIdNull() // explicit JSON null
        .build());
```

### Streaming archive downloads (`BinaryStream`)

`batchDownload` returns an `AutoCloseable` `BinaryStream`. With the default managed transport (when no custom `HttpClient` is configured), it runs over a single-shot HTTP/1.1 connection (`retryable = false`, sharing one absolute deadline across connect, TLS, and response headers, then clearing the body idle timeout) so single-use download tickets are never replayed. If you supply a custom `HttpClient`, SDK-level retries remain disabled, while underlying connection replay behavior depends on your `HttpClient`:

```java
import cn.fastgpt.sdk.BinaryStream;
import cn.fastgpt.sdk.generated.models.DatasetsCollectionsBatchDownloadParams;
import cn.fastgpt.sdk.generated.models.DatasetsCollectionsGetDownloadTicketParams;
import java.nio.file.Path;
import java.util.List;

var ticketRes = client.datasets().collections().getDownloadTicket(
    DatasetsCollectionsGetDownloadTicketParams.builder()
        .datasetId("68ad85a7463006c963799a05")
        .collectionIds(List.of(created.collectionId()))
        .build());

try (BinaryStream archive = client.datasets().collections().batchDownload(
    DatasetsCollectionsBatchDownloadParams.builder()
        .ticket(ticketRes.ticket())
        .build())) {
  archive.writeTo(Path.of("collections.zip"));
}
```

### Automatic pagination (`AutoPager<T>`)

Offset, page-number, and cursor endpoints expose `*AutoPaging` methods configurable via `PagerOptions` (`pageSize`, `maxPages`, `maxItems`, `requestOptions`) and consumable via `for-each`, `.pages()`, `.stream()`, or `.collect()`:

```java
import cn.fastgpt.sdk.generated.models.AppsLogsSearchParams;
import cn.fastgpt.sdk.generated.models.DatasetsDataListParams;
import cn.fastgpt.sdk.pagination.PagerOptions;

// 1. Offset auto-pagination across Chunks
for (var chunk : client.datasets().data().listAutoPaging(
    DatasetsDataListParams.builder().collectionId(created.collectionId()).build(),
    PagerOptions.builder().pageSize(50).maxItems(500).build())) {
  System.out.println(chunk.id_() + ": " + chunk.q());
}

// 2. Cursor auto-pagination for App chat logs (POST /core/app/logs/search)
var logs = client.apps().logs().searchAutoPaging(
    AppsLogsSearchParams.builder()
        .dateStart("2026-01-01T00:00:00.000Z")
        .dateEnd("2026-01-31T23:59:59.999Z")
        .build(),
    PagerOptions.builder().maxPages(5).build()).collect();
logs.forEach(item -> System.out.println(item.chatId() + " " + item.title()));
```

## Observability and Exception Hierarchy

### `FastGPTHooks` and automatic secret redaction

Attach `onRequest`, `onResponse`, and `onError` callbacks through `FastGPTHooks`. The SDK redacts credentials across exception messages, headers, URL query parameters (`ticket`, `token`, `apiKey`), and cause chains, and strips `data` payloads from `onError` hooks while keeping `data()` and `chatGeneratingConflict()` available to callers:

```java
import cn.fastgpt.sdk.FastGPTClient;
import cn.fastgpt.sdk.FastGPTHooks;

FastGPTHooks hooks = FastGPTHooks.builder()
    .onRequest(req -> System.out.printf("-> %s %s (attempt %d)%n", req.method(), req.url(), req.attempt()))
    .onResponse(res -> System.out.printf("<- %d reqId=%s (%dms)%n", res.statusCode(), res.requestId(), res.duration().toMillis()))
    .onError(err -> System.err.printf("!! %s: %s%n", err.operationId(), err.error().getMessage()))
    .build();

try (FastGPTClient observed = FastGPTClient.builder()
    .apiKey(System.getenv("FASTGPT_API_KEY"))
    .hooks(hooks)
    .build()) {
  System.out.println(observed.models().list().models().size());
}
```

### Exception hierarchy

All SDK failures extend `cn.fastgpt.sdk.errors.FastGPTException` (`RuntimeException`):

| Exception Class              | Trigger Condition                                                           |
| ---------------------------- | --------------------------------------------------------------------------- |
| `FastGPTAuthException`       | HTTP `401` / `403`, server code `514`, `unAuth*` status, or missing API key |
| `FastGPTBadRequestException` | HTTP `400` / `422` validation errors or local precondition checks           |
| `FastGPTNotFoundException`   | HTTP `404` / `410` or `*UnExist` / `*NotFound` errors                       |
| `FastGPTConflictException`   | HTTP `409` or `chatIsGenerating` (inspect `chatGeneratingConflict()`)       |
| `FastGPTRateLimitException`  | HTTP `429` or `tooManyRequest` / `uploadFileIntervalLimit`                  |
| `FastGPTServerException`     | `5xx` server errors                                                         |
| `FastGPTTimeoutException`    | Connect/handshake deadline or full non-streaming body read timeout          |
| `FastGPTNetworkException`    | Socket errors or truncated SSE stream before `[DONE]`                       |
| `FastGPTAbortedException`    | Caller-canceled `CompletableFuture` or thread interruption                  |
