file: ./content/developers/coze-migration.en.mdx url: https://doc.fastgpt.io/developers/coze-migration title: Migrate Coze Assets to FastGPT last_updated: 2026-11-28T07:02:13+08:00 meta: { "title": "Migrate Coze Assets to FastGPT", "description": "Migrate Coze Datasets, toolkits, Skills, workflows, and Agents to FastGPT China using the official migration Skill and FastGPT CLI." } FastGPT provides a standardized Coze migration Skill that pairs with the official `@fastgpt/cli` (`fastgpt`) tool. An AI coding assistant can use it to migrate Coze Datasets, MCP and HTTP toolkits, custom Skills, workflows, Agents, and avatars end to end, then verify and repair every workflow with `workflow-build` and live smoke tests. *** ## Prerequisites Confirm all three requirements before starting a migration: > 1. **FastGPT China only**: This migration workflow currently targets FastGPT China (`https://cloud.fastgpt.cn`) only. FastGPT International and unadapted older deployments are not supported yet. > 2. **FastGPT credentials and available credits**: Provide your FastGPT China username and password for CLI login. Signing in to `cloud.fastgpt.cn` in your browser as well is recommended for side-by-side inspection. Make sure your team has available credits, because Dataset indexing, workflow Test Runs, and Agent smoke tests consume credits. > 3. **Signed-in Coze browser session**: Sign in to Coze (`https://www.coze.cn`) in your browser beforehand so the AI Agent can export Bots, workflows, plugins, Dataset source files, and avatars from your workspace. *** ## Run the migration with an AI Agent If you use an AI coding assistant with terminal and browser capabilities (such as **Codex** or **Claude Code**), send it the prompt below. The assistant will fetch the official migration Skill and mapping reference, then migrate your assets in dependency order: > Send this prompt in your AI coding assistant chat: ```text Follow https://doc.fastgpt.io/skills/coze-to-fastgpt/SKILL.md to migrate my Coze assets to FastGPT China (cloud.fastgpt.cn). ``` To download the Skill and reference guide locally for offline inspection or custom Agent setups, run: ```bash mkdir -p ./coze-to-fastgpt/references curl -fsSL https://doc.fastgpt.io/skills/coze-to-fastgpt/SKILL.md -o ./coze-to-fastgpt/SKILL.md curl -fsSL https://doc.fastgpt.io/skills/coze-to-fastgpt/references/mapping-and-pitfalls.md -o ./coze-to-fastgpt/references/mapping-and-pitfalls.md ``` For CLI installation, authentication, and command reference, see [Manage FastGPT with the CLI](https://doc.fastgpt.io/guide/getting-started/cli). *** ## Supported assets and mapping | Coze Asset | FastGPT Target Type | Folder Tree | CLI Command Group | Notes | | ----------------------------- | ---------------------------------------------------------------------------- | ------------------------------ | ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Knowledge Base & files/chunks | Dataset (`dataset`) & Collections | Dataset tree | `fastgpt dataset` | Preserves avatars, uploads source files or text chunks, and verifies Collection counts | | MCP / HTTP plugins | MCP / HTTP Toolkit | Tool tree | `fastgpt tool mcp` / `tool http` | Parses tool metadata, creates the Toolkit, updates intro text, and runs a live tool call | | Custom Skill | Agent Skill (`skill`) | Skill tree | `fastgpt skill import` | Imports a `.zip` package containing a root `SKILL.md` | | Workflow | Workflow (`advanced`) | Agent tree | `fastgpt agent` + `workflow-build` | Converts Nodes and models, then enforces `workflow-build` validation, repair, and publishing | | Bot | Standard Chat App (`simple`, default) or Agent V2 (`chatAgent`, when needed) | Agent tree | `fastgpt agent` | Defaults to `simple` (supports global variables, Datasets, Toolkits, and workflows); uses `chatAgent` only when Skills or VM sandbox capabilities are required | | Avatars & folders | Uploaded avatars & 4 folder trees | Dataset / Tool / Skill / Agent | `fastgpt file upload-avatar` | Organizes resources into FastGPT's four independent folder trees | > **Compatibility boundary**: Coze store plugins that depend on platform-managed OAuth or third-party credentials (such as Lark Docs or LinkReader) cannot have their credentials migrated automatically. The migration Skill explicitly flags these plugins in the workflow description and final handoff report so you can rebind equivalent tools or credentials manually in FastGPT. *** ## Migration workflow overview The migration Skill runs in 8 ordered stages so every downstream binding references verified FastGPT resource IDs: 1. **CLI readiness and login**: Verify the `fastgpt` version, sign in to `https://cloud.fastgpt.cn` over standard input, fetch the team's available models, and confirm credit availability. 2. **Coze inventory and export**: Reuse the signed-in Coze browser session to export Bots, workflow `schema_json`, plugin configurations, Dataset source files, and avatars. 3. **Avatar upload and 4-tree folder setup**: Upload all Coze avatars and create target folders across the Dataset, Tool, Skill, and Agent trees. 4. **Datasets and Collections**: Create each Dataset, import source files or text chunks as Collections, and verify Collection totals. 5. **MCP and HTTP Toolkits**: Probe tool definitions, create each Toolkit, verify child tools, and execute a live tool call. 6. **Skill import**: Import packaged `.zip` Skills into the Skill folder tree and verify the active version. 7. **Workflow migration and `workflow-build` repair**: Create each workflow, then run `agent pull` -> `workflow-build inspect/validate` -> fix stray `catch` edges or schema issues -> `agent save` / `agent publish` -> `workflow diff` -> `agent test --detail`. 8. **Agent assembly and end-to-end verification**: Default to `simple` (preserving global variables, Datasets, and tool or workflow bindings), and use `chatAgent` (Agent V2) only when Skills or VM sandbox capabilities are needed. Publish and verify with `agent test`, `agent run`, and conversation logs. ### Built-in safeguards * **Per-resource live progress updates**: The Skill requires reporting each folder, Dataset, Toolkit, Skill, workflow, and Agent immediately before it starts and after it finishes, including its name, status, and FastGPT ID. * **Idempotent reruns**: Each step checks existing resources by name and parent folder before creating new ones, preventing duplicates after retries. * **Workflow self-repair**: Every migrated workflow passes `workflow-build` structural checks and live Test Runs to confirm the local graph matches the published version. *** ## FAQ and troubleshooting ### Should a migrated Bot use `simple` or `chatAgent` (Agent V2)? Default to `simple` ([Chat Agent / Standard App](https://doc.fastgpt.io/guide/build/chat-agent)): `simple` supports **global variables**, Dataset retrieval, and MCP, HTTP, or workflow tool calls, covering most Coze Bots. Use `chatAgent` ([Chat Agent V2](https://doc.fastgpt.io/guide/build/agentv2/settings)) only when the Bot requires **Agent Skills**, a **VM execution sandbox**, or Agent V2 autonomous planning. Note that **Agent V2 does not support global variables yet**; if a Coze Bot relies on both global variables and Skills, prioritize one or handle variables in a workflow. ### Why can folder avatars appear blank? The FastGPT backend does not automatically populate a default avatar when creating Dataset or Agent folders. `fastgpt tool folder create` and `fastgpt agent folder create` inject `/imgs/files/folder.svg` automatically, while `fastgpt dataset create --type folder` requires passing `--avatar "/imgs/files/folder.svg"` explicitly. Skill folders can omit the avatar and rely on the server default icon. ### How should I handle `WORKFLOW_BINDING_UNVERIFIED` from `workflow-build validate`? `chatNode` model bindings use remote validation, so offline local checks cannot confirm team model permissions and emit a non-blocking warning while still returning `valid: true`. Run `fastgpt agent test --detail` once to verify the remote model call finishes with `finishReason: stop`. ### Why does the migration require available team credits? Importing Dataset Collections triggers embedding and vector indexing, and post-migration verification runs real `agent test` and `agent run` calls against LLMs. Both steps consume team credits or model quota and will fail if the account balance is exhausted. file: ./content/developers/index.en.mdx url: https://doc.fastgpt.io/developers title: Developers last_updated: 2026-12-02T10:14:48+08:00 meta: { "title": "Developers", "description": "Choose API integration or extension development to connect FastGPT and build plugins, model presets, and Skills." } ## Choose a development task * [API integration](https://doc.fastgpt.io/openapi/intro): Make your first request, then integrate Apps, conversations, and Datasets. - [Plugin system](#plugin-system): Build system tool plugins, contribute model presets, and package them for FastGPT. ## Developer Integration Architecture FastGPT provides an open capability matrix for enterprise systems and developers: ![Integrate through a trusted backend](https://cdn.jsdelivr.net/gh/labring/fastgpt-img@main/diagrams/integration-overview.en.light.svg) Keep API keys on a trusted server. Identity proxy is optional and requires endpoint support and a trusted mapping to a member in the same team. MCP clients use the separately configured MCP service and its authentication. ## Credential Types and Authentication Each endpoint declares the credentials it accepts. Check the authentication method for each endpoint in the [System OpenAPI Reference Overview](https://doc.fastgpt.io/openapi/api-reference) or your deployment's `/apidoc/systemopenapi` or `/apidoc/devapi` before integrating. | Credential | Transport Location | Permission Scope | Recommended Scenario | | -------------------------- | ---------------------------------------- | ---------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- | | **Personal API key** | `Authorization: Bearer ` | Accesses permitted team resources as the issuing member on endpoints that accept personal API keys | Backend integrations, automated jobs, model calls | | **App API key** (v4.18.0+) | `Authorization: Bearer ` | Bound to one app for its chat and chat management endpoints; authorization comes from the key itself | Integrating a specific app and identifying business users with `customUid` | | **User Session Token** | Cookie `fastgpt_token` or `token` header | Current member permissions, subject to endpoint authorization and session checks | Web UI communication, same-origin management APIs | | **Root Key** | Header `rootkey: ` | Administrative operations on endpoints that explicitly enable root authentication | Cross-team maintenance, model status probing, migrations | ## Core Integration Workflows 1. [API Quick Start](https://doc.fastgpt.io/openapi/intro): Choose a personal API key or an app API key, execute the first end-to-end request, and connect via the official OpenAI SDK. 2. [Official TypeScript SDK](https://doc.fastgpt.io/openapi/sdk/typescript), [Official Python SDK](https://doc.fastgpt.io/openapi/sdk/python), [Official Go SDK](https://doc.fastgpt.io/openapi/sdk/go), & [Official Java SDK](https://doc.fastgpt.io/openapi/sdk/java): Use the strongly typed official SDKs for sync/async chat, SSE streaming, interactive Workflow resumption, Dataset management, and auto-pagination. 3. [Identity Proxy](https://doc.fastgpt.io/openapi/identity-proxy): Execute on behalf of end users using `authProxy` to enforce member-level permissions and audit logging. 4. [Knowledge Base Integration](https://doc.fastgpt.io/openapi/dataset): Create collections via API, push content to training queues asynchronously, and run search tests. ## Plugin System * [Plugin development](https://doc.fastgpt.io/plugin/intro): Explore plugin types and development paths, start with [your first tool](https://doc.fastgpt.io/plugin/quick-start), and continue to [debugging and publishing](https://doc.fastgpt.io/plugin/debugging-and-publishing). * [System Tool Development](https://doc.fastgpt.io/plugin/system-tool-development): Build single tools (`defineTool`) and tool suites (`defineToolSet`) with `@fastgpt-plugin/cli`. * [Content moderation guide](https://doc.fastgpt.io/plugin/moderation): Configure global moderation policies, runtime checkpoints, and build custom `defineModeration` Plugins. * [Model Presets](https://doc.fastgpt.io/plugin/model-presets): Register new model providers and map AIProxy channels. * [Package and SDK Reference](https://doc.fastgpt.io/plugin/package-reference): Inspect plugin directory conventions, package archive formats, and SDK type definitions. * [Skill Development Tutorial](https://doc.fastgpt.io/guide/build/skill/development): Author custom Skills in the sandbox and bind them to an Agent. ## Machine-Readable OpenAPI Contracts Read the static reference and OpenAPI 3.1 contract on the official documentation site, or open the interactive Scalar console on any FastGPT deployment: * **Official System OpenAPI Reference & Spec**: Browse the [System OpenAPI Reference Overview](https://doc.fastgpt.io/openapi/api-reference), or fetch the CORS-enabled [OpenAPI 3.1 JSON Spec](https://doc.fastgpt.io/openapi.json) (`/openapi.json`) and [OpenAPI LLM Corpus](https://doc.fastgpt.io/llms-openapi.txt) (`/llms-openapi.txt`). * **Instance System OpenAPI (Interactive Try-It-Out)**: Access `/apidoc/systemopenapi` (UI) or `/api/apidoc/systemopenapi.json` (JSON) on your FastGPT deployment. * **Instance Dev API (Full Internal Developer Operations)**: Access `/apidoc/devapi` (UI) or `/api/apidoc/devapi.json` (JSON) on your FastGPT deployment. When maintaining older integrations, refer to [Historical API Parameters and Migration](https://doc.fastgpt.io/openapi/legacy). file: ./content/openapi/api-reference.en.mdx url: https://doc.fastgpt.io/openapi/api-reference title: System OpenAPI Reference Overview last_updated: 2026-11-20T00:55:57+08:00 meta: { "title": "System OpenAPI Reference Overview", "seoTitle": "System OpenAPI Reference Overview & Index | FastGPT OpenAPI", "description": "Browse FastGPT System OpenAPI across 4 groups and 11 modules, including auth rules, base URLs, OpenAPI 3.1 JSON specs, and Scalar consoles." } This documentation portal provides static, structured reference pages for FastGPT **System OpenAPI**—covering 51 operations organized into 4 groups and 11 modules explicitly exposed for API key authentication. It is designed for browser navigation, single-page Markdown retrieval, and AI coding agents. To run same-origin **Try it out** requests in a browser or inspect internal **Dev API** operations, open the `/apidoc/*` interactive consoles on FastGPT Cloud or your self-hosted deployment. ## Base URLs and Endpoints | Environment | API Request Base URL | Instance Interactive Console (Scalar) | | -------------------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------- | | International Cloud | `https://cloud.fastgpt.io/api` | [System OpenAPI](https://cloud.fastgpt.io/apidoc/systemopenapi) · [Dev API](https://cloud.fastgpt.io/apidoc/devapi) | | Mainland China Cloud | `https://cloud.fastgpt.cn/api` | [System OpenAPI](https://cloud.fastgpt.cn/apidoc/systemopenapi) · [Dev API](https://cloud.fastgpt.cn/apidoc/devapi) | | Self-Hosted Instance | `/api` | `/apidoc/systemopenapi` · `/apidoc/devapi` | ## Authentication and Identity Rules Pass your API key in the standard `Authorization` HTTP header: ```http Authorization: Bearer ``` * **Personal API Key**: Created under **Account → API Keys**, executing with the issuing team member's resource permissions. Pass `appId` explicitly when calling application chat endpoints (or use the OpenAI SDK compatibility suffix `Bearer -`). Supports `authProxy` (FastGPT >= v4.15.0) to delegate identity to another active team member; see [API and MCP identity proxy](https://doc.fastgpt.io/openapi/identity-proxy). * **App API Key** (FastGPT >= v4.18.0): Created under **Studio → Target App → Publish Channels → API Access → App keys**. Bound to a single application for chat, history, and log endpoints without passing `appId`, and supports `customUid` to identify external end users. * **First Integration**: Start with [API getting started: make your first request](https://doc.fastgpt.io/openapi/intro) for end-to-end cURL and OpenAI SDK examples. ## 4 Groups and 11 Modules ### 1. Foundation * **Models (`model`)**: [Get Model Display Summaries](https://doc.fastgpt.io/openapi/reference/model/summary) · [List Public System Models](https://doc.fastgpt.io/openapi/reference/model/list) · [Get Available Model Catalog](https://doc.fastgpt.io/openapi/reference/model/catalog) ### 2. Applications * **App Logs (`app-log`)**: [List App Chat Logs](https://doc.fastgpt.io/openapi/reference/app-log/list) · [Get App Total Statistics](https://doc.fastgpt.io/openapi/reference/app-log/get-total-data) · [Get App Chart Analytics](https://doc.fastgpt.io/openapi/reference/app-log/get-chart-data) · [List App Log Users](https://doc.fastgpt.io/openapi/reference/app-log/get-users) ### 3. Chat * **Chat Completions & Control (`chat-controller`)**: [Create Chat Completion (v2)](https://doc.fastgpt.io/openapi/reference/chat-controller/v2-chat-completions) · [Stop Chat Completion](https://doc.fastgpt.io/openapi/reference/chat-controller/v2-chat-stop) * **Chat History (`chat-history`)**: [List Chat Histories](https://doc.fastgpt.io/openapi/reference/chat-history/get-histories) · [Batch Get Chat History Status](https://doc.fastgpt.io/openapi/reference/chat-history/get-history-status) · [Mark Chat History Read](https://doc.fastgpt.io/openapi/reference/chat-history/mark-read) · [Update Chat History](https://doc.fastgpt.io/openapi/reference/chat-history/update-history) · [Delete Chat History](https://doc.fastgpt.io/openapi/reference/chat-history/del-history) · [Clear Chat Histories](https://doc.fastgpt.io/openapi/reference/chat-history/clear-histories) · [Batch Delete Chat Histories](https://doc.fastgpt.io/openapi/reference/chat-history/batch-delete) · [Initialize Chat Session](https://doc.fastgpt.io/openapi/reference/chat-history/init) * **Chat Records (`chat-record`)**: [List Chat Records (Paginated)](https://doc.fastgpt.io/openapi/reference/chat-record/get-pagination-records) · [List Chat Records by Cursor](https://doc.fastgpt.io/openapi/reference/chat-record/get-records-v2) · [Get Chat Record Response Details](https://doc.fastgpt.io/openapi/reference/chat-record/get-res-data) · [Get Chat Record Citations](https://doc.fastgpt.io/openapi/reference/chat-record/get-quote) · [Get Collection Citation Chunks](https://doc.fastgpt.io/openapi/reference/chat-record/get-collection-quote) · [Delete Chat Records](https://doc.fastgpt.io/openapi/reference/chat-record/delete) * **Chat Feedback (`chat-feedback`)**: [Update User Chat Feedback](https://doc.fastgpt.io/openapi/reference/chat-feedback/update-user-feedback) ### 4. Knowledge Base * **Datasets (`dataset`)**: [Create Dataset](https://doc.fastgpt.io/openapi/reference/dataset/create) · [List Datasets (V2)](https://doc.fastgpt.io/openapi/reference/dataset/list-v2) · [Get Dataset Details](https://doc.fastgpt.io/openapi/reference/dataset/detail) · [Update Dataset](https://doc.fastgpt.io/openapi/reference/dataset/update) · [Delete Dataset](https://doc.fastgpt.io/openapi/reference/dataset/delete) · [Batch Move Datasets](https://doc.fastgpt.io/openapi/reference/dataset/batch-move) · [Batch Delete Datasets](https://doc.fastgpt.io/openapi/reference/dataset/batch-delete) * **Collections (`dataset-collection`)**: [List Dataset Collections (V2)](https://doc.fastgpt.io/openapi/reference/dataset-collection/list-v2) · [Get Collection Details](https://doc.fastgpt.io/openapi/reference/dataset-collection/detail) · [Update Dataset Collection](https://doc.fastgpt.io/openapi/reference/dataset-collection/update) · [Delete Dataset Collections](https://doc.fastgpt.io/openapi/reference/dataset-collection/delete) · [Create Collection Download Ticket](https://doc.fastgpt.io/openapi/reference/dataset-collection/get-download-ticket) · [Download Collections Archive](https://doc.fastgpt.io/openapi/reference/dataset-collection/batch-download) * **Create Collections (`dataset-collection-create`)**: [Create Empty Collection or Folder](https://doc.fastgpt.io/openapi/reference/dataset-collection-create/create) · [Create Collection from Local File](https://doc.fastgpt.io/openapi/reference/dataset-collection-create/local-file) · [Create Collection from Link](https://doc.fastgpt.io/openapi/reference/dataset-collection-create/link) · [Create Collection from Text](https://doc.fastgpt.io/openapi/reference/dataset-collection-create/text) * **Dataset Data (`dataset-data`)**: [List Dataset Data Items](https://doc.fastgpt.io/openapi/reference/dataset-data/v2-list) · [Get Dataset Data Item Details](https://doc.fastgpt.io/openapi/reference/dataset-data/detail) · [Update Dataset Data Item](https://doc.fastgpt.io/openapi/reference/dataset-data/update) · [Delete Dataset Data Item](https://doc.fastgpt.io/openapi/reference/dataset-data/delete) · [Push Data Items to Training Queue](https://doc.fastgpt.io/openapi/reference/dataset-data/push-data) * **Dataset Search (`dataset-search`)**: [Search Datasets API](https://doc.fastgpt.io/openapi/reference/dataset-search/search) ## Machine-Readable Discovery (GEO & Tooling) For coding agents, SDK generators, and HTTP schema importers, the official documentation portal publishes machine-readable contracts: * **OpenAPI 3.1 JSON Spec**: [https://doc.fastgpt.io/openapi.json](https://doc.fastgpt.io/openapi.json) (`/openapi.json`, served with `Access-Control-Allow-Origin: *` for direct cross-origin tool ingestion). * **OpenAPI Markdown Corpus**: [https://doc.fastgpt.io/llms-openapi.txt](https://doc.fastgpt.io/llms-openapi.txt) (`/llms-openapi.txt`, full clean Markdown for all active System OpenAPI pages, parameter schemas, and SSE examples). * **Root LLM Index**: [https://doc.fastgpt.io/llms.txt](https://doc.fastgpt.io/llms.txt) (`/llms.txt`). * **Single-Page Markdown**: Append `.md` to any endpoint reference URL (for example, `https://doc.fastgpt.io/openapi/reference/dataset-search/search.md`) or send `Accept: text/markdown`. ## Interactive Scalar Consoles and Dev API * **Scalar API Explorer**: Each endpoint reference page includes a direct anchor link to the cloud Scalar explorer so you can supply an API key and test requests interactively. On self-hosted deployments, open `/apidoc/systemopenapi` (or `/api/apidoc/systemopenapi.json` for the instance-local JSON). * **Dev API (Internal & Administrative Operations)**: Covers source-code customization, web UI RPCs, and root maintenance operations secured by session cookies (`fastgpt_token`) or `rootkey`. To keep authentication scopes unambiguous, Dev API is excluded from static public docs and default AI corpora; inspect it directly on your deployment at `/apidoc/devapi` (or on FastGPT Cloud `/apidoc/devapi`). * **Legacy Reference**: Handwritten historical parameter docs remain archived in [Historical API parameters and migration](https://doc.fastgpt.io/openapi/legacy). file: ./content/openapi/best-practices/app-integration.en.mdx url: https://doc.fastgpt.io/openapi/best-practices/app-integration title: Integrate apps into your business system last_updated: 2026-11-13T13:26:57+08:00 meta: { "title": "Integrate apps into your business system", "description": "Connect a FastGPT app to your product with an app key, your own user identities, and chat history APIs." } > **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): `/apidoc/systemopenapi` **Version compatibility: FastGPT v4.18.0 or later.** Earlier versions do not support the **app keys** (bound to an `appId`) or the `customUid` parameter used in this guide. This guide walks through adding an AI assistant to your product: calling an app, identifying your users, and managing chat history. The examples use an **app key** bound to one app, so `appId` is optional. For personal keys, see [API documentation introduction](https://doc.fastgpt.io/openapi/intro). Use `/apidoc/systemopenapi` on your deployment for the exact API contract. FastGPT's chat completions endpoint supports the **OpenAI SDK**. Point the SDK's `base_url` at your FastGPT instance and pass `chatId` and `customUid` through `extra_body` to call your app and continue sessions. See the [Python SDK example](#using-the-openai-sdk) below. ## Integration flow ![The frontend calls FastGPT through a backend that stores the app key and validates session ownership](https://cdn.jsdelivr.net/gh/labring/fastgpt-img@main/diagrams/app-integration.en.light.svg) Keep your existing login system. Your backend identifies the signed-in user, calls FastGPT, and returns the result to the frontend. Store the app key only in your backend configuration. ## 1. Create an app key Publish the app, then go to **App → Publishing channels → API access → App key** and create a key for your backend. Viewing, creating, and managing app keys requires app administrator permissions. ![API access page with App key selected and the Create app key button](https://cdn.jsdelivr.net/gh/labring/fastgpt-img@main/optimized/current/app-integration-api-key.zh-CN.png.webp) Screenshots use the Chinese interface. Under **API access**, select **App key**, then click **Create app key**. The key is bound to the current app. Set a name for your backend integration and configure a points limit and expiration time as needed. ```bash export FASTGPT_BASE_URL='http://localhost:3000/api' export FASTGPT_APP_KEY='YOUR_APP_API_KEY' ``` `FASTGPT_BASE_URL` includes `/api`. Append `/v1/chat/completions` for chat requests and `/core/chat/...` for chat history requests. Do not add `/v1` to every endpoint. ## 2. Map your users Pass a stable user identifier from your platform as `customUid`. You do not need to create a FastGPT team member for every user. | Field | Purpose | Example | | ----------- | -------------------------------------------------- | ------------------------------ | | App key | Authorizes calls to the bound FastGPT app | Key stored on your backend | | `customUid` | Identifies the user of your product | `tenant-01:user-42` | | `chatId` | Identifies one session; reuse it across chat turns | UUID generated by your backend | * Derive `customUid` from the authenticated user on your backend. Do not trust a user ID submitted directly by the frontend. * Use a different `chatId` for each new session. Keep both `chatId` and `customUid` unchanged when continuing a session. * For multi-tenant products, include a tenant prefix to distinguish users with the same local ID. * `customUid` accepts up to 1024 characters. For a new session, omitting it or passing an empty string uses the default identity. Once the first turn establishes the identity, continuing a session cannot change, omit, or clear its bound `customUid`. It is mutually exclusive with `authProxy`; app keys do not support `authProxy`. **`customUid` identifies a user; it does not authenticate them.** An app key authorizes access to its bound app. Your backend must still check which sessions each user owns. Store a mapping in your database for the user's session list and subsequent ownership checks: ```json { "tenantId": "tenant-01", "userId": "user-42", "fastgptAppId": "YOUR_FASTGPT_APP_ID", "customUid": "tenant-01:user-42", "chatId": "de305d54-75b4-431b-adb2-eb6b9e546014" } ``` `fastgptAppId` records the binding in your product. Requests made with the app key can still omit `appId`. ## 3. Start and continue a chat For a new session, generate a `chatId`, record its owner, and send the first request from your backend: ```bash curl "$FASTGPT_BASE_URL/v1/chat/completions" \ --header "Authorization: Bearer $FASTGPT_APP_KEY" \ --header 'Content-Type: application/json' \ --data '{ "chatId": "de305d54-75b4-431b-adb2-eb6b9e546014", "customUid": "tenant-01:user-42", "stream": false, "messages": [{ "role": "user", "content": "Hello, what can you help me with?" }] }' ``` Before continuing, verify that the current user owns the `chatId`. Reuse the same `chatId` and `customUid`, and replace `messages` with the new question. FastGPT loads the saved history for that session; a normal continuation does not require resending the full history. For streaming text, set `stream` to `true` and handle or forward the SSE stream on your backend. Finish the current turn before starting the next one. See your deployment's API documentation for event details. ### Using the OpenAI SDK To use the [OpenAI Python SDK](https://developers.openai.com/api/reference/python), install the package: ```bash python -m pip install openai ``` Reuse `FASTGPT_BASE_URL` and `FASTGPT_APP_KEY` from above. Append `/v2` to the `/api` base URL so the SDK calls `/api/v2/chat/completions`: ```python import os from uuid import uuid4 from openai import OpenAI client = OpenAI( api_key=os.environ["FASTGPT_APP_KEY"], base_url=f"{os.environ['FASTGPT_BASE_URL'].rstrip('/')}/v2", ) chat_id = str(uuid4()) custom_uid = "tenant-01:user-42" # Derive this from the authenticated user on your backend. response = client.chat.completions.create( model="fastgpt", messages=[{"role": "user", "content": "Hello, what can you help me with?"}], stream=False, extra_body={"chatId": chat_id, "customUid": custom_uid}, ) print(response.choices[0].message.content) ``` The SDK requires `model` as a placeholder; the FastGPT app configuration selects the actual model. Pass FastGPT's `chatId` and `customUid` fields through `extra_body`. Generate and save `chat_id` when starting a session. For subsequent turns, reuse the same `chat_id` and `custom_uid`, replacing only the current `messages`. ## 4. Display and manage chat history ### Session list Call `getHistories` from your backend with the current user's `customUid`, derived from their authenticated identity. An app key lists API-source sessions for its bound app; `customUid` further limits the list to that user: ```bash curl "$FASTGPT_BASE_URL/core/chat/history/getHistories" \ --header "Authorization: Bearer $FASTGPT_APP_KEY" \ --header 'Content-Type: application/json' \ --data '{ "customUid": "tenant-01:user-42", "offset": 0, "pageSize": 20 }' ``` Omitting `customUid` lists API sessions across users of the app, which is useful for backend administration. Do not return that unfiltered list to an end user. Your own session mappings remain useful for ownership checks and product-specific features. For message counts, feedback, or date-based reporting, use `POST /core/app/logs/list` with `outLinkUids: ["tenant-01:user-42"]`. Read `data.list` and `data.total` from the response. Entries include `chatId`, `title`, `customTitle`, and `updateTime`. Increase `offset` for the next page, or use `pageNum` starting at `1`. If both are provided, `offset` takes precedence. ### Open a session Check ownership on your backend before loading its messages: ```bash curl "$FASTGPT_BASE_URL/core/chat/record/getPaginationRecords" \ --header "Authorization: Bearer $FASTGPT_APP_KEY" \ --header 'Content-Type: application/json' \ --data '{ "chatId": "de305d54-75b4-431b-adb2-eb6b9e546014", "customUid": "tenant-01:user-42", "offset": 0, "pageSize": 20 }' ``` Read messages from `data.list` and use `data.total` to determine whether more are available. The `obj` field distinguishes `Human` and `AI` messages. The `value` field contains text, files, and other content blocks; render each block according to its type. ### Other common operations These endpoints also accept an app key without `appId`. Check session ownership on your backend and pass the current user's `customUid` with each operation. In Query parameters, `customUid` is a plain string; encode it with a tool such as URLSearchParams. | Operation | Method and path (relative to `/api`) | Main parameters | | ------------------------------------- | ------------------------------------------ | ----------------------------------------------- | | Rename or pin a session | `PUT /core/chat/history/updateHistory` | `chatId` and `customTitle` or `top` in the body | | Delete one session | `DELETE /core/chat/history/delHistory` | `chatId` in the query | | Read session running statuses in bulk | `POST /core/chat/history/getHistoryStatus` | `chatIds` in the body | With `customUid`, `clearHistories` clears only that user's API-source sessions. Without it, the request clears API-source sessions across the app. Batch physical deletion is a log management endpoint that does not process user identity parameters; do not use it for an end user's “clear my sessions” action. ## Troubleshoot in FastGPT Open the app's **Chat logs** and search for the session ID: * **User:** Shows `customUid`, which maps back to a user of your product. * **Authorizer:** Identifies the team member used for authorization. This column is hidden by default; enable it in the column settings. * **Call channel / Channel name:** Identifies the API call and its key channel. ![Chat log filters and Field Configuration showing User, Authorizer, and Channel name](https://cdn.jsdelivr.net/gh/labring/fastgpt-img@main/optimized/current/app-integration-log-fields.zh-CN.png.webp) The screenshot uses test records. In **Field Configuration**, show **Authorizer** and **Channel name** when needed. Start with creating a session, continuing it, reading messages, and deleting it. Then add file uploads, feedback, and streaming. Use your deployment's System OpenAPI documentation for field and response details. file: ./content/openapi/dataset.en.mdx url: https://doc.fastgpt.io/openapi/dataset title: Integrate knowledge ingestion and retrieval last_updated: 2026-11-13T13:26:57+08:00 meta: { "title": "Integrate knowledge ingestion and retrieval", "description": "Use generated API contracts for import, processing checks, retrieval testing, and application association." } > **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): `/apidoc/systemopenapi` Prepare a personal API key and the required read/write permissions on the Dataset. See [API getting started](https://doc.fastgpt.io/openapi/intro) for authentication setup. ## Objects and identifiers `datasetId` identifies a knowledge base and `collectionId` a collection. Content collections hold chunks; folder collections organize other collections. Chunks have retrieval indexes. The interface URL helps locate a resource; submit its identifier in the field specified by the selected operation. ## Build an ingestion path 1. Find knowledge-base creation or existing-base lookup in the generated reference. Verify creation permissions, type, and model configuration. 2. Choose a collection-creation operation for files, text, URLs, or external sources. Verify its format and processing settings. 3. Retain returned knowledge-base and collection identifiers. Use the corresponding query operation to inspect processing status and failures. 4. Once processing completes, submit a question with a known answer to the search-test operation. Inspect returned text and collection origin. 5. Associate the Dataset with an app and follow [business system app integration](https://doc.fastgpt.io/openapi/best-practices/app-integration) to verify retrieval through to an answer. Reuse the material and expected answers from [your first knowledge-base Q\&A](https://doc.fastgpt.io/guide/getting-started/knowledge-qa). ## Example: import text and retrieve it First create a general knowledge base with an available embedding model in the interface and copy its ID. Use the origin and key from API getting started, then set `FASTGPT_DATASET_ID`. This import creates a collection and consumes processing quota; repeating it creates another collection. ```bash export FASTGPT_DATASET_ID='YOUR_DATASET_ID' curl --fail-with-body "$FASTGPT_ORIGIN/api/core/dataset/collection/create/text" \ -H "Authorization: Bearer $FASTGPT_API_KEY" \ -H 'Content-Type: application/json' \ --data @- <`: ### 1. Knowledge Base Management (`dataset`) | Method | Path | Summary | Key Parameters (Query / Body) | | -------- | -------------------------------- | ------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `POST` | `/api/core/dataset/create` | Create a knowledge base or folder | Body: `name` (required), `type` (`dataset`/`folder`/`websiteDataset`/`externalFile`, required), `intro` (required), `vectorModel`, `agentModel`, `vlmModel`, `parentId` | | `POST` | `/api/core/dataset/list` | List accessible knowledge bases (deprecated; use `listV2`) | Body: `parentId`, `type`, `searchKey` | | `POST` | `/api/core/dataset/listV2` | List paginated knowledge bases; pass `withFileCount: true` to return non-folder file counts | Body: `parentId`, `type`, `searchKey`, `datasetIds`, `withFileCount`, `offset`/`pageNum`, `pageSize` | | `GET` | `/api/core/dataset/detail` | Get knowledge base details (models, permissions, sync status) | Query: `id` (knowledge base ID, required) | | `DELETE` | `/api/core/dataset/delete` | Delete a knowledge base and child resources (owner only) | Query: `id` (knowledge base ID, required) | | `POST` | `/api/core/dataset/batch/move` | Batch-move knowledge bases to a target folder | Body: `ids` (ID array), `parentId` (target folder ID or empty) | | `POST` | `/api/core/dataset/batch/delete` | Batch-delete multiple knowledge bases | Body: `ids` (ID array) | ### 2. Collection Creation and Ingestion (`datasetCollectionCreate`) | Method | Path | Summary | Key Parameters (Body / Form) | | ------ | --------------------------------------------------- | ------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------- | | `POST` | `/api/core/dataset/collection/create` | Create an empty collection or folder | Body: `datasetId` (required), `name` (required), `type` (`folder`/`virtual`, required), `parentId`, `tags` | | `POST` | `/api/core/dataset/collection/create/localFile` | Upload a local file to create a collection and start training | `multipart/form-data`: `file` (binary) + `data` (JSON string with `datasetId`, `trainingType`, `chunkSize`, `tags`) | | `POST` | `/api/core/dataset/collection/create/text` | Create a collection from raw text and start training | Body: `datasetId` (required), `name` (required), `text` (required), `trainingType`, `chunkSettingMode`, `tags` | | `POST` | `/api/core/dataset/collection/create/link` | Crawl a web URL to create a collection and start training | Body: `datasetId` (required), `link` (required), `trainingType`, `metadata` (`webPageSelector`) | | `POST` | `/api/core/dataset/collection/create/apiCollection` | Create a collection from an external API dataset file (deprecated) | Body: `datasetId` (required), `name` (required), `apiFileId` (required), `trainingType` | ### 3. Collection Query, Update, and Archive Download (`datasetCollection`) | Method | Path | Summary | Key Parameters (Query / Body) | | ------ | ------------------------------------------------ | -------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | | `POST` | `/api/core/dataset/collection/listV2` | List paginated collections (supports search and `tagFilters`) | Body: `datasetId` (required), `parentId`, `searchText`, `tagFilters`, `selectFolder`, `pageSize` (max 100) | | `GET` | `/api/core/dataset/collection/detail` | Get collection details (index count, training status, file metadata) | Query: `id` (collection ID, required) | | `POST` | `/api/core/dataset/collection/update` | Update collection name, parent folder, enabled state, or tags | Body: `id` (or `datasetId` + `externalFileId`), `name`, `parentId`, `forbid`, `tags` | | `POST` | `/api/core/dataset/collection/delete` | Delete one or more collections (collection owner only) | Query: `id` or Body: `collectionIds` (string array) | | `POST` | `/api/core/dataset/collection/getDownloadTicket` | Request a short-lived ticket for batch collection ZIP download | Body: `datasetId` (required), `collectionIds` (required, at least 1 collection ID) | | `GET` | `/api/core/dataset/collection/batchDownload` | Stream a ZIP archive of collection source files using a ticket | Query: `ticket` (required) | ### 4. Data Chunk Maintenance and Search Test (`datasetData` / `datasetOther`) | Method | Path | Summary | Key Parameters (Query / Body) | | -------- | --------------------------------- | --------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | | `POST` | `/api/core/dataset/data/pushData` | Push data chunks to the training queue in batch (up to 200 items) | Body: `collectionId` (required), `data` (`{ q, a, indexes }[]` array, required), `trainingType` | | `POST` | `/api/core/dataset/data/v2/list` | List paginated data chunks inside a collection | Body: `collectionId` (required), `searchText`, `offset`/`pageNum`, `pageSize` | | `GET` | `/api/core/dataset/data/detail` | Get a single data chunk and its vector indexes | Query: `id` (data chunk ID, required) | | `PUT` | `/api/core/dataset/data/update` | Update a chunk's `q`, `a`, or `indexes` and re-embed | Body: `dataId` (required), `q` (required), `a`, `indexes` | | `DELETE` | `/api/core/dataset/data/delete` | Delete a single data chunk and its indexes | Query: `id` (data chunk ID, required) | | `POST` | `/api/core/dataset/searchTest` | Run a retrieval test (semantic/full-text/hybrid, image query, rerank) | Body: `datasetId` (required), `text`, `queryImageUrls`, `limit` (max tokens), `similarity`, `searchMode`, `usingReRank` | **Earlier section links** [Dataset ](https://doc.fastgpt.io/openapi/legacy/dataset#dataset) [Create Dataset ](https://doc.fastgpt.io/openapi/legacy/dataset#create-dataset) [Get Dataset List ](https://doc.fastgpt.io/openapi/legacy/dataset#get-dataset-list) [Get Dataset Details ](https://doc.fastgpt.io/openapi/legacy/dataset#get-dataset-details) [Delete Dataset ](https://doc.fastgpt.io/openapi/legacy/dataset#delete-dataset) [Collection ](https://doc.fastgpt.io/openapi/legacy/dataset#collection) [Common Creation Parameters (Must Read) ](https://doc.fastgpt.io/openapi/legacy/dataset#common-creation-parameters-must-read) [Create Empty Collection/Folder ](https://doc.fastgpt.io/openapi/legacy/dataset#create-empty-collectionfolder) [Create a Text Collection ](https://doc.fastgpt.io/openapi/legacy/dataset#create-a-text-collection) [Create a Link Collection ](https://doc.fastgpt.io/openapi/legacy/dataset#create-a-link-collection) [Create a File Collection ](https://doc.fastgpt.io/openapi/legacy/dataset#create-a-file-collection) [Create a Collection from an API Dataset (V1) ](https://doc.fastgpt.io/openapi/legacy/dataset#create-a-collection-from-an-api-dataset-v1) [Create an External File Collection (Commercial) ](https://doc.fastgpt.io/openapi/legacy/dataset#create-an-external-file-collection-commercial) [Get Collection List ](https://doc.fastgpt.io/openapi/legacy/dataset#get-collection-list) [Get Collection Details ](https://doc.fastgpt.io/openapi/legacy/dataset#get-collection-details) [Update Collection Info ](https://doc.fastgpt.io/openapi/legacy/dataset#update-collection-info) [Delete Collection ](https://doc.fastgpt.io/openapi/legacy/dataset#delete-collection) [Data ](https://doc.fastgpt.io/openapi/legacy/dataset#data) [Data Structure ](https://doc.fastgpt.io/openapi/legacy/dataset#data-structure) [Push Data to Processing Queue ](https://doc.fastgpt.io/openapi/legacy/dataset#push-data-to-processing-queue) [Get Collection Data List ](https://doc.fastgpt.io/openapi/legacy/dataset#get-collection-data-list) [Get Single Data Details ](https://doc.fastgpt.io/openapi/legacy/dataset#get-single-data-details) [Update Single Data ](https://doc.fastgpt.io/openapi/legacy/dataset#update-single-data) [Delete Single Data ](https://doc.fastgpt.io/openapi/legacy/dataset#delete-single-data) [Search Test ](https://doc.fastgpt.io/openapi/legacy/dataset#search-test) file: ./content/openapi/identity-proxy.en.mdx url: https://doc.fastgpt.io/openapi/identity-proxy title: API and MCP identity proxy last_updated: 2026-11-12T14:01:38+08:00 meta: { "title": "API and MCP identity proxy", "description": "Execute as a member of the same team through a trusted server and that member’s resource permissions." } Identity proxy attributes an execution to a selected team member. The integration server authenticates the business user, resolves the member from a trusted mapping, and verifies the permitted delegation scope. ## Enablement requirements * A team Owner can enable proxying on a team-level API key or MCP publication they manage. Creators can disable proxying on their own credentials or publications. * The target must be an `active` member of the same team with application read permission and the relevant conversation permissions. * API proxying requires a team-level API key with `authProxy` enabled. Legacy application-bound keys, login tokens, and shared-link credentials have their own access purposes. ## API request body The conversation endpoint accepts `authProxy.username` or `authProxy.tmbId` in the request body: ```json { "appId": "YOUR_APP_ID", "authProxy": { "username": "member@example.com" }, "messages": [{ "role": "user", "content": "Summarize the travel policy." }], "stream": false } ``` The username is the member's login username. When both `tmbId` and `username` are supplied in the API request body, `tmbId` takes precedence; if `tmbId` is invalid, the request fails directly and `username` is ignored. Omitting proxy fields uses the credential's member. Server-side permission checks determine access after membership or conversation ownership changes. ## MCP headers MCP uses transport request headers: ```json { "x-fastgpt-auth-proxy-username": "member@example.com" } ``` Alternatively, use `x-fastgpt-auth-proxy-tmb-id`. Both headers must identify the same member when supplied together. SSE stores identity at connection time, so reconnect after changing identity. Streamable HTTP reads headers per request. See [MCP service publishing](https://doc.fastgpt.io/guide/build/publish/mcp_server) for complete connection examples. ## Verify and troubleshoot Call as a member with read access and inspect conversation ownership. Then verify rejection using a test member lacking access. Check enablement, team, member status, identifier agreement, and resource permissions. An MCP tool list establishes metadata visibility; execution performs further permission checks. The trusted server holds credentials and generates proxy fields. The user-facing client supplies business identity and the server authorizes its mapping. MCP identity proxying passes the member identifier through the `x-fastgpt-auth-proxy-username` or `x-fastgpt-auth-proxy-tmb-id` request header. file: ./content/openapi/interactive-and-variables.en.mdx url: https://doc.fastgpt.io/openapi/interactive-and-variables title: Interactive Suspension Resume and File Input API Flow last_updated: 2026-11-13T13:26:57+08:00 meta: { "title": "Interactive Suspension Resume and File Input API Flow", "description": "Handle workflow interactive suspension (User Selection and Form Input), checkpoint resumption, global variables, and multimodal file inputs via OpenAPI." } When a workflow includes [User Selection (`userSelect`)](https://doc.fastgpt.io/guide/build/workflow/nodes/user-selection) or [Form Input (`formInput`)](https://doc.fastgpt.io/guide/build/workflow/nodes/form_input) nodes, or accepts pre-chat global variables, documents, and images, your client interacts with `/api/v2/chat/completions` (or `/api/v1/chat/completions`) using the contracts below. ## 1. Global Variables and Multimodal File Inputs ### 1. Pass Global Variables (`variables`) Supply values matching your application's declared [global variable keys](https://doc.fastgpt.io/guide/build/workflow/variables) inside the `variables` object: ```json { "appId": "YOUR_APP_ID", "chatId": "session_20261028_001", "stream": true, "detail": true, "variables": { "department": "Finance", "maxBudget": 5000, "strictMode": true }, "messages": [{ "role": "user", "content": "Verify this travel reimbursement request" }] } ``` ### 2. Pass Images and Documents (Multimodal Message Array) When vision or document parsing is enabled on the application, pass a structured array in `messages[].content` using `file_url` for documents and `image_url` for images reachable by the FastGPT server: ```json { "appId": "YOUR_APP_ID", "chatId": "session_20261028_002", "stream": false, "detail": true, "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Extract the signing date and total amount from the attached contract" }, { "type": "file_url", "name": "contract.pdf", "url": "https://example.com/files/contract.pdf" }, { "type": "image_url", "image_url": { "url": "https://example.com/images/receipt.png" } } ] } ] } ``` ## 2. Interactive Suspension (Human-in-the-Loop) and Resumption When execution reaches a `userSelect` or `formInput` node, the server saves a runtime checkpoint under the active `chatId` and emits an `interactive` payload to the client. ![Workflow interactive suspension and resumption flow](https://cdn.jsdelivr.net/gh/labring/fastgpt-img@main/diagrams/workflow-interaction.en.light.svg) ### Step 1: Parse the Suspension Payload (`detail: true` Required) * **Streaming mode (`stream: true, detail: true`)**: The server emits an `event: interactive` frame before closing the current stream with `data: [DONE]`: ```text event: interactive data: {"interactive":{"type":"userSelect","params":{"description":"Select an action","userSelectOptions":[{"key":"opt_1","value":"Approve rewrite"},{"key":"opt_2","value":"Cancel"}]}}} event: answer data: [DONE] ``` * **Form Input node (workflow node type `formInput`, response discriminator `interactive.type: "userInput"`)**: When execution pauses at a Form Input node, the returned `interactive` object uses `"type": "userInput"`, and `params.inputForm` contains the array of form field definitions (`key`, `label`, `type`, `required`, and `list` options). ### Step 2: Resume Execution with the Same `chatId` Render the options or form in your client UI. Once the user submits their choice or form values, send a follow-up request to `chat/completions` with the **exact same `appId` and `chatId`** and a single `role: "user"` message: 1. **Resume a User Selection node (`userSelect`)**: Send the selected option string as `content`: ```json { "appId": "YOUR_APP_ID", "chatId": "session_20261028_001", "stream": true, "detail": true, "messages": [{ "role": "user", "content": "Approve rewrite" }] } ``` 2. **Resume a Form Input node (`formInput`)**: Serialize the submitted key-value form object as a **JSON string** in `content`: ```json { "appId": "YOUR_APP_ID", "chatId": "session_20261028_001", "stream": true, "detail": true, "messages": [ { "role": "user", "content": "{\"reason\":\"Receipt explanation attached\",\"amount\":1280}" } ] } ``` The server restores the saved checkpoint for `chatId` and continues executing downstream nodes from the suspended step. ## Troubleshooting | Symptom | Cause and Resolution | | ---------------------------------------------------------------- | -------------------------------------------------------------------------------------- | | Workflow pauses at an interactive node without returning options | `detail: true` was omitted; enable `detail: true` to receive `interactive` events | | Follow-up submission restarts the workflow from the start node | `chatId` was omitted or changed; pass the exact `chatId` from the suspended turn | | Form input resumption fails or fields arrive empty | Ensure `content` is a JSON-serialized string whose keys match `params.inputForm[].key` | Next: Follow [business system app integration](https://doc.fastgpt.io/openapi/best-practices/app-integration) to connect your product and manage sessions. file: ./content/openapi/intro.en.mdx url: https://doc.fastgpt.io/openapi/intro title: API getting started: make your first request last_updated: 2026-11-13T13:26:57+08:00 meta: { "title": "API getting started: make your first request", "description": "Configure a service address, member API key, and application ID, then call a published application." } ## Prerequisites Find the current endpoint contracts and documentation links on [API reference addresses](https://doc.fastgpt.io/openapi/api-reference). Prepare a debugged, published application and available model quota, then create or manage API keys in either location: 1. **Account → API Keys**: manage personal keys for the current member (visible to members granted the **Create API Keys** permission under **Account → Team management → Permissions**). 2. **Studio → Target App → Publish Channels → API Access**: switch between **App keys** (FastGPT 4.18.0 or later) and **Personal keys**. Legacy keys that store an `appId` remain personal keys. That ID is only the default App for `chat/completions`; the request body or SDK suffix can override it, and the owning member’s permissions still apply. Only explicitly created App keys enforce the App binding described below. | Type | Scope | Management | | ------------ | -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- | | App key | Chat and chat management endpoints for its bound app, including chat logs, chat files, and Sandbox files | App administrators view, create, and manage all keys on the same app | | Personal key | Team resources accessible to the owning member on endpoints that accept API keys | Members manage their own keys | An app key grants access independently of its owning member's app permissions as long as the key, member, team, and bound app remain valid. Personal keys support `authProxy` when enabled by the team owner (FastGPT >= v4.15.0; see [identity proxy](https://doc.fastgpt.io/openapi/identity-proxy)), while app keys identify external users via `customUid`. When the team has an active subscription usage plan, you can configure **Max usage points** and **Expiration time** when creating or editing a key. Store keys on a trusted server or in a secret manager. ## First request Set `FASTGPT_ORIGIN` to your FastGPT instance and copy `appId` from the application details URL (with a 4.18.0+ app key, `appId` can be omitted because the server uses the bound app). This request calls the published version through `/api/v2/chat/completions` (`v2` is recommended; `/api/v1/chat/completions` is retained for legacy compatibility): ```bash export FASTGPT_ORIGIN='https://cloud.fastgpt.io' export FASTGPT_API_KEY='YOUR_API_KEY' export FASTGPT_APP_ID='YOUR_APP_ID' curl --fail-with-body "$FASTGPT_ORIGIN/api/v2/chat/completions" \ -H "Authorization: Bearer $FASTGPT_API_KEY" \ -H 'Content-Type: application/json' \ --data @- <-` composite format; FastGPT resolves target applications in order of request body `body.appId` -> Bearer header suffix -> default application saved on a legacy personal key. ### List sessions with an app key With an app key, `/api/core/chat/history/getHistories` queries API-source sessions for the bound app. Omit `appId`, `sourceType`, and `source`: ```bash export FASTGPT_ORIGIN='https://cloud.fastgpt.io' export FASTGPT_APP_API_KEY='YOUR_APP_API_KEY' curl --fail-with-body "$FASTGPT_ORIGIN/api/core/chat/history/getHistories" \ -H "Authorization: Bearer $FASTGPT_APP_API_KEY" \ -H 'Content-Type: application/json' \ --data @- <`—Supports **App API Key** ( `appId` optional) and **Personal API Key** ( `appId` required) (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E5%BA%94%E7%94%A8%E6%97%A5%E5%BF%97/POST/proApi/core/app/logs/getChartData) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E5%BA%94%E7%94%A8%E6%97%A5%E5%BF%97/POST/proApi/core/app/logs/getChartData` ) ## Description & Notes Queries strictly within the exact absolute start and end timestamps without expanding the window. User, chat, and app buckets are grouped by the fixed timezone offset carried in `dateStart` (or server timezone if omitted); no separate timezone parameter is accepted. ## Request Parameters ### Request Body ( `application/json` ) #### Shared Parameters Across Branches | Field | Type | Required | Default | Constraints & Description | | -------------- | -------------------- | -------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `dateStart` | `string` | Yes | - | Inclusive start timestamp as an ISO string preserving timezone offset and milliseconds; buckets use this fixed offset (server timezone if omitted, `Z` for UTC) | | `dateEnd` | `string` | Yes | - | Inclusive end timestamp (server timezone if offset is omitted); preserves the exact boundary without date expansion | | `source` | `string` (enum)\[]\` | No | - | Chat source filter; omit for all sources, pass an empty array to match nothing | | `offset` | `number` | No | `1` | Retention offset measured in `userTimespan` units (defaults to 1); counts subsequent activity within the selected range only | | `userTimespan` | `string` (enum) | Yes | - | User analytics timespan. Allowed values: `day` , `week` , `month` , `quarter` | | `chatTimespan` | `string` (enum) | Yes | - | Chat analytics timespan. Allowed values: `day` , `week` , `month` , `quarter` | | `appTimespan` | `string` (enum) | Yes | - | App analytics timespan. Allowed values: `day` , `week` , `month` , `quarter` | **Mutually Exclusive Branches ( `anyOf` )** * **Explicit App ID** Personal API keys and login sessions must pass `appId` ; an App API Key always uses the bound application. | Field | Type | Required | Default | Constraints & Description | | ------- | -------- | -------- | ------- | ---------------------------- | | `appId` | `string` | Yes | - | Application ID. minLength: 1 | * **App API Key (no appId required)** When authorizing with an app-bound App API Key, omit `appId` and `sourceType` ; the server resolves the bound app with `sourceType` fixed to `app` . Personal keys and login sessions cannot omit `appId` , and an explicit `appId` does not override an App API Key binding. No extra branch-specific fields are required. ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X POST "https://cloud.fastgpt.io/api/proApi/core/app/logs/getChartData" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ --data-raw '{ "appId": "68ad85a7463006c963799a05", "dateStart": "2024-01-01T00:00:00.000Z", "dateEnd": "2024-12-31T23:59:59.999Z", "userTimespan": "day", "chatTimespan": "day", "appTimespan": "day" }' ``` ### Minimal Valid JSON Body ```json { "appId": "68ad85a7463006c963799a05", "dateStart": "2024-01-01T00:00:00.000Z", "dateEnd": "2024-12-31T23:59:59.999Z", "userTimespan": "day", "chatTimespan": "day", "appTimespan": "day" } ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Successfully retrieved application chart analytics **Content-Type** : `application/json` | Field | Type | Required | Default | Constraints & Description | | --------------------------------------- | ---------- | -------- | ------- | ----------------------------------------------------------- | | `userData` | `object[]` | Yes | - | User statistics | | `userData[].timestamp` | `number` | Yes | - | Timestamp | | `userData[].summary` | `object` | Yes | - | User summary metrics for the current time bucket | | `userData[].summary.userCount` | `number` | Yes | - | Total user count | | `userData[].summary.newUserCount` | `number` | Yes | - | New user count | | `userData[].summary.retentionUserCount` | `number` | Yes | - | Retained user count | | `userData[].summary.points` | `number` | Yes | - | Credit points consumed | | `userData[].summary.inputTokens` | `number` | Yes | - | Input tokens consumed | | `userData[].summary.outputTokens` | `number` | Yes | - | Output tokens consumed | | `userData[].summary.sourceCountMap` | `object` | Yes | - | User count by source | | `chatData` | `object[]` | Yes | - | Chat statistics | | `chatData[].timestamp` | `number` | Yes | - | Timestamp | | `chatData[].summary` | `object` | Yes | - | Chat summary metrics for the current time bucket | | `chatData[].summary.chatItemCount` | `number` | Yes | - | Total message count | | `chatData[].summary.chatCount` | `number` | Yes | - | Total chat sessions | | `chatData[].summary.errorCount` | `number` | Yes | - | Error message count | | `chatData[].summary.points` | `number` | Yes | - | Credit points consumed | | `chatData[].summary.inputTokens` | `number` | Yes | - | Input tokens consumed | | `chatData[].summary.outputTokens` | `number` | Yes | - | Output tokens consumed | | `appData` | `object[]` | Yes | - | App statistics | | `appData[].timestamp` | `number` | Yes | - | Timestamp | | `appData[].summary` | `object` | Yes | - | App performance summary metrics for the current time bucket | | `appData[].summary.goodFeedBackCount` | `number` | Yes | - | Positive feedback count | | `appData[].summary.badFeedBackCount` | `number` | Yes | - | Negative feedback count | | `appData[].summary.chatCount` | `number` | Yes | - | Chat item count | | `appData[].summary.totalResponseTime` | `number` | Yes | - | Total response time (ms) | file: ./content/openapi/reference/app-log/get-total-data.en.mdx url: https://doc.fastgpt.io/openapi/reference/app-log/get-total-data title: Get App Total Statistics last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "Get App Total Statistics", "seoTitle": "Get App Total Statistics - GET /api/proApi/core/app/logs/getTotalData | FastGPT OpenAPI", "description": "Retrieve cumulative usage statistics for a FastGPT app, including total users, chats, credit points, and token consumption." } ## Endpoint Overview * **Method** : `GET` * **Path** : `/api/proApi/core/app/logs/getTotalData` * **Module** : Applications / App Logs * **Authentication** : `Authorization: Bearer `—Supports **App API Key** ( `appId` optional) and **Personal API Key** ( `appId` required) (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E5%BA%94%E7%94%A8%E6%97%A5%E5%BF%97/GET/proApi/core/app/logs/getTotalData) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E5%BA%94%E7%94%A8%E6%97%A5%E5%BF%97/GET/proApi/core/app/logs/getTotalData` ) ## Description & Notes Retrieve cumulative application statistics including total users, total chats, and total credit consumption. ## Request Parameters ### Query Parameters **Mutually Exclusive Branches ( `anyOf` )** * **Explicit App ID** Personal API keys and login sessions must pass `appId` ; an App API Key always uses the bound application. | Field | Type | Required | Default | Constraints & Description | | ------- | -------- | -------- | ------- | ---------------------------- | | `appId` | `string` | Yes | - | Application ID. minLength: 1 | * **App API Key (no appId required)** When authorizing with an app-bound App API Key, omit `appId` and `sourceType` ; the server resolves the bound app with `sourceType` fixed to `app` . Personal keys and login sessions cannot omit `appId` , and an explicit `appId` does not override an App API Key binding. No extra branch-specific fields are required. ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X GET "https://cloud.fastgpt.io/api/proApi/core/app/logs/getTotalData?appId=68ad85a7463006c963799a05" \ -H "Authorization: Bearer YOUR_API_KEY" ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Successfully retrieved application total statistics **Content-Type** : `application/json` | Field | Type | Required | Default | Constraints & Description | | ------------------- | -------- | -------- | ------- | ---------------------------- | | `totalUsers` | `number` | Yes | - | Total users | | `totalChats` | `number` | Yes | - | Total chats | | `totalPoints` | `number` | Yes | - | Total credit points consumed | | `totalInputTokens` | `number` | Yes | - | Total input tokens consumed | | `totalOutputTokens` | `number` | Yes | - | Total output tokens consumed | file: ./content/openapi/reference/app-log/get-users.en.mdx url: https://doc.fastgpt.io/openapi/reference/app-log/get-users title: List App Log Users last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "List App Log Users", "seoTitle": "List App Log Users - POST /api/core/app/logs/getUsers | FastGPT OpenAPI", "description": "List team members and external users appearing in application chat logs, sorted by chat volume with search and pagination support." } ## Endpoint Overview * **Method** : `POST` * **Path** : `/api/core/app/logs/getUsers` * **Module** : Applications / App Logs * **Authentication** : `Authorization: Bearer `—Supports **App API Key** ( `appId` optional) and **Personal API Key** ( `appId` required) (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E5%BA%94%E7%94%A8%E6%97%A5%E5%BF%97/POST/core/app/logs/getUsers) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E5%BA%94%E7%94%A8%E6%97%A5%E5%BF%97/POST/core/app/logs/getUsers` ) ## Description & Notes Retrieve external users and team members from application chat logs, sorted by chat count with search and pagination. ## Request Parameters ### Request Body ( `application/json` ) **Mutually Exclusive Branches ( `anyOf` )** * **Explicit App ID** Personal API keys and login sessions must pass `appId` ; an App API Key always uses the bound application. | Field | Type | Required | Default | Constraints & Description | | ------- | -------- | -------- | ------- | ---------------------------- | | `appId` | `string` | Yes | - | Application ID. minLength: 1 | * **App API Key (no appId required)** When authorizing with an app-bound App API Key, omit `appId` and `sourceType` ; the server resolves the bound app with `sourceType` fixed to `app` . Personal keys and login sessions cannot omit `appId` , and an explicit `appId` does not override an App API Key binding. No extra branch-specific fields are required. #### Shared Parameters Across Branches | Field | Type | Required | Default | Constraints & Description | | ----------- | ---------- | -------- | ------- | ------------------------- | | `dateStart` | `string` | Yes | - | Start time | | `dateEnd` | `string` | Yes | - | End time | | `searchKey` | `string` | No | - | Search by username | | `sources` | `string[]` | No | - | Source filter | **Mutually Exclusive Branches ( `anyOf` )** * **Offset Pagination** Specify the 0-based starting offset; when both `offset` and `pageNum` are provided, `offset` takes precedence. | Field | Type | Required | Default | Constraints & Description | | ---------- | --------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | `offset` | `integer` | Yes | - | **Mutually Exclusive Group: Pagination Parameters** . 0-based offset. min: 0; max: 9007199254740991 | | `pageSize` | `integer` | No | `20` | **Mutually Exclusive Group: Pagination Parameters** . Items per page. Defaults to 20, capped at 500 (larger values are clamped to 500). max: 500 | * **Page-Number Pagination** Paginate by page number (starts at page 1); `pageSize` controls items per page. | Field | Type | Required | Default | Constraints & Description | | ---------- | --------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | `pageNum` | `integer` | No | `1` | **Mutually Exclusive Group: Pagination Parameters** . 1-based page number; ignored when `offset` is provided. max: 9007199254740991 | | `pageSize` | `integer` | No | `20` | **Mutually Exclusive Group: Pagination Parameters** . Items per page. Defaults to 20, capped at 500 (larger values are clamped to 500). max: 500 | ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X POST "https://cloud.fastgpt.io/api/core/app/logs/getUsers" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ --data-raw '{ "appId": "68ad85a7463006c963799a05", "offset": 0, "dateStart": "2024-01-01T00:00:00.000Z", "dateEnd": "2024-12-31T23:59:59.999Z" }' ``` ### Minimal Valid JSON Body ```json { "appId": "68ad85a7463006c963799a05", "offset": 0, "dateStart": "2024-01-01T00:00:00.000Z", "dateEnd": "2024-12-31T23:59:59.999Z" } ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Successfully retrieved application log users **Content-Type** : `application/json` | Field | Type | Required | Default | Constraints & Description | | ------------------- | ---------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------- | | `total` | `number` | Yes | `0` | - | | `list` | `object[]` | Yes | `[]` | - | | `list[].outLinkUid` | `string \| null` | Yes | - | End user ID from a share link visitor or API `customUid` ; takes precedence over `tmbId` when non-empty | | `list[].tmbId` | `string \| null` | Yes | - | Effective authenticated team member ID (or proxied member ID when using `authProxy` ) | | `list[].name` | `string` | Yes | - | User display name | | `list[].avatar` | `string` | No | - | Avatar | | `list[].count` | `number` | Yes | - | Chat item count | file: ./content/openapi/reference/app-log/search.en.mdx url: https://doc.fastgpt.io/openapi/reference/app-log/search title: Search App Chat Logs last_updated: 2026-11-20T00:55:57+08:00 meta: { "title": "Search App Chat Logs", "seoTitle": "Search App Chat Logs - POST /api/core/app/logs/search | FastGPT OpenAPI", "description": "Search FastGPT app chat logs by title or exact session ID. Get up to 50 results per page and use the returned cursor to continue." } ## Endpoint Overview * **Method** : `POST` * **Path** : `/api/core/app/logs/search` * **Module** : Applications / App Logs * **Authentication** : `Authorization: Bearer `—Supports **App API Key** ( `appId` optional) and **Personal API Key** ( `appId` required) (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E5%BA%94%E7%94%A8%E6%97%A5%E5%BF%97/POST/core/app/logs/search) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E5%BA%94%E7%94%A8%E6%97%A5%E5%BF%97/POST/core/app/logs/search` ) ## Description & Notes Search app chat logs with cursor-based pagination. The page size is fixed at 50 and the response does not include a total count. ## Request Parameters ### Request Body ( `application/json` ) | Field | Type | Required | Default | Constraints & Description | | ------------------ | -------------------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `feedbackType` | `string` (enum) | No | - | Feedback filter: `all` (all logs), `has_feedback` (logs with feedback), `good` (likes), `bad` (dislikes). Allowed values: `all` , `has_feedback` , `good` , `bad` | | `unreadOnly` | `boolean` | No | - | Whether to return only unread feedback (ignored when `feedbackType` is `all` ) | | `errorFilter` | `string` (enum) | No | - | Error filter: `all` (all logs), `has_error` (error logs only). Allowed values: `all` , `has_error` | | `dateStart` | `string` | Yes | - | Start time | | `dateEnd` | `string` | Yes | - | End time | | `sources` | `string` (enum)\[]\` | No | - | Chat source filter | | `tmbIds` | `string[]` | No | - | List of team member IDs | | `outLinkUids` | `string[]` | No | - | List of external user IDs | | `chatSearch` | `string` | No | - | Search term. Use with `searchType` to search titles or match a session ID exactly. | | `searchType` | `string` (enum) | No | - | Search mode. Use `title` to search titles or `chatId` to match a session ID exactly. Omit this field to use the legacy search behavior. Allowed values: `title` , `chatId` | | `cursor` | `object` | No | - | The `nextCursor` from the previous response. Omit this field on the first page and pass the cursor unchanged for subsequent pages. | | `cursor.timestamp` | `integer` | Yes | - | Cursor timestamp in milliseconds. min: 0; max: 9007199254740991 | | `cursor.id` | `string` | Yes | - | Log ID in the cursor. pattern: `^[a-f\d]{24}$` | **Mutually Exclusive Branches ( `anyOf` )** * **Explicit App ID** Personal API keys and login sessions must pass `appId` ; an App API Key always uses the bound application. | Field | Type | Required | Default | Constraints & Description | | ------- | -------- | -------- | ------- | ---------------------------- | | `appId` | `string` | Yes | - | Application ID. minLength: 1 | * **App API Key (no appId required)** When authorizing with an app-bound App API Key, omit `appId` and `sourceType` ; the server resolves the bound app with `sourceType` fixed to `app` . Personal keys and login sessions cannot omit `appId` , and an explicit `appId` does not override an App API Key binding. No extra branch-specific fields are required. ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X POST "https://cloud.fastgpt.io/api/core/app/logs/search" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ --data-raw '{ "appId": "68ad85a7463006c963799a05", "dateStart": "2024-01-01T00:00:00.000Z", "dateEnd": "2024-12-31T23:59:59.999Z" }' ``` ### Minimal Valid JSON Body ```json { "appId": "68ad85a7463006c963799a05", "dateStart": "2024-01-01T00:00:00.000Z", "dateEnd": "2024-12-31T23:59:59.999Z" } ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 App log search completed successfully **Content-Type** : `application/json` | Field | Type | Required | Default | Constraints & Description | | ------------------------------ | ----------------- | -------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `list` | `object[]` | Yes | - | Chat log records for this page. The page size is fixed at 50. | | `list[].publishSource` | `object` | No | - | - | | `list[].publishSource.type` | `string` (enum) | No | `"unknown"` | Channel type of the latest run; falls back to `unknown` if unrecognized. Allowed values: `test` , `online` , `share` , `api` , `cronJob` , `feishu` , `official_account` , `wecom` , `wechat` , `mcp` , `dingtalk` , `unknown` | | `list[].publishSource.id` | `string` | No | - | Database ID of the channel record; omitted for internal entry points or legacy data without recoverable references. pattern: `^[0-9a-fA-F]{24}$` | | `list[].publishSource.name` | `string` | No | - | Current channel name, compatible with legacy source names | | `list[]._id` | `string` | Yes | - | Chat log ID | | `list[].chatId` | `string` | Yes | - | Chat ID. maxLength: 1024 | | `list[].title` | `string \| null` | No | - | Chat title | | `list[].customTitle` | `string \| null` | No | - | Custom chat title | | `list[].source` | `string` (enum) | Yes | `"unknown"` | **Deprecated** . Legacy channel type retained for compatibility; use `publishSource.type` instead. Allowed values: `test` , `online` , `share` , `api` , `cronJob` , `feishu` , `official_account` , `wecom` , `wechat` , `mcp` , `dingtalk` , `unknown` | | `list[].sourceName` | `string \| null` | No | - | **Deprecated** . Legacy channel name retained for compatibility; use `publishSource.name` instead | | `list[].updateTime` | `string` | Yes | - | Update time | | `list[].createTime` | `string \| null` | No | - | Creation time | | `list[].messageCount` | `integer \| null` | No | - | Message count | | `list[].userGoodFeedbackCount` | `integer \| null` | No | - | Positive feedback count | | `list[].userBadFeedbackCount` | `integer \| null` | No | - | Negative feedback count | | `list[].customFeedbacksCount` | `integer \| null` | No | - | Custom feedback count | | `list[].markCount` | `integer \| null` | No | - | Marked count | | `list[].averageResponseTime` | `number \| null` | No | - | Average response time (ms) | | `list[].errorCount` | `integer \| null` | No | - | Error count | | `list[].totalPoints` | `number \| null` | No | - | Total credit points consumed | | `list[].outLinkUid` | `string \| null` | No | - | End user ID from a share link visitor or API `customUid` ; takes precedence over `tmbId` when non-empty | | `list[].tmbId` | `string \| null` | No | - | Effective authenticated team member ID (or proxied member ID when using `authProxy` ) | | `list[].sourceMember` | `object \| null` | No | - | Source member details (compatibility field; may represent a guest for share-link traffic) | | `list[].authMember` | `object \| null` | No | - | Authenticated member metadata resolved by `tmbId` , for display only | | `list[].versionName` | `string \| null` | No | - | Version name | | `list[].originIp` | `string \| null` | No | - | Origin IP address | | `list[].region` | `string \| null` | No | - | Region | | `nextCursor` | `object` | No | - | Cursor for the next page. This field is absent when no more results are available. | | `nextCursor.timestamp` | `integer` | Yes | - | Cursor timestamp in milliseconds. min: 0; max: 9007199254740991 | | `nextCursor.id` | `string` | Yes | - | Log ID in the cursor. pattern: `^[a-f\d]{24}$` | file: ./content/openapi/reference/chat-controller/v2-chat-completions.en.mdx url: https://doc.fastgpt.io/openapi/reference/chat-controller/v2-chat-completions title: Create Chat Completion (v2) last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "Create Chat Completion (v2)", "seoTitle": "Create Chat Completion (v2) - POST /api/v2/chat/completions | FastGPT OpenAPI", "description": "Invoke a published FastGPT app via the OpenAI-compatible v2 endpoint with non-streaming JSON, multi-event SSE, and interactive resume." } ## Endpoint Overview * **Method** : `POST` * **Path** : `/api/v2/chat/completions` * **Module** : Chat / Chat Completions & Control * **Authentication** : `Authorization: Bearer `—Supports **App API Key** ( `appId` optional) and **Personal API Key** ( `appId` required); also supports `authProxy` team member proxy and `outLinkAuthData` share link (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E4%BC%9A%E8%AF%9D%E6%93%8D%E4%BD%9C/POST/v2/chat/completions) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E4%BC%9A%E8%AF%9D%E6%93%8D%E4%BD%9C/POST/v2/chat/completions` ) ## Description & Notes The v2 chat completions endpoint follows the OpenAI Chat Completions schema. **API Key Usage** * Authenticate with an API Key. When calling `chat/completions` with a personal key, passing `body.appId` in the request body is recommended. * For OpenAI SDK compatibility, `Authorization: Bearer -` is also supported without passing `body.appId` . * Some SDKs append `/v1` to `baseURL` while others do not; if you receive a 404, try adjusting `/v1` in `baseURL` . * `appId` resolution precedence: `body.appId` > `-` header suffix > legacy key-bound `appId` . **Important Notes** * Backend callers can pass `customUid` to identify their end users (passed to workflow `userId` ). It does not change the authenticating member and is mutually exclusive with `authProxy` (max 1024 chars; empty string uses the default member; supported in FastGPT >= 4.18.0). * To impersonate a team member via `authProxy` , a team owner must enable `authProxy` on the personal API key; the proxied member must still have access to the target app and chat session (FastGPT >= v4.15.0). * Request fields such as `model` and `temperature` are ignored because model and inference parameters are controlled by the published app workflow. * Standard `usage` tokens are placeholder values; set `detail=true` and sum `tokens` in `responseData` if you need per-node token usage. **`chatId` Behavior** * Omitted or empty: FastGPT server-side history is disabled; context is constructed solely from the request `messages` array. * Non-empty string: FastGPT loads existing conversation history for `chatId` from storage and uses only the last message in `messages` as the user prompt (earlier entries are ignored). Ensure `chatId` is unique (max 1024 chars). **`stream` / `detail` Combinations** * `detail=false, stream=false` : Returns compact OpenAI-compatible JSON ( `choices` , `usage` , `id` ). * `detail=false, stream=true` : Returns an OpenAI-compatible SSE stream with answer deltas and `[DONE]` . * `detail=true, stream=false` : Includes `responseData` (per-node execution details) and `newVariables` in the JSON response. * `detail=true, stream=true` : Returns a multi-event SSE stream ( `answer` , `flowNodeStatus` , `flowNodeResponse` , `workflowDuration` , etc.). Share-link calls use the same per-node SSE protocol with public fields filtered by share settings ( `showCite` , `showRunningStatus` , `showSkillReferences` , and download permissions). **Interactive Nodes** If the workflow includes interactive nodes, set `detail=true` : * `stream=true` : Read interactive payloads from `event: interactive` . * `stream=false` : Read the `interactive` entry from `choices[].message.content` . Non-streaming `interactive` payloads unwrap nested `children` / `loop` / `tool` wrappers down to the innermost prompt and strip internal runtime fields ( `entryNodeIds` , `memoryEdges` , `nodeOutputs` ). SSE frames may preserve wrapper envelopes whose inner payload sits under `params.childrenResponse` . To resume execution after rendering the interactive prompt to the user, call this endpoint again with the same `chatId` : * User selection: Send the selected option value directly as the user message `content` . * Form input: Serialize the form key-value map as a JSON string in the user message `content` . ## Request Parameters ### Request Body ( `application/json` ) #### Shared Parameters Across Branches | Field | Type | Required | Default | Constraints & Description | | --------------------- | ---------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------- | | `chatId` | `string` | No | - | Chat session ID; automatically generated if omitted or empty. maxLength: 1024 | | `metadata` | `object` | No | - | Metadata | | `messages` | `object[]` | No | `[]` | Messages list | | `stream` | `boolean` | No | `false` | Whether to stream the response via SSE | | `variables` | `object` | No | `{}` | Global workflow variables or plugin inputs | | `responseChatItemId` | `string` | No | - | Custom ID for the assistant response message; auto-generated if omitted | | `detail` | `boolean` | No | `false` | Whether to include detailed execution metadata such as `responseData` , `reasoning_content` , `tool_calls` , and `newVariables` | | `retainDatasetCite` | `boolean` | No | `false` | Whether to retain dataset citations | | `showSkillReferences` | `boolean` | No | `false` | Whether to include skill references | **Mutually Exclusive Branches ( `anyOf` )** * **App Chat** Identify the application via `appId` and authenticate with an API Key or login session. Personal API Key requests may omit `body.appId` when using an `apiKey-appId` header suffix or legacy bound key; login sessions must provide `appId` . App API Keys do not support `authProxy` . | Field | Type | Required | Default | Constraints & Description | | ------- | -------- | -------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `appId` | `string` | Yes | - | Application ID. App API Keys ignore this field and SDK suffixes in favor of the bound app; personal keys resolve in order: `body.appId` > `Authorization` `key-appId` suffix. The suffix is never persisted. pattern: `^[0-9a-fA-F]{24}$` | **Default Identity** : Omit `customUid` and `authProxy` to execute using the team member identity associated with the credential. **Custom end user ( `customUid` )**: Tag end users from your own system via `customUid` without changing the authenticating member or permissions. Passed as workflow `userId` and used to scope chat management. | Field | Type | Required | Default | Constraints & Description | | ----------- | -------- | -------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `customUid` | `string` | Yes | - | End user ID supplied by your backend during API Key calls (FastGPT >= 4.18.0, max 1024 chars); does not alter member permissions and is mutually exclusive with `authProxy` . New chats treat empty string as default user; existing chats bound to a `customUid` reject missing, empty, or mismatched values. Share-link calls use `outLinkAuthData.outLinkUid` instead. maxLength: 1024 | **Proxy Team Member ( `authProxy` )**: Act on behalf of another member in the same team via `authProxy` . Available only on personal API keys with `authProxy` enabled; mutually exclusive with `customUid` . | Field | Type | Required | Default | Constraints & Description | | -------------------- | -------- | -------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `authProxy` | `object` | Yes | - | Team member identity to proxy via API Key (mutually exclusive with `customUid` ; unsupported on share-link chats). Specify `tmbId` or `username` ; if both are sent, `tmbId` takes precedence without falling back to `username` on invalid ID. | | `authProxy.tmbId` | `string` | Yes | - | **Branch: By Team Member ID** . Proxied team member ID ( `tmbId` ), takes precedence over `username` . pattern: `^[0-9a-fA-F]{24}$` | | `authProxy.username` | `string` | Yes | - | **Branch: By Username** . Proxied team member username. minLength: 1; maxLength: 128 | * **App API Key (no appId required)** When using an app-bound App API Key, `appId` is omitted and resolved from the key binding; supports default identity or `customUid` (not `authProxy` ). Compatible with personal key `key-appId` SDK suffixes (which follow App Chat proxy rules); regular personal keys and login sessions require `appId` . **Default Identity** : Omit `customUid` and `authProxy` to execute using the team member identity associated with the credential. **Custom end user ( `customUid` )**: Tag end users from your own system via `customUid` without changing the authenticating member or permissions. Passed as workflow `userId` and used to scope chat management. | Field | Type | Required | Default | Constraints & Description | | ----------- | -------- | -------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `customUid` | `string` | Yes | - | End user ID supplied by your backend during API Key calls (FastGPT >= 4.18.0, max 1024 chars); does not alter member permissions and is mutually exclusive with `authProxy` . New chats treat empty string as default user; existing chats bound to a `customUid` reject missing, empty, or mismatched values. Share-link calls use `outLinkAuthData.outLinkUid` instead. maxLength: 1024 | * **Share-Link Chat** Resolves the app via `outLinkAuthData` , scoping the end user by `outLinkUid` . Takes precedence over `appId` and header auth without fallback on failure; protected share links still require login token/cookie and do not support `authProxy` . | Field | Type | Required | Default | Constraints & Description | | ---------------------------- | -------- | -------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | `outLinkAuthData` | `object` | Yes | - | Share-link auth payload containing `shareId` and `outLinkUid` . Overrides `appId` ; protected links still verify login session cookies/tokens. | | `outLinkAuthData.shareId` | `string` | Yes | - | Share link ID. minLength: 1 | | `outLinkAuthData.outLinkUid` | `string` | Yes | - | External share user ID. minLength: 1 | #### Polymorphic Field: `messages` * **Variant 1** ( `role="system"` ): `role` , `content` , `name` , `reasoning_content` , `dataId` , `hideInUI` * **Variant 2** ( `role="developer"` ): `role` , `content` , `name` , `reasoning_content` , `dataId` , `hideInUI` * **Variant 3** ( `role="user"` ): `role` , `content` , `name` , `reasoning_content` , `dataId` , `hideInUI` * **Variant 4** ( `role="assistant"` ): `role` , `content` , `tool_calls` , `interactive` , `audio` , `function_call` , `refusal` , `name` * **Variant 5** ( `role="tool"` ): `role` , `content` , `tool_call_id` , `name` , `reasoning_content` , `dataId` , `hideInUI` * **Variant 6** ( `role="function"` ): `role` , `content` , `name` , `reasoning_content` , `dataId` , `hideInUI` ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X POST "https://cloud.fastgpt.io/api/v2/chat/completions" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ --data-raw '{ "appId": "68ad85a7463006c963799a05" }' ``` ### Minimal Valid JSON Body ```json { "appId": "68ad85a7463006c963799a05" } ``` ## Response Schema & Examples ### HTTP 200 **Content-Type** : `application/json` | Field | Type | Required | Default | Constraints & Description | | ------------------------------------- | ----------------- | -------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | `string` | Yes | - | Conversation ID ( `chatId` ) | | `title` | `string` | No | - | Auto-generated title returned when naming an untitled conversation | | `model` | `""` | Yes | - | Model name (always empty string in v1). Fixed: `""` | | `usage` | `object` | Yes | - | Token usage summary (placeholder in v1; compute actual tokens from `responseData` when `detail=true` ) | | `usage.prompt_tokens` | `1` | Yes | - | Fixed placeholder `1` ; compute per-node token usage from `responseData` when `detail=true` . Fixed: `1` | | `usage.completion_tokens` | `1` | Yes | - | Fixed placeholder `1` ; compute per-node token usage from `responseData` when `detail=true` . Fixed: `1` | | `usage.total_tokens` | `1` | Yes | - | Fixed placeholder `1` ; compute per-node token usage from `responseData` when `detail=true` . Fixed: `1` | | `choices` | `object[]` | Yes | - | Completion choices list | | `choices[].message` | `object` | Yes | - | Assistant message | | `choices[].message.role` | `"assistant"` | Yes | - | Message role. Fixed: `"assistant"` | | `choices[].message.content` | `string \| array` | Yes | - | Message content. Plain string for standard replies, or an array of typed blocks ( `text` , `interactive` , `tool` , `file` , `reasoning` ) when `detail=true` or an interactive Node.js pauses execution. v1 adds an explicit `type` field on each block while v2 omits it; interactive items strip internal runtime fields. | | `choices[].message.reasoning_content` | `string` | No | - | Reasoning trace content (for reasoning models only) | | `choices[].finish_reason` | `string` | Yes | - | Completion finish reason, e.g. `stop` | | `choices[].index` | `number` | Yes | - | Choice index | | `responseData` | `object[]` | No | - | Per-node workflow execution details (returned only when `detail=true` ), including `moduleName` , `moduleType` , `runningTime` , `quoteList` , etc. | | `newVariables` | `object` | No | - | Workflow variables updated during execution (returned only when `detail=true` ) | **Content-Type** : `text/event-stream` ### HTTP 409 Rejects the request when the conversation already has an active generation without persisting the rejected message. Non-streaming calls return HTTP 409; streaming calls emit the same payload on `event: error` . Use `data.responseChatItemId` to resume the active assistant message (or reuse the latest AI message when `data.reusePreviousAi=true` ). **Content-Type** : `application/json` | Field | Type | Required | Default | Constraints & Description | | ------------------------- | -------------------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------- | | `code` | `504001` | Yes | - | Fixed: `504001` | | `statusText` | `"chatIsGenerating"` | Yes | - | Fixed: `"chatIsGenerating"` | | `message` | `string` | Yes | - | Localized display error message; use `code` or `statusText` for programmatic handling. Defaults to English when no translation is available. | | `data` | `object` | Yes | - | - | | `data.responseChatItemId` | `string` | No | - | Active assistant message ID currently generating on the server; clients should resume tracking this ID. minLength: 1 | | `data.reusePreviousAi` | `true` | No | - | Indicates an interactive resume reusing the latest assistant message; refresh records before resuming. Fixed: `true` | ### Non-Streaming JSON Response Examples (v2) #### Compact JSON `detail=false, stream=false` ; returns only core reply fields. ```json { "id": "adsfasf", "title": "Suzume Director", "model": "", "usage": { "prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 1 }, "choices": [ { "message": { "role": "assistant", "content": "Makoto Shinkai directed the film Suzume." }, "finish_reason": "stop", "index": 0 } ] } ``` #### Detailed JSON `detail=true, stream=false` ; includes `responseData` and `newVariables` . ```json { "responseData": [ { "moduleName": "Dataset Search", "price": 1.2000000000000002, "model": "Embedding-2", "tokens": 6, "similarity": 0.61, "limit": 3 }, { "moduleName": "AI Chat", "price": 454.5, "model": "FastAI-4k", "tokens": 303, "question": "Who is the director?", "answer": "Makoto Shinkai directed the film Suzume.", "maxToken": 2050, "quoteList": [ { "dataset_id": "646627f4f7b896cfd8910e38", "id": "8099", "q": "Who is the protagonist of this film?", "a": "The protagonist is a young girl named Suzume.", "source": "Manual Edit" }, { "dataset_id": "646627f4f7b896cfd8910e38", "id": "19339", "q": "Who directed the film Suzume?", "a": "Makoto Shinkai directed the film Suzume.", "source": "Manual Edit" } ], "completeMessages": [ { "obj": "System", "value": "Knowledge base context:\n1. [Who is the protagonist of this film?\nThe protagonist is a young girl named Suzume.]\n2. [Who directed the film Suzume?\nMakoto Shinkai directed the film Suzume.]\n" }, { "obj": "Human", "value": "Who is the director?" }, { "obj": "AI", "value": "Makoto Shinkai directed the film Suzume." } ] } ], "newVariables": { "uid": "asdfadsfasfd2323", "name": "Alice" }, "id": "", "title": "Suzume Director", "model": "", "usage": { "prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 1 }, "choices": [ { "message": { "role": "assistant", "content": "Makoto Shinkai directed the film Suzume." }, "finish_reason": "stop", "index": 0 } ] } ``` #### User Selection `detail=true` ; read the `interactive` display configuration from `choices[].message.content` . ```json { "id": "chatId", "model": "", "usage": { "prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 1 }, "choices": [ { "message": { "role": "assistant", "content": [ { "interactive": { "type": "userSelect", "params": { "description": "Test prompt", "userSelectOptions": [ { "value": "Confirm", "key": "option1" }, { "value": "Cancel", "key": "option2" } ] } } } ] }, "finish_reason": "stop", "index": 0 } ] } ``` #### Form Input `detail=true` ; submit serialized JSON keyed by form field names while keeping the same `chatId` . ```json { "id": "chatId", "model": "", "usage": { "prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 1 }, "choices": [ { "message": { "role": "assistant", "content": [ { "interactive": { "type": "userInput", "params": { "description": "Test prompt", "inputForm": [ { "type": "input", "key": "Test 1", "label": "Test 1", "description": "", "value": "", "defaultValue": "", "valueType": "string", "required": false, "list": [ { "label": "", "value": "" } ] }, { "type": "numberInput", "key": "Test 2", "label": "Test 2", "description": "", "value": "", "defaultValue": "", "valueType": "number", "required": false, "list": [ { "label": "", "value": "" } ] } ] } } } ] }, "finish_reason": "stop", "index": 0 } ] } ``` ### Streaming SSE Flow Examples (v2) #### Compact SSE `detail=false, stream=true` ; standard replies emit only `data:` frames followed by `[DONE]` . ```text data: {"choices":[{"delta":{"role":"assistant","content":""},"index":0,"finish_reason":null}]} data: {"choices":[{"delta":{"role":"assistant","content":"Makoto Shinkai "},"index":0,"finish_reason":null}]} data: {"choices":[{"delta":{"role":"assistant","content":"directed the film Suzume."},"index":0,"finish_reason":null}]} data: {"choices":[{"delta":{"role":"assistant","content":null},"index":0,"finish_reason":"stop"}]} data: [DONE] ``` #### Full Execution Stream `detail=true, stream=true` ; Node.js details arrive individually via `flowNodeResponse` . Frame ordering is illustrative and `chatTitle` may arrive earlier. ```text event: flowNodeStatus data: {"status":"running","name":"Dataset Search"} event: answer data: {"choices":[{"delta":{"role":"assistant","content":"Makoto Shinkai "},"index":0,"finish_reason":null}]} event: answer data: {"choices":[{"delta":{"role":"assistant","content":"directed the film Suzume."},"index":0,"finish_reason":null}]} event: flowNodeResponse data: {"id":"response-ai-1","nodeId":"ai-1","moduleType":"chatNode","moduleName":"AI Chat","runningTime":1.86,"textOutput":"Makoto Shinkai directed the film Suzume."} event: updateVariables data: {"lastQuestion":"Who is the director?","searchCount":1,"found":true,"movieNames":["Suzume"],"director":{"name":"Makoto Shinkai"},"nextPage":null} event: workflowDuration data: {"durationSeconds":2.41} event: chatTitle data: {"title":"Suzume Director"} event: answer data: {"choices":[{"delta":{"role":"assistant","content":null},"index":0,"finish_reason":"stop"}]} event: answer data: [DONE] ``` #### User Selection `detail=true` ; display options upon receiving `interactive` , then submit the chosen value to resume. ```text event: interactive data: {"interactive":{"type":"userSelect","params":{"description":"Test prompt","userSelectOptions":[{"value":"Confirm","key":"option1"},{"value":"Cancel","key":"option2"}]}}} event: answer data: [DONE] ``` #### Form Input `detail=true` ; render the form upon receiving `interactive` , then submit a serialized JSON string to resume. ```text event: interactive data: {"interactive":{"type":"userInput","params":{"description":"Test prompt","inputForm":[{"type":"input","key":"Test 1","label":"Test 1","description":"","value":"","defaultValue":"","valueType":"string","required":false,"list":[{"label":"","value":""}]},{"type":"numberInput","key":"Test 2","label":"Test 2","description":"","value":"","defaultValue":"","valueType":"number","required":false,"list":[{"label":"","value":""}]}]}}} event: answer data: [DONE] ``` ### SSE `event` Types Reference (v2) #### `answer` · Answer Delta Includes empty heartbeat deltas, answer text, `reasoning_content` deltas, `stop` finish chunks, and `[DONE]` markers. ```text : 1. Empty heartbeat event: answer data: {"choices":[{"delta":{"role":"assistant","content":""},"index":0,"finish_reason":null}]} : 2. Answer text event: answer data: {"choices":[{"delta":{"role":"assistant","content":"Makoto Shinkai directed the film Suzume."},"index":0,"finish_reason":null}]} : 3. Reasoning delta event: answer data: {"choices":[{"delta":{"role":"assistant","reasoning_content":"Verify the director of Suzume first."},"index":0,"finish_reason":null}]} : 4. Stop finish chunk event: answer data: {"choices":[{"delta":{"role":"assistant","content":null},"index":0,"finish_reason":"stop"}]} : 5. End of stream event: answer data: [DONE] ``` #### `fastAnswer` · Specified Reply Emitted for immediate outputs such as Specified Reply nodes; includes text deltas and a stop chunk. ```text : 1. Specified reply text event: fastAnswer data: {"choices":[{"delta":{"role":"assistant","content":"Looking up relevant resources."},"index":0,"finish_reason":null}]} : 2. Specified reply stop chunk event: fastAnswer data: {"choices":[{"delta":{"role":"assistant","content":null},"index":0,"finish_reason":"stop"}]} ``` #### `flowNodeStatus` · Node.js Status Emitted when a workflow Node.js starts running; governed by `showRunningStatus` on share links. ```text event: flowNodeStatus data: {"status":"running","name":"Dataset Search"} ``` #### `flowNodeResponse` · Node.js Response Emitted per Node.js in v2 for top-level and child nodes; group by `id` and `parentId` (top-level when `parentId` is omitted). ```text : 1. Top-level node event: flowNodeResponse data: {"id":"response-ai-1","nodeId":"ai-1","moduleType":"chatNode","moduleName":"AI Chat","runningTime":1.86,"textOutput":"Makoto Shinkai directed the film Suzume."} : 2. Nested child node event: flowNodeResponse data: {"id":"response-ai-child-1","nodeId":"ai-1","moduleType":"chatNode","moduleName":"AI Chat","runningTime":1.86,"textOutput":"Makoto Shinkai directed the film Suzume.","parentId":"response-agent-1"} ``` #### `toolCall` · Tool Call Initializes a tool call card; shows both standard calls and `hideDetails` calls with hidden parameters. ```text : 1. Standard tool call event: toolCall data: {"tool":{"id":"call-search-1","toolName":"Dataset Search","toolAvatar":"/imgs/workflow/db.png","functionName":"dataset_search","params":"{\"query\":\"Suzume director\"}"},"responseValueId":"call-search-1"} : 2. Tool call hiding params and response details event: toolCall data: {"tool":{"id":"call-search-1","toolName":"Dataset Search","toolAvatar":"/imgs/workflow/db.png","functionName":"dataset_search","params":"","hideDetails":true},"responseValueId":"call-search-1"} ``` #### `toolParams` · Tool Params Delta Appends or merges tool arguments keyed by `tool.id` ; does not indicate execution completion. ```text event: toolParams data: {"tool":{"id":"call-search-1","params":"{\"query\":\"Suzume director\"}"},"responseValueId":"call-search-1"} ``` #### `toolResponse` · Tool Response Delivers the tool execution result keyed by `tool.id` ; `response` can be a string or `null` . ```text : 1. String response event: toolResponse data: {"tool":{"id":"call-search-1","response":"Director: Makoto Shinkai"},"responseValueId":"call-search-1"} : 2. Empty response event: toolResponse data: {"tool":{"id":"call-search-1","response":null},"responseValueId":"call-search-1"} ``` #### `updateVariables` · Variable Updates Updates workflow variables for the current turn; values may be strings, numbers, booleans, arrays, objects, or `null` . ```text event: updateVariables data: {"lastQuestion":"Who is the director?","searchCount":1,"found":true,"movieNames":["Suzume"],"director":{"name":"Makoto Shinkai"},"nextPage":null} ``` #### `workflowDuration` · Workflow Duration Total elapsed execution time for the turn, with `durationSeconds` measured in seconds. ```text event: workflowDuration data: {"durationSeconds":2.41} ``` #### `chatTitle` · Chat Title Emitted only when `detail=true` and an untitled conversation receives an auto-generated title; never overwrites manual titles. ```text event: chatTitle data: {"title":"Suzume Director"} ``` #### `interactive` · Interactive Prompt Demonstrates user selection, form input, agent follow-up questions, billing pause, and sub-workflow wrappers (read inner prompts from `params.childrenResponse` ). Internal runtime fields are omitted, and variants are mutually exclusive. ```text : 1. User selection: userSelect event: interactive data: {"interactive":{"type":"userSelect","params":{"description":"Test prompt","userSelectOptions":[{"value":"Confirm","key":"option1"},{"value":"Cancel","key":"option2"}]}}} : 2. Form input: userInput event: interactive data: {"interactive":{"type":"userInput","params":{"description":"Test prompt","inputForm":[{"type":"input","key":"Test 1","label":"Test 1","description":"","value":"","defaultValue":"","valueType":"string","required":false,"list":[{"label":"","value":""}]},{"type":"numberInput","key":"Test 2","label":"Test 2","description":"","value":"","defaultValue":"","valueType":"number","required":false,"list":[{"label":"","value":""}]}]}}} : 3. Agent follow-up: agentAsk event: interactive data: {"interactive":{"type":"agentAsk","params":{"toolCallId":"ask-1","arguments":"{\"reason\":\"Confirm the search scope to continue.\",\"blockerType\":\"user_choice\",\"questions\":[{\"question\":\"Which scope should be queried?\",\"options\":[{\"summary\":\"Current film only\",\"value\":\"current_movie\"},{\"summary\":\"All works by this director\",\"value\":\"all_movies\"}]}]}"}}} : 4. Payment pause: paymentPause event: interactive data: {"interactive":{"type":"paymentPause","params":{"description":"Insufficient credits. Please top up to continue."}}} : 5. Sub-workflow wrapper: childrenInteractive event: interactive data: {"interactive":{"type":"childrenInteractive","params":{"childrenResponse":{"type":"userSelect","params":{"description":"Test prompt","userSelectOptions":[{"value":"Confirm","key":"option1"},{"value":"Cancel","key":"option2"}]}}}}} : 6. Tool sub-workflow wrapper: toolChildrenInteractive event: interactive data: {"interactive":{"type":"toolChildrenInteractive","params":{"childrenResponse":{"type":"userInput","params":{"description":"Test prompt","inputForm":[{"type":"input","key":"Test 1","label":"Test 1","description":"","value":"","defaultValue":"","valueType":"string","required":false,"list":[{"label":"","value":""}]},{"type":"numberInput","key":"Test 2","label":"Test 2","description":"","value":"","defaultValue":"","valueType":"number","required":false,"list":[{"label":"","value":""}]}]}},"toolCallId":"call-search-1"}}} : 7. Loop sub-workflow wrapper: loopInteractive event: interactive data: {"interactive":{"type":"loopInteractive","params":{"childrenResponse":{"type":"userSelect","params":{"description":"Test prompt","userSelectOptions":[{"value":"Confirm","key":"option1"},{"value":"Cancel","key":"option2"}]}},"currentIndex":0,"loopResult":[]}}} : 8. Loop run wrapper: loopRunInteractive event: interactive data: {"interactive":{"type":"loopRunInteractive","params":{"childrenResponse":{"type":"userInput","params":{"description":"Test prompt","inputForm":[{"type":"input","key":"Test 1","label":"Test 1","description":"","value":"","defaultValue":"","valueType":"string","required":false,"list":[{"label":"","value":""}]},{"type":"numberInput","key":"Test 2","label":"Test 2","description":"","value":"","defaultValue":"","valueType":"number","required":false,"list":[{"label":"","value":""}]}]}},"iteration":1,"loopHistory":[]}}} ``` #### `planStatus` · Plan Generation Status Emitted only when planning is enabled; shows `generating` and `updating` statuses. ```text : 1. Generating plan event: planStatus data: {"planStatus":{"status":"generating"}} : 2. Updating plan event: planStatus data: {"planStatus":{"status":"updating"}} ``` #### `plan` · Agent Plan Identifies the plan with `plan.planId` and each step with `steps[].id` ; step statuses update during execution. ```text event: plan data: {"plan":{"planId":"plan-1","name":"Look up director info","steps":[{"id":"step-1","name":"Confirm film title","status":"done"},{"id":"step-2","name":"Search film references","status":"in_progress"},{"id":"step-3","name":"Compile director details","status":"pending"},{"id":"step-4","name":"Verify paid sources","status":"blocked","note":"Waiting for user authorization"},{"id":"step-5","name":"Add unrelated works","status":"skipped","note":"Out of scope"}]}} ``` #### `skillCall` · Skill Call Emitted when loading skill instructions, only when skill capabilities are enabled. ```text event: skillCall data: {"skill":{"id":"skill-call-1","skillName":"Reference Lookup","skillAvatar":"/icon/logo.svg","description":"Search related reference documents","skillMdPath":"/skills/search/SKILL.md"}} ``` #### `sandboxStatus` · Sandbox Status Shows visible sandbox lifecycle phases ( `ready` allows tool execution, `failed` may carry `message` , skill deployment phases may include `skillName` ). Phases represent distinct states rather than a fixed sequence. ```text : 1. Phase: checkExisting event: sandboxStatus data: {"sandboxId":"sandbox-1","phase":"checkExisting"} : 2. Phase: connecting event: sandboxStatus data: {"sandboxId":"sandbox-1","phase":"connecting","isWarmStart":true} : 3. Phase: fetchSkills event: sandboxStatus data: {"sandboxId":"sandbox-1","phase":"fetchSkills"} : 4. Phase: creatingContainer event: sandboxStatus data: {"sandboxId":"sandbox-1","phase":"creatingContainer"} : 5. Phase: deployingSkills event: sandboxStatus data: {"sandboxId":"sandbox-1","phase":"deployingSkills","skillName":"Reference Lookup"} : 6. Phase: downloadingPackage event: sandboxStatus data: {"sandboxId":"sandbox-1","phase":"downloadingPackage","skillName":"Reference Lookup"} : 7. Phase: uploadingPackage event: sandboxStatus data: {"sandboxId":"sandbox-1","phase":"uploadingPackage","skillName":"Reference Lookup"} : 8. Phase: extractingPackage event: sandboxStatus data: {"sandboxId":"sandbox-1","phase":"extractingPackage","skillName":"Reference Lookup"} : 9. Phase: lazyInit event: sandboxStatus data: {"sandboxId":"sandbox-1","phase":"lazyInit"} : 10. Phase: upgrading event: sandboxStatus data: {"sandboxId":"sandbox-1","phase":"upgrading"} : 11. Phase: ready event: sandboxStatus data: {"sandboxId":"sandbox-1","phase":"ready","isWarmStart":true} : 12. Phase: failed event: sandboxStatus data: {"sandboxId":"sandbox-1","phase":"failed","message":"Sandbox initialization failed. Please retry shortly."} ``` #### `error` · Stream Error Error emitted after the SSE stream opens, including plain `message` errors or structured business errors with `code` , `statusText` , and `data` . Do not rely on HTTP 200 alone. ```text : 1. Generic error event: error data: {"message":"Model request failed. Please retry shortly."} : 2. Business error event: error data: {"code":510003,"statusText":"runtimeUpgradeInProgress","message":"Sandbox upgrade in progress. Please retry shortly.","data":null,"httpStatus":409} ``` file: ./content/openapi/reference/chat-controller/v2-chat-stop.en.mdx url: https://doc.fastgpt.io/openapi/reference/chat-controller/v2-chat-stop title: Stop Chat Completion last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "Stop Chat Completion", "seoTitle": "Stop Chat Completion - POST /api/v2/chat/stop | FastGPT OpenAPI", "description": "Write a stop flag for an active FastGPT workflow chat session so execution halts at the next safe checkpoint." } ## Endpoint Overview * **Method** : `POST` * **Path** : `/api/v2/chat/stop` * **Module** : Chat / Chat Completions & Control * **Authentication** : `Authorization: Bearer `—Supports **App API Key** ( `appId` optional) and **Personal API Key** ( `appId` required); also supports `authProxy` team member proxy and `outLinkAuthData` share link (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E4%BC%9A%E8%AF%9D%E6%93%8D%E4%BD%9C/POST/v2/chat/stop) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E4%BC%9A%E8%AF%9D%E6%93%8D%E4%BD%9C/POST/v2/chat/stop` ) ## Description & Notes Writes a stop flag for an active conversation and returns immediately. Clients should abort the open stream upon receiving success. The workflow halts scheduling at the next safe checkpoint; non-interruptible in-flight nodes such as HTTP requests still wait for their current step to finish. ## Request Parameters ### Request Body ( `application/json` ) #### Shared Parameters Across Branches | Field | Type | Required | Default | Constraints & Description | | -------- | -------- | -------- | ------- | -------------------------------------- | | `chatId` | `string` | Yes | - | Chat ID. minLength: 1; maxLength: 1024 | **Mutually Exclusive Branches ( `anyOf` )** * **App Chat** Identify the conversation via `appId` . When both API Key and login session are supported, `Authorization` takes precedence over token/Cookie. | Field | Type | Required | Default | Constraints & Description | | ------------ | --------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `appId` | `string` | Yes | - | Application ID authenticated with the request header credentials allowed by this endpoint. pattern: `^[0-9a-fA-F]{24}$` | | `sourceType` | `string` (enum) | No | - | Session resource type associated with `appId` . Defaults to `app` ; pass the matching `sourceType` for assistant builder sessions. Allowed values: `app` , `chatAgentHelper` , `workflowBuilder` | **Default Identity** : Omit `customUid` and `authProxy` to execute using the team member identity associated with the credential. **Custom end user ( `customUid` )**: Tag end users from your own system via `customUid` without changing the authenticating member or permissions. Passed as workflow `userId` and used to scope chat management. | Field | Type | Required | Default | Constraints & Description | | ----------- | -------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `customUid` | `string` | Yes | - | Supported only for standard app API Key calls. Exact match against the external user ID ( `outLinkUid` , not `tmbId` ). Omit to keep full scope or pass to restrict reads, updates, and deletions (max 1024 chars, cannot be empty or `null` , does not change member identity). minLength: 1; maxLength: 1024 | **Proxy Team Member ( `authProxy` )**: Act on behalf of another member in the same team via `authProxy` . Available only on personal API keys with `authProxy` enabled; mutually exclusive with `customUid` . | Field | Type | Required | Default | Constraints & Description | | -------------------- | -------- | -------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `authProxy` | `object` | Yes | - | API Key proxy caller identity. Available only for personal keys with `authProxy` enabled; specify `tmbId` or `username` ( `tmbId` takes precedence without falling back to `username` on invalid ID). | | `authProxy.tmbId` | `string` | Yes | - | **Branch: By Team Member ID** . Proxied team member ID ( `tmbId` ), takes precedence over `username` . pattern: `^[0-9a-fA-F]{24}$` | | `authProxy.username` | `string` | Yes | - | **Branch: By Username** . Proxied team member username. minLength: 1; maxLength: 128 | * **Skill Debug Session** Identify the debug session via `skillId` (takes precedence over `appId` and ignores `sourceType` ), authenticated with allowed request header credentials. | Field | Type | Required | Default | Constraints & Description | | --------- | -------- | -------- | ------- | ------------------------------------------------------------------------------------------------------- | | `skillId` | `string` | Yes | - | Skill Edit debug ID authenticated with allowed request header credentials. pattern: `^[0-9a-fA-F]{24}$` | * **Share-Link Chat** Resolves the underlying app via `outLinkAuthData` , taking precedence over `skillId` and `appId` (ignoring `sourceType` ). Protected links still validate login cookies/tokens and never fall back to standard auth on failure. | Field | Type | Required | Default | Constraints & Description | | ---------------------------- | -------- | -------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | | `outLinkAuthData` | `object` | Yes | - | Share-link auth payload ( `shareId` / `outLinkUid` ). Overrides `skillId` and `appId` ; protected links still validate login session cookies/tokens. | | `outLinkAuthData.shareId` | `string` | Yes | - | Share link ID. minLength: 1 | | `outLinkAuthData.outLinkUid` | `string` | Yes | - | External share user ID. minLength: 1 | * **App API Key (no appId required)** When authorizing with an app-bound App API Key, omit `appId` and `sourceType` ; the server resolves the bound app with `sourceType` fixed to `app` . Personal keys and login sessions cannot omit `appId` , and an explicit `appId` does not override an App API Key binding. **Default Identity** : Omit `customUid` and `authProxy` to execute using the team member identity associated with the credential. **Custom end user ( `customUid` )**: Tag end users from your own system via `customUid` without changing the authenticating member or permissions. Passed as workflow `userId` and used to scope chat management. | Field | Type | Required | Default | Constraints & Description | | ----------- | -------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `customUid` | `string` | Yes | - | Supported only for standard app API Key calls. Exact match against the external user ID ( `outLinkUid` , not `tmbId` ). Omit to keep full scope or pass to restrict reads, updates, and deletions (max 1024 chars, cannot be empty or `null` , does not change member identity). minLength: 1; maxLength: 1024 | ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X POST "https://cloud.fastgpt.io/api/v2/chat/stop" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ --data-raw '{ "appId": "68ad85a7463006c963799a05", "chatId": "1234567890" }' ``` ### Minimal Valid JSON Body ```json { "appId": "68ad85a7463006c963799a05", "chatId": "1234567890" } ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Successfully wrote workflow stop flag **Content-Type** : `application/json` | Field | Type | Required | Default | Constraints & Description | | -------------------- | --------------- | -------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `success` | `boolean` | Yes | - | Whether the stop signal was written successfully | | `completed` | `boolean` | Yes | - | **Deprecated** . Whether full workflow teardown is confirmed; the endpoint returns immediately without waiting, so this is always `false` | | `chatGenerateStatus` | `number` (enum) | No | - | **Deprecated** . Legacy conservative generating flag for backward compatibility; does not mean new workflow nodes will keep scheduling. Allowed values: `0` , `1` | file: ./content/openapi/reference/chat-feedback/update-user-feedback.en.mdx url: https://doc.fastgpt.io/openapi/reference/chat-feedback/update-user-feedback title: Update User Chat Feedback last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "Update User Chat Feedback", "seoTitle": "Update User Chat Feedback - POST /api/core/chat/feedback/updateUserFeedback | FastGPT OpenAPI", "description": "Submit, update, or clear positive and negative user feedback notes on a specific AI message record." } ## Endpoint Overview * **Method** : `POST` * **Path** : `/api/core/chat/feedback/updateUserFeedback` * **Module** : Chat / Chat Feedback * **Authentication** : `Authorization: Bearer `—Supports **App API Key** ( `appId` optional) and **Personal API Key** ( `appId` required); also supports `authProxy` team member proxy and `outLinkAuthData` share link (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E5%8F%8D%E9%A6%88%E7%AE%A1%E7%90%86/POST/core/chat/feedback/updateUserFeedback) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E5%8F%8D%E9%A6%88%E7%AE%A1%E7%90%86/POST/core/chat/feedback/updateUserFeedback` ) ## Description & Notes Add, update, or clear positive or negative user feedback on a chat message. ## Request Parameters ### Request Body ( `application/json` ) #### Shared Parameters Across Branches | Field | Type | Required | Default | Constraints & Description | | ------------------ | ---------------- | -------- | ------- | -------------------------------------- | | `chatId` | `string` | Yes | - | Chat ID. minLength: 1; maxLength: 1024 | | `dataId` | `string` | Yes | - | Message data ID. minLength: 1 | | `userGoodFeedback` | `string \| null` | No | - | Positive user feedback text | | `userBadFeedback` | `string \| null` | No | - | Negative user feedback text | **Mutually Exclusive Branches ( `anyOf` )** * **App Chat** Identify the conversation via `appId` . When both API Key and login session are supported, `Authorization` takes precedence over token/Cookie. | Field | Type | Required | Default | Constraints & Description | | ------------ | --------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `appId` | `string` | Yes | - | Application ID authenticated with the request header credentials allowed by this endpoint. pattern: `^[0-9a-fA-F]{24}$` | | `sourceType` | `string` (enum) | No | - | Session resource type associated with `appId` . Defaults to `app` ; pass the matching `sourceType` for assistant builder sessions. Allowed values: `app` , `chatAgentHelper` , `workflowBuilder` | **Default Identity** : Omit `customUid` and `authProxy` to execute using the team member identity associated with the credential. **Custom end user ( `customUid` )**: Tag end users from your own system via `customUid` without changing the authenticating member or permissions. Passed as workflow `userId` and used to scope chat management. | Field | Type | Required | Default | Constraints & Description | | ----------- | -------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `customUid` | `string` | Yes | - | Supported only for standard app API Key calls. Exact match against the external user ID ( `outLinkUid` , not `tmbId` ). Omit to keep full scope or pass to restrict reads, updates, and deletions (max 1024 chars, cannot be empty or `null` , does not change member identity). minLength: 1; maxLength: 1024 | **Proxy Team Member ( `authProxy` )**: Act on behalf of another member in the same team via `authProxy` . Available only on personal API keys with `authProxy` enabled; mutually exclusive with `customUid` . | Field | Type | Required | Default | Constraints & Description | | -------------------- | -------- | -------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `authProxy` | `object` | Yes | - | API Key proxy caller identity. Available only for personal keys with `authProxy` enabled; specify `tmbId` or `username` ( `tmbId` takes precedence without falling back to `username` on invalid ID). | | `authProxy.tmbId` | `string` | Yes | - | **Branch: By Team Member ID** . Proxied team member ID ( `tmbId` ), takes precedence over `username` . pattern: `^[0-9a-fA-F]{24}$` | | `authProxy.username` | `string` | Yes | - | **Branch: By Username** . Proxied team member username. minLength: 1; maxLength: 128 | * **Skill Debug Session** Identify the debug session via `skillId` (takes precedence over `appId` and ignores `sourceType` ), authenticated with allowed request header credentials. | Field | Type | Required | Default | Constraints & Description | | --------- | -------- | -------- | ------- | ------------------------------------------------------------------------------------------------------- | | `skillId` | `string` | Yes | - | Skill Edit debug ID authenticated with allowed request header credentials. pattern: `^[0-9a-fA-F]{24}$` | * **Share-Link Chat** Resolves the underlying app via `outLinkAuthData` , taking precedence over `skillId` and `appId` (ignoring `sourceType` ). Protected links still validate login cookies/tokens and never fall back to standard auth on failure. | Field | Type | Required | Default | Constraints & Description | | ---------------------------- | -------- | -------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | | `outLinkAuthData` | `object` | Yes | - | Share-link auth payload ( `shareId` / `outLinkUid` ). Overrides `skillId` and `appId` ; protected links still validate login session cookies/tokens. | | `outLinkAuthData.shareId` | `string` | Yes | - | Share link ID. minLength: 1 | | `outLinkAuthData.outLinkUid` | `string` | Yes | - | External share user ID. minLength: 1 | * **App API Key (no appId required)** When authorizing with an app-bound App API Key, omit `appId` and `sourceType` ; the server resolves the bound app with `sourceType` fixed to `app` . Personal keys and login sessions cannot omit `appId` , and an explicit `appId` does not override an App API Key binding. **Default Identity** : Omit `customUid` and `authProxy` to execute using the team member identity associated with the credential. **Custom end user ( `customUid` )**: Tag end users from your own system via `customUid` without changing the authenticating member or permissions. Passed as workflow `userId` and used to scope chat management. | Field | Type | Required | Default | Constraints & Description | | ----------- | -------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `customUid` | `string` | Yes | - | Supported only for standard app API Key calls. Exact match against the external user ID ( `outLinkUid` , not `tmbId` ). Omit to keep full scope or pass to restrict reads, updates, and deletions (max 1024 chars, cannot be empty or `null` , does not change member identity). minLength: 1; maxLength: 1024 | ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X POST "https://cloud.fastgpt.io/api/core/chat/feedback/updateUserFeedback" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ --data-raw '{ "appId": "68ad85a7463006c963799a05", "chatId": "chat123", "dataId": "data123" }' ``` ### Minimal Valid JSON Body ```json { "appId": "68ad85a7463006c963799a05", "chatId": "chat123", "dataId": "data123" } ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Successfully updated user feedback **Content-Type** : `application/json` file: ./content/openapi/reference/chat-history/batch-delete.en.mdx url: https://doc.fastgpt.io/openapi/reference/chat-history/batch-delete title: Batch Delete Chat Histories last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "Batch Delete Chat Histories", "seoTitle": "Batch Delete Chat Histories - POST /api/core/chat/history/batchDelete | FastGPT OpenAPI", "description": "Permanently delete multiple chat sessions along with their messages, response records, and uploaded chat files." } ## Endpoint Overview * **Method** : `POST` * **Path** : `/api/core/chat/history/batchDelete` * **Module** : Chat / Chat History * **Authentication** : `Authorization: Bearer `—Supports **App API Key** ( `appId` optional) and **Personal API Key** ( `appId` required) (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E4%BC%9A%E8%AF%9D%E7%AE%A1%E7%90%86/POST/core/chat/history/batchDelete) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E4%BC%9A%E8%AF%9D%E7%AE%A1%E7%90%86/POST/core/chat/history/batchDelete` ) ## Description & Notes Permanently deletes selected chat sessions along with their messages, response logs, and uploaded chat files (requires log management permission). ## Request Parameters ### Request Body ( `application/json` ) #### Shared Parameters Across Branches | Field | Type | Required | Default | Constraints & Description | | --------- | ---------- | -------- | ------- | ----------------------------- | | `chatIds` | `string[]` | Yes | - | List of chat IDs. minItems: 1 | **Mutually Exclusive Branches ( `anyOf` )** * **App Chat** Identify the conversation via `appId` . When both API Key and login session are supported, `Authorization` takes precedence over token/Cookie. | Field | Type | Required | Default | Constraints & Description | | ------------ | --------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `appId` | `string` | Yes | - | Application ID authenticated with the request header credentials allowed by this endpoint. pattern: `^[0-9a-fA-F]{24}$` | | `sourceType` | `string` (enum) | No | - | Session resource type associated with `appId` . Defaults to `app` ; pass the matching `sourceType` for assistant builder sessions. Allowed values: `app` , `chatAgentHelper` , `workflowBuilder` | * **Skill Debug Session** Identify the debug session via `skillId` (takes precedence over `appId` and ignores `sourceType` ), authenticated with allowed request header credentials. | Field | Type | Required | Default | Constraints & Description | | --------- | -------- | -------- | ------- | ------------------------------------------------------------------------------------------------------- | | `skillId` | `string` | Yes | - | Skill Edit debug ID authenticated with allowed request header credentials. pattern: `^[0-9a-fA-F]{24}$` | * **App API Key (no appId required)** When authorizing with an app-bound App API Key, omit `appId` and `sourceType` ; the server resolves the bound app with `sourceType` fixed to `app` . Personal keys and login sessions cannot omit `appId` , and an explicit `appId` does not override an App API Key binding. No extra branch-specific fields are required. ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X POST "https://cloud.fastgpt.io/api/core/chat/history/batchDelete" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ --data-raw '{ "appId": "68ad85a7463006c963799a05", "chatIds": [ "chat_123456", "chat_789012" ] }' ``` ### Minimal Valid JSON Body ```json { "appId": "68ad85a7463006c963799a05", "chatIds": ["chat_123456", "chat_789012"] } ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Successfully deleted chat session Returns the standard FastGPT success envelope ( `{ "code": 200, "statusText": "", "message": "", "data": ... }` ). The exact `data` payload schema is not declared in this OpenAPI contract; refer to the status description above or inspect runtime responses. file: ./content/openapi/reference/chat-history/clear-histories.en.mdx url: https://doc.fastgpt.io/openapi/reference/chat-history/clear-histories title: Clear Chat Histories last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "Clear Chat Histories", "seoTitle": "Clear Chat Histories - DELETE /api/core/chat/history/clearHistories | FastGPT OpenAPI", "description": "Soft-delete all conversation histories under the specified app, skill debug session, customUid, or share link context." } ## Endpoint Overview * **Method** : `DELETE` * **Path** : `/api/core/chat/history/clearHistories` * **Module** : Chat / Chat History * **Authentication** : `Authorization: Bearer `—Supports **App API Key** ( `appId` optional) and **Personal API Key** ( `appId` required); also supports `authProxy` team member proxy and `outLinkAuthData` share link (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E4%BC%9A%E8%AF%9D%E7%AE%A1%E7%90%86/DELETE/core/chat/history/clearHistories) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E4%BC%9A%E8%AF%9D%E7%AE%A1%E7%90%86/DELETE/core/chat/history/clearHistories` ) ## Description & Notes Soft-deletes all chat sessions under the target context. ## Request Parameters ### Query Parameters **Mutually Exclusive Branches ( `anyOf` )** * **App Chat** Identify the conversation via `appId` . When both API Key and login session are supported, `Authorization` takes precedence over token/Cookie. | Field | Type | Required | Default | Constraints & Description | | ------------ | --------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `appId` | `string` | Yes | - | Application ID authenticated with the request header credentials allowed by this endpoint. pattern: `^[0-9a-fA-F]{24}$` | | `sourceType` | `string` (enum) | No | - | Session resource type associated with `appId` . Defaults to `app` ; pass the matching `sourceType` for assistant builder sessions. Allowed values: `app` , `chatAgentHelper` , `workflowBuilder` | **Default Identity** : Omit `customUid` and `authProxy` to execute using the team member identity associated with the credential. **Custom end user ( `customUid` )**: Tag end users from your own system via `customUid` without changing the authenticating member or permissions. Passed as workflow `userId` and used to scope chat management. | Field | Type | Required | Default | Constraints & Description | | ----------- | -------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `customUid` | `string` | Yes | - | Supported only for standard app API Key calls. Exact match against the external user ID ( `outLinkUid` , not `tmbId` ). Omit to keep full scope or pass to restrict reads, updates, and deletions (max 1024 chars, cannot be empty or `null` , does not change member identity). minLength: 1; maxLength: 1024 | **Proxy Team Member ( `authProxy` )**: Act on behalf of another member in the same team via `authProxy` . Available only on personal API keys with `authProxy` enabled; mutually exclusive with `customUid` . | Field | Type | Required | Default | Constraints & Description | | ----------- | -------- | -------- | ------- | -------------------------------------------------------------------------------------- | | `authProxy` | `string` | Yes | - | JSON-serialized proxy identity, e.g. `{"tmbId":"member-id"}` or `{"username":"alice"}` | * **Skill Debug Session** Identify the debug session via `skillId` (takes precedence over `appId` and ignores `sourceType` ), authenticated with allowed request header credentials. | Field | Type | Required | Default | Constraints & Description | | --------- | -------- | -------- | ------- | ------------------------------------------------------------------------------------------------------- | | `skillId` | `string` | Yes | - | Skill Edit debug ID authenticated with allowed request header credentials. pattern: `^[0-9a-fA-F]{24}$` | * **Share-Link Chat** Resolves the underlying app via `outLinkAuthData` , taking precedence over `skillId` and `appId` (ignoring `sourceType` ). Protected links still validate login cookies/tokens and never fall back to standard auth on failure. | Field | Type | Required | Default | Constraints & Description | | ----------------- | -------- | -------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `outLinkAuthData` | `string` | Yes | - | JSON-serialized share-link auth payload containing `shareId` and `outLinkUid` . Overrides `skillId` and `appId` ; protected links still check login session cookies/tokens. | * **App API Key (no appId required)** When authorizing with an app-bound App API Key, omit `appId` and `sourceType` ; the server resolves the bound app with `sourceType` fixed to `app` . Personal keys and login sessions cannot omit `appId` , and an explicit `appId` does not override an App API Key binding. **Default Identity** : Omit `customUid` and `authProxy` to execute using the team member identity associated with the credential. **Custom end user ( `customUid` )**: Tag end users from your own system via `customUid` without changing the authenticating member or permissions. Passed as workflow `userId` and used to scope chat management. | Field | Type | Required | Default | Constraints & Description | | ----------- | -------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `customUid` | `string` | Yes | - | Supported only for standard app API Key calls. Exact match against the external user ID ( `outLinkUid` , not `tmbId` ). Omit to keep full scope or pass to restrict reads, updates, and deletions (max 1024 chars, cannot be empty or `null` , does not change member identity). minLength: 1; maxLength: 1024 | ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X DELETE "https://cloud.fastgpt.io/api/core/chat/history/clearHistories?appId=68ad85a7463006c963799a05" \ -H "Authorization: Bearer YOUR_API_KEY" ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Successfully cleared chat histories Returns the standard FastGPT success envelope ( `{ "code": 200, "statusText": "", "message": "", "data": ... }` ). The exact `data` payload schema is not declared in this OpenAPI contract; refer to the status description above or inspect runtime responses. file: ./content/openapi/reference/chat-history/del-history.en.mdx url: https://doc.fastgpt.io/openapi/reference/chat-history/del-history title: Delete Chat History last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "Delete Chat History", "seoTitle": "Delete Chat History - DELETE /api/core/chat/history/delHistory | FastGPT OpenAPI", "description": "Soft-delete a single conversation record via query parameters without immediately purging underlying messages or files." } ## Endpoint Overview * **Method** : `DELETE` * **Path** : `/api/core/chat/history/delHistory` * **Module** : Chat / Chat History * **Authentication** : `Authorization: Bearer `—Supports **App API Key** ( `appId` optional) and **Personal API Key** ( `appId` required); also supports `authProxy` team member proxy and `outLinkAuthData` share link (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E4%BC%9A%E8%AF%9D%E7%AE%A1%E7%90%86/DELETE/core/chat/history/delHistory) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E4%BC%9A%E8%AF%9D%E7%AE%A1%E7%90%86/DELETE/core/chat/history/delHistory` ) ## Description & Notes Soft-deletes a single chat session without immediately removing underlying data. ## Request Parameters ### Query Parameters #### Shared Parameters Across Branches | Field | Type | Required | Default | Constraints & Description | | -------- | -------- | -------- | ------- | -------------------------------------- | | `chatId` | `string` | Yes | - | Chat ID. minLength: 1; maxLength: 1024 | **Mutually Exclusive Branches ( `anyOf` )** * **App Chat** Identify the conversation via `appId` . When both API Key and login session are supported, `Authorization` takes precedence over token/Cookie. | Field | Type | Required | Default | Constraints & Description | | ------------ | --------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `appId` | `string` | Yes | - | Application ID authenticated with the request header credentials allowed by this endpoint. pattern: `^[0-9a-fA-F]{24}$` | | `sourceType` | `string` (enum) | No | - | Session resource type associated with `appId` . Defaults to `app` ; pass the matching `sourceType` for assistant builder sessions. Allowed values: `app` , `chatAgentHelper` , `workflowBuilder` | **Default Identity** : Omit `customUid` and `authProxy` to execute using the team member identity associated with the credential. **Custom end user ( `customUid` )**: Tag end users from your own system via `customUid` without changing the authenticating member or permissions. Passed as workflow `userId` and used to scope chat management. | Field | Type | Required | Default | Constraints & Description | | ----------- | -------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `customUid` | `string` | Yes | - | Supported only for standard app API Key calls. Exact match against the external user ID ( `outLinkUid` , not `tmbId` ). Omit to keep full scope or pass to restrict reads, updates, and deletions (max 1024 chars, cannot be empty or `null` , does not change member identity). minLength: 1; maxLength: 1024 | **Proxy Team Member ( `authProxy` )**: Act on behalf of another member in the same team via `authProxy` . Available only on personal API keys with `authProxy` enabled; mutually exclusive with `customUid` . | Field | Type | Required | Default | Constraints & Description | | ----------- | -------- | -------- | ------- | -------------------------------------------------------------------------------------- | | `authProxy` | `string` | Yes | - | JSON-serialized proxy identity, e.g. `{"tmbId":"member-id"}` or `{"username":"alice"}` | * **Skill Debug Session** Identify the debug session via `skillId` (takes precedence over `appId` and ignores `sourceType` ), authenticated with allowed request header credentials. | Field | Type | Required | Default | Constraints & Description | | --------- | -------- | -------- | ------- | ------------------------------------------------------------------------------------------------------- | | `skillId` | `string` | Yes | - | Skill Edit debug ID authenticated with allowed request header credentials. pattern: `^[0-9a-fA-F]{24}$` | * **Share-Link Chat** Resolves the underlying app via `outLinkAuthData` , taking precedence over `skillId` and `appId` (ignoring `sourceType` ). Protected links still validate login cookies/tokens and never fall back to standard auth on failure. | Field | Type | Required | Default | Constraints & Description | | ----------------- | -------- | -------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `outLinkAuthData` | `string` | Yes | - | JSON-serialized share-link auth payload containing `shareId` and `outLinkUid` . Overrides `skillId` and `appId` ; protected links still check login session cookies/tokens. | * **App API Key (no appId required)** When authorizing with an app-bound App API Key, omit `appId` and `sourceType` ; the server resolves the bound app with `sourceType` fixed to `app` . Personal keys and login sessions cannot omit `appId` , and an explicit `appId` does not override an App API Key binding. **Default Identity** : Omit `customUid` and `authProxy` to execute using the team member identity associated with the credential. **Custom end user ( `customUid` )**: Tag end users from your own system via `customUid` without changing the authenticating member or permissions. Passed as workflow `userId` and used to scope chat management. | Field | Type | Required | Default | Constraints & Description | | ----------- | -------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `customUid` | `string` | Yes | - | Supported only for standard app API Key calls. Exact match against the external user ID ( `outLinkUid` , not `tmbId` ). Omit to keep full scope or pass to restrict reads, updates, and deletions (max 1024 chars, cannot be empty or `null` , does not change member identity). minLength: 1; maxLength: 1024 | ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X DELETE "https://cloud.fastgpt.io/api/core/chat/history/delHistory?appId=68ad85a7463006c963799a05&chatId=string" \ -H "Authorization: Bearer YOUR_API_KEY" ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Successfully deleted chat session Returns the standard FastGPT success envelope ( `{ "code": 200, "statusText": "", "message": "", "data": ... }` ). The exact `data` payload schema is not declared in this OpenAPI contract; refer to the status description above or inspect runtime responses. file: ./content/openapi/reference/chat-history/get-histories.en.mdx url: https://doc.fastgpt.io/openapi/reference/chat-history/get-histories title: List Chat Histories last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "List Chat Histories", "seoTitle": "List Chat Histories - POST /api/core/chat/history/getHistories | FastGPT OpenAPI", "description": "Retrieve paginated chat history records for an app, skill debug session, or share link with date range and source filtering." } ## Endpoint Overview * **Method** : `POST` * **Path** : `/api/core/chat/history/getHistories` * **Module** : Chat / Chat History * **Authentication** : `Authorization: Bearer `—Supports **App API Key** ( `appId` optional) and **Personal API Key** ( `appId` required); also supports `authProxy` team member proxy and `outLinkAuthData` share link (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E4%BC%9A%E8%AF%9D%E7%AE%A1%E7%90%86/POST/core/chat/history/getHistories) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E4%BC%9A%E8%AF%9D%E7%AE%A1%E7%90%86/POST/core/chat/history/getHistories` ) ## Description & Notes Retrieve paginated chat conversation histories. ## Request Parameters ### Request Body ( `application/json` ) #### Shared Parameters Across Branches | Field | Type | Required | Default | Constraints & Description | | ----------------- | -------- | -------- | ------- | ------------------------- | | `startCreateTime` | `string` | No | - | Creation time range start | | `endCreateTime` | `string` | No | - | Creation time range end | | `startUpdateTime` | `string` | No | - | Update time range start | | `endUpdateTime` | `string` | No | - | Update time range end | **Mutually Exclusive Branches ( `anyOf` )** * **App Chat** Identify the conversation via `appId` . When both API Key and login session are supported, `Authorization` takes precedence over token/Cookie. | Field | Type | Required | Default | Constraints & Description | | ------------ | --------------- | -------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `appId` | `string` | Yes | - | Application ID authenticated with the request header credentials allowed by this endpoint. pattern: `^[0-9a-fA-F]{24}$` | | `sourceType` | `string` (enum) | No | - | Session resource type associated with `appId` . Defaults to `app` ; pass the matching `sourceType` for assistant builder sessions. Allowed values: `app` , `chatAgentHelper` , `workflowBuilder` | | `source` | `string` (enum) | No | - | Chat source filter; App API Key requests automatically query the `api` source and ignore this field. Allowed values: `test` , `online` , `share` , `api` , `cronJob` , `feishu` , `official_account` , `wecom` , `wechat` , `mcp` , `dingtalk` , `unknown` | **Default Identity** : Omit `customUid` and `authProxy` to execute using the team member identity associated with the credential. **Custom end user ( `customUid` )**: Tag end users from your own system via `customUid` without changing the authenticating member or permissions. Passed as workflow `userId` and used to scope chat management. | Field | Type | Required | Default | Constraints & Description | | ----------- | -------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `customUid` | `string` | Yes | - | Supported only for standard app API Key calls. Exact match against the external user ID ( `outLinkUid` , not `tmbId` ). Omit to keep full scope or pass to restrict reads, updates, and deletions (max 1024 chars, cannot be empty or `null` , does not change member identity). minLength: 1; maxLength: 1024 | **Proxy Team Member ( `authProxy` )**: Act on behalf of another member in the same team via `authProxy` . Available only on personal API keys with `authProxy` enabled; mutually exclusive with `customUid` . | Field | Type | Required | Default | Constraints & Description | | -------------------- | -------- | -------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `authProxy` | `object` | Yes | - | API Key proxy caller identity. Available only for personal keys with `authProxy` enabled; specify `tmbId` or `username` ( `tmbId` takes precedence without falling back to `username` on invalid ID). | | `authProxy.tmbId` | `string` | Yes | - | **Branch: By Team Member ID** . Proxied team member ID ( `tmbId` ), takes precedence over `username` . pattern: `^[0-9a-fA-F]{24}$` | | `authProxy.username` | `string` | Yes | - | **Branch: By Username** . Proxied team member username. minLength: 1; maxLength: 128 | **Mutually Exclusive Branches ( `anyOf` )** * **Offset Pagination** Specify the 0-based starting offset; when both `offset` and `pageNum` are provided, `offset` takes precedence. | Field | Type | Required | Default | Constraints & Description | | ---------- | --------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | `offset` | `integer` | Yes | - | **Mutually Exclusive Group: Pagination Parameters** . 0-based offset. min: 0; max: 9007199254740991 | | `pageSize` | `integer` | No | `20` | **Mutually Exclusive Group: Pagination Parameters** . Items per page. Defaults to 20, capped at 500 (larger values are clamped to 500). max: 500 | * **Page-Number Pagination** Paginate by page number (starts at page 1); `pageSize` controls items per page. | Field | Type | Required | Default | Constraints & Description | | ---------- | --------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | `pageNum` | `integer` | No | `1` | **Mutually Exclusive Group: Pagination Parameters** . 1-based page number; ignored when `offset` is provided. max: 9007199254740991 | | `pageSize` | `integer` | No | `20` | **Mutually Exclusive Group: Pagination Parameters** . Items per page. Defaults to 20, capped at 500 (larger values are clamped to 500). max: 500 | * **Skill Debug Session** Identify the debug session via `skillId` (takes precedence over `appId` and ignores `sourceType` ), authenticated with allowed request header credentials. | Field | Type | Required | Default | Constraints & Description | | --------- | --------------- | -------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `skillId` | `string` | Yes | - | Skill Edit debug ID authenticated with allowed request header credentials. pattern: `^[0-9a-fA-F]{24}$` | | `source` | `string` (enum) | No | - | Chat source filter; App API Key requests automatically query the `api` source and ignore this field. Allowed values: `test` , `online` , `share` , `api` , `cronJob` , `feishu` , `official_account` , `wecom` , `wechat` , `mcp` , `dingtalk` , `unknown` | **Offset Pagination** : Specify the 0-based starting offset; when both `offset` and `pageNum` are provided, `offset` takes precedence. | Field | Type | Required | Default | Constraints & Description | | ---------- | --------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | `offset` | `integer` | Yes | - | **Mutually Exclusive Group: Pagination Parameters** . 0-based offset. min: 0; max: 9007199254740991 | | `pageSize` | `integer` | No | `20` | **Mutually Exclusive Group: Pagination Parameters** . Items per page. Defaults to 20, capped at 500 (larger values are clamped to 500). max: 500 | **Page-Number Pagination** : Paginate by page number (starts at page 1); `pageSize` controls items per page. | Field | Type | Required | Default | Constraints & Description | | ---------- | --------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | `pageNum` | `integer` | No | `1` | **Mutually Exclusive Group: Pagination Parameters** . 1-based page number; ignored when `offset` is provided. max: 9007199254740991 | | `pageSize` | `integer` | No | `20` | **Mutually Exclusive Group: Pagination Parameters** . Items per page. Defaults to 20, capped at 500 (larger values are clamped to 500). max: 500 | * **Share-Link Chat** Resolves the underlying app via `outLinkAuthData` , taking precedence over `skillId` and `appId` (ignoring `sourceType` ). Protected links still validate login cookies/tokens and never fall back to standard auth on failure. | Field | Type | Required | Default | Constraints & Description | | ---------------------------- | --------------- | -------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `outLinkAuthData` | `object` | Yes | - | Share-link auth payload ( `shareId` / `outLinkUid` ). Overrides `skillId` and `appId` ; protected links still validate login session cookies/tokens. | | `outLinkAuthData.shareId` | `string` | Yes | - | Share link ID. minLength: 1 | | `outLinkAuthData.outLinkUid` | `string` | Yes | - | External share user ID. minLength: 1 | | `source` | `string` (enum) | No | - | Chat source filter; App API Key requests automatically query the `api` source and ignore this field. Allowed values: `test` , `online` , `share` , `api` , `cronJob` , `feishu` , `official_account` , `wecom` , `wechat` , `mcp` , `dingtalk` , `unknown` | **Offset Pagination** : Specify the 0-based starting offset; when both `offset` and `pageNum` are provided, `offset` takes precedence. | Field | Type | Required | Default | Constraints & Description | | ---------- | --------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | `offset` | `integer` | Yes | - | **Mutually Exclusive Group: Pagination Parameters** . 0-based offset. min: 0; max: 9007199254740991 | | `pageSize` | `integer` | No | `20` | **Mutually Exclusive Group: Pagination Parameters** . Items per page. Defaults to 20, capped at 500 (larger values are clamped to 500). max: 500 | **Page-Number Pagination** : Paginate by page number (starts at page 1); `pageSize` controls items per page. | Field | Type | Required | Default | Constraints & Description | | ---------- | --------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | `pageNum` | `integer` | No | `1` | **Mutually Exclusive Group: Pagination Parameters** . 1-based page number; ignored when `offset` is provided. max: 9007199254740991 | | `pageSize` | `integer` | No | `20` | **Mutually Exclusive Group: Pagination Parameters** . Items per page. Defaults to 20, capped at 500 (larger values are clamped to 500). max: 500 | * **App API Key (no appId required)** When authorizing with an app-bound App API Key, omit `appId` and `sourceType` ; the server resolves the bound app with `sourceType` fixed to `app` . Personal keys and login sessions cannot omit `appId` , and an explicit `appId` does not override an App API Key binding. **Default Identity** : Omit `customUid` and `authProxy` to execute using the team member identity associated with the credential. **Custom end user ( `customUid` )**: Tag end users from your own system via `customUid` without changing the authenticating member or permissions. Passed as workflow `userId` and used to scope chat management. | Field | Type | Required | Default | Constraints & Description | | ----------- | -------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `customUid` | `string` | Yes | - | Supported only for standard app API Key calls. Exact match against the external user ID ( `outLinkUid` , not `tmbId` ). Omit to keep full scope or pass to restrict reads, updates, and deletions (max 1024 chars, cannot be empty or `null` , does not change member identity). minLength: 1; maxLength: 1024 | **Mutually Exclusive Branches ( `anyOf` )** * **Offset Pagination** Specify the 0-based starting offset; when both `offset` and `pageNum` are provided, `offset` takes precedence. | Field | Type | Required | Default | Constraints & Description | | ---------- | --------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | `offset` | `integer` | Yes | - | **Mutually Exclusive Group: Pagination Parameters** . 0-based offset. min: 0; max: 9007199254740991 | | `pageSize` | `integer` | No | `20` | **Mutually Exclusive Group: Pagination Parameters** . Items per page. Defaults to 20, capped at 500 (larger values are clamped to 500). max: 500 | * **Page-Number Pagination** Paginate by page number (starts at page 1); `pageSize` controls items per page. | Field | Type | Required | Default | Constraints & Description | | ---------- | --------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | `pageNum` | `integer` | No | `1` | **Mutually Exclusive Group: Pagination Parameters** . 1-based page number; ignored when `offset` is provided. max: 9007199254740991 | | `pageSize` | `integer` | No | `20` | **Mutually Exclusive Group: Pagination Parameters** . Items per page. Defaults to 20, capped at 500 (larger values are clamped to 500). max: 500 | ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X POST "https://cloud.fastgpt.io/api/core/chat/history/getHistories" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ --data-raw '{ "appId": "68ad85a7463006c963799a05", "offset": 0 }' ``` ### Minimal Valid JSON Body ```json { "appId": "68ad85a7463006c963799a05", "offset": 0 } ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Successfully retrieved chat history list **Content-Type** : `application/json` | Field | Type | Required | Default | Constraints & Description | | --------------------------- | --------------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------- | | `total` | `number` | Yes | `0` | - | | `list` | `object[]` | Yes | `[]` | - | | `list[].chatId` | `string` | Yes | - | maxLength: 1024 | | `list[].updateTime` | `string` | Yes | - | - | | `list[].customTitle` | `string` | No | - | - | | `list[].title` | `string` | Yes | - | - | | `list[].top` | `boolean` | No | - | - | | `list[].chatGenerateStatus` | `number` (enum) | No | - | Live generation status from Redis lease: `0` ( `generating` ), `1` ( `done` / idle). Allowed values: `0` , `1` | | `list[].hasBeenRead` | `boolean` | No | - | - | file: ./content/openapi/reference/chat-history/get-history-status.en.mdx url: https://doc.fastgpt.io/openapi/reference/chat-history/get-history-status title: Batch Get Chat History Status last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "Batch Get Chat History Status", "seoTitle": "Batch Get Chat History Status - POST /api/core/chat/history/getHistoryStatus | FastGPT OpenAPI", "description": "Batch fetch live generation lease status, read flags, and update timestamps for multiple chat IDs for sidebar polling." } ## Endpoint Overview * **Method** : `POST` * **Path** : `/api/core/chat/history/getHistoryStatus` * **Module** : Chat / Chat History * **Authentication** : `Authorization: Bearer `—Supports **App API Key** ( `appId` optional) and **Personal API Key** ( `appId` required); also supports `authProxy` team member proxy and `outLinkAuthData` share link (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E4%BC%9A%E8%AF%9D%E7%AE%A1%E7%90%86/POST/core/chat/history/getHistoryStatus) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E4%BC%9A%E8%AF%9D%E7%AE%A1%E7%90%86/POST/core/chat/history/getHistoryStatus` ) ## Description & Notes Batch reads Redis generation lease state, `hasBeenRead` , and `updateTime` by `chatId` for lightweight sidebar polling. Returns an error on read failure so callers can retain prior state and retry. ## Request Parameters ### Request Body ( `application/json` ) #### Shared Parameters Across Branches | Field | Type | Required | Default | Constraints & Description | | --------- | ---------- | -------- | ------- | ---------------------------------------------------------------- | | `chatIds` | `string[]` | Yes | - | List of chat IDs to check status for. minItems: 1; maxItems: 200 | **Mutually Exclusive Branches ( `anyOf` )** * **App Chat** Identify the conversation via `appId` . When both API Key and login session are supported, `Authorization` takes precedence over token/Cookie. | Field | Type | Required | Default | Constraints & Description | | ------------ | --------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `appId` | `string` | Yes | - | Application ID authenticated with the request header credentials allowed by this endpoint. pattern: `^[0-9a-fA-F]{24}$` | | `sourceType` | `string` (enum) | No | - | Session resource type associated with `appId` . Defaults to `app` ; pass the matching `sourceType` for assistant builder sessions. Allowed values: `app` , `chatAgentHelper` , `workflowBuilder` | **Default Identity** : Omit `customUid` and `authProxy` to execute using the team member identity associated with the credential. **Custom end user ( `customUid` )**: Tag end users from your own system via `customUid` without changing the authenticating member or permissions. Passed as workflow `userId` and used to scope chat management. | Field | Type | Required | Default | Constraints & Description | | ----------- | -------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `customUid` | `string` | Yes | - | Supported only for standard app API Key calls. Exact match against the external user ID ( `outLinkUid` , not `tmbId` ). Omit to keep full scope or pass to restrict reads, updates, and deletions (max 1024 chars, cannot be empty or `null` , does not change member identity). minLength: 1; maxLength: 1024 | **Proxy Team Member ( `authProxy` )**: Act on behalf of another member in the same team via `authProxy` . Available only on personal API keys with `authProxy` enabled; mutually exclusive with `customUid` . | Field | Type | Required | Default | Constraints & Description | | -------------------- | -------- | -------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `authProxy` | `object` | Yes | - | API Key proxy caller identity. Available only for personal keys with `authProxy` enabled; specify `tmbId` or `username` ( `tmbId` takes precedence without falling back to `username` on invalid ID). | | `authProxy.tmbId` | `string` | Yes | - | **Branch: By Team Member ID** . Proxied team member ID ( `tmbId` ), takes precedence over `username` . pattern: `^[0-9a-fA-F]{24}$` | | `authProxy.username` | `string` | Yes | - | **Branch: By Username** . Proxied team member username. minLength: 1; maxLength: 128 | * **Skill Debug Session** Identify the debug session via `skillId` (takes precedence over `appId` and ignores `sourceType` ), authenticated with allowed request header credentials. | Field | Type | Required | Default | Constraints & Description | | --------- | -------- | -------- | ------- | ------------------------------------------------------------------------------------------------------- | | `skillId` | `string` | Yes | - | Skill Edit debug ID authenticated with allowed request header credentials. pattern: `^[0-9a-fA-F]{24}$` | * **Share-Link Chat** Resolves the underlying app via `outLinkAuthData` , taking precedence over `skillId` and `appId` (ignoring `sourceType` ). Protected links still validate login cookies/tokens and never fall back to standard auth on failure. | Field | Type | Required | Default | Constraints & Description | | ---------------------------- | -------- | -------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | | `outLinkAuthData` | `object` | Yes | - | Share-link auth payload ( `shareId` / `outLinkUid` ). Overrides `skillId` and `appId` ; protected links still validate login session cookies/tokens. | | `outLinkAuthData.shareId` | `string` | Yes | - | Share link ID. minLength: 1 | | `outLinkAuthData.outLinkUid` | `string` | Yes | - | External share user ID. minLength: 1 | * **App API Key (no appId required)** When authorizing with an app-bound App API Key, omit `appId` and `sourceType` ; the server resolves the bound app with `sourceType` fixed to `app` . Personal keys and login sessions cannot omit `appId` , and an explicit `appId` does not override an App API Key binding. **Default Identity** : Omit `customUid` and `authProxy` to execute using the team member identity associated with the credential. **Custom end user ( `customUid` )**: Tag end users from your own system via `customUid` without changing the authenticating member or permissions. Passed as workflow `userId` and used to scope chat management. | Field | Type | Required | Default | Constraints & Description | | ----------- | -------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `customUid` | `string` | Yes | - | Supported only for standard app API Key calls. Exact match against the external user ID ( `outLinkUid` , not `tmbId` ). Omit to keep full scope or pass to restrict reads, updates, and deletions (max 1024 chars, cannot be empty or `null` , does not change member identity). minLength: 1; maxLength: 1024 | ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X POST "https://cloud.fastgpt.io/api/core/chat/history/getHistoryStatus" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ --data-raw '{ "appId": "68ad85a7463006c963799a05", "chatIds": [ "string" ] }' ``` ### Minimal Valid JSON Body ```json { "appId": "68ad85a7463006c963799a05", "chatIds": ["string"] } ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Success **Content-Type** : `application/json` | Field | Type | Required | Default | Constraints & Description | | --------------------------- | --------------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------- | | `list` | `object[]` | Yes | - | - | | `list[].chatId` | `string` | Yes | - | maxLength: 1024 | | `list[].updateTime` | `string` | Yes | - | - | | `list[].chatGenerateStatus` | `number` (enum) | No | - | Live generation status from Redis lease: `0` ( `generating` ), `1` ( `done` / idle). Allowed values: `0` , `1` | | `list[].hasBeenRead` | `boolean` | No | - | - | file: ./content/openapi/reference/chat-history/init.en.mdx url: https://doc.fastgpt.io/openapi/reference/chat-history/init title: Initialize Chat Session last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "Initialize Chat Session", "seoTitle": "Initialize Chat Session - GET /api/core/chat/init | FastGPT OpenAPI", "description": "Initialize an app or skill debug chat session and retrieve welcome text, variables, module settings, and conversation state." } ## Endpoint Overview * **Method** : `GET` * **Path** : `/api/core/chat/init` * **Module** : Chat / Chat History * **Authentication** : `Authorization: Bearer `—Supports **App API Key** ( `appId` optional) and **Personal API Key** ( `appId` required); also supports `authProxy` team member proxy (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E4%BC%9A%E8%AF%9D%E7%AE%A1%E7%90%86/GET/core/chat/init) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E4%BC%9A%E8%AF%9D%E7%AE%A1%E7%90%86/GET/core/chat/init` ) ## Description & Notes Initializes an application chat session or a Skill Edit debug session, returning chat configuration, variables, and existing conversation state. Pass either `appId` (app chat) or `skillId` (skill debug) together with `chatId` in Query parameters ( `skillId` takes precedence if both are provided). For builder assistant sessions, pass `appId` with `sourceType` ( `chatAgentHelper` or `workflowBuilder` ); omit `sourceType` for regular app chats. Share-link sessions use `GET /api/core/chat/outLink/init` with JSON-serialized `outLinkAuthData` . Starting or resuming a skill runtime sandbox uses `POST /api/core/ai/skill/runtime/init` . ## Request Parameters ### Query Parameters #### Shared Parameters Across Branches | Field | Type | Required | Default | Constraints & Description | | --------------------- | --------- | -------- | ------- | -------------------------------------- | | `chatId` | `string` | Yes | - | Chat ID. minLength: 1; maxLength: 1024 | | `loadCustomFeedbacks` | `boolean` | No | - | Whether to load custom feedback items | **Mutually Exclusive Branches ( `anyOf` )** * **App Chat** Identify the conversation via `appId` . When both API Key and login session are supported, `Authorization` takes precedence over token/Cookie. | Field | Type | Required | Default | Constraints & Description | | ------------ | --------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `appId` | `string` | Yes | - | Application ID authenticated with the request header credentials allowed by this endpoint. pattern: `^[0-9a-fA-F]{24}$` | | `sourceType` | `string` (enum) | No | - | Session resource type associated with `appId` . Defaults to `app` ; pass the matching `sourceType` for assistant builder sessions. Allowed values: `app` , `chatAgentHelper` , `workflowBuilder` | **Default Identity** : Omit `customUid` and `authProxy` to execute using the team member identity associated with the credential. **Custom end user ( `customUid` )**: Tag end users from your own system via `customUid` without changing the authenticating member or permissions. Passed as workflow `userId` and used to scope chat management. | Field | Type | Required | Default | Constraints & Description | | ----------- | -------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `customUid` | `string` | Yes | - | Supported only for standard app API Key calls. Exact match against the external user ID ( `outLinkUid` , not `tmbId` ). Omit to keep full scope or pass to restrict reads, updates, and deletions (max 1024 chars, cannot be empty or `null` , does not change member identity). minLength: 1; maxLength: 1024 | **Proxy Team Member ( `authProxy` )**: Act on behalf of another member in the same team via `authProxy` . Available only on personal API keys with `authProxy` enabled; mutually exclusive with `customUid` . | Field | Type | Required | Default | Constraints & Description | | ----------- | -------- | -------- | ------- | -------------------------------------------------------------------------------------- | | `authProxy` | `string` | Yes | - | JSON-serialized proxy identity, e.g. `{"tmbId":"member-id"}` or `{"username":"alice"}` | * **Skill Debug Session** Identify the debug session via `skillId` (takes precedence over `appId` and ignores `sourceType` ), authenticated with allowed request header credentials. | Field | Type | Required | Default | Constraints & Description | | --------- | -------- | -------- | ------- | ------------------------------------------------------------------------------------------------------- | | `skillId` | `string` | Yes | - | Skill Edit debug ID authenticated with allowed request header credentials. pattern: `^[0-9a-fA-F]{24}$` | * **App API Key (no appId required)** When authorizing with an app-bound App API Key, omit `appId` and `sourceType` ; the server resolves the bound app with `sourceType` fixed to `app` . Personal keys and login sessions cannot omit `appId` , and an explicit `appId` does not override an App API Key binding. **Default Identity** : Omit `customUid` and `authProxy` to execute using the team member identity associated with the credential. **Custom end user ( `customUid` )**: Tag end users from your own system via `customUid` without changing the authenticating member or permissions. Passed as workflow `userId` and used to scope chat management. | Field | Type | Required | Default | Constraints & Description | | ----------- | -------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `customUid` | `string` | Yes | - | Supported only for standard app API Key calls. Exact match against the external user ID ( `outLinkUid` , not `tmbId` ). Omit to keep full scope or pass to restrict reads, updates, and deletions (max 1024 chars, cannot be empty or `null` , does not change member identity). minLength: 1; maxLength: 1024 | ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X GET "https://cloud.fastgpt.io/api/core/chat/init?appId=68ad85a7463006c963799a05&chatId=1234567890" \ -H "Authorization: Bearer YOUR_API_KEY" ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Successfully returned chat initialization data **Content-Type** : `application/json` | Field | Type | Required | Default | Constraints & Description | | -------------------------------------------------------------- | -------------------------------------------------------- | -------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `chatId` | `string` | No | - | Chat ID. maxLength: 1024 | | `userAvatar` | `string` | No | - | User avatar URL | | `title` | `string` | Yes | - | Chat title | | `variables` | `object` | No | - | Global variable values | | `chatGenerateStatus` | `number` (enum) | No | - | Live generation status from Redis lease: `0` ( `generating` ), `1` ( `done` / idle). Allowed values: `0` , `1` | | `hasBeenRead` | `boolean` | No | - | Whether the conversation has been read | | `app` | `object` | Yes | - | Application configuration | | `app.chatConfig` | `object` | No | - | Chat configuration | | `app.chatConfig.welcomeText` | `string` | No | - | Welcome message displayed when starting a new conversation | | `app.chatConfig.welcomeConfig` | `object` | No | - | Opening prompt configuration | | `app.chatConfig.welcomeConfig.welcomeText` | `string` | No | - | Welcome message displayed when starting a new conversation | | `app.chatConfig.welcomeConfig.welcomeQuestions` | `string[]` | No | - | Suggested starter questions shown below the welcome text | | `app.chatConfig.variables` | `object[]` | No | - | List of variables users fill in before starting a conversation | | `app.chatConfig.variables[].maxFiles` | `integer` | No | - | Maximum number of files allowed for this variable. min: 0; max: 9007199254740991 | | `app.chatConfig.variables[].canSelectFile` | `boolean` | No | - | Whether regular document files are allowed for this variable | | `app.chatConfig.variables[].customPdfParse` | `boolean` | No | - | Whether custom PDF parsing is enabled | | `app.chatConfig.variables[].canSelectImg` | `boolean` | No | - | Whether images are allowed for this variable | | `app.chatConfig.variables[].canSelectVideo` | `boolean` | No | - | Whether videos are allowed for this variable | | `app.chatConfig.variables[].canSelectAudio` | `boolean` | No | - | Whether audio files are allowed for this variable | | `app.chatConfig.variables[].canSelectCustomFileExtension` | `boolean` | No | - | Whether custom file extensions are allowed for this variable | | `app.chatConfig.variables[].customFileExtensionList` | `string[]` | No | - | List of allowed custom file extensions for this variable | | `app.chatConfig.variables[].key` | `string` | Yes | - | Variable key used in prompts and workflow references | | `app.chatConfig.variables[].label` | `string` | Yes | - | Variable display label | | `app.chatConfig.variables[].valueType` | `string` (enum) | No | - | Variable value data type. Allowed values: `string` , `number` , `boolean` , `object` , `arrayString` , `arrayNumber` , `arrayBoolean` , `arrayObject` , `arrayAny` , `any` , `chatHistory` , `datasetQuote` , `dynamic` , `selectDataset` , `selectApp` | | `app.chatConfig.variables[].required` | `boolean` | No | - | Whether this variable is required | | `app.chatConfig.variables[].defaultValue` | `object \| array \| string \| number \| boolean \| null` | No | - | Default value for the variable | | `app.chatConfig.variables[].referencePlaceholder` | `string` | No | - | Placeholder text displayed when referencing the variable | | `app.chatConfig.variables[].isRichText` | `boolean` | No | - | Whether rich-text input is enabled | | `app.chatConfig.variables[].placeholder` | `string` | No | - | Input field placeholder text | | `app.chatConfig.variables[].maxLength` | `integer` | No | - | Maximum input character length for text variables. min: 0; max: 9007199254740991 | | `app.chatConfig.variables[].minLength` | `integer` | No | - | Minimum input character length for text variables. min: 0; max: 9007199254740991 | | `app.chatConfig.variables[].markList` | `object[]` | No | - | Scale tick marks for numeric slider variables | | `app.chatConfig.variables[].step` | `number` | No | - | Numeric step increment | | `app.chatConfig.variables[].max` | `number` | No | - | Maximum numeric value | | `app.chatConfig.variables[].min` | `number` | No | - | Minimum numeric value | | `app.chatConfig.variables[].precision` | `number` | No | - | Decimal precision for numeric variables | | `app.chatConfig.variables[].canLocalUpload` | `boolean` | No | - | Whether local file upload is allowed for this variable | | `app.chatConfig.variables[].canUrlUpload` | `boolean` | No | - | Whether importing files by URL is allowed for this variable | | `app.chatConfig.variables[].timeGranularity` | `string` (enum) | No | - | Granularity of time selection. Allowed values: `day` , `hour` , `minute` , `second` | | `app.chatConfig.variables[].timeRangeStart` | `string` | No | - | Start timestamp of the time range variable | | `app.chatConfig.variables[].timeRangeEnd` | `string` | No | - | End timestamp of the time range variable | | `app.chatConfig.variables[].datasetOptions` | `object[]` | No | - | Selectable datasets for dataset-picker variables | | `app.chatConfig.variables[].customInputConfig` | `object` | No | - | Custom input configuration in the workflow editor | | `app.chatConfig.variables[].type` | `string` (enum) | Yes | - | Variable input component type. Allowed values: `input` , `textarea` , `numberInput` , `select` , `multipleSelect` , `timePointSelect` , `timeRangeSelect` , `switch` , `password` , `file` , `llmSelect` , `datasetSelect` , `custom` , `internal` | | `app.chatConfig.variables[].description` | `string` | Yes | - | Description of the variable purpose | | `app.chatConfig.variables[].list` | `object[]` | No | - | Options for select-type variables | | `app.chatConfig.variables[].enums` | `object[]` | No | - | **Deprecated** . Deprecated: legacy enum options | | `app.chatConfig.autoExecute` | `object` | No | - | Auto-execute configuration | | `app.chatConfig.autoExecute.open` | `boolean` | Yes | - | Whether to trigger execution automatically when opening a chat | | `app.chatConfig.autoExecute.defaultPrompt` | `string` | Yes | `""` | Default prompt injected during auto-execution | | `app.chatConfig.questionGuide` | `object` | No | - | Follow-up question suggestion configuration | | `app.chatConfig.questionGuide.open` | `boolean` | Yes | - | Whether follow-up question suggestions are enabled | | `app.chatConfig.questionGuide.modelId` | `string` | No | - | Model ID used to generate follow-up question suggestions | | `app.chatConfig.questionGuide.model` | `string` | No | - | **Deprecated** . Legacy model identifier for follow-up suggestions | | `app.chatConfig.questionGuide.customPrompt` | `string` | No | - | Custom prompt appended for follow-up suggestions | | `app.chatConfig.ttsConfig` | `object` | No | - | Text-to-speech (TTS) configuration | | `app.chatConfig.ttsConfig.type` | `string` (enum) | Yes | - | TTS output mode: disabled, browser TTS, or model TTS. Allowed values: `none` , `web` , `model` | | `app.chatConfig.ttsConfig.modelId` | `string` | No | - | TTS model ID used for speech synthesis | | `app.chatConfig.ttsConfig.model` | `string` | No | - | **Deprecated** . TTS model name used for speech synthesis | | `app.chatConfig.ttsConfig.voice` | `string` | No | - | TTS voice identifier | | `app.chatConfig.ttsConfig.speed` | `number` | No | - | TTS playback speed | | `app.chatConfig.whisperConfig` | `object` | No | - | Speech-to-text (STT) input configuration | | `app.chatConfig.whisperConfig.open` | `boolean` | Yes | - | Whether voice input transcription is enabled | | `app.chatConfig.whisperConfig.autoSend` | `boolean` | Yes | `false` | Whether to auto-send after voice transcription completes | | `app.chatConfig.whisperConfig.autoTTSResponse` | `boolean` | Yes | `false` | Whether to auto-play TTS replies after voice input | | `app.chatConfig.scheduledTriggerConfig` | `object` | No | - | Scheduled trigger configuration | | `app.chatConfig.scheduledTriggerConfig.cronString` | `string` | Yes | - | Cron schedule expression | | `app.chatConfig.scheduledTriggerConfig.timezone` | `string` | Yes | - | Timezone used by the schedule | | `app.chatConfig.scheduledTriggerConfig.defaultPrompt` | `string` | Yes | `""` | Default prompt injected on scheduled runs | | `app.chatConfig.chatInputGuide` | `object` | No | - | Chat input guide configuration | | `app.chatConfig.chatInputGuide.open` | `boolean` | Yes | - | Whether chat input guidance is enabled | | `app.chatConfig.chatInputGuide.customUrl` | `string` | Yes | - | Custom input guide page URL | | `app.chatConfig.fileSelectConfig` | `object` | No | - | Chat file upload configuration | | `app.chatConfig.fileSelectConfig.maxFiles` | `integer` | No | - | Maximum files allowed per chat turn. min: 0; max: 9007199254740991 | | `app.chatConfig.fileSelectConfig.canSelectFile` | `boolean` | No | - | Whether document files can be uploaded in chat | | `app.chatConfig.fileSelectConfig.customPdfParse` | `boolean` | No | - | Whether custom PDF parsing is enabled | | `app.chatConfig.fileSelectConfig.canSelectImg` | `boolean` | No | - | Whether images can be uploaded in chat | | `app.chatConfig.fileSelectConfig.canSelectVideo` | `boolean` | No | - | Whether videos can be uploaded in chat | | `app.chatConfig.fileSelectConfig.canSelectAudio` | `boolean` | No | - | Whether audio files can be uploaded in chat | | `app.chatConfig.fileSelectConfig.canSelectCustomFileExtension` | `boolean` | No | - | Whether custom file extensions are allowed in chat | | `app.chatConfig.fileSelectConfig.customFileExtensionList` | `string[]` | No | - | List of allowed custom file extensions in chat | | `app.chatConfig.entryPoints` | `object[]` | No | - | Feature menu entries shown on the chat page | | `app.chatConfig.entryPoints[].id` | `string` | Yes | - | - | | `app.chatConfig.entryPoints[].name` | `string` | Yes | - | - | | `app.chatConfig.entryPoints[].icon` | `string` | No | - | - | | `app.chatConfig.instruction` | `string` | No | - | Usage instructions shown to users on the chat page | | `app.chatModels` | `string[]` | No | - | Chat model | | `app.name` | `string` | Yes | - | Application name. minLength: 1 | | `app.avatar` | `string` | Yes | - | Application avatar URL | | `app.intro` | `string` | Yes | - | Application introduction | | `app.canUse` | `boolean` | No | - | Whether the resource is available | | `app.type` | `string` (enum) | Yes | - | Application type. Allowed values: `folder` , `toolFolder` , `simple` , `chatAgent` , `advanced` , `plugin` , `toolSet` , `httpToolSet` , `hidden` , `tool` , `httpPlugin` | | `app.pluginInputs` | `object[]` | Yes | - | Plugin input | | `app.pluginInputs[].key` | `string` | Yes | - | Variable key used in prompts and workflow references | | `app.pluginInputs[].label` | `string` | Yes | - | Variable display label | | `app.pluginInputs[].valueType` | `string` (enum) | No | - | Variable value data type. Allowed values: `string` , `number` , `boolean` , `object` , `arrayString` , `arrayNumber` , `arrayBoolean` , `arrayObject` , `arrayAny` , `any` , `chatHistory` , `datasetQuote` , `dynamic` , `selectDataset` , `selectApp` | | `app.pluginInputs[].required` | `boolean` | No | - | Whether this variable is required | | `app.pluginInputs[].defaultValue` | `object \| array \| string \| number \| boolean \| null` | No | - | Default value for the variable | | `app.pluginInputs[].referencePlaceholder` | `string` | No | - | Placeholder text displayed when referencing the variable | | `app.pluginInputs[].isRichText` | `boolean` | No | - | Whether rich-text input is enabled | | `app.pluginInputs[].placeholder` | `string` | No | - | Input field placeholder text | | `app.pluginInputs[].maxLength` | `integer` | No | - | Maximum input character length for text variables. min: 0; max: 9007199254740991 | | `app.pluginInputs[].minLength` | `integer` | No | - | Minimum input character length for text variables. min: 0; max: 9007199254740991 | | `app.pluginInputs[].markList` | `object[]` | No | - | Scale tick marks for numeric slider variables | | `app.pluginInputs[].markList[].label` | `string` | Yes | - | Tick label | | `app.pluginInputs[].markList[].value` | `number` | Yes | - | Tick numeric value | | `app.pluginInputs[].step` | `number` | No | - | Numeric step increment | | `app.pluginInputs[].max` | `number` | No | - | Maximum numeric value | | `app.pluginInputs[].min` | `number` | No | - | Minimum numeric value | | `app.pluginInputs[].precision` | `number` | No | - | Decimal precision for numeric variables | | `app.pluginInputs[].canSelectFile` | `boolean` | No | - | Whether regular document files are allowed for this variable | | `app.pluginInputs[].canSelectImg` | `boolean` | No | - | Whether images are allowed for this variable | | `app.pluginInputs[].canSelectVideo` | `boolean` | No | - | Whether videos are allowed for this variable | | `app.pluginInputs[].canSelectAudio` | `boolean` | No | - | Whether audio files are allowed for this variable | | `app.pluginInputs[].canSelectCustomFileExtension` | `boolean` | No | - | Whether custom file extensions are allowed for this variable | | `app.pluginInputs[].customFileExtensionList` | `string[]` | No | - | List of allowed custom file extensions for this variable | | `app.pluginInputs[].canLocalUpload` | `boolean` | No | - | Whether local file upload is allowed for this variable | | `app.pluginInputs[].canUrlUpload` | `boolean` | No | - | Whether importing files by URL is allowed for this variable | | `app.pluginInputs[].maxFiles` | `integer` | No | - | Maximum number of files allowed for this variable. min: 0; max: 9007199254740991 | | `app.pluginInputs[].timeGranularity` | `string` (enum) | No | - | Granularity of time selection. Allowed values: `day` , `hour` , `minute` , `second` | | `app.pluginInputs[].timeRangeStart` | `string` | No | - | Start timestamp of the time range variable | | `app.pluginInputs[].timeRangeEnd` | `string` | No | - | End timestamp of the time range variable | | `app.pluginInputs[].datasetOptions` | `object[]` | No | - | Selectable datasets for dataset-picker variables | | `app.pluginInputs[].datasetOptions[].datasetId` | `string` | Yes | - | Selectable dataset ID | | `app.pluginInputs[].datasetOptions[].avatar` | `string` | Yes | - | Selectable dataset icon URL | | `app.pluginInputs[].datasetOptions[].name` | `string` | Yes | - | Selectable dataset name | | `app.pluginInputs[].datasetOptions[].vectorModel` | `object` | Yes | - | - | | `app.pluginInputs[].datasetOptions[].error` | `string` | No | - | - | | `app.pluginInputs[].customInputConfig` | `object` | No | - | Custom input configuration in the workflow editor | | `app.pluginInputs[].customInputConfig.selectValueTypeList` | `string` (enum)\[]\` | No | - | Allowed value types for custom variable input | | `app.pluginInputs[].customInputConfig.showDefaultValue` | `boolean` | No | - | Whether to show default value settings in the editor | | `app.pluginInputs[].customInputConfig.showDescription` | `boolean` | No | - | Whether to show field description settings in the editor | | `app.pluginInputs[].customInputConfig.hideBottomDivider` | `boolean` | No | - | Whether to hide the bottom divider in variable editing | | `app.pluginInputs[].selectedType` | `string` (enum) | No | - | Active UI render type for multi-type inputs. Allowed values: `reference` , `input` , `textarea` , `numberInput` , `switch` , `select` , `multipleSelect` , `JSONEditor` , `addInputParam` , `customVariable` , `selectApp` , `selectLLMModel` , `settingLLMModel` , `selectDataset` , `selectDatasetParamsModal` , `settingDatasetQuotePrompt` , `hidden` , `custom` , `selectSkill` , `selectTool`…… | | `app.pluginInputs[].renderTypeList` | `string` (enum)\[]\` | Yes | - | Allowed UI render types in the workflow editor | | `app.pluginInputs[].valueDesc` | `string` | No | - | Human-readable description of the input value | | `app.pluginInputs[].value` | `object \| array \| string \| number \| boolean \| null` | No | - | Current Node.js input value | | `app.pluginInputs[].debugLabel` | `string` | No | - | Input label shown in debug mode | | `app.pluginInputs[].description` | `string` | No | - | Node.js input description | | `app.pluginInputs[].toolDescription` | `string` | No | - | Semantic description when exposed as a tool parameter | | `app.pluginInputs[].defaultToAgentGenerated` | `boolean` | No | - | Whether the Agent populates this parameter by default when unset | | `app.pluginInputs[].canAgentGenerated` | `boolean` | No | - | Whether Agent auto-generation is allowed for this input | | `app.pluginInputs[].customJsonSchema` | `object` | No | - | Custom JSON Schema property definition for tool parameters | | `app.pluginInputs[].enum` | `string` | No | - | Deprecated: legacy enum configuration | | `app.pluginInputs[].inputList` | `object[]` | No | - | List of system input definitions | | `app.pluginInputs[].inputList[].key` | `string` | Yes | - | Input key name | | `app.pluginInputs[].inputList[].label` | `string` | Yes | - | Input display label | | `app.pluginInputs[].inputList[].description` | `string` | No | - | Input description | | `app.pluginInputs[].inputList[].placeholder` | `string` | No | - | Input placeholder text | | `app.pluginInputs[].inputList[].required` | `boolean` | No | - | Whether this input is required | | `app.pluginInputs[].inputList[].inputType` | `string` (enum) | Yes | - | Input render component type. Allowed values: `input` , `numberInput` , `secret` , `switch` , `select` | | `app.pluginInputs[].inputList[].value` | `object` | No | - | Default value or secret configuration | | `app.pluginInputs[].inputList[].list` | `object[]` | No | - | Options for select-type system inputs | | `app.pluginInputs[].canEdit` | `boolean` | No | - | Whether this input can be edited in the editor | | `app.pluginInputs[].isPro` | `boolean` | No | - | Whether this input requires a commercial edition | | `app.pluginInputs[].isToolOutput` | `boolean` | No | - | Whether this input originates from a tool output | | `app.pluginInputs[].deprecated` | `boolean` | No | - | Whether this input is deprecated | | `app.pluginInputs[].list` | `object[]` | No | - | Options for select-type variables | | `app.pluginInputs[].list[].label` | `string` | Yes | - | Option display label | | `app.pluginInputs[].list[].value` | `string` | Yes | - | Option underlying value | | `app.pluginInputs[].list[].icon` | `string` | No | - | Option icon | | `app.pluginInputs[].list[].description` | `string` | No | - | Option description | | `app.pluginInputs[].enums` | `object[]` | No | - | **Deprecated** . Deprecated: legacy enum options | | `app.pluginInputs[].enums[].value` | `string` | Yes | - | Enum option value | | `app.pluginInputs[].enums[].label` | `string` | Yes | - | Enum option display label | | `app.useAgentSandbox` | `boolean` | No | - | Whether VM execution is enabled | **Mutually Exclusive Branches ( `anyOf` )** * **Option 1** | Field | Type | Required | Default | Constraints & Description | | ------------ | ------------------- | -------- | ------- | --------------------------------------------------------------------------------------------------- | | `appId` | `string` | Yes | - | Application ID; returned only for workflow builder assistant sessions. pattern: `^[0-9a-fA-F]{24}$` | | `skillId` | `any` | No | - | - | | `sourceType` | `"workflowBuilder"` | Yes | - | Resource type for workflow builder sessions. Fixed: `"workflowBuilder"` | * **Option 2** | Field | Type | Required | Default | Constraints & Description | | ------------ | ------------------- | -------- | ------- | ------------------------------------------------------------------------------------------ | | `appId` | `string` | Yes | - | Application ID; returned only for `chatAgentHelper` sessions. pattern: `^[0-9a-fA-F]{24}$` | | `skillId` | `any` | No | - | - | | `sourceType` | `"chatAgentHelper"` | Yes | - | Resource type for `chatAgentHelper` sessions. Fixed: `"chatAgentHelper"` | * **Option 3** | Field | Type | Required | Default | Constraints & Description | | --------- | -------- | -------- | ------- | ------------------------------------------------------------------------------------------ | | `appId` | `string` | Yes | - | Application ID; returned only for standard app chat sessions. pattern: `^[0-9a-fA-F]{24}$` | | `skillId` | `any` | No | - | - | * **Option 4** | Field | Type | Required | Default | Constraints & Description | | --------- | -------- | -------- | ------- | ---------------------------------------------------------------------------------------- | | `appId` | `any` | No | - | - | | `skillId` | `string` | Yes | - | Skill Edit debug ID; returned only for Skill Edit sessions. pattern: `^[0-9a-fA-F]{24}$` | file: ./content/openapi/reference/chat-history/mark-read.en.mdx url: https://doc.fastgpt.io/openapi/reference/chat-history/mark-read title: Mark Chat History Read last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "Mark Chat History Read", "seoTitle": "Mark Chat History Read - POST /api/core/chat/history/markRead | FastGPT OpenAPI", "description": "Mark a specified conversation as read in storage across app API Key, personal key, identity proxy, or share link contexts." } ## Endpoint Overview * **Method** : `POST` * **Path** : `/api/core/chat/history/markRead` * **Module** : Chat / Chat History * **Authentication** : `Authorization: Bearer `—Supports **App API Key** ( `appId` optional) and **Personal API Key** ( `appId` required); also supports `authProxy` team member proxy and `outLinkAuthData` share link (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E4%BC%9A%E8%AF%9D%E7%AE%A1%E7%90%86/POST/core/chat/history/markRead) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E4%BC%9A%E8%AF%9D%E7%AE%A1%E7%90%86/POST/core/chat/history/markRead` ) ## Description & Notes Called after the user finishes reading replies to sync `hasBeenRead` in MongoDB. App sessions require app read permission while other sources require resource write permission, along with session scope checks. ## Request Parameters ### Request Body ( `application/json` ) #### Shared Parameters Across Branches | Field | Type | Required | Default | Constraints & Description | | -------- | -------- | -------- | ------- | -------------------------------------- | | `chatId` | `string` | Yes | - | Chat ID. minLength: 1; maxLength: 1024 | **Mutually Exclusive Branches ( `anyOf` )** * **App Chat** Identify the conversation via `appId` . When both API Key and login session are supported, `Authorization` takes precedence over token/Cookie. | Field | Type | Required | Default | Constraints & Description | | ------------ | --------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `appId` | `string` | Yes | - | Application ID authenticated with the request header credentials allowed by this endpoint. pattern: `^[0-9a-fA-F]{24}$` | | `sourceType` | `string` (enum) | No | - | Session resource type associated with `appId` . Defaults to `app` ; pass the matching `sourceType` for assistant builder sessions. Allowed values: `app` , `chatAgentHelper` , `workflowBuilder` | **Default Identity** : Omit `customUid` and `authProxy` to execute using the team member identity associated with the credential. **Custom end user ( `customUid` )**: Tag end users from your own system via `customUid` without changing the authenticating member or permissions. Passed as workflow `userId` and used to scope chat management. | Field | Type | Required | Default | Constraints & Description | | ----------- | -------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `customUid` | `string` | Yes | - | Supported only for standard app API Key calls. Exact match against the external user ID ( `outLinkUid` , not `tmbId` ). Omit to keep full scope or pass to restrict reads, updates, and deletions (max 1024 chars, cannot be empty or `null` , does not change member identity). minLength: 1; maxLength: 1024 | **Proxy Team Member ( `authProxy` )**: Act on behalf of another member in the same team via `authProxy` . Available only on personal API keys with `authProxy` enabled; mutually exclusive with `customUid` . | Field | Type | Required | Default | Constraints & Description | | -------------------- | -------- | -------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `authProxy` | `object` | Yes | - | API Key proxy caller identity. Available only for personal keys with `authProxy` enabled; specify `tmbId` or `username` ( `tmbId` takes precedence without falling back to `username` on invalid ID). | | `authProxy.tmbId` | `string` | Yes | - | **Branch: By Team Member ID** . Proxied team member ID ( `tmbId` ), takes precedence over `username` . pattern: `^[0-9a-fA-F]{24}$` | | `authProxy.username` | `string` | Yes | - | **Branch: By Username** . Proxied team member username. minLength: 1; maxLength: 128 | * **Skill Debug Session** Identify the debug session via `skillId` (takes precedence over `appId` and ignores `sourceType` ), authenticated with allowed request header credentials. | Field | Type | Required | Default | Constraints & Description | | --------- | -------- | -------- | ------- | ------------------------------------------------------------------------------------------------------- | | `skillId` | `string` | Yes | - | Skill Edit debug ID authenticated with allowed request header credentials. pattern: `^[0-9a-fA-F]{24}$` | * **Share-Link Chat** Resolves the underlying app via `outLinkAuthData` , taking precedence over `skillId` and `appId` (ignoring `sourceType` ). Protected links still validate login cookies/tokens and never fall back to standard auth on failure. | Field | Type | Required | Default | Constraints & Description | | ---------------------------- | -------- | -------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | | `outLinkAuthData` | `object` | Yes | - | Share-link auth payload ( `shareId` / `outLinkUid` ). Overrides `skillId` and `appId` ; protected links still validate login session cookies/tokens. | | `outLinkAuthData.shareId` | `string` | Yes | - | Share link ID. minLength: 1 | | `outLinkAuthData.outLinkUid` | `string` | Yes | - | External share user ID. minLength: 1 | * **App API Key (no appId required)** When authorizing with an app-bound App API Key, omit `appId` and `sourceType` ; the server resolves the bound app with `sourceType` fixed to `app` . Personal keys and login sessions cannot omit `appId` , and an explicit `appId` does not override an App API Key binding. **Default Identity** : Omit `customUid` and `authProxy` to execute using the team member identity associated with the credential. **Custom end user ( `customUid` )**: Tag end users from your own system via `customUid` without changing the authenticating member or permissions. Passed as workflow `userId` and used to scope chat management. | Field | Type | Required | Default | Constraints & Description | | ----------- | -------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `customUid` | `string` | Yes | - | Supported only for standard app API Key calls. Exact match against the external user ID ( `outLinkUid` , not `tmbId` ). Omit to keep full scope or pass to restrict reads, updates, and deletions (max 1024 chars, cannot be empty or `null` , does not change member identity). minLength: 1; maxLength: 1024 | ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X POST "https://cloud.fastgpt.io/api/core/chat/history/markRead" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ --data-raw '{ "appId": "68ad85a7463006c963799a05", "chatId": "string" }' ``` ### Minimal Valid JSON Body ```json { "appId": "68ad85a7463006c963799a05", "chatId": "string" } ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Success Returns the standard FastGPT success envelope ( `{ "code": 200, "statusText": "", "message": "", "data": ... }` ). The exact `data` payload schema is not declared in this OpenAPI contract; refer to the status description above or inspect runtime responses. file: ./content/openapi/reference/chat-history/update-history.en.mdx url: https://doc.fastgpt.io/openapi/reference/chat-history/update-history title: Update Chat History last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "Update Chat History", "seoTitle": "Update Chat History - PUT /api/core/chat/history/updateHistory | FastGPT OpenAPI", "description": "Update a conversation title, custom title, or pinned status using app API Key, personal key, proxy, or share authentication." } ## Endpoint Overview * **Method** : `PUT` * **Path** : `/api/core/chat/history/updateHistory` * **Module** : Chat / Chat History * **Authentication** : `Authorization: Bearer `—Supports **App API Key** ( `appId` optional) and **Personal API Key** ( `appId` required); also supports `authProxy` team member proxy and `outLinkAuthData` share link (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E4%BC%9A%E8%AF%9D%E7%AE%A1%E7%90%86/PUT/core/chat/history/updateHistory) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E4%BC%9A%E8%AF%9D%E7%AE%A1%E7%90%86/PUT/core/chat/history/updateHistory` ) ## Description & Notes Update the title, custom title, or pinned status of a chat session. ## Request Parameters ### Request Body ( `application/json` ) #### Shared Parameters Across Branches | Field | Type | Required | Default | Constraints & Description | | ------------- | --------- | -------- | ------- | -------------------------------------- | | `chatId` | `string` | Yes | - | Chat ID. minLength: 1; maxLength: 1024 | | `title` | `string` | No | - | Title | | `customTitle` | `string` | No | - | Custom Title | | `top` | `boolean` | No | - | Whether the conversation is pinned | **Mutually Exclusive Branches ( `anyOf` )** * **App Chat** Identify the conversation via `appId` . When both API Key and login session are supported, `Authorization` takes precedence over token/Cookie. | Field | Type | Required | Default | Constraints & Description | | ------------ | --------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `appId` | `string` | Yes | - | Application ID authenticated with the request header credentials allowed by this endpoint. pattern: `^[0-9a-fA-F]{24}$` | | `sourceType` | `string` (enum) | No | - | Session resource type associated with `appId` . Defaults to `app` ; pass the matching `sourceType` for assistant builder sessions. Allowed values: `app` , `chatAgentHelper` , `workflowBuilder` | **Default Identity** : Omit `customUid` and `authProxy` to execute using the team member identity associated with the credential. **Custom end user ( `customUid` )**: Tag end users from your own system via `customUid` without changing the authenticating member or permissions. Passed as workflow `userId` and used to scope chat management. | Field | Type | Required | Default | Constraints & Description | | ----------- | -------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `customUid` | `string` | Yes | - | Supported only for standard app API Key calls. Exact match against the external user ID ( `outLinkUid` , not `tmbId` ). Omit to keep full scope or pass to restrict reads, updates, and deletions (max 1024 chars, cannot be empty or `null` , does not change member identity). minLength: 1; maxLength: 1024 | **Proxy Team Member ( `authProxy` )**: Act on behalf of another member in the same team via `authProxy` . Available only on personal API keys with `authProxy` enabled; mutually exclusive with `customUid` . | Field | Type | Required | Default | Constraints & Description | | -------------------- | -------- | -------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `authProxy` | `object` | Yes | - | API Key proxy caller identity. Available only for personal keys with `authProxy` enabled; specify `tmbId` or `username` ( `tmbId` takes precedence without falling back to `username` on invalid ID). | | `authProxy.tmbId` | `string` | Yes | - | **Branch: By Team Member ID** . Proxied team member ID ( `tmbId` ), takes precedence over `username` . pattern: `^[0-9a-fA-F]{24}$` | | `authProxy.username` | `string` | Yes | - | **Branch: By Username** . Proxied team member username. minLength: 1; maxLength: 128 | * **Skill Debug Session** Identify the debug session via `skillId` (takes precedence over `appId` and ignores `sourceType` ), authenticated with allowed request header credentials. | Field | Type | Required | Default | Constraints & Description | | --------- | -------- | -------- | ------- | ------------------------------------------------------------------------------------------------------- | | `skillId` | `string` | Yes | - | Skill Edit debug ID authenticated with allowed request header credentials. pattern: `^[0-9a-fA-F]{24}$` | * **Share-Link Chat** Resolves the underlying app via `outLinkAuthData` , taking precedence over `skillId` and `appId` (ignoring `sourceType` ). Protected links still validate login cookies/tokens and never fall back to standard auth on failure. | Field | Type | Required | Default | Constraints & Description | | ---------------------------- | -------- | -------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | | `outLinkAuthData` | `object` | Yes | - | Share-link auth payload ( `shareId` / `outLinkUid` ). Overrides `skillId` and `appId` ; protected links still validate login session cookies/tokens. | | `outLinkAuthData.shareId` | `string` | Yes | - | Share link ID. minLength: 1 | | `outLinkAuthData.outLinkUid` | `string` | Yes | - | External share user ID. minLength: 1 | * **App API Key (no appId required)** When authorizing with an app-bound App API Key, omit `appId` and `sourceType` ; the server resolves the bound app with `sourceType` fixed to `app` . Personal keys and login sessions cannot omit `appId` , and an explicit `appId` does not override an App API Key binding. **Default Identity** : Omit `customUid` and `authProxy` to execute using the team member identity associated with the credential. **Custom end user ( `customUid` )**: Tag end users from your own system via `customUid` without changing the authenticating member or permissions. Passed as workflow `userId` and used to scope chat management. | Field | Type | Required | Default | Constraints & Description | | ----------- | -------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `customUid` | `string` | Yes | - | Supported only for standard app API Key calls. Exact match against the external user ID ( `outLinkUid` , not `tmbId` ). Omit to keep full scope or pass to restrict reads, updates, and deletions (max 1024 chars, cannot be empty or `null` , does not change member identity). minLength: 1; maxLength: 1024 | ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X PUT "https://cloud.fastgpt.io/api/core/chat/history/updateHistory" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ --data-raw '{ "appId": "68ad85a7463006c963799a05", "chatId": "string" }' ``` ### Minimal Valid JSON Body ```json { "appId": "68ad85a7463006c963799a05", "chatId": "string" } ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Successfully updated chat history Returns the standard FastGPT success envelope ( `{ "code": 200, "statusText": "", "message": "", "data": ... }` ). The exact `data` payload schema is not declared in this OpenAPI contract; refer to the status description above or inspect runtime responses. file: ./content/openapi/reference/chat-record/delete.en.mdx url: https://doc.fastgpt.io/openapi/reference/chat-record/delete title: Delete Chat Records last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "Delete Chat Records", "seoTitle": "Delete Chat Records - DELETE /api/core/chat/record/delete | FastGPT OpenAPI", "description": "Soft-delete specific messages in a chat session by dataId or contentIds while preserving conversation turn consistency." } ## Endpoint Overview * **Method** : `DELETE` * **Path** : `/api/core/chat/record/delete` * **Module** : Chat / Chat Records * **Authentication** : `Authorization: Bearer `—Supports **App API Key** ( `appId` optional) and **Personal API Key** ( `appId` required); also supports `authProxy` team member proxy and `outLinkAuthData` share link (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E5%AF%B9%E8%AF%9D%E7%AE%A1%E7%90%86/DELETE/core/chat/record/delete) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E5%AF%B9%E8%AF%9D%E7%AE%A1%E7%90%86/DELETE/core/chat/record/delete` ) ## Description & Notes Soft-deletes specified messages via JSON body ( `outLinkAuthData` as an object, `contentIds` as an array). Pending Ask/Preview state is recalculated from remaining records, allowing re-answering when the final reply is deleted. ## Request Parameters ### Request Body ( `application/json` ) #### Shared Parameters Across Branches | Field | Type | Required | Default | Constraints & Description | | ------------ | ---------- | -------- | ------- | -------------------------------------- | | `chatId` | `string` | Yes | - | Chat ID. maxLength: 1024 | | `contentId` | `string` | No | - | Message `dataId` to delete | | `contentIds` | `string[]` | No | - | List of message `contentIds` to delete | **Mutually Exclusive Branches ( `anyOf` )** * **App Chat** Identify the conversation via `appId` . When both API Key and login session are supported, `Authorization` takes precedence over token/Cookie. | Field | Type | Required | Default | Constraints & Description | | ------------ | --------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `appId` | `string` | Yes | - | Application ID authenticated with the request header credentials allowed by this endpoint. pattern: `^[0-9a-fA-F]{24}$` | | `sourceType` | `string` (enum) | No | - | Session resource type associated with `appId` . Defaults to `app` ; pass the matching `sourceType` for assistant builder sessions. Allowed values: `app` , `chatAgentHelper` , `workflowBuilder` | **Default Identity** : Omit `customUid` and `authProxy` to execute using the team member identity associated with the credential. **Custom end user ( `customUid` )**: Tag end users from your own system via `customUid` without changing the authenticating member or permissions. Passed as workflow `userId` and used to scope chat management. | Field | Type | Required | Default | Constraints & Description | | ----------- | -------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `customUid` | `string` | Yes | - | Supported only for standard app API Key calls. Exact match against the external user ID ( `outLinkUid` , not `tmbId` ). Omit to keep full scope or pass to restrict reads, updates, and deletions (max 1024 chars, cannot be empty or `null` , does not change member identity). minLength: 1; maxLength: 1024 | **Proxy Team Member ( `authProxy` )**: Act on behalf of another member in the same team via `authProxy` . Available only on personal API keys with `authProxy` enabled; mutually exclusive with `customUid` . | Field | Type | Required | Default | Constraints & Description | | -------------------- | -------- | -------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `authProxy` | `object` | Yes | - | API Key proxy caller identity. Available only for personal keys with `authProxy` enabled; specify `tmbId` or `username` ( `tmbId` takes precedence without falling back to `username` on invalid ID). | | `authProxy.tmbId` | `string` | Yes | - | **Branch: By Team Member ID** . Proxied team member ID ( `tmbId` ), takes precedence over `username` . pattern: `^[0-9a-fA-F]{24}$` | | `authProxy.username` | `string` | Yes | - | **Branch: By Username** . Proxied team member username. minLength: 1; maxLength: 128 | * **Skill Debug Session** Identify the debug session via `skillId` (takes precedence over `appId` and ignores `sourceType` ), authenticated with allowed request header credentials. | Field | Type | Required | Default | Constraints & Description | | --------- | -------- | -------- | ------- | ------------------------------------------------------------------------------------------------------- | | `skillId` | `string` | Yes | - | Skill Edit debug ID authenticated with allowed request header credentials. pattern: `^[0-9a-fA-F]{24}$` | * **Share-Link Chat** Resolves the underlying app via `outLinkAuthData` , taking precedence over `skillId` and `appId` (ignoring `sourceType` ). Protected links still validate login cookies/tokens and never fall back to standard auth on failure. | Field | Type | Required | Default | Constraints & Description | | ---------------------------- | -------- | -------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | | `outLinkAuthData` | `object` | Yes | - | Share-link auth payload ( `shareId` / `outLinkUid` ). Overrides `skillId` and `appId` ; protected links still validate login session cookies/tokens. | | `outLinkAuthData.shareId` | `string` | Yes | - | Share link ID. minLength: 1 | | `outLinkAuthData.outLinkUid` | `string` | Yes | - | External share user ID. minLength: 1 | * **App API Key (no appId required)** When authorizing with an app-bound App API Key, omit `appId` and `sourceType` ; the server resolves the bound app with `sourceType` fixed to `app` . Personal keys and login sessions cannot omit `appId` , and an explicit `appId` does not override an App API Key binding. **Default Identity** : Omit `customUid` and `authProxy` to execute using the team member identity associated with the credential. **Custom end user ( `customUid` )**: Tag end users from your own system via `customUid` without changing the authenticating member or permissions. Passed as workflow `userId` and used to scope chat management. | Field | Type | Required | Default | Constraints & Description | | ----------- | -------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `customUid` | `string` | Yes | - | Supported only for standard app API Key calls. Exact match against the external user ID ( `outLinkUid` , not `tmbId` ). Omit to keep full scope or pass to restrict reads, updates, and deletions (max 1024 chars, cannot be empty or `null` , does not change member identity). minLength: 1; maxLength: 1024 | ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X DELETE "https://cloud.fastgpt.io/api/core/chat/record/delete" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ --data-raw '{ "appId": "68ad85a7463006c963799a05", "chatId": "chat123" }' ``` ### Minimal Valid JSON Body ```json { "appId": "68ad85a7463006c963799a05", "chatId": "chat123" } ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Deleted successfully Returns the standard FastGPT success envelope ( `{ "code": 200, "statusText": "", "message": "", "data": ... }` ). The exact `data` payload schema is not declared in this OpenAPI contract; refer to the status description above or inspect runtime responses. file: ./content/openapi/reference/chat-record/get-collection-quote.en.mdx url: https://doc.fastgpt.io/openapi/reference/chat-record/get-collection-quote title: Get Collection Citation Chunks last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "Get Collection Citation Chunks", "seoTitle": "Get Collection Citation Chunks - POST /api/core/chat/record/getCollectionQuote | FastGPT OpenAPI", "description": "Paginate forward and backward around a cited chunk index inside a referenced dataset collection during chat inspection." } ## Endpoint Overview * **Method** : `POST` * **Path** : `/api/core/chat/record/getCollectionQuote` * **Module** : Chat / Chat Records * **Authentication** : `Authorization: Bearer `—Supports **App API Key** ( `appId` optional) and **Personal API Key** ( `appId` required); also supports `authProxy` team member proxy and `outLinkAuthData` share link (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E5%AF%B9%E8%AF%9D%E7%AE%A1%E7%90%86/POST/core/chat/record/getCollectionQuote) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E5%AF%B9%E8%AF%9D%E7%AE%A1%E7%90%86/POST/core/chat/record/getCollectionQuote` ) ## Description & Notes Paginate forward or backward around a cited chunk index inside a collection (requires chat access). ## Request Parameters ### Request Body ( `application/json` ) #### Shared Parameters Across Branches | Field | Type | Required | Default | Constraints & Description | | ---------------- | --------- | -------- | ------- | -------------------------------------------------------------- | | `chatId` | `string` | Yes | - | Chat ID. minLength: 1; maxLength: 1024 | | `chatItemDataId` | `string` | Yes | - | Chat message `dataId` . minLength: 1; maxLength: 256 | | `collectionId` | `string` | Yes | - | Collection ID. pattern: `^[0-9a-fA-F]{24}$` | | `pageSize` | `integer` | No | `20` | Items per page (default 20, range `[1, 30]` ). min: 1; max: 30 | | `anchor` | `number` | No | - | Current anchor `chunkIndex` | | `initialId` | `string` | No | - | Initial anchor message data ID | | `nextId` | `string` | No | - | Cursor data ID for paging forward | | `prevId` | `string` | No | - | Cursor data ID for paging backward | **Mutually Exclusive Branches ( `anyOf` )** * **App Chat** Identify the conversation via `appId` . When both API Key and login session are supported, `Authorization` takes precedence over token/Cookie. | Field | Type | Required | Default | Constraints & Description | | ------------ | --------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `appId` | `string` | Yes | - | Application ID authenticated with the request header credentials allowed by this endpoint. pattern: `^[0-9a-fA-F]{24}$` | | `sourceType` | `string` (enum) | No | - | Session resource type associated with `appId` . Defaults to `app` ; pass the matching `sourceType` for assistant builder sessions. Allowed values: `app` , `chatAgentHelper` , `workflowBuilder` | **Default Identity** : Omit `customUid` and `authProxy` to execute using the team member identity associated with the credential. **Custom end user ( `customUid` )**: Tag end users from your own system via `customUid` without changing the authenticating member or permissions. Passed as workflow `userId` and used to scope chat management. | Field | Type | Required | Default | Constraints & Description | | ----------- | -------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `customUid` | `string` | Yes | - | Supported only for standard app API Key calls. Exact match against the external user ID ( `outLinkUid` , not `tmbId` ). Omit to keep full scope or pass to restrict reads, updates, and deletions (max 1024 chars, cannot be empty or `null` , does not change member identity). minLength: 1; maxLength: 1024 | **Proxy Team Member ( `authProxy` )**: Act on behalf of another member in the same team via `authProxy` . Available only on personal API keys with `authProxy` enabled; mutually exclusive with `customUid` . | Field | Type | Required | Default | Constraints & Description | | -------------------- | -------- | -------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `authProxy` | `object` | Yes | - | API Key proxy caller identity. Available only for personal keys with `authProxy` enabled; specify `tmbId` or `username` ( `tmbId` takes precedence without falling back to `username` on invalid ID). | | `authProxy.tmbId` | `string` | Yes | - | **Branch: By Team Member ID** . Proxied team member ID ( `tmbId` ), takes precedence over `username` . pattern: `^[0-9a-fA-F]{24}$` | | `authProxy.username` | `string` | Yes | - | **Branch: By Username** . Proxied team member username. minLength: 1; maxLength: 128 | * **Skill Debug Session** Identify the debug session via `skillId` (takes precedence over `appId` and ignores `sourceType` ), authenticated with allowed request header credentials. | Field | Type | Required | Default | Constraints & Description | | --------- | -------- | -------- | ------- | ------------------------------------------------------------------------------------------------------- | | `skillId` | `string` | Yes | - | Skill Edit debug ID authenticated with allowed request header credentials. pattern: `^[0-9a-fA-F]{24}$` | * **Share-Link Chat** Resolves the underlying app via `outLinkAuthData` , taking precedence over `skillId` and `appId` (ignoring `sourceType` ). Protected links still validate login cookies/tokens and never fall back to standard auth on failure. | Field | Type | Required | Default | Constraints & Description | | ---------------------------- | -------- | -------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | | `outLinkAuthData` | `object` | Yes | - | Share-link auth payload ( `shareId` / `outLinkUid` ). Overrides `skillId` and `appId` ; protected links still validate login session cookies/tokens. | | `outLinkAuthData.shareId` | `string` | Yes | - | Share link ID. minLength: 1 | | `outLinkAuthData.outLinkUid` | `string` | Yes | - | External share user ID. minLength: 1 | * **App API Key (no appId required)** When authorizing with an app-bound App API Key, omit `appId` and `sourceType` ; the server resolves the bound app with `sourceType` fixed to `app` . Personal keys and login sessions cannot omit `appId` , and an explicit `appId` does not override an App API Key binding. **Default Identity** : Omit `customUid` and `authProxy` to execute using the team member identity associated with the credential. **Custom end user ( `customUid` )**: Tag end users from your own system via `customUid` without changing the authenticating member or permissions. Passed as workflow `userId` and used to scope chat management. | Field | Type | Required | Default | Constraints & Description | | ----------- | -------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `customUid` | `string` | Yes | - | Supported only for standard app API Key calls. Exact match against the external user ID ( `outLinkUid` , not `tmbId` ). Omit to keep full scope or pass to restrict reads, updates, and deletions (max 1024 chars, cannot be empty or `null` , does not change member identity). minLength: 1; maxLength: 1024 | ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X POST "https://cloud.fastgpt.io/api/core/chat/record/getCollectionQuote" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ --data-raw '{ "appId": "68ad85a7463006c963799a05", "chatId": "string", "chatItemDataId": "item_abc123", "collectionId": "68ee0bd23d17260b7829b137" }' ``` ### Minimal Valid JSON Body ```json { "appId": "68ad85a7463006c963799a05", "chatId": "string", "chatItemDataId": "item_abc123", "collectionId": "68ee0bd23d17260b7829b137" } ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Successfully returned paginated collection chunks **Content-Type** : `application/json` | Field | Type | Required | Default | Constraints & Description | | ----------------------------- | ---------- | -------- | ------- | ------------------------------------------------------- | | `list` | `object[]` | Yes | - | - | | `list[]._id` | `string` | Yes | - | Data item ID. pattern: `^[0-9a-fA-F]{24}$` | | `list[].q` | `string` | Yes | - | Primary chunk content / question | | `list[].a` | `string` | No | - | Supplementary answer / text | | `list[].imagePreivewUrl` | `string` | No | - | Image preview URL | | `list[].history` | `object[]` | No | - | Legacy snapshot flag | | `list[].history[].q` | `string` | Yes | - | Primary chunk content / question | | `list[].history[].a` | `string` | No | - | Supplementary answer / text | | `list[].history[].imageId` | `string` | No | - | Image ID | | `list[].history[].updateTime` | `string` | Yes | - | Update time | | `list[].updateTime` | `string` | Yes | - | Update time | | `list[].index` | `integer` | Yes | - | Chunk index. min: 0; max: 9007199254740991 | | `list[].updated` | `boolean` | No | - | Whether the chunk has been updated since citation | | `list[].id` | `string` | Yes | - | Data ID (alias of `_id` ) | | `list[].anchor` | `number` | No | - | Chunk sequence index (alias of `index` ) | | `hasMorePrev` | `boolean` | Yes | - | Whether earlier messages exist before the current slice | | `hasMoreNext` | `boolean` | Yes | - | Whether newer messages exist after the current slice | file: ./content/openapi/reference/chat-record/get-pagination-records.en.mdx url: https://doc.fastgpt.io/openapi/reference/chat-record/get-pagination-records title: List Chat Records (Paginated) last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "List Chat Records (Paginated)", "seoTitle": "List Chat Records (Paginated) - POST /api/core/chat/record/getPaginationRecords | FastGPT OpenAPI", "description": "Fetch paginated message records within a conversation using offset or page-number pagination across supported auth modes." } ## Endpoint Overview * **Method** : `POST` * **Path** : `/api/core/chat/record/getPaginationRecords` * **Module** : Chat / Chat Records * **Authentication** : `Authorization: Bearer `—Supports **App API Key** ( `appId` optional) and **Personal API Key** ( `appId` required); also supports `authProxy` team member proxy and `outLinkAuthData` share link (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E5%AF%B9%E8%AF%9D%E7%AE%A1%E7%90%86/POST/core/chat/record/getPaginationRecords) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E5%AF%B9%E8%AF%9D%E7%AE%A1%E7%90%86/POST/core/chat/record/getPaginationRecords` ) ## Description & Notes Retrieve paginated conversation records for a specified chat session across supported authentication modes. ## Request Parameters ### Request Body ( `application/json` ) #### Shared Parameters Across Branches | Field | Type | Required | Default | Constraints & Description | | --------------------- | --------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------ | | `chatId` | `string` | No | - | Chat ID. maxLength: 1024 | | `loadCustomFeedbacks` | `boolean` | No | - | Whether to load custom feedback items | | `type` | `string` (enum) | No | - | Fetch mode controlling message visibility and filtering. Allowed values: `normal` , `outLink` , `home` | | `includeDeleted` | `boolean` | No | - | Whether to include soft-deleted messages | **Mutually Exclusive Branches ( `anyOf` )** * **App Chat** Identify the conversation via `appId` . When both API Key and login session are supported, `Authorization` takes precedence over token/Cookie. | Field | Type | Required | Default | Constraints & Description | | ------------ | --------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `appId` | `string` | Yes | - | Application ID authenticated with the request header credentials allowed by this endpoint. pattern: `^[0-9a-fA-F]{24}$` | | `sourceType` | `string` (enum) | No | - | Session resource type associated with `appId` . Defaults to `app` ; pass the matching `sourceType` for assistant builder sessions. Allowed values: `app` , `chatAgentHelper` , `workflowBuilder` | **Default Identity** : Omit `customUid` and `authProxy` to execute using the team member identity associated with the credential. **Custom end user ( `customUid` )**: Tag end users from your own system via `customUid` without changing the authenticating member or permissions. Passed as workflow `userId` and used to scope chat management. | Field | Type | Required | Default | Constraints & Description | | ----------- | -------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `customUid` | `string` | Yes | - | Supported only for standard app API Key calls. Exact match against the external user ID ( `outLinkUid` , not `tmbId` ). Omit to keep full scope or pass to restrict reads, updates, and deletions (max 1024 chars, cannot be empty or `null` , does not change member identity). minLength: 1; maxLength: 1024 | **Proxy Team Member ( `authProxy` )**: Act on behalf of another member in the same team via `authProxy` . Available only on personal API keys with `authProxy` enabled; mutually exclusive with `customUid` . | Field | Type | Required | Default | Constraints & Description | | -------------------- | -------- | -------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `authProxy` | `object` | Yes | - | API Key proxy caller identity. Available only for personal keys with `authProxy` enabled; specify `tmbId` or `username` ( `tmbId` takes precedence without falling back to `username` on invalid ID). | | `authProxy.tmbId` | `string` | Yes | - | **Branch: By Team Member ID** . Proxied team member ID ( `tmbId` ), takes precedence over `username` . pattern: `^[0-9a-fA-F]{24}$` | | `authProxy.username` | `string` | Yes | - | **Branch: By Username** . Proxied team member username. minLength: 1; maxLength: 128 | **Mutually Exclusive Branches ( `anyOf` )** * **Offset Pagination** Specify the 0-based starting offset; when both `offset` and `pageNum` are provided, `offset` takes precedence. | Field | Type | Required | Default | Constraints & Description | | ---------- | --------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | `offset` | `integer` | Yes | - | **Mutually Exclusive Group: Pagination Parameters** . 0-based offset. min: 0; max: 9007199254740991 | | `pageSize` | `integer` | No | `20` | **Mutually Exclusive Group: Pagination Parameters** . Items per page. Defaults to 20, capped at 500 (larger values are clamped to 500). max: 500 | * **Page-Number Pagination** Paginate by page number (starts at page 1); `pageSize` controls items per page. | Field | Type | Required | Default | Constraints & Description | | ---------- | --------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | `pageNum` | `integer` | No | `1` | **Mutually Exclusive Group: Pagination Parameters** . 1-based page number; ignored when `offset` is provided. max: 9007199254740991 | | `pageSize` | `integer` | No | `20` | **Mutually Exclusive Group: Pagination Parameters** . Items per page. Defaults to 20, capped at 500 (larger values are clamped to 500). max: 500 | * **Skill Debug Session** Identify the debug session via `skillId` (takes precedence over `appId` and ignores `sourceType` ), authenticated with allowed request header credentials. | Field | Type | Required | Default | Constraints & Description | | --------- | -------- | -------- | ------- | ------------------------------------------------------------------------------------------------------- | | `skillId` | `string` | Yes | - | Skill Edit debug ID authenticated with allowed request header credentials. pattern: `^[0-9a-fA-F]{24}$` | **Offset Pagination** : Specify the 0-based starting offset; when both `offset` and `pageNum` are provided, `offset` takes precedence. | Field | Type | Required | Default | Constraints & Description | | ---------- | --------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | `offset` | `integer` | Yes | - | **Mutually Exclusive Group: Pagination Parameters** . 0-based offset. min: 0; max: 9007199254740991 | | `pageSize` | `integer` | No | `20` | **Mutually Exclusive Group: Pagination Parameters** . Items per page. Defaults to 20, capped at 500 (larger values are clamped to 500). max: 500 | **Page-Number Pagination** : Paginate by page number (starts at page 1); `pageSize` controls items per page. | Field | Type | Required | Default | Constraints & Description | | ---------- | --------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | `pageNum` | `integer` | No | `1` | **Mutually Exclusive Group: Pagination Parameters** . 1-based page number; ignored when `offset` is provided. max: 9007199254740991 | | `pageSize` | `integer` | No | `20` | **Mutually Exclusive Group: Pagination Parameters** . Items per page. Defaults to 20, capped at 500 (larger values are clamped to 500). max: 500 | * **Share-Link Chat** Resolves the underlying app via `outLinkAuthData` , taking precedence over `skillId` and `appId` (ignoring `sourceType` ). Protected links still validate login cookies/tokens and never fall back to standard auth on failure. | Field | Type | Required | Default | Constraints & Description | | ---------------------------- | -------- | -------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | | `outLinkAuthData` | `object` | Yes | - | Share-link auth payload ( `shareId` / `outLinkUid` ). Overrides `skillId` and `appId` ; protected links still validate login session cookies/tokens. | | `outLinkAuthData.shareId` | `string` | Yes | - | Share link ID. minLength: 1 | | `outLinkAuthData.outLinkUid` | `string` | Yes | - | External share user ID. minLength: 1 | **Offset Pagination** : Specify the 0-based starting offset; when both `offset` and `pageNum` are provided, `offset` takes precedence. | Field | Type | Required | Default | Constraints & Description | | ---------- | --------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | `offset` | `integer` | Yes | - | **Mutually Exclusive Group: Pagination Parameters** . 0-based offset. min: 0; max: 9007199254740991 | | `pageSize` | `integer` | No | `20` | **Mutually Exclusive Group: Pagination Parameters** . Items per page. Defaults to 20, capped at 500 (larger values are clamped to 500). max: 500 | **Page-Number Pagination** : Paginate by page number (starts at page 1); `pageSize` controls items per page. | Field | Type | Required | Default | Constraints & Description | | ---------- | --------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | `pageNum` | `integer` | No | `1` | **Mutually Exclusive Group: Pagination Parameters** . 1-based page number; ignored when `offset` is provided. max: 9007199254740991 | | `pageSize` | `integer` | No | `20` | **Mutually Exclusive Group: Pagination Parameters** . Items per page. Defaults to 20, capped at 500 (larger values are clamped to 500). max: 500 | * **App API Key (no appId required)** When authorizing with an app-bound App API Key, omit `appId` and `sourceType` ; the server resolves the bound app with `sourceType` fixed to `app` . Personal keys and login sessions cannot omit `appId` , and an explicit `appId` does not override an App API Key binding. **Default Identity** : Omit `customUid` and `authProxy` to execute using the team member identity associated with the credential. **Custom end user ( `customUid` )**: Tag end users from your own system via `customUid` without changing the authenticating member or permissions. Passed as workflow `userId` and used to scope chat management. | Field | Type | Required | Default | Constraints & Description | | ----------- | -------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `customUid` | `string` | Yes | - | Supported only for standard app API Key calls. Exact match against the external user ID ( `outLinkUid` , not `tmbId` ). Omit to keep full scope or pass to restrict reads, updates, and deletions (max 1024 chars, cannot be empty or `null` , does not change member identity). minLength: 1; maxLength: 1024 | **Mutually Exclusive Branches ( `anyOf` )** * **Offset Pagination** Specify the 0-based starting offset; when both `offset` and `pageNum` are provided, `offset` takes precedence. | Field | Type | Required | Default | Constraints & Description | | ---------- | --------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | `offset` | `integer` | Yes | - | **Mutually Exclusive Group: Pagination Parameters** . 0-based offset. min: 0; max: 9007199254740991 | | `pageSize` | `integer` | No | `20` | **Mutually Exclusive Group: Pagination Parameters** . Items per page. Defaults to 20, capped at 500 (larger values are clamped to 500). max: 500 | * **Page-Number Pagination** Paginate by page number (starts at page 1); `pageSize` controls items per page. | Field | Type | Required | Default | Constraints & Description | | ---------- | --------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | `pageNum` | `integer` | No | `1` | **Mutually Exclusive Group: Pagination Parameters** . 1-based page number; ignored when `offset` is provided. max: 9007199254740991 | | `pageSize` | `integer` | No | `20` | **Mutually Exclusive Group: Pagination Parameters** . Items per page. Defaults to 20, capped at 500 (larger values are clamped to 500). max: 500 | ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X POST "https://cloud.fastgpt.io/api/core/chat/record/getPaginationRecords" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ --data-raw '{ "appId": "68ad85a7463006c963799a05", "offset": 0 }' ``` ### Minimal Valid JSON Body ```json { "appId": "68ad85a7463006c963799a05", "offset": 0 } ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Successfully returned chat records **Content-Type** : `application/json` | Field | Type | Required | Default | Constraints & Description | | ------- | ---------- | -------- | ------- | ------------------------------------------ | | `list` | `object[]` | Yes | - | Chat record list | | `total` | `integer` | Yes | - | Total count. min: 0; max: 9007199254740991 | file: ./content/openapi/reference/chat-record/get-quote.en.mdx url: https://doc.fastgpt.io/openapi/reference/chat-record/get-quote title: Get Chat Record Citations last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "Get Chat Record Citations", "seoTitle": "Get Chat Record Citations - POST /api/core/chat/record/getQuote | FastGPT OpenAPI", "description": "Retrieve referenced knowledge base chunk contents, scores, and source details for a specified chat message." } ## Endpoint Overview * **Method** : `POST` * **Path** : `/api/core/chat/record/getQuote` * **Module** : Chat / Chat Records * **Authentication** : `Authorization: Bearer `—Supports **App API Key** ( `appId` optional) and **Personal API Key** ( `appId` required); also supports `authProxy` team member proxy and `outLinkAuthData` share link (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E5%AF%B9%E8%AF%9D%E7%AE%A1%E7%90%86/POST/core/chat/record/getQuote) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E5%AF%B9%E8%AF%9D%E7%AE%A1%E7%90%86/POST/core/chat/record/getQuote` ) ## Description & Notes Retrieve dataset citation chunks for a specified chat message (requires chat read access). ## Request Parameters ### Request Body ( `application/json` ) #### Shared Parameters Across Branches | Field | Type | Required | Default | Constraints & Description | | ------------------- | ---------- | -------- | ------- | ---------------------------------------------------- | | `chatId` | `string` | Yes | - | Chat ID. minLength: 1; maxLength: 1024 | | `chatItemDataId` | `string` | Yes | - | Chat message `dataId` . minLength: 1; maxLength: 256 | | `datasetDataIdList` | `string[]` | Yes | - | List of dataset data item IDs. maxItems: 200 | | `collectionIdList` | `string[]` | Yes | - | List of collection IDs. maxItems: 200 | **Mutually Exclusive Branches ( `anyOf` )** * **App Chat** Identify the conversation via `appId` . When both API Key and login session are supported, `Authorization` takes precedence over token/Cookie. | Field | Type | Required | Default | Constraints & Description | | ------------ | --------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `appId` | `string` | Yes | - | Application ID authenticated with the request header credentials allowed by this endpoint. pattern: `^[0-9a-fA-F]{24}$` | | `sourceType` | `string` (enum) | No | - | Session resource type associated with `appId` . Defaults to `app` ; pass the matching `sourceType` for assistant builder sessions. Allowed values: `app` , `chatAgentHelper` , `workflowBuilder` | **Default Identity** : Omit `customUid` and `authProxy` to execute using the team member identity associated with the credential. **Custom end user ( `customUid` )**: Tag end users from your own system via `customUid` without changing the authenticating member or permissions. Passed as workflow `userId` and used to scope chat management. | Field | Type | Required | Default | Constraints & Description | | ----------- | -------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `customUid` | `string` | Yes | - | Supported only for standard app API Key calls. Exact match against the external user ID ( `outLinkUid` , not `tmbId` ). Omit to keep full scope or pass to restrict reads, updates, and deletions (max 1024 chars, cannot be empty or `null` , does not change member identity). minLength: 1; maxLength: 1024 | **Proxy Team Member ( `authProxy` )**: Act on behalf of another member in the same team via `authProxy` . Available only on personal API keys with `authProxy` enabled; mutually exclusive with `customUid` . | Field | Type | Required | Default | Constraints & Description | | -------------------- | -------- | -------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `authProxy` | `object` | Yes | - | API Key proxy caller identity. Available only for personal keys with `authProxy` enabled; specify `tmbId` or `username` ( `tmbId` takes precedence without falling back to `username` on invalid ID). | | `authProxy.tmbId` | `string` | Yes | - | **Branch: By Team Member ID** . Proxied team member ID ( `tmbId` ), takes precedence over `username` . pattern: `^[0-9a-fA-F]{24}$` | | `authProxy.username` | `string` | Yes | - | **Branch: By Username** . Proxied team member username. minLength: 1; maxLength: 128 | * **Skill Debug Session** Identify the debug session via `skillId` (takes precedence over `appId` and ignores `sourceType` ), authenticated with allowed request header credentials. | Field | Type | Required | Default | Constraints & Description | | --------- | -------- | -------- | ------- | ------------------------------------------------------------------------------------------------------- | | `skillId` | `string` | Yes | - | Skill Edit debug ID authenticated with allowed request header credentials. pattern: `^[0-9a-fA-F]{24}$` | * **Share-Link Chat** Resolves the underlying app via `outLinkAuthData` , taking precedence over `skillId` and `appId` (ignoring `sourceType` ). Protected links still validate login cookies/tokens and never fall back to standard auth on failure. | Field | Type | Required | Default | Constraints & Description | | ---------------------------- | -------- | -------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | | `outLinkAuthData` | `object` | Yes | - | Share-link auth payload ( `shareId` / `outLinkUid` ). Overrides `skillId` and `appId` ; protected links still validate login session cookies/tokens. | | `outLinkAuthData.shareId` | `string` | Yes | - | Share link ID. minLength: 1 | | `outLinkAuthData.outLinkUid` | `string` | Yes | - | External share user ID. minLength: 1 | * **App API Key (no appId required)** When authorizing with an app-bound App API Key, omit `appId` and `sourceType` ; the server resolves the bound app with `sourceType` fixed to `app` . Personal keys and login sessions cannot omit `appId` , and an explicit `appId` does not override an App API Key binding. **Default Identity** : Omit `customUid` and `authProxy` to execute using the team member identity associated with the credential. **Custom end user ( `customUid` )**: Tag end users from your own system via `customUid` without changing the authenticating member or permissions. Passed as workflow `userId` and used to scope chat management. | Field | Type | Required | Default | Constraints & Description | | ----------- | -------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `customUid` | `string` | Yes | - | Supported only for standard app API Key calls. Exact match against the external user ID ( `outLinkUid` , not `tmbId` ). Omit to keep full scope or pass to restrict reads, updates, and deletions (max 1024 chars, cannot be empty or `null` , does not change member identity). minLength: 1; maxLength: 1024 | ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X POST "https://cloud.fastgpt.io/api/core/chat/record/getQuote" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ --data-raw '{ "appId": "68ad85a7463006c963799a05", "chatId": "string", "chatItemDataId": "item_abc123", "datasetDataIdList": [ "68ad85a7463006c963799a05" ], "collectionIdList": [ "68ad85a7463006c963799a06" ] }' ``` ### Minimal Valid JSON Body ```json { "appId": "68ad85a7463006c963799a05", "chatId": "string", "chatItemDataId": "item_abc123", "datasetDataIdList": ["68ad85a7463006c963799a05"], "collectionIdList": ["68ad85a7463006c963799a06"] } ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Successfully returned citation list **Content-Type** : `application/json` **Root Type** : Array ( `object[]` ). Each array item has the following fields: | Field | Type | Required | Default | Constraints & Description | | ---------------------- | ---------- | -------- | ------- | ------------------------------------------------- | | `_id` | `string` | Yes | - | Data item ID. pattern: `^[0-9a-fA-F]{24}$` | | `q` | `string` | Yes | - | Primary chunk content / question | | `a` | `string` | No | - | Supplementary answer / text | | `imagePreivewUrl` | `string` | No | - | Image preview URL | | `history` | `object[]` | No | - | Legacy snapshot flag | | `history[].q` | `string` | Yes | - | Primary chunk content / question | | `history[].a` | `string` | No | - | Supplementary answer / text | | `history[].imageId` | `string` | No | - | Image ID | | `history[].updateTime` | `string` | Yes | - | Update time | | `updateTime` | `string` | Yes | - | Update time | | `index` | `integer` | Yes | - | Chunk index. min: 0; max: 9007199254740991 | | `updated` | `boolean` | No | - | Whether the chunk has been updated since citation | file: ./content/openapi/reference/chat-record/get-records-v2.en.mdx url: https://doc.fastgpt.io/openapi/reference/chat-record/get-records-v2 title: List Chat Records by Cursor last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "List Chat Records by Cursor", "seoTitle": "List Chat Records by Cursor - POST /api/core/chat/record/getRecords_v2 | FastGPT OpenAPI", "description": "Retrieve chronological conversation messages around a cursor anchor with automatic turn alignment and bidirectional cursors." } ## Endpoint Overview * **Method** : `POST` * **Path** : `/api/core/chat/record/getRecords_v2` * **Module** : Chat / Chat Records * **Authentication** : `Authorization: Bearer `—Supports **App API Key** ( `appId` optional) and **Personal API Key** ( `appId` required); also supports `authProxy` team member proxy and `outLinkAuthData` share link (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E5%AF%B9%E8%AF%9D%E7%AE%A1%E7%90%86/POST/core/chat/record/getRecords_v2) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E5%AF%B9%E8%AF%9D%E7%AE%A1%E7%90%86/POST/core/chat/record/getRecords_v2` ) ## Description & Notes Fetches the latest messages by default in chronological order. Provide at most one of `prevId` (targets Human turn boundary), `nextId` , or `initialId` (targets AI turn boundary). Pass `prevCursor` / `nextCursor` directly to `prevId` / `nextId` ( `null` when no further page exists). Returned count may slightly exceed `pageSize` to complete turn boundaries. ## Request Parameters ### Request Body ( `application/json` ) #### Shared Parameters Across Branches | Field | Type | Required | Default | Constraints & Description | | --------------------- | --------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------ | | `chatId` | `string` | No | - | Chat ID. maxLength: 1024 | | `loadCustomFeedbacks` | `boolean` | No | - | Whether to load custom feedback items | | `type` | `string` (enum) | No | - | Fetch mode controlling message visibility and filtering. Allowed values: `normal` , `outLink` , `home` | | `includeDeleted` | `boolean` | No | - | Whether to include soft-deleted messages | **Mutually Exclusive Branches ( `anyOf` )** * **App Chat** Identify the conversation via `appId` . When both API Key and login session are supported, `Authorization` takes precedence over token/Cookie. | Field | Type | Required | Default | Constraints & Description | | ------------ | --------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `appId` | `string` | Yes | - | Application ID authenticated with the request header credentials allowed by this endpoint. pattern: `^[0-9a-fA-F]{24}$` | | `sourceType` | `string` (enum) | No | - | Session resource type associated with `appId` . Defaults to `app` ; pass the matching `sourceType` for assistant builder sessions. Allowed values: `app` , `chatAgentHelper` , `workflowBuilder` | **Default Identity** : Omit `customUid` and `authProxy` to execute using the team member identity associated with the credential. **Custom end user ( `customUid` )**: Tag end users from your own system via `customUid` without changing the authenticating member or permissions. Passed as workflow `userId` and used to scope chat management. | Field | Type | Required | Default | Constraints & Description | | ----------- | -------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `customUid` | `string` | Yes | - | Supported only for standard app API Key calls. Exact match against the external user ID ( `outLinkUid` , not `tmbId` ). Omit to keep full scope or pass to restrict reads, updates, and deletions (max 1024 chars, cannot be empty or `null` , does not change member identity). minLength: 1; maxLength: 1024 | **Proxy Team Member ( `authProxy` )**: Act on behalf of another member in the same team via `authProxy` . Available only on personal API keys with `authProxy` enabled; mutually exclusive with `customUid` . | Field | Type | Required | Default | Constraints & Description | | -------------------- | -------- | -------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `authProxy` | `object` | Yes | - | API Key proxy caller identity. Available only for personal keys with `authProxy` enabled; specify `tmbId` or `username` ( `tmbId` takes precedence without falling back to `username` on invalid ID). | | `authProxy.tmbId` | `string` | Yes | - | **Branch: By Team Member ID** . Proxied team member ID ( `tmbId` ), takes precedence over `username` . pattern: `^[0-9a-fA-F]{24}$` | | `authProxy.username` | `string` | Yes | - | **Branch: By Username** . Proxied team member username. minLength: 1; maxLength: 128 | * **Skill Debug Session** Identify the debug session via `skillId` (takes precedence over `appId` and ignores `sourceType` ), authenticated with allowed request header credentials. | Field | Type | Required | Default | Constraints & Description | | --------- | -------- | -------- | ------- | ------------------------------------------------------------------------------------------------------- | | `skillId` | `string` | Yes | - | Skill Edit debug ID authenticated with allowed request header credentials. pattern: `^[0-9a-fA-F]{24}$` | * **Share-Link Chat** Resolves the underlying app via `outLinkAuthData` , taking precedence over `skillId` and `appId` (ignoring `sourceType` ). Protected links still validate login cookies/tokens and never fall back to standard auth on failure. | Field | Type | Required | Default | Constraints & Description | | ---------------------------- | -------- | -------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | | `outLinkAuthData` | `object` | Yes | - | Share-link auth payload ( `shareId` / `outLinkUid` ). Overrides `skillId` and `appId` ; protected links still validate login session cookies/tokens. | | `outLinkAuthData.shareId` | `string` | Yes | - | Share link ID. minLength: 1 | | `outLinkAuthData.outLinkUid` | `string` | Yes | - | External share user ID. minLength: 1 | * **App API Key (no appId required)** When authorizing with an app-bound App API Key, omit `appId` and `sourceType` ; the server resolves the bound app with `sourceType` fixed to `app` . Personal keys and login sessions cannot omit `appId` , and an explicit `appId` does not override an App API Key binding. **Default Identity** : Omit `customUid` and `authProxy` to execute using the team member identity associated with the credential. **Custom end user ( `customUid` )**: Tag end users from your own system via `customUid` without changing the authenticating member or permissions. Passed as workflow `userId` and used to scope chat management. | Field | Type | Required | Default | Constraints & Description | | ----------- | -------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `customUid` | `string` | Yes | - | Supported only for standard app API Key calls. Exact match against the external user ID ( `outLinkUid` , not `tmbId` ). Omit to keep full scope or pass to restrict reads, updates, and deletions (max 1024 chars, cannot be empty or `null` , does not change member identity). minLength: 1; maxLength: 1024 | #### Shared Parameters Across Branches | Field | Type | Required | Default | Constraints & Description | | -------- | -------------------------------------------------------- | -------- | ------- | ----------------------------------------------- | | `anchor` | `object \| array \| string \| number \| boolean \| null` | No | - | Current anchor position (such as `chunkIndex` ) | **Mutually Exclusive Branches ( `anyOf` )** * **Page Backward ( `prevId` )** | Field | Type | Required | Default | Constraints & Description | | ---------- | --------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `prevId` | `string` | Yes | - | Cursor data ID for paging backward | | `pageSize` | `integer` | No | `20` | **Mutually Exclusive Group: Pagination Parameters** . Target messages per page (default 20, max 500; may be slightly exceeded to complete turn boundaries). max: 500 | * **Page Forward ( `nextId` )** | Field | Type | Required | Default | Constraints & Description | | ---------- | --------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `nextId` | `string` | Yes | - | Cursor data ID for paging forward | | `pageSize` | `integer` | No | `20` | **Mutually Exclusive Group: Pagination Parameters** . Target messages per page (default 20, max 500; may be slightly exceeded to complete turn boundaries). max: 500 | * **Anchor Record ( `initialId` )** | Field | Type | Required | Default | Constraints & Description | | ----------- | --------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `initialId` | `string` | Yes | - | Initial anchor message data ID | | `pageSize` | `integer` | No | `20` | **Mutually Exclusive Group: Pagination Parameters** . Target messages per page (default 20, max 500; may be slightly exceeded to complete turn boundaries). max: 500 | * **Default Latest Page** | Field | Type | Required | Default | Constraints & Description | | ---------- | --------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `pageSize` | `integer` | No | `20` | **Mutually Exclusive Group: Pagination Parameters** . Target messages per page (default 20, max 500; may be slightly exceeded to complete turn boundaries). max: 500 | ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X POST "https://cloud.fastgpt.io/api/core/chat/record/getRecords_v2" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ --data-raw '{ "appId": "68ad85a7463006c963799a05", "prevId": "68ad85a7463006c963799a04" }' ``` ### Minimal Valid JSON Body ```json { "appId": "68ad85a7463006c963799a05", "prevId": "68ad85a7463006c963799a04" } ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Successfully returned chat records **Content-Type** : `application/json` | Field | Type | Required | Default | Constraints & Description | | ------------- | ---------------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------- | | `hasMorePrev` | `boolean` | Yes | - | Whether earlier messages exist before the current slice | | `hasMoreNext` | `boolean` | Yes | - | Whether newer messages exist after the current slice | | `list` | `object[]` | Yes | - | Chronological list of chat records (use `dataId` as the canonical identifier) | | `total` | `integer` | Yes | - | min: -9007199254740991; max: 9007199254740991 | | `prevCursor` | `string \| null` | Yes | - | Cursor `dataId` for paging backward ( `prevId` ; server locates the Human turn start; `null` when unavailable) | | `nextCursor` | `string \| null` | Yes | - | Cursor `dataId` for paging forward ( `nextId` ; server locates the AI turn end; `null` when unavailable) | #### Polymorphic Field: `list` * **Variant 1** ( `obj="Human"` ): `obj` , `value` , `hideInUI` , `useAgentSandbox` , `totalQuoteList` , `toolCiteLinks` , `errorText` , `llmModuleAccount` * **Variant 2** ( `obj="System"` ): `obj` , `value` , `useAgentSandbox` , `totalQuoteList` , `toolCiteLinks` , `errorText` , `llmModuleAccount` , `historyPreviewLength` * **Variant 3** ( `obj="AI"` ): `obj` , `value` , `memories` , `userGoodFeedback` , `userBadFeedback` , `customFeedbacks` , `adminFeedback` , `isFeedbackRead` file: ./content/openapi/reference/chat-record/get-res-data.en.mdx url: https://doc.fastgpt.io/openapi/reference/chat-record/get-res-data title: Get Chat Record Response Details last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "Get Chat Record Response Details", "seoTitle": "Get Chat Record Response Details - GET /api/core/chat/record/getResData | FastGPT OpenAPI", "description": "Fetch detailed workflow node execution data (responseData) for a specific AI assistant message by dataId." } ## Endpoint Overview * **Method** : `GET` * **Path** : `/api/core/chat/record/getResData` * **Module** : Chat / Chat Records * **Authentication** : `Authorization: Bearer `—Supports **App API Key** ( `appId` optional) and **Personal API Key** ( `appId` required); also supports `authProxy` team member proxy and `outLinkAuthData` share link (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E5%AF%B9%E8%AF%9D%E7%AE%A1%E7%90%86/GET/core/chat/record/getResData) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E5%AF%B9%E8%AF%9D%E7%AE%A1%E7%90%86/GET/core/chat/record/getResData` ) ## Description & Notes Retrieve detailed Node.js execution data ( `responseData` ) for a specific AI message by `dataId` . ## Request Parameters ### Query Parameters #### Shared Parameters Across Branches | Field | Type | Required | Default | Constraints & Description | | -------- | -------- | -------- | ------- | ------------------------- | | `chatId` | `string` | No | - | Chat ID. maxLength: 1024 | | `dataId` | `string` | Yes | - | Chat record data ID | **Mutually Exclusive Branches ( `anyOf` )** * **App Chat** Identify the conversation via `appId` . When both API Key and login session are supported, `Authorization` takes precedence over token/Cookie. | Field | Type | Required | Default | Constraints & Description | | ------------ | --------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `appId` | `string` | Yes | - | Application ID authenticated with the request header credentials allowed by this endpoint. pattern: `^[0-9a-fA-F]{24}$` | | `sourceType` | `string` (enum) | No | - | Session resource type associated with `appId` . Defaults to `app` ; pass the matching `sourceType` for assistant builder sessions. Allowed values: `app` , `chatAgentHelper` , `workflowBuilder` | **Default Identity** : Omit `customUid` and `authProxy` to execute using the team member identity associated with the credential. **Custom end user ( `customUid` )**: Tag end users from your own system via `customUid` without changing the authenticating member or permissions. Passed as workflow `userId` and used to scope chat management. | Field | Type | Required | Default | Constraints & Description | | ----------- | -------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `customUid` | `string` | Yes | - | Supported only for standard app API Key calls. Exact match against the external user ID ( `outLinkUid` , not `tmbId` ). Omit to keep full scope or pass to restrict reads, updates, and deletions (max 1024 chars, cannot be empty or `null` , does not change member identity). minLength: 1; maxLength: 1024 | **Proxy Team Member ( `authProxy` )**: Act on behalf of another member in the same team via `authProxy` . Available only on personal API keys with `authProxy` enabled; mutually exclusive with `customUid` . | Field | Type | Required | Default | Constraints & Description | | ----------- | -------- | -------- | ------- | -------------------------------------------------------------------------------------- | | `authProxy` | `string` | Yes | - | JSON-serialized proxy identity, e.g. `{"tmbId":"member-id"}` or `{"username":"alice"}` | * **Skill Debug Session** Identify the debug session via `skillId` (takes precedence over `appId` and ignores `sourceType` ), authenticated with allowed request header credentials. | Field | Type | Required | Default | Constraints & Description | | --------- | -------- | -------- | ------- | ------------------------------------------------------------------------------------------------------- | | `skillId` | `string` | Yes | - | Skill Edit debug ID authenticated with allowed request header credentials. pattern: `^[0-9a-fA-F]{24}$` | * **Share-Link Chat** Resolves the underlying app via `outLinkAuthData` , taking precedence over `skillId` and `appId` (ignoring `sourceType` ). Protected links still validate login cookies/tokens and never fall back to standard auth on failure. | Field | Type | Required | Default | Constraints & Description | | ----------------- | -------- | -------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `outLinkAuthData` | `string` | Yes | - | JSON-serialized share-link auth payload containing `shareId` and `outLinkUid` . Overrides `skillId` and `appId` ; protected links still check login session cookies/tokens. | * **App API Key (no appId required)** When authorizing with an app-bound App API Key, omit `appId` and `sourceType` ; the server resolves the bound app with `sourceType` fixed to `app` . Personal keys and login sessions cannot omit `appId` , and an explicit `appId` does not override an App API Key binding. **Default Identity** : Omit `customUid` and `authProxy` to execute using the team member identity associated with the credential. **Custom end user ( `customUid` )**: Tag end users from your own system via `customUid` without changing the authenticating member or permissions. Passed as workflow `userId` and used to scope chat management. | Field | Type | Required | Default | Constraints & Description | | ----------- | -------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `customUid` | `string` | Yes | - | Supported only for standard app API Key calls. Exact match against the external user ID ( `outLinkUid` , not `tmbId` ). Omit to keep full scope or pass to restrict reads, updates, and deletions (max 1024 chars, cannot be empty or `null` , does not change member identity). minLength: 1; maxLength: 1024 | ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X GET "https://cloud.fastgpt.io/api/core/chat/record/getResData?appId=68ad85a7463006c963799a05&dataId=string" \ -H "Authorization: Bearer YOUR_API_KEY" ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Successfully returned response details Returns the standard FastGPT success envelope ( `{ "code": 200, "statusText": "", "message": "", "data": ... }` ). The exact `data` payload schema is not declared in this OpenAPI contract; refer to the status description above or inspect runtime responses. file: ./content/openapi/reference/dataset-collection-create/create.en.mdx url: https://doc.fastgpt.io/openapi/reference/dataset-collection-create/create title: Create Empty Collection or Folder last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "Create Empty Collection or Folder", "seoTitle": "Create Empty Collection or Folder - POST /api/core/dataset/collection/create | FastGPT OpenAPI", "description": "Create an empty virtual collection or folder inside a dataset with optional tags and parent permission inheritance." } ## Endpoint Overview * **Method** : `POST` * **Path** : `/api/core/dataset/collection/create` * **Module** : Datasets / Create Collections * **Authentication** : `Authorization: Bearer `—Personal API Key (access scoped by team member permissions) (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E9%9B%86%E5%90%88%E5%88%9B%E5%BB%BA/POST/core/dataset/collection/create) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E9%9B%86%E5%90%88%E5%88%9B%E5%BB%BA/POST/core/dataset/collection/create` ) ## Description & Notes Create an empty virtual dataset collection or folder. ## Request Parameters ### Request Body ( `application/json` ) | Field | Type | Required | Default | Constraints & Description | | ------------------- | -------------------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `datasetId` | `string` | Yes | - | Dataset ID | | `parentId` | `string \| null` | No | - | Parent folder ID | | `name` | `string` | Yes | - | Collection name | | `type` | `string` (enum) | Yes | - | Collection type ( `folder` or `virtual` manual collection). Allowed values: `folder` , `virtual` | | `tags` | `string \| object[]` | No | - | List of collection tags. String items map to legacy `default_tag` tags; object items `{ tag, value }` resolve by tag name. | | `inheritPermission` | `boolean` | No | - | Whether to inherit parent permissions (default `true` , applies only when `type=folder` ). `true` inherits from parent/dataset; `false` creates an isolated folder with creator `owner` permission only (requires collection-level permissions enabled on the dataset, otherwise returns `collectionPermissionDisabled` ). | ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X POST "https://cloud.fastgpt.io/api/core/dataset/collection/create" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ --data-raw '{ "datasetId": "string", "name": "string", "type": "folder" }' ``` ### Minimal Valid JSON Body ```json { "datasetId": "string", "name": "string", "type": "folder" } ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Successfully returned the newly created collection ID Returns the standard FastGPT success envelope ( `{ "code": 200, "statusText": "", "message": "", "data": ... }` ). The exact `data` payload schema is not declared in this OpenAPI contract; refer to the status description above or inspect runtime responses. file: ./content/openapi/reference/dataset-collection-create/link.en.mdx url: https://doc.fastgpt.io/openapi/reference/dataset-collection-create/link title: Create Collection from Link last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "Create Collection from Link", "seoTitle": "Create Collection from Link - POST /api/core/dataset/collection/create/link | FastGPT OpenAPI", "description": "Fetch web page content from a specified URL, split it using chunking settings, and create a dataset collection." } ## Endpoint Overview * **Method** : `POST` * **Path** : `/api/core/dataset/collection/create/link` * **Module** : Datasets / Create Collections * **Authentication** : `Authorization: Bearer `—Personal API Key (access scoped by team member permissions) (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E9%9B%86%E5%90%88%E5%88%9B%E5%BB%BA/POST/core/dataset/collection/create/link) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E9%9B%86%E5%90%88%E5%88%9B%E5%BB%BA/POST/core/dataset/collection/create/link` ) ## Description & Notes Fetch content from a specified web URL, create a collection, and trigger indexing training. ## Request Parameters ### Request Body ( `application/json` ) | Field | Type | Required | Default | Constraints & Description | | --------------------------- | -------------------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------- | | `trainingType` | `string` (enum) | No | - | Training mode. Allowed values: `chunk` , `qa` , `imageParse` , `backup` , `template` , `auto` | | `chunkTriggerType` | `string` (enum) | No | - | Chunk trigger mode. Allowed values: `minSize` , `forceChunk` , `maxSize` | | `chunkTriggerMinSize` | `number` | No | - | Minimum size threshold to trigger chunking | | `dataEnhanceCollectionName` | `boolean` | No | - | Prepend collection name to chunks | | `imageIndex` | `boolean` | No | - | Enable image indexing | | `autoIndexes` | `boolean` | No | - | Auto-generate vector indexes | | `indexPrefixTitle` | `boolean` | No | - | Prefix title for indexes | | `chunkSettingMode` | `string` (enum) | No | - | Chunk setting preset ( `auto` , `custom` , or `intelligent` ). Allowed values: `auto` , `custom` , `intelligent` | | `chunkSplitMode` | `string` (enum) | No | - | Chunk splitting mode. Allowed values: `paragraph` , `size` , `char` | | `paragraphChunkAIMode` | `string` (enum) | No | - | AI paragraph chunking mode. Allowed values: `auto` , `force` , `forbid` | | `paragraphChunkDeep` | `number` | No | - | Paragraph heading split depth | | `paragraphChunkMinSize` | `number` | No | - | Minimum paragraph chunk size | | `chunkSize` | `number` | No | - | Target chunk size | | `chunkSplitter` | `string` | No | - | Custom primary chunk separator | | `indexSize` | `number` | No | - | Vector index chunk size | | `qaPrompt` | `string` | No | - | Custom prompt for Q\&A extraction | | `parentId` | `string \| null` | No | - | Parent folder ID | | `metadata` | `object` | No | - | Metadata | | `customPdfParse` | `boolean` | No | - | Custom PDF parser | | `datasetId` | `string` | Yes | - | Dataset ID | | `tags` | `string \| object[]` | No | - | List of collection tags. String items map to legacy `default_tag` tags; object items `{ tag, value }` resolve by tag name. | | `link` | `string` | Yes | - | Source web page URL | ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X POST "https://cloud.fastgpt.io/api/core/dataset/collection/create/link" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ --data-raw '{ "datasetId": "string", "link": "string" }' ``` ### Minimal Valid JSON Body ```json { "datasetId": "string", "link": "string" } ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Successfully returned collection ID and chunk insertion results Returns the standard FastGPT success envelope ( `{ "code": 200, "statusText": "", "message": "", "data": ... }` ). The exact `data` payload schema is not declared in this OpenAPI contract; refer to the status description above or inspect runtime responses. file: ./content/openapi/reference/dataset-collection-create/local-file.en.mdx url: https://doc.fastgpt.io/openapi/reference/dataset-collection-create/local-file title: Create Collection from Local File last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "Create Collection from Local File", "seoTitle": "Create Collection from Local File - POST /api/core/dataset/collection/create/localFile | FastGPT OpenAPI", "description": "Upload a local file via multipart/form-data with chunking and training settings to create a collection and start indexing." } ## Endpoint Overview * **Method** : `POST` * **Path** : `/api/core/dataset/collection/create/localFile` * **Module** : Datasets / Create Collections * **Authentication** : `Authorization: Bearer `—Personal API Key (access scoped by team member permissions) (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E9%9B%86%E5%90%88%E5%88%9B%E5%BB%BA/POST/core/dataset/collection/create/localFile) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E9%9B%86%E5%90%88%E5%88%9B%E5%BB%BA/POST/core/dataset/collection/create/localFile` ) ## Description & Notes Upload a local file via `multipart/form-data` ( `file` binary part + JSON-serialized `data` part), store it in S3, create the collection, and trigger training. ## Request Parameters ### Request Body ( `multipart/form-data` ) | Field | Type | Required | Default | Constraints & Description | | -------------------------------- | -------------------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------- | | `file` | `binary` (file) | Yes | - | Uploaded binary file | | `data` | `object` | Yes | - | Collection parameters passed as a serialized JSON string | | `data.trainingType` | `string` (enum) | No | - | Training mode. Allowed values: `chunk` , `qa` , `imageParse` , `backup` , `template` , `auto` | | `data.chunkTriggerType` | `string` (enum) | No | - | Chunk trigger mode. Allowed values: `minSize` , `forceChunk` , `maxSize` | | `data.chunkTriggerMinSize` | `number` | No | - | Minimum size threshold to trigger chunking | | `data.dataEnhanceCollectionName` | `boolean` | No | - | Prepend collection name to chunks | | `data.imageIndex` | `boolean` | No | - | Enable image indexing | | `data.autoIndexes` | `boolean` | No | - | Auto-generate vector indexes | | `data.indexPrefixTitle` | `boolean` | No | - | Prefix title for indexes | | `data.chunkSettingMode` | `string` (enum) | No | - | Chunk setting preset ( `auto` , `custom` , or `intelligent` ). Allowed values: `auto` , `custom` , `intelligent` | | `data.chunkSplitMode` | `string` (enum) | No | - | Chunk splitting mode. Allowed values: `paragraph` , `size` , `char` | | `data.paragraphChunkAIMode` | `string` (enum) | No | - | AI paragraph chunking mode. Allowed values: `auto` , `force` , `forbid` | | `data.paragraphChunkDeep` | `number` | No | - | Paragraph heading split depth | | `data.paragraphChunkMinSize` | `number` | No | - | Minimum paragraph chunk size | | `data.chunkSize` | `number` | No | - | Target chunk size | | `data.chunkSplitter` | `string` | No | - | Custom primary chunk separator | | `data.indexSize` | `number` | No | - | Vector index chunk size | | `data.qaPrompt` | `string` | No | - | Custom prompt for Q\&A extraction | | `data.parentId` | `string \| null` | No | - | Parent folder ID | | `data.metadata` | `object` | No | - | Metadata | | `data.customPdfParse` | `boolean` | No | - | Custom PDF parser | | `data.datasetId` | `string` | Yes | - | Dataset ID | | `data.tags` | `string \| object[]` | No | - | List of collection tags. String items map to legacy `default_tag` tags; object items `{ tag, value }` resolve by tag name. | ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X POST "https://cloud.fastgpt.io/api/core/dataset/collection/create/localFile" \ -H "Authorization: Bearer YOUR_API_KEY" \ -F "file=@/path/to/document.pdf" \ -F 'data={"datasetId":"string"};type=application/json' ``` ### Minimal Valid JSON Body ```json { "datasetId": "string" } ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Successfully returned collection ID and chunk insertion results Returns the standard FastGPT success envelope ( `{ "code": 200, "statusText": "", "message": "", "data": ... }` ). The exact `data` payload schema is not declared in this OpenAPI contract; refer to the status description above or inspect runtime responses. file: ./content/openapi/reference/dataset-collection-create/text.en.mdx url: https://doc.fastgpt.io/openapi/reference/dataset-collection-create/text title: Create Collection from Text last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "Create Collection from Text", "seoTitle": "Create Collection from Text - POST /api/core/dataset/collection/create/text | FastGPT OpenAPI", "description": "Store raw text or Markdown content as a dataset collection and trigger asynchronous chunking and embedding training." } ## Endpoint Overview * **Method** : `POST` * **Path** : `/api/core/dataset/collection/create/text` * **Module** : Datasets / Create Collections * **Authentication** : `Authorization: Bearer `—Personal API Key (access scoped by team member permissions) (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E9%9B%86%E5%90%88%E5%88%9B%E5%BB%BA/POST/core/dataset/collection/create/text) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E9%9B%86%E5%90%88%E5%88%9B%E5%BB%BA/POST/core/dataset/collection/create/text` ) ## Description & Notes Store raw text content as a file, create a collection, and trigger indexing training. ## Request Parameters ### Request Body ( `application/json` ) | Field | Type | Required | Default | Constraints & Description | | --------------------------- | -------------------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------- | | `trainingType` | `string` (enum) | No | - | Training mode. Allowed values: `chunk` , `qa` , `imageParse` , `backup` , `template` , `auto` | | `chunkTriggerType` | `string` (enum) | No | - | Chunk trigger mode. Allowed values: `minSize` , `forceChunk` , `maxSize` | | `chunkTriggerMinSize` | `number` | No | - | Minimum size threshold to trigger chunking | | `dataEnhanceCollectionName` | `boolean` | No | - | Prepend collection name to chunks | | `imageIndex` | `boolean` | No | - | Enable image indexing | | `autoIndexes` | `boolean` | No | - | Auto-generate vector indexes | | `indexPrefixTitle` | `boolean` | No | - | Prefix title for indexes | | `chunkSettingMode` | `string` (enum) | No | - | Chunk setting preset ( `auto` , `custom` , or `intelligent` ). Allowed values: `auto` , `custom` , `intelligent` | | `chunkSplitMode` | `string` (enum) | No | - | Chunk splitting mode. Allowed values: `paragraph` , `size` , `char` | | `paragraphChunkAIMode` | `string` (enum) | No | - | AI paragraph chunking mode. Allowed values: `auto` , `force` , `forbid` | | `paragraphChunkDeep` | `number` | No | - | Paragraph heading split depth | | `paragraphChunkMinSize` | `number` | No | - | Minimum paragraph chunk size | | `chunkSize` | `number` | No | - | Target chunk size | | `chunkSplitter` | `string` | No | - | Custom primary chunk separator | | `indexSize` | `number` | No | - | Vector index chunk size | | `qaPrompt` | `string` | No | - | Custom prompt for Q\&A extraction | | `parentId` | `string \| null` | No | - | Parent folder ID | | `metadata` | `object` | No | - | Metadata | | `customPdfParse` | `boolean` | No | - | Custom PDF parser | | `datasetId` | `string` | Yes | - | Dataset ID | | `tags` | `string \| object[]` | No | - | List of collection tags. String items map to legacy `default_tag` tags; object items `{ tag, value }` resolve by tag name. | | `name` | `string` | Yes | - | Collection name | | `text` | `string` | Yes | - | Raw text content | ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X POST "https://cloud.fastgpt.io/api/core/dataset/collection/create/text" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ --data-raw '{ "datasetId": "string", "name": "string", "text": "string" }' ``` ### Minimal Valid JSON Body ```json { "datasetId": "string", "name": "string", "text": "string" } ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Successfully returned collection ID and chunk insertion results Returns the standard FastGPT success envelope ( `{ "code": 200, "statusText": "", "message": "", "data": ... }` ). The exact `data` payload schema is not declared in this OpenAPI contract; refer to the status description above or inspect runtime responses. file: ./content/openapi/reference/dataset-collection/batch-download.en.mdx url: https://doc.fastgpt.io/openapi/reference/dataset-collection/batch-download title: Download Collections Archive last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "Download Collections Archive", "seoTitle": "Download Collections Archive - GET /api/core/dataset/collection/batchDownload | FastGPT OpenAPI", "description": "Stream a ZIP archive containing original source files for dataset collections authorized by a short-lived download ticket." } ## Endpoint Overview * **Method** : `GET` * **Path** : `/api/core/dataset/collection/batchDownload` * **Module** : Datasets / Collections * **Authentication** : `Authorization: Bearer `—Personal API Key (access scoped by team member permissions) (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E9%9B%86%E5%90%88%E7%AE%A1%E7%90%86/GET/core/dataset/collection/batchDownload) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E9%9B%86%E5%90%88%E7%AE%A1%E7%90%86/GET/core/dataset/collection/batchDownload` ) ## Description & Notes Stream original source files for validated collections as a ZIP archive using a short-lived ticket. ## Request Parameters ### Query Parameters | Field | Type | Required | Default | Constraints & Description | | -------- | -------- | -------- | ------- | ---------------------------------------------------------------------------------- | | `ticket` | `string` | Yes | - | Short-lived single-use ticket issued by the download ticket endpoint. minLength: 1 | ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X GET "https://cloud.fastgpt.io/api/core/dataset/collection/batchDownload?ticket=01JZZ8B7M5Y7QJX9J7S5V7QJ4F" \ -H "Authorization: Bearer YOUR_API_KEY" ``` ## Response Schema & Examples ### HTTP 200 Successfully returned ZIP archive stream **Content-Type** : `application/zip` Returns raw binary stream ( `application/zip` ). Save with `curl -o archive.zip` . file: ./content/openapi/reference/dataset-collection/delete.en.mdx url: https://doc.fastgpt.io/openapi/reference/dataset-collection/delete title: Delete Dataset Collections last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "Delete Dataset Collections", "seoTitle": "Delete Dataset Collections - POST /api/core/dataset/collection/delete | FastGPT OpenAPI", "description": "Delete one or more collections and their child collections by ID, ID list, or external API file IDs (owner only)." } ## Endpoint Overview * **Method** : `POST` * **Path** : `/api/core/dataset/collection/delete` * **Module** : Datasets / Collections * **Authentication** : `Authorization: Bearer `—Personal API Key (access scoped by team member permissions) (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E9%9B%86%E5%90%88%E7%AE%A1%E7%90%86/POST/core/dataset/collection/delete) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E9%9B%86%E5%90%88%E7%AE%A1%E7%90%86/POST/core/dataset/collection/delete` ) ## Description & Notes Delete one or more collections and their child collections. Choose one body selector: `body.id` (single), `body.collectionIds` (batch), or `body.datasetId` + `body.apiFileIds` (external API dataset IDs). Owner permission is required (collaborators with manage/write cannot delete). Returns collection-not-found if no `apiFileIds` match. Legacy `query.id` remains supported for compatibility (takes precedence over valid body if both are sent, though deprecated in favor of `body.id` ). ## Request Parameters > **Parameter Alternatives** : Provide one of the following locator sets: `body.id` OR `body.collectionIds` OR `body.datasetId` + `body.apiFileIds` OR `query.id` . ### Query Parameters | Field | Type | Required | Default | Constraints & Description | | ----- | -------- | -------- | ------- | ------------------------------------------------------------------------------------------------ | | `id` | `string` | No | - | **Deprecated** . Legacy single collection ID query parameter (deprecated; use `body.id` instead) | ### Request Body ( `application/json` ) **Mutually Exclusive Branches ( `anyOf` )** * **Delete by Collection ID** Delete a single collection and all nested child collections | Field | Type | Required | Default | Constraints & Description | | ----- | -------- | -------- | ------- | ---------------------------------------------------------------------- | | `id` | `string` | Yes | - | Collection ID to delete along with all child collections. minLength: 1 | * **Delete by Collection ID List** Batch delete multiple collections and all nested child collections | Field | Type | Required | Default | Constraints & Description | | --------------- | ---------- | -------- | ------- | -------------------------------------------------------------------------------- | | `collectionIds` | `string[]` | Yes | - | List of collection IDs to delete along with their child collections. minItems: 1 | * **Delete by API File IDs** For external integrations targeting files/folders by `apiFileId` inside a dataset, deleting matched collections and their children. | Field | Type | Required | Default | Constraints & Description | | ------------ | ---------- | -------- | ------- | ------------------------------------------------------------------------------------- | | `datasetId` | `string` | Yes | - | Target dataset ID backed by an API file store. minLength: 1 | | `apiFileIds` | `string[]` | Yes | - | List of external API file or folder IDs; returns not-found if none match. minItems: 1 | * **Legacy `query.id` Compatibility** Allows an empty body when targeting via deprecated `query.id` ; rejected if no target selector is provided. No extra branch-specific fields are required. ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X POST "https://cloud.fastgpt.io/api/core/dataset/collection/delete" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ --data-raw '{ "id": "68ad85a7463006c963799a05" }' ``` ### Minimal Valid JSON Body ```json { "id": "68ad85a7463006c963799a05" } ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Successfully deleted collection(s) Returns the standard FastGPT success envelope ( `{ "code": 200, "statusText": "", "message": "", "data": ... }` ). The exact `data` payload schema is not declared in this OpenAPI contract; refer to the status description above or inspect runtime responses. file: ./content/openapi/reference/dataset-collection/detail.en.mdx url: https://doc.fastgpt.io/openapi/reference/dataset-collection/detail title: Get Collection Details last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "Get Collection Details", "seoTitle": "Get Collection Details - GET /api/core/dataset/collection/detail | FastGPT OpenAPI", "description": "Retrieve collection metadata, source file info, chunk and training status counts, and effective caller permissions." } ## Endpoint Overview * **Method** : `GET` * **Path** : `/api/core/dataset/collection/detail` * **Module** : Datasets / Collections * **Authentication** : `Authorization: Bearer `—Personal API Key (access scoped by team member permissions) (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E9%9B%86%E5%90%88%E7%AE%A1%E7%90%86/GET/core/dataset/collection/detail) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E9%9B%86%E5%90%88%E7%AE%A1%E7%90%86/GET/core/dataset/collection/detail` ) ## Description & Notes Retrieve detailed collection metadata including index counts, error counts, and file details (requires dataset and collection read access). ## Request Parameters ### Query Parameters | Field | Type | Required | Default | Constraints & Description | | ----- | -------- | -------- | ------- | ------------------------- | | `id` | `string` | Yes | - | Collection ID | ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X GET "https://cloud.fastgpt.io/api/core/dataset/collection/detail?id=string" \ -H "Authorization: Bearer YOUR_API_KEY" ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Successfully returned collection details Returns the standard FastGPT success envelope ( `{ "code": 200, "statusText": "", "message": "", "data": ... }` ). The exact `data` payload schema is not declared in this OpenAPI contract; refer to the status description above or inspect runtime responses. file: ./content/openapi/reference/dataset-collection/get-download-ticket.en.mdx url: https://doc.fastgpt.io/openapi/reference/dataset-collection/get-download-ticket title: Create Collection Download Ticket last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "Create Collection Download Ticket", "seoTitle": "Create Collection Download Ticket - POST /api/core/dataset/collection/getDownloadTicket | FastGPT OpenAPI", "description": "Validate access permissions and issue a short-lived single-use ticket for batch downloading dataset collection files." } ## Endpoint Overview * **Method** : `POST` * **Path** : `/api/core/dataset/collection/getDownloadTicket` * **Module** : Datasets / Collections * **Authentication** : `Authorization: Bearer `—Personal API Key (access scoped by team member permissions) (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E9%9B%86%E5%90%88%E7%AE%A1%E7%90%86/POST/core/dataset/collection/getDownloadTicket) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E9%9B%86%E5%90%88%E7%AE%A1%E7%90%86/POST/core/dataset/collection/getDownloadTicket` ) ## Description & Notes Validate access permissions and issue a short-lived single-use ticket for batch downloading dataset collections. ## Request Parameters ### Request Body ( `application/json` ) | Field | Type | Required | Default | Constraints & Description | | --------------- | ---------- | -------- | ------- | ----------------------------------------------- | | `datasetId` | `string` | Yes | - | Dataset ID. pattern: `^[0-9a-fA-F]{24}$` | | `collectionIds` | `string[]` | Yes | - | List of collection IDs to download. minItems: 1 | ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X POST "https://cloud.fastgpt.io/api/core/dataset/collection/getDownloadTicket" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ --data-raw '{ "datasetId": "68ad85a7463006c963799a05", "collectionIds": [ "68ad85a7463006c963799a06" ] }' ``` ### Minimal Valid JSON Body ```json { "datasetId": "68ad85a7463006c963799a05", "collectionIds": ["68ad85a7463006c963799a06"] } ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Successfully returned short-lived single-use download ticket **Content-Type** : `application/json` | Field | Type | Required | Default | Constraints & Description | | ----------- | -------- | -------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `ticket` | `string` | Yes | - | Short-lived single-use download ticket. minLength: 1 | | `expiresAt` | `string` | Yes | - | Ticket expiration timestamp. pattern: `^(?:(?:\d\d[2468][048]\|\d\d[13579][26]\|\d\d0[48]\|[02468][048]00\|[13579][26]00)-02-29\|\d{4}-(?:(?:0[13578]\|1[02])-(?:0[1-9]\|[12]\d\|3[01])\|(?:0[469]\|11)-(?:0[1-9]\|[12]\d\|30)\|(?:02)-(?:0[1-9]\|1\d\|2[0-8])))T(?:(?:[01]\d\|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z))$` | file: ./content/openapi/reference/dataset-collection/list-v2.en.mdx url: https://doc.fastgpt.io/openapi/reference/dataset-collection/list-v2 title: List Dataset Collections (V2) last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "List Dataset Collections (V2)", "seoTitle": "List Dataset Collections (V2) - POST /api/core/dataset/collection/listV2 | FastGPT OpenAPI", "description": "Query paginated collections and folders inside a dataset with keyword search, structured tag filters, and permission checks." } ## Endpoint Overview * **Method** : `POST` * **Path** : `/api/core/dataset/collection/listV2` * **Module** : Datasets / Collections * **Authentication** : `Authorization: Bearer `—Personal API Key (access scoped by team member permissions) (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E9%9B%86%E5%90%88%E7%AE%A1%E7%90%86/POST/core/dataset/collection/listV2) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E9%9B%86%E5%90%88%E7%AE%A1%E7%90%86/POST/core/dataset/collection/listV2` ) ## Description & Notes List collections in a dataset with pagination, search, and tag filters (requires dataset read permission and parent folder read permission when `parentId` is specified). When collection-level permissions are enabled, results are filtered per collection with effective permissions returned. ## Request Parameters ### Request Body ( `application/json` ) #### Shared Parameters Across Branches | Field | Type | Required | Default | Constraints & Description | | --------------------- | -------------------- | -------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | | `datasetId` | `string` | Yes | - | Dataset ID | | `parentId` | `string \| null` | No | `null` | Parent folder ID | | `searchText` | `string` | No | `""` | Search query text. maxLength: 100 | | `selectFolder` | `boolean` | No | `false` | Return folders only | | `tagFilters` | `object[]` | No | - | Filter by tag values (OR across values of the same tag, AND across distinct tags) | | `tagFilters[].tagId` | `string` | Yes | - | Tag ID. pattern: `^[0-9a-fA-F]{24}$` | | `tagFilters[].values` | `string \| number[]` | Yes | - | Selected tag values (strings for text/select, numbers for numeric, UTC millisecond timestamps for dates; OR across values of the same tag). minItems: 1 | | `sortBy` | `string` (enum) | No | `"updateTime"` | Sort field supporting name, creation time, and update time. Allowed values: `name` , `createTime` , `updateTime` | | `sortOrder` | `string` (enum) | No | `"desc"` | Sort direction. Allowed values: `asc` , `desc` | | `simple` | `boolean` | No | `false` | Simple mode (skips total item counts) | **Mutually Exclusive Branches ( `anyOf` )** * **Offset Pagination** Specify the 0-based starting offset; when both `offset` and `pageNum` are provided, `offset` takes precedence. | Field | Type | Required | Default | Constraints & Description | | ---------- | --------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | `offset` | `integer` | Yes | - | **Mutually Exclusive Group: Pagination Parameters** . 0-based offset. min: 0; max: 9007199254740991 | | `pageSize` | `integer` | No | `20` | **Mutually Exclusive Group: Pagination Parameters** . Items per page. Defaults to 20, capped at 500 (larger values are clamped to 500). max: 500 | * **Page-Number Pagination** Paginate by page number (starts at page 1); `pageSize` controls items per page. | Field | Type | Required | Default | Constraints & Description | | ---------- | --------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | `pageNum` | `integer` | No | `1` | **Mutually Exclusive Group: Pagination Parameters** . 1-based page number; ignored when `offset` is provided. max: 9007199254740991 | | `pageSize` | `integer` | No | `20` | **Mutually Exclusive Group: Pagination Parameters** . Items per page. Defaults to 20, capped at 500 (larger values are clamped to 500). max: 500 | ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X POST "https://cloud.fastgpt.io/api/core/dataset/collection/listV2" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ --data-raw '{ "offset": 0, "datasetId": "string" }' ``` ### Minimal Valid JSON Body ```json { "offset": 0, "datasetId": "string" } ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Successfully returned collection list and total count Returns the standard FastGPT success envelope ( `{ "code": 200, "statusText": "", "message": "", "data": ... }` ). The exact `data` payload schema is not declared in this OpenAPI contract; refer to the status description above or inspect runtime responses. file: ./content/openapi/reference/dataset-collection/update.en.mdx url: https://doc.fastgpt.io/openapi/reference/dataset-collection/update title: Update Dataset Collection last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "Update Dataset Collection", "seoTitle": "Update Dataset Collection - POST /api/core/dataset/collection/update | FastGPT OpenAPI", "description": "Update collection name, parent folder, disabled flag, or tags by collection ID or by datasetId and externalFileId." } ## Endpoint Overview * **Method** : `POST` * **Path** : `/api/core/dataset/collection/update` * **Module** : Datasets / Collections * **Authentication** : `Authorization: Bearer `—Personal API Key (access scoped by team member permissions) (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E9%9B%86%E5%90%88%E7%AE%A1%E7%90%86/POST/core/dataset/collection/update) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E9%9B%86%E5%90%88%E7%AE%A1%E7%90%86/POST/core/dataset/collection/update` ) ## Description & Notes Update collection metadata by collection ID or `datasetId` + `externalFileId` (requires collection write permission). Changing `parentId` moves the collection, requiring manage permissions on source and target parents (plus team dataset creation permission when moving between root and a folder); `inheritPermission` is not accepted and existing inheritance mode is preserved. ## Request Parameters ### Request Body ( `application/json` ) #### Shared Parameters Across Branches | Field | Type | Required | Default | Constraints & Description | | ------------ | -------------------- | -------- | ------- | ------------------------------------------------------------------- | | `parentId` | `string \| null` | No | - | Parent folder ID | | `name` | `string` | No | - | Collection name | | `tags` | `string \| object[]` | No | - | Tag list (supports legacy string names or `{ tag, value }` objects) | | `forbid` | `boolean` | No | - | Whether the collection is disabled | | `createTime` | `string` | No | - | Creation time | **Mutually Exclusive Branches ( `anyOf` )** * **Identify by `id`** | Field | Type | Required | Default | Constraints & Description | | ---------------- | -------- | -------- | ------- | ----------------------------------------------------------------------------------------------------- | | `id` | `string` | Yes | - | Collection ID (mutually exclusive with `datasetId` + `externalFileId` ). pattern: `^[0-9a-fA-F]{24}$` | | `datasetId` | `string` | No | - | Dataset ID used together with `externalFileId` | | `externalFileId` | `string` | No | - | External file ID used together with `datasetId` | * **Identify by `datasetId` & `externalFileId`** | Field | Type | Required | Default | Constraints & Description | | ---------------- | -------- | -------- | ------- | ----------------------------------------------------------------------------------------------------- | | `datasetId` | `string` | Yes | - | Dataset ID used together with `externalFileId` | | `externalFileId` | `string` | Yes | - | External file ID used together with `datasetId` | | `id` | `string` | No | - | Collection ID (mutually exclusive with `datasetId` + `externalFileId` ). pattern: `^[0-9a-fA-F]{24}$` | ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X POST "https://cloud.fastgpt.io/api/core/dataset/collection/update" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ --data-raw '{ "id": "68ee0bd23d17260b7829b137" }' ``` ### Minimal Valid JSON Body ```json { "id": "68ee0bd23d17260b7829b137" } ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Successfully updated collection metadata Returns the standard FastGPT success envelope ( `{ "code": 200, "statusText": "", "message": "", "data": ... }` ). The exact `data` payload schema is not declared in this OpenAPI contract; refer to the status description above or inspect runtime responses. file: ./content/openapi/reference/dataset-data/delete.en.mdx url: https://doc.fastgpt.io/openapi/reference/dataset-data/delete title: Delete Dataset Data Item last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "Delete Dataset Data Item", "seoTitle": "Delete Dataset Data Item - DELETE /api/core/dataset/data/delete | FastGPT OpenAPI", "description": "Delete a single data chunk and all of its associated vector and full-text search indexes from a dataset collection." } ## Endpoint Overview * **Method** : `DELETE` * **Path** : `/api/core/dataset/data/delete` * **Module** : Datasets / Dataset Data * **Authentication** : `Authorization: Bearer `—Personal API Key (access scoped by team member permissions) (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E6%95%B0%E6%8D%AE%E7%AE%A1%E7%90%86/DELETE/core/dataset/data/delete) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E6%95%B0%E6%8D%AE%E7%AE%A1%E7%90%86/DELETE/core/dataset/data/delete` ) ## Description & Notes Delete a specified dataset data item (requires write permission). ## Request Parameters ### Query Parameters | Field | Type | Required | Default | Constraints & Description | | ----- | -------- | -------- | ------- | ------------------------------------------ | | `id` | `string` | Yes | - | Data item ID. pattern: `^[0-9a-fA-F]{24}$` | ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X DELETE "https://cloud.fastgpt.io/api/core/dataset/data/delete?id=68ad85a7463006c963799a05" \ -H "Authorization: Bearer YOUR_API_KEY" ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Deleted successfully **Content-Type** : `application/json` file: ./content/openapi/reference/dataset-data/detail.en.mdx url: https://doc.fastgpt.io/openapi/reference/dataset-data/detail title: Get Dataset Data Item Details last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "Get Dataset Data Item Details", "seoTitle": "Get Dataset Data Item Details - GET /api/core/dataset/data/detail | FastGPT OpenAPI", "description": "Retrieve full question, answer, signed image URLs, and vector index entries for a single dataset data item by ID." } ## Endpoint Overview * **Method** : `GET` * **Path** : `/api/core/dataset/data/detail` * **Module** : Datasets / Dataset Data * **Authentication** : `Authorization: Bearer `—Personal API Key (access scoped by team member permissions) (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E6%95%B0%E6%8D%AE%E7%AE%A1%E7%90%86/GET/core/dataset/data/detail) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E6%95%B0%E6%8D%AE%E7%AE%A1%E7%90%86/GET/core/dataset/data/detail` ) ## Description & Notes Retrieve detailed content and vector indexes for a single dataset data item. ## Request Parameters ### Query Parameters | Field | Type | Required | Default | Constraints & Description | | ----- | -------- | -------- | ------- | ------------------------------------------ | | `id` | `string` | Yes | - | Data item ID. pattern: `^[0-9a-fA-F]{24}$` | ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X GET "https://cloud.fastgpt.io/api/core/dataset/data/detail?id=68ad85a7463006c963799a05" \ -H "Authorization: Bearer YOUR_API_KEY" ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Successfully returned data item details **Content-Type** : `application/json` | Field | Type | Required | Default | Constraints & Description | | ------------------ | --------------- | -------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `q` | `string` | Yes | - | Primary chunk content / question | | `a` | `string` | No | - | Supplementary answer / text | | `imageId` | `string` | No | - | Image ID | | `id` | `string` | Yes | - | Data item ID. pattern: `^[0-9a-fA-F]{24}$` | | `teamId` | `string` | Yes | - | Team ID. pattern: `^[0-9a-fA-F]{24}$` | | `datasetId` | `string` | Yes | - | Dataset ID. pattern: `^[0-9a-fA-F]{24}$` | | `collectionId` | `string` | Yes | - | Collection ID. pattern: `^[0-9a-fA-F]{24}$` | | `imagePreivewUrl` | `string` | No | - | Image preview URL | | `updateTime` | `string` | Yes | - | Update time | | `sourceName` | `string` | Yes | - | Source name | | `sourceId` | `string` | No | - | Source ID | | `chunkIndex` | `number` | Yes | - | Chunk index | | `indexes` | `object[]` | Yes | - | Vector indexes | | `indexes[].type` | `string` (enum) | Yes | `"custom"` | Index type (external callers omit or use `custom` ; other types are system-generated). Allowed values: `default` , `imageEmbedding` , `summary` , `question` , `image` , `custom` | | `indexes[].dataId` | `string` | Yes | - | Optional vector store ID used to reuse matching indexes without re-embedding | | `indexes[].text` | `string` | Yes | - | Indexed text content by default; for `imageEmbedding` , the image `objectKey` or URL | | `indexStatus` | `string` (enum) | No | - | Index status (absent on legacy already-indexed records). Allowed values: `indexing` , `indexed` , `error` , `rebuildIndexPending` , `rebuildIndexRunning` , `rebuildIndexFailed` , `rebuildSynonymPending` , `rebuildSynonymRunning` , `rebuildSynonymFailed` | | `indexErrorMsg` | `string` | No | - | Indexing error details | | `imageDescMap` | `object` | No | - | Image description mapping | | `isOwner` | `boolean` | Yes | - | Whether the caller is the owner | | `metadata` | `object` | No | - | Custom metadata | file: ./content/openapi/reference/dataset-data/push-data.en.mdx url: https://doc.fastgpt.io/openapi/reference/dataset-data/push-data title: Push Data Items to Training Queue last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "Push Data Items to Training Queue", "seoTitle": "Push Data Items to Training Queue - POST /api/core/dataset/data/pushData | FastGPT OpenAPI", "description": "Batch insert up to 200 structured data items with optional custom indexes into a dataset collection training queue." } ## Endpoint Overview * **Method** : `POST` * **Path** : `/api/core/dataset/data/pushData` * **Module** : Datasets / Dataset Data * **Authentication** : `Authorization: Bearer `—Personal API Key (access scoped by team member permissions) (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E6%95%B0%E6%8D%AE%E7%AE%A1%E7%90%86/POST/core/dataset/data/pushData) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E6%95%B0%E6%8D%AE%E7%AE%A1%E7%90%86/POST/core/dataset/data/pushData` ) ## Description & Notes Batch insert up to 200 data items into the collection training queue. ## Request Parameters ### Request Body ( `application/json` ) | Field | Type | Required | Default | Constraints & Description | | ----------------------- | --------------- | -------- | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `collectionId` | `string` | Yes | - | Collection ID. pattern: `^[0-9a-fA-F]{24}$` | | `data` | `object[]` | Yes | - | List of data items (up to 200 per request). maxItems: 200 | | `data[].q` | `string` | No | - | Primary chunk content / question | | `data[].a` | `string` | No | - | Supplementary answer / text | | `data[].imageId` | `string` | No | - | Image ID | | `data[].chunkIndex` | `number` | No | - | Chunk index | | `data[].indexes` | `object[]` | No | - | Additional vector indexes | | `data[].indexes[].type` | `string` (enum) | No | `"custom"` | Index type (external callers omit or use `custom` ; other types are system-generated). Allowed values: `default` , `imageEmbedding` , `summary` , `question` , `image` , `custom` | | `data[].indexes[].text` | `string` | Yes | - | Indexed text content by default; for `imageEmbedding` , the image `objectKey` or URL | | `data[].metadata` | `object` | No | - | Custom metadata | | `trainingType` | `string` (enum) | No | - | Training mode. Allowed values: `chunk` , `qa` , `imageParse` , `backup` , `template` , `auto` | | `indexSize` | `number` | No | - | Index chunk size limit | | `autoIndexes` | `boolean` | No | - | Whether to auto-generate vector indexes | | `imageIndex` | `boolean` | No | - | Whether to generate image indexes | | `prompt` | `string` | No | - | Custom prompt | | `billId` | `string` | No | - | Optional training billing ID; created automatically when omitted | | `trainingMode` | `string` (enum) | No | - | **Deprecated** . Training mode. Allowed values: `chunk` , `qa` , `imageParse` , `backup` , `template` , `auto` | ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X POST "https://cloud.fastgpt.io/api/core/dataset/data/pushData" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ --data-raw '{ "collectionId": "68ad85a7463006c963799a06", "data": [ {} ] }' ``` ### Minimal Valid JSON Body ```json { "collectionId": "68ad85a7463006c963799a06", "data": [{}] } ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Successfully returned inserted item count Returns the standard FastGPT success envelope ( `{ "code": 200, "statusText": "", "message": "", "data": ... }` ). The exact `data` payload schema is not declared in this OpenAPI contract; refer to the status description above or inspect runtime responses. file: ./content/openapi/reference/dataset-data/update.en.mdx url: https://doc.fastgpt.io/openapi/reference/dataset-data/update title: Update Dataset Data Item last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "Update Dataset Data Item", "seoTitle": "Update Dataset Data Item - PUT /api/core/dataset/data/update | FastGPT OpenAPI", "description": "Update the question, answer, and custom vector indexes of a dataset data item, automatically triggering re-embedding." } ## Endpoint Overview * **Method** : `PUT` * **Path** : `/api/core/dataset/data/update` * **Module** : Datasets / Dataset Data * **Authentication** : `Authorization: Bearer `—Personal API Key (access scoped by team member permissions) (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E6%95%B0%E6%8D%AE%E7%AE%A1%E7%90%86/PUT/core/dataset/data/update) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E6%95%B0%E6%8D%AE%E7%AE%A1%E7%90%86/PUT/core/dataset/data/update` ) ## Description & Notes Update `q` , `a` , and custom vector indexes for a dataset data item, triggering re-embedding. ## Request Parameters ### Request Body ( `application/json` ) | Field | Type | Required | Default | Constraints & Description | | ------------------ | --------------- | -------- | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `dataId` | `string` | Yes | - | Data item ID. pattern: `^[0-9a-fA-F]{24}$` | | `q` | `string` | Yes | - | Primary chunk content / question | | `a` | `string` | No | - | Supplementary answer / text | | `indexes` | `object[]` | No | - | Vector index list | | `indexes[].type` | `string` (enum) | No | `"custom"` | Index type (external callers omit or use `custom` ; other types are system-generated). Allowed values: `default` , `imageEmbedding` , `summary` , `question` , `image` , `custom` | | `indexes[].text` | `string` | Yes | - | Indexed text content by default; for `imageEmbedding` , the image `objectKey` or URL | | `indexes[].dataId` | `string` | No | - | Optional vector store ID used to reuse matching indexes without re-embedding | | `imageId` | `string` | No | - | Image ID | | `indexPrefix` | `string` | No | - | Prefix title for indexes | ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X PUT "https://cloud.fastgpt.io/api/core/dataset/data/update" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ --data-raw '{ "dataId": "68ad85a7463006c963799a05", "q": "What is FastGPT?" }' ``` ### Minimal Valid JSON Body ```json { "dataId": "68ad85a7463006c963799a05", "q": "What is FastGPT?" } ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Updated successfully **Content-Type** : `application/json` | Field | Type | Required | Default | Constraints & Description | | ----- | -------- | -------- | ------- | --------------------------------------------------------------------- | | `q` | `string` | No | - | Display primary question/text with internal S3 image links signed | | `a` | `string` | No | - | Display supplementary answer/text with internal S3 image links signed | file: ./content/openapi/reference/dataset-data/v2-list.en.mdx url: https://doc.fastgpt.io/openapi/reference/dataset-data/v2-list title: List Dataset Data Items last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "List Dataset Data Items", "seoTitle": "List Dataset Data Items - POST /api/core/dataset/data/v2/list | FastGPT OpenAPI", "description": "Paginate through data chunks within a dataset collection with keyword search across question/answer fields and image URLs." } ## Endpoint Overview * **Method** : `POST` * **Path** : `/api/core/dataset/data/v2/list` * **Module** : Datasets / Dataset Data * **Authentication** : `Authorization: Bearer `—Personal API Key (access scoped by team member permissions) (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E6%95%B0%E6%8D%AE%E7%AE%A1%E7%90%86/POST/core/dataset/data/v2/list) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E6%95%B0%E6%8D%AE%E7%AE%A1%E7%90%86/POST/core/dataset/data/v2/list` ) ## Description & Notes Query paginated data items inside a collection with keyword search and signed image preview URLs. ## Request Parameters ### Request Body ( `application/json` ) #### Shared Parameters Across Branches | Field | Type | Required | Default | Constraints & Description | | -------------- | -------- | -------- | ------- | ------------------------------------------- | | `collectionId` | `string` | Yes | - | Collection ID. pattern: `^[0-9a-fA-F]{24}$` | | `searchText` | `string` | No | - | Search keyword matching `q` and `a` fields | **Mutually Exclusive Branches ( `anyOf` )** * **Offset Pagination** Specify the 0-based starting offset; when both `offset` and `pageNum` are provided, `offset` takes precedence. | Field | Type | Required | Default | Constraints & Description | | ---------- | --------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | `offset` | `integer` | Yes | - | **Mutually Exclusive Group: Pagination Parameters** . 0-based offset. min: 0; max: 9007199254740991 | | `pageSize` | `integer` | No | `20` | **Mutually Exclusive Group: Pagination Parameters** . Items per page. Defaults to 20, capped at 500 (larger values are clamped to 500). max: 500 | * **Page-Number Pagination** Paginate by page number (starts at page 1); `pageSize` controls items per page. | Field | Type | Required | Default | Constraints & Description | | ---------- | --------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | `pageNum` | `integer` | No | `1` | **Mutually Exclusive Group: Pagination Parameters** . 1-based page number; ignored when `offset` is provided. max: 9007199254740991 | | `pageSize` | `integer` | No | `20` | **Mutually Exclusive Group: Pagination Parameters** . Items per page. Defaults to 20, capped at 500 (larger values are clamped to 500). max: 500 | ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X POST "https://cloud.fastgpt.io/api/core/dataset/data/v2/list" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ --data-raw '{ "offset": 0, "collectionId": "68ad85a7463006c963799a06" }' ``` ### Minimal Valid JSON Body ```json { "offset": 0, "collectionId": "68ad85a7463006c963799a06" } ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Successfully returned paginated data items **Content-Type** : `application/json` | Field | Type | Required | Default | Constraints & Description | | ------------------------ | --------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `total` | `number` | Yes | `0` | - | | `list` | `object[]` | Yes | `[]` | - | | `list[]._id` | `string` | Yes | - | Data item ID. pattern: `^[0-9a-fA-F]{24}$` | | `list[].datasetId` | `string` | Yes | - | Dataset ID. pattern: `^[0-9a-fA-F]{24}$` | | `list[].collectionId` | `string` | Yes | - | Collection ID. pattern: `^[0-9a-fA-F]{24}$` | | `list[].q` | `string` | No | - | Primary chunk content / question | | `list[].a` | `string` | No | - | Supplementary answer / text | | `list[].imageId` | `string` | No | - | Image ID | | `list[].imageSize` | `number` | No | - | Image size in bytes | | `list[].imagePreviewUrl` | `string` | No | - | Image preview URL | | `list[].chunkIndex` | `number` | No | - | Chunk index | | `list[].indexStatus` | `string` (enum) | No | - | Index status (absent on legacy already-indexed records). Allowed values: `indexing` , `indexed` , `error` , `rebuildIndexPending` , `rebuildIndexRunning` , `rebuildIndexFailed` , `rebuildSynonymPending` , `rebuildSynonymRunning` , `rebuildSynonymFailed` | | `list[].indexErrorMsg` | `string` | No | - | Indexing error details | | `list[].updated` | `boolean` | No | - | Whether the chunk has been updated since citation | file: ./content/openapi/reference/dataset-search/search.en.mdx url: https://doc.fastgpt.io/openapi/reference/dataset-search/search title: Search Datasets API last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "Search Datasets API", "seoTitle": "Search Datasets API - POST /api/core/dataset/search | FastGPT OpenAPI", "description": "Search across one or more readable datasets with semantic/hybrid recall, reranking, tag filters, and topk/maxTokens limits." } ## Endpoint Overview * **Method** : `POST` * **Path** : `/api/core/dataset/search` * **Module** : Datasets / Dataset Search * **Authentication** : `Authorization: Bearer `—Personal API Key (access scoped by team member permissions) (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E7%9F%A5%E8%AF%86%E5%BA%93%E6%90%9C%E7%B4%A2/POST/core/dataset/search) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E7%9F%A5%E8%AF%86%E5%BA%93%E6%90%9C%E7%B4%A2/POST/core/dataset/search` ) ## Description & Notes Search across one or more readable datasets using an API Key or login session. Vector recall requires matching active embedding models across target datasets, and results respect collection-level permissions. Choose either `result.topk` (returns top 1–100 items without token truncation) or `result.maxTokens` (truncates on complete chunks with no fixed cap); defaults to `topk=20` when omitted, and prioritizes `topk` if both are sent. Response `meta` reports effective execution parameters. ## Request Parameters ### Request Body ( `application/json` ) | Field | Type | Required | Default | Constraints & Description | | ----------------------------- | --------------- | -------- | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `scope` | `object` | Yes | - | Search scope | | `scope.datasetIds` | `string[]` | Yes | - | Target dataset IDs (max 100; deduplicated server-side with per-dataset read permission checks). minItems: 1; maxItems: 100 | | `scope.filter` | `object` | No | - | Collection and tag filters (requires server-side filter support) | | `scope.filter.collectionIds` | `string[]` | No | - | Restrict search to these collections or folders (intersected with other filters). minItems: 1; maxItems: 500 | | `scope.filter.createTime` | `object` | No | - | Collection creation time range | | `scope.filter.createTime.gte` | `string` | No | - | Inclusive lower bound of creation time. pattern: `^(?:(?:\d\d[2468][048]\|\d\d[13579][26]\|\d\d0[48]\|[02468][048]00\|[13579][26]00)-02-29\|\d{4}-(?:(?:0[13578]\|1[02])-(?:0[1-9]\|[12]\d\|3[01])\|(?:0[469]\|11)-(?:0[1-9]\|[12]\d\|30)\|(?:02)-(?:0[1-9]\|1\d\|2[0-8])))T(?:(?:[01]\d\|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z\|([+-](?:[01]\d\|2[0-3]):[0-5]\d)))$` | | `scope.filter.createTime.lte` | `string` | No | - | Inclusive upper bound of creation time. pattern: `^(?:(?:\d\d[2468][048]\|\d\d[13579][26]\|\d\d0[48]\|[02468][048]00\|[13579][26]00)-02-29\|\d{4}-(?:(?:0[13578]\|1[02])-(?:0[1-9]\|[12]\d\|3[01])\|(?:0[469]\|11)-(?:0[1-9]\|[12]\d\|30)\|(?:02)-(?:0[1-9]\|1\d\|2[0-8])))T(?:(?:[01]\d\|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z\|([+-](?:[01]\d\|2[0-3]):[0-5]\d)))$` | | `scope.filter.tags` | `object` | No | - | Tag filter conditions; `and` and `or` groups are intersected | | `scope.filter.tags.and` | `object[]` | No | - | Tag conditions where all entries must match (AND). minItems: 1; maxItems: 50 | | `scope.filter.tags.or` | `object[]` | No | - | Tag conditions where at least one entry must match (OR). minItems: 1; maxItems: 50 | | `query` | `object` | Yes | - | Search query input | | `query.text` | `string` | Yes | - | **Branch: text** . Query text (max 10,000 chars after trimming); at least one of `text` or `queryImageUrls` is required. minLength: 1; maxLength: 10000 | | `query.imageKeys` | `string[]` | No | `[]` | **Branch: text** . Temporary object keys for team-uploaded query images (max 10). maxItems: 10 | | `query.imageKeys` | `string[]` | Yes | - | **Branch: imageKeys** . Temporary object keys for team-uploaded query images (max 10). minItems: 1; maxItems: 10 | | `query.text` | `string` | No | `""` | **Branch: imageKeys** . Query text (max 10,000 chars after trimming); at least one of `text` or `queryImageUrls` is required. maxLength: 10000 | | `retrieval` | `object` | No | `{}` | Recall configuration | | `retrieval.mode` | `string` (enum) | No | `"embedding"` | `embedding` , `fullTextRecall` , or `mixedRecall` . Allowed values: `embedding` , `fullTextRecall` , `mixedRecall` | | `retrieval.embeddingWeight` | `number` | No | `0.5` | Embedding fusion weight in mixed recall. min: 0; max: 1 | | `rerank` | `object` | No | `{"enabled":false}` | Rerank configuration; do not pass model or weight when disabled | | `rerank.enabled` | `false` | Yes | - | **Branch: enabled=false** . Disable Rerank. Fixed: `false` | | `rerank.enabled` | `true` | Yes | - | **Branch: enabled=true** . Enable Rerank. Fixed: `true` | | `rerank.modelId` | `string` | No | - | **Branch: enabled=true** . Rerank model ID; uses the default accessible model if omitted. minLength: 1 | | `rerank.candidateNum` | `integer` | No | - | **Branch: enabled=true** . Rerank candidate pool size ( `10–100` ; defaults to `100` ). min: 10; max: 100 | | `rerank.weight` | `number` | No | `0.5` | **Branch: enabled=true** . Fusion weight for rerank scores. min: 0; max: 1 | | `queryExtension` | `object` | No | `{"enabled":false}` | Query extension configuration | | `queryExtension.enabled` | `false` | Yes | - | **Branch: enabled=false** . Disable Query Extension. Fixed: `false` | | `queryExtension.enabled` | `true` | Yes | - | **Branch: enabled=true** . Enable Query Extension. Fixed: `true` | | `queryExtension.modelId` | `string` | No | - | **Branch: enabled=true** . Rerank model ID; uses the default accessible model if omitted. minLength: 1 | | `queryExtension.background` | `string` | No | `""` | **Branch: enabled=true** . Background context helping the model interpret the query. maxLength: 100000 | | `result` | `object` | No | `{}` | Specify either `topk` or `maxTokens` ; defaults to `topk=20` with no token budget | | `result.similarity` | `number` | No | `0` | Minimum similarity score threshold (applied when `usingSimilarityFilter` is enabled). min: 0; max: 1 | | `result.maxTokens` | `integer` | Yes | - | **Branch: maxTokens** . Total token budget across returned chunks (no fixed cap; preserves complete chunks, so the final chunk may exceed the budget). min: 1; max: 9007199254740991 | | `result.topk` | `integer` | No | `20` | **Branch: anyOf #2** . Return top `k` ranked results ( `1–100` ; defaults to `20` when neither budget is set). min: 1; max: 100 | | `usageScene` | `string` (enum) | No | `"search"` | Billing label: `search` for Dataset Search or `searchTest` for Search Test (does not affect retrieval or permissions). Allowed values: `search` , `searchTest` | ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X POST "https://cloud.fastgpt.io/api/core/dataset/search" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ --data-raw '{ "scope": { "datasetIds": [ "507f1f77bcf86cd799439011" ] }, "query": { "text": "How do I create a dataset?" } }' ``` ### Minimal Valid JSON Body ```json { "scope": { "datasetIds": ["507f1f77bcf86cd799439011"] }, "query": { "text": "How do I create a dataset?" } } ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Matched chunks and effective search metadata **Content-Type** : `application/json` | Field | Type | Required | Default | Constraints & Description | | ---------------------------- | --------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `list` | `object[]` | Yes | - | Merged and ranked dataset chunks | | `list[].q` | `string` | Yes | - | Primary chunk content / question | | `list[].a` | `string` | No | - | Supplementary answer / text | | `list[].imageId` | `string` | No | - | Image ID | | `list[].id` | `string` | Yes | - | Data item ID. pattern: `^[0-9a-fA-F]{24}$` | | `list[].datasetId` | `string` | Yes | - | Dataset ID. pattern: `^[0-9a-fA-F]{24}$` | | `list[].collectionId` | `string` | Yes | - | Collection ID. pattern: `^[0-9a-fA-F]{24}$` | | `list[].imagePreivewUrl` | `string` | No | - | Image preview URL | | `list[].updateTime` | `string` | Yes | - | Update time | | `list[].sourceName` | `string` | Yes | - | Source name | | `list[].sourceId` | `string` | No | - | Source ID | | `list[].chunkIndex` | `number` | Yes | - | Chunk index | | `list[].indexStatus` | `string` (enum) | No | - | Index status (absent on legacy already-indexed records). Allowed values: `indexing` , `indexed` , `error` , `rebuildIndexPending` , `rebuildIndexRunning` , `rebuildIndexFailed` , `rebuildSynonymPending` , `rebuildSynonymRunning` , `rebuildSynonymFailed` | | `list[].indexErrorMsg` | `string` | No | - | Indexing error details | | `list[].imageDescMap` | `object` | No | - | Image description mapping | | `list[].score` | `object[]` | Yes | - | Retrieval score breakdown list | | `list[].score[].type` | `string` (enum) | Yes | - | Score type. Allowed values: `embedding` , `fullText` , `reRank` , `rrf` | | `list[].score[].value` | `number` | Yes | - | Score value | | `list[].score[].index` | `number` | Yes | - | Index | | `list[].metadata` | `object` | No | - | Custom metadata | | `list[].retrievalRank` | `number` | No | - | Retrieval rank | | `list[].synonymMappings` | `object` | No | - | Mapping from original terms appearing in chunks or user questions to canonical terms | | `meta` | `object` | Yes | - | - | | `meta.durationMs` | `number` | Yes | - | Search latency in milliseconds. min: 0 | | `meta.usingSimilarityFilter` | `boolean` | Yes | - | Whether similarity filtering was applied | | `meta.usingReRank` | `boolean` | Yes | - | Whether reranking was executed | | `meta.queryExtensionModelId` | `string` | No | - | Model ID used for query extension | file: ./content/openapi/reference/dataset/batch-delete.en.mdx url: https://doc.fastgpt.io/openapi/reference/dataset/batch-delete title: Batch Delete Datasets last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "Batch Delete Datasets", "seoTitle": "Batch Delete Datasets - POST /api/core/dataset/batch/delete | FastGPT OpenAPI", "description": "Batch delete multiple datasets or folders by ID, handling recursive subtree removal and returning per-ID results." } ## Endpoint Overview * **Method** : `POST` * **Path** : `/api/core/dataset/batch/delete` * **Module** : Datasets / Datasets * **Authentication** : `Authorization: Bearer `—Personal API Key (access scoped by team member permissions) (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E7%9F%A5%E8%AF%86%E5%BA%93%E7%AE%A1%E7%90%86/POST/core/dataset/batch/delete) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E7%9F%A5%E8%AF%86%E5%BA%93%E7%AE%A1%E7%90%86/POST/core/dataset/batch/delete` ) ## Description & Notes Batch delete datasets or folders; subtree handling and async cleanup are handled by the dataset service. ## Request Parameters ### Request Body ( `application/json` ) | Field | Type | Required | Default | Constraints & Description | | ----- | ---------- | -------- | ------- | ----------------------------------------------- | | `ids` | `string[]` | Yes | - | List of resource IDs to operate on. minItems: 1 | ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X POST "https://cloud.fastgpt.io/api/core/dataset/batch/delete" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ --data-raw '{ "ids": [ "68ad85a7463006c963799a05" ] }' ``` ### Minimal Valid JSON Body ```json { "ids": ["68ad85a7463006c963799a05"] } ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Successfully deleted dataset **Content-Type** : `application/json` | Field | Type | Required | Default | Constraints & Description | | ------------- | ---------- | -------- | ------- | -------------------------------------------------------------------------------- | | `successIds` | `string[]` | Yes | - | List of requested resource IDs processed successfully | | `failedIds` | `string[]` | Yes | - | List of requested resource IDs that failed | | `affectedIds` | `string[]` | Yes | - | List of resource IDs actually affected (deletions may include removed child IDs) | file: ./content/openapi/reference/dataset/batch-move.en.mdx url: https://doc.fastgpt.io/openapi/reference/dataset/batch-move title: Batch Move Datasets last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "Batch Move Datasets", "seoTitle": "Batch Move Datasets - POST /api/core/dataset/batch/move | FastGPT OpenAPI", "description": "Move multiple datasets or folders into a target parent folder or root directory with permission and hierarchy checks." } ## Endpoint Overview * **Method** : `POST` * **Path** : `/api/core/dataset/batch/move` * **Module** : Datasets / Datasets * **Authentication** : `Authorization: Bearer `—Personal API Key (access scoped by team member permissions) (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E7%9F%A5%E8%AF%86%E5%BA%93%E7%AE%A1%E7%90%86/POST/core/dataset/batch/move) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E7%9F%A5%E8%AF%86%E5%BA%93%E7%AE%A1%E7%90%86/POST/core/dataset/batch/move` ) ## Description & Notes Batch move datasets or folders; permissions, depth limits, and permission inheritance are enforced by the dataset service. ## Request Parameters ### Request Body ( `application/json` ) | Field | Type | Required | Default | Constraints & Description | | ---------- | ---------------- | -------- | ------- | ---------------------------------------------------- | | `ids` | `string[]` | Yes | - | List of resource IDs to operate on. minItems: 1 | | `parentId` | `string \| null` | Yes | - | Target parent folder ID; pass `null` to move to root | ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X POST "https://cloud.fastgpt.io/api/core/dataset/batch/move" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ --data-raw '{ "ids": [ "68ad85a7463006c963799a05" ], "parentId": "68ee0bd23d17260b7829b137" }' ``` ### Minimal Valid JSON Body ```json { "ids": ["68ad85a7463006c963799a05"], "parentId": "68ee0bd23d17260b7829b137" } ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Successfully moved datasets **Content-Type** : `application/json` | Field | Type | Required | Default | Constraints & Description | | ------------- | ---------- | -------- | ------- | -------------------------------------------------------------------------------- | | `successIds` | `string[]` | Yes | - | List of requested resource IDs processed successfully | | `failedIds` | `string[]` | Yes | - | List of requested resource IDs that failed | | `affectedIds` | `string[]` | Yes | - | List of resource IDs actually affected (deletions may include removed child IDs) | file: ./content/openapi/reference/dataset/create.en.mdx url: https://doc.fastgpt.io/openapi/reference/dataset/create title: Create Dataset last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "Create Dataset", "seoTitle": "Create Dataset - POST /api/core/dataset/create | FastGPT OpenAPI", "description": "Create a new FastGPT dataset or folder supporting standard, website, external file, and third-party API dataset configurations." } ## Endpoint Overview * **Method** : `POST` * **Path** : `/api/core/dataset/create` * **Module** : Datasets / Datasets * **Authentication** : `Authorization: Bearer `—Personal API Key (access scoped by team member permissions) (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E7%9F%A5%E8%AF%86%E5%BA%93%E7%AE%A1%E7%90%86/POST/core/dataset/create) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E7%9F%A5%E8%AF%86%E5%BA%93%E7%AE%A1%E7%90%86/POST/core/dataset/create` ) ## Description & Notes Create a new dataset or folder supporting standard, site sync, external file, and API datasets. ## Request Parameters ### Request Body ( `application/json` ) | Field | Type | Required | Default | Constraints & Description | | ----------------------------------------------- | ---------------- | -------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `parentId` | `string \| null` | No | - | Parent folder ID; omit to create at the root level | | `type` | `string` (enum) | Yes | - | Dataset type. Allowed values: `folder` , `dataset` , `websiteDataset` , `externalFile` , `apiDataset` , `feishu` , `yuque` , `dingtalk` | | `name` | `string` | Yes | - | Dataset name | | `intro` | `string` | Yes | - | Dataset introduction | | `avatar` | `string` | No | - | Dataset avatar URL (optional; uses default icon when omitted) | | `vectorModelId` | `string` | No | - | Embedding model ID; uses the system default if omitted | | `vectorModel` | `string` | No | - | **Deprecated** . Embedding model identifier; uses the system default if omitted | | `agentModelId` | `string` | No | - | Dataset Agent model ID; uses the default model if omitted | | `agentModel` | `string` | No | - | **Deprecated** . Dataset Agent model identifier; uses the default model if omitted | | `vlmModelId` | `string \| null` | No | - | Vision-Language Model (VLM) ID; keeps default when omitted, `null` or empty string clears it | | `vlmModel` | `string` | No | - | **Deprecated** . Vision-Language Model (VLM) identifier | | `apiDatasetServer` | `object` | No | - | Third-party dataset server configuration (API / Lark / Yuque / DingTalk) | | `apiDatasetServer.apiServer` | `object` | No | - | API dataset server configuration | | `apiDatasetServer.apiServer.baseUrl` | `string` | Yes | - | - | | `apiDatasetServer.apiServer.authorization` | `string` | No | - | - | | `apiDatasetServer.apiServer.basePath` | `string` | No | - | - | | `apiDatasetServer.feishuServer` | `object` | No | - | Lark (Feishu) server configuration | | `apiDatasetServer.feishuServer.appId` | `string` | Yes | - | - | | `apiDatasetServer.feishuServer.appSecret` | `string` | No | - | - | | `apiDatasetServer.feishuServer.folderToken` | `string` | Yes | - | - | | `apiDatasetServer.yuqueServer` | `object` | No | - | Yuque server configuration | | `apiDatasetServer.yuqueServer.userId` | `string` | Yes | - | - | | `apiDatasetServer.yuqueServer.token` | `string` | No | - | - | | `apiDatasetServer.yuqueServer.basePath` | `string` | No | - | - | | `apiDatasetServer.dingtalkServer` | `object` | No | - | DingTalk dataset configuration | | `apiDatasetServer.dingtalkServer.appKey` | `string` | Yes | - | - | | `apiDatasetServer.dingtalkServer.appSecret` | `string` | No | - | - | | `apiDatasetServer.dingtalkServer.userId` | `string` | Yes | - | - | | `apiDatasetServer.dingtalkServer.operatorId` | `string` | No | - | - | | `apiDatasetServer.dingtalkServer.workspaceId` | `string` | No | - | - | | `apiDatasetServer.dingtalkServer.rootNodeId` | `string` | No | - | - | | `apiDatasetServer.dingtalkServer.workspaceName` | `string` | No | - | - | | `sangforFileParseConfig` | `object` | No | - | External PDF parsing switches (header/footer, appendix, image OCR, chart-to-table); applies only when `customPdfParse` is enabled | | `sangforFileParseConfig.keep_header_footer` | `boolean` | No | - | Whether to keep page headers and footers (default `false` , strips headers/footers) | | `sangforFileParseConfig.keep_appendix` | `boolean` | No | - | Whether to keep appendix sections (default `true` ) | | `sangforFileParseConfig.image_analysis` | `boolean` | No | - | Whether to retain OCR/image recognition results including stamps (default `false` ) | | `sangforFileParseConfig.chart_analysis` | `boolean` | No | - | Whether to keep chart-to-table extraction results alongside original images (default `false` ) | | `inheritPermission` | `boolean` | No | - | Whether to inherit parent permissions (default `true` ). `true` merges the parent permission snapshot and tracks future changes; `false` creates an isolated Node.js with only creator `owner` permission. | ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X POST "https://cloud.fastgpt.io/api/core/dataset/create" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ --data-raw '{ "type": "folder", "name": "My Dataset", "intro": "A knowledge base dataset for storing product documentation." }' ``` ### Minimal Valid JSON Body ```json { "type": "folder", "name": "My Dataset", "intro": "A knowledge base dataset for storing product documentation." } ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Successfully returned the newly created dataset ID Returns the standard FastGPT success envelope ( `{ "code": 200, "statusText": "", "message": "", "data": ... }` ). The exact `data` payload schema is not declared in this OpenAPI contract; refer to the status description above or inspect runtime responses. file: ./content/openapi/reference/dataset/delete.en.mdx url: https://doc.fastgpt.io/openapi/reference/dataset/delete title: Delete Dataset last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "Delete Dataset", "seoTitle": "Delete Dataset - DELETE /api/core/dataset/delete | FastGPT OpenAPI", "description": "Delete a dataset or folder along with all nested child datasets, collections, and vector indexes (requires owner role)." } ## Endpoint Overview * **Method** : `DELETE` * **Path** : `/api/core/dataset/delete` * **Module** : Datasets / Datasets * **Authentication** : `Authorization: Bearer `—Personal API Key (access scoped by team member permissions) (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E7%9F%A5%E8%AF%86%E5%BA%93%E7%AE%A1%E7%90%86/DELETE/core/dataset/delete) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E7%9F%A5%E8%AF%86%E5%BA%93%E7%AE%A1%E7%90%86/DELETE/core/dataset/delete` ) ## Description & Notes Delete a dataset or folder and all nested child datasets (requires owner permission). ## Request Parameters ### Query Parameters | Field | Type | Required | Default | Constraints & Description | | ----- | -------- | -------- | ------- | ---------------------------------------- | | `id` | `string` | Yes | - | Dataset ID. pattern: `^[0-9a-fA-F]{24}$` | ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X DELETE "https://cloud.fastgpt.io/api/core/dataset/delete?id=68ad85a7463006c963799a05" \ -H "Authorization: Bearer YOUR_API_KEY" ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Successfully deleted dataset Returns the standard FastGPT success envelope ( `{ "code": 200, "statusText": "", "message": "", "data": ... }` ). The exact `data` payload schema is not declared in this OpenAPI contract; refer to the status description above or inspect runtime responses. file: ./content/openapi/reference/dataset/detail.en.mdx url: https://doc.fastgpt.io/openapi/reference/dataset/detail title: Get Dataset Details last_updated: 2026-11-24T13:58:40+08:00 meta: { "title": "Get Dataset Details", "seoTitle": "Get Dataset Details - GET /api/core/dataset/detail | FastGPT OpenAPI", "description": "Retrieve full dataset configuration details including embedding, agent, and VLM models, sync state, and caller permissions." } ## Endpoint Overview * **Method** : `GET` * **Path** : `/api/core/dataset/detail` * **Module** : Datasets / Datasets * **Authentication** : `Authorization: Bearer `—Personal API Key (access scoped by team member permissions) (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E7%9F%A5%E8%AF%86%E5%BA%93%E7%AE%A1%E7%90%86/GET/core/dataset/detail) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E7%9F%A5%E8%AF%86%E5%BA%93%E7%AE%A1%E7%90%86/GET/core/dataset/detail` ) ## Description & Notes Retrieve full dataset configuration including model bindings, permissions, and synchronization status. ## Request Parameters ### Query Parameters | Field | Type | Required | Default | Constraints & Description | | ----- | -------- | -------- | ------- | ---------------------------------------- | | `id` | `string` | Yes | - | Dataset ID. pattern: `^[0-9a-fA-F]{24}$` | ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X GET "https://cloud.fastgpt.io/api/core/dataset/detail?id=68ad85a7463006c963799a05" \ -H "Authorization: Bearer YOUR_API_KEY" ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Successfully returned dataset details (omits `createTime` ) **Content-Type** : `application/json` | Field | Type | Required | Default | Constraints & Description | | ----------------------------------------------- | ---------------- | -------- | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------- | | `_id` | `string` | Yes | - | Dataset ID. pattern: `^[0-9a-fA-F]{24}$` | | `parentId` | `string \| null` | No | - | Parent folder ID | | `userId` | `string` | No | - | **Deprecated** . User ID. pattern: `^[0-9a-fA-F]{24}$` | | `teamId` | `string` | Yes | - | Team ID. pattern: `^[0-9a-fA-F]{24}$` | | `tmbId` | `string` | Yes | - | Team member ID. pattern: `^[0-9a-fA-F]{24}$` | | `updateTime` | `string` | Yes | - | Update time | | `inheritPermission` | `boolean` | Yes | - | Whether permissions are inherited from parent | | `collectionPermissionEnabled` | `boolean` | No | - | Collection-level permission toggle ( `false` by default, inheriting dataset readability) | | `avatar` | `string` | Yes | `"/icon/logo.svg"` | Avatar | | `name` | `string` | Yes | - | Name | | `intro` | `string` | Yes | - | Introduction | | `type` | `string` (enum) | Yes | - | Dataset type. Allowed values: `folder` , `dataset` , `websiteDataset` , `externalFile` , `apiDataset` , `feishu` , `yuque` , `dingtalk` | | `vectorModelId` | `string` | No | - | Embedding model ID | | `agentModelId` | `string` | No | - | AI model ID | | `vlmModelId` | `string` | No | - | VLM model ID | | `websiteConfig` | `object` | No | - | Site sync configuration | | `websiteConfig.url` | `string` | Yes | - | Site URL | | `websiteConfig.selector` | `string` | Yes | - | CSS selector for site scraping | | `chunkSettings` | `object` | No | - | Chunking configuration | | `chunkSettings.trainingType` | `string` (enum) | No | - | Training mode. Allowed values: `chunk` , `qa` , `imageParse` , `backup` , `template` , `auto` | | `chunkSettings.chunkTriggerType` | `string` (enum) | No | - | Chunk trigger mode. Allowed values: `minSize` , `forceChunk` , `maxSize` | | `chunkSettings.chunkTriggerMinSize` | `number` | No | - | Minimum size threshold to trigger chunking | | `chunkSettings.dataEnhanceCollectionName` | `boolean` | No | - | Prepend collection name to chunks | | `chunkSettings.imageIndex` | `boolean` | No | - | Enable image indexing | | `chunkSettings.autoIndexes` | `boolean` | No | - | Auto-generate vector indexes | | `chunkSettings.indexPrefixTitle` | `boolean` | No | - | Prefix title for indexes | | `chunkSettings.chunkSettingMode` | `string` (enum) | No | - | Chunk setting preset ( `auto` , `custom` , or `intelligent` ). Allowed values: `auto` , `custom` , `intelligent` | | `chunkSettings.chunkSplitMode` | `string` (enum) | No | - | Chunk splitting mode. Allowed values: `paragraph` , `size` , `char` | | `chunkSettings.paragraphChunkAIMode` | `string` (enum) | No | - | AI paragraph chunking mode. Allowed values: `auto` , `force` , `forbid` | | `chunkSettings.paragraphChunkDeep` | `number` | No | - | Paragraph heading split depth | | `chunkSettings.paragraphChunkMinSize` | `number` | No | - | Minimum paragraph chunk size | | `chunkSettings.chunkSize` | `number` | No | - | Target chunk size | | `chunkSettings.chunkSplitter` | `string` | No | - | Custom primary chunk separator | | `chunkSettings.indexSize` | `number` | No | - | Vector index chunk size | | `chunkSettings.qaPrompt` | `string` | No | - | Custom prompt for Q\&A extraction | | `sangforFileParseConfig` | `object` | No | - | External PDF parse configuration | | `sangforFileParseConfig.keep_header_footer` | `boolean` | No | - | Whether to keep page headers and footers (default `false` , strips headers/footers) | | `sangforFileParseConfig.keep_appendix` | `boolean` | No | - | Whether to keep appendix sections (default `true` ) | | `sangforFileParseConfig.image_analysis` | `boolean` | No | - | Whether to retain OCR/image recognition results including stamps (default `false` ) | | `sangforFileParseConfig.chart_analysis` | `boolean` | No | - | Whether to keep chart-to-table extraction results alongside original images (default `false` ) | | `apiDatasetServer` | `object` | No | - | API dataset server configuration | | `apiDatasetServer.apiServer` | `object` | No | - | API dataset server configuration | | `apiDatasetServer.apiServer.baseUrl` | `string` | Yes | - | - | | `apiDatasetServer.apiServer.authorization` | `string` | No | - | - | | `apiDatasetServer.apiServer.basePath` | `string` | No | - | - | | `apiDatasetServer.feishuServer` | `object` | No | - | Lark (Feishu) server configuration | | `apiDatasetServer.feishuServer.appId` | `string` | Yes | - | - | | `apiDatasetServer.feishuServer.appSecret` | `string` | No | - | - | | `apiDatasetServer.feishuServer.folderToken` | `string` | Yes | - | - | | `apiDatasetServer.yuqueServer` | `object` | No | - | Yuque server configuration | | `apiDatasetServer.yuqueServer.userId` | `string` | Yes | - | - | | `apiDatasetServer.yuqueServer.token` | `string` | No | - | - | | `apiDatasetServer.yuqueServer.basePath` | `string` | No | - | - | | `apiDatasetServer.dingtalkServer` | `object` | No | - | DingTalk dataset configuration | | `apiDatasetServer.dingtalkServer.appKey` | `string` | Yes | - | - | | `apiDatasetServer.dingtalkServer.appSecret` | `string` | No | - | - | | `apiDatasetServer.dingtalkServer.userId` | `string` | Yes | - | - | | `apiDatasetServer.dingtalkServer.operatorId` | `string` | No | - | - | | `apiDatasetServer.dingtalkServer.workspaceId` | `string` | No | - | - | | `apiDatasetServer.dingtalkServer.rootNodeId` | `string` | No | - | - | | `apiDatasetServer.dingtalkServer.workspaceName` | `string` | No | - | - | | `deleteTime` | `string \| null` | No | - | Deletion timestamp | | `autoSync` | `boolean` | No | - | Auto-sync enabled | | `externalReadUrl` | `string` | No | - | **Deprecated** . External source URL | | `defaultPermission` | `number` | No | - | **Deprecated** . Default permission level | | `apiServer` | `object` | No | - | **Deprecated** . API dataset server configuration | | `apiServer.baseUrl` | `string` | Yes | - | - | | `apiServer.authorization` | `string` | No | - | - | | `apiServer.basePath` | `string` | No | - | - | | `feishuServer` | `object` | No | - | **Deprecated** . Lark (Feishu) server configuration | | `feishuServer.appId` | `string` | Yes | - | - | | `feishuServer.appSecret` | `string` | No | - | - | | `feishuServer.folderToken` | `string` | Yes | - | - | | `yuqueServer` | `object` | No | - | **Deprecated** . Yuque server configuration | | `yuqueServer.userId` | `string` | Yes | - | - | | `yuqueServer.token` | `string` | No | - | - | | `yuqueServer.basePath` | `string` | No | - | - | | `dingtalkServer` | `object` | No | - | **Deprecated** . DingTalk dataset configuration | | `dingtalkServer.appKey` | `string` | Yes | - | - | | `dingtalkServer.appSecret` | `string` | No | - | - | | `dingtalkServer.userId` | `string` | Yes | - | - | | `dingtalkServer.operatorId` | `string` | No | - | - | | `dingtalkServer.workspaceId` | `string` | No | - | - | | `dingtalkServer.rootNodeId` | `string` | No | - | - | | `dingtalkServer.workspaceName` | `string` | No | - | - | | `status` | `string` (enum) | Yes | - | Synchronization/training status. Allowed values: `active` , `syncing` , `waiting` , `error` | | `hasTrainingTask` | `boolean` | Yes | - | Whether active training jobs or pending/failed index/synonym rebuild tasks exist | | `errorMsg` | `string` | No | - | Error details | | `vectorModel` | `object` | No | - | Embedding model details (empty if deleted; inactive models still return display metadata) | | `vectorModel.pricing` | `object` | No | - | Credit price per fixed billing unit; omitted if free | | `vectorModel.pricing.unitPrice` | `number` | No | - | Composite credit price per million units (tokens/TTS) or per 60 seconds (STT). min: 0 | | `vectorModel.provider` | `string` | Yes | - | minLength: 1 | | `vectorModel.model` | `string` | Yes | - | minLength: 1 | | `vectorModel.name` | `string` | Yes | - | minLength: 1 | | `vectorModel.scope` | `string` (enum) | Yes | `"system"` | Allowed values: `system` , `team` | | `vectorModel.sortOrder` | `integer` | No | - | Display rank within the same scope (smaller numbers appear first). min: 0; max: 9007199254740991 | | `vectorModel.tmbId` | `string \| null` | No | - | - | | `vectorModel.teamId` | `string \| null` | No | - | - | | `vectorModel.isActive` | `boolean` | No | - | - | | `vectorModel.isUpcomingDeprecation` | `boolean` | No | - | Whether the model is scheduled for deprecation | | `vectorModel.requestUrl` | `string` | No | - | - | | `vectorModel.requestAuth` | `string` | No | - | - | | `vectorModel.testMode` | `boolean` | No | - | - | | `vectorModel.type` | `"embedding"` | Yes | - | Fixed: `"embedding"` | | `vectorModel.config` | `object` | Yes | - | - | | `vectorModel.config.defaultToken` | `number` | Yes | - | - | | `vectorModel.config.maxToken` | `number` | Yes | - | - | | `vectorModel.config.weight` | `number` | Yes | `0` | - | | `vectorModel.config.hidden` | `boolean` | No | - | - | | `vectorModel.config.vision` | `boolean` | No | - | - | | `vectorModel.config.normalization` | `boolean` | No | - | - | | `vectorModel.config.batchSize` | `number` | No | - | - | | `vectorModel.config.defaultConfig` | `object` | No | - | - | | `vectorModel.config.dbConfig` | `object` | No | - | - | | `vectorModel.config.queryConfig` | `object` | No | - | - | | `vectorModel.modelId` | `string` | Yes | - | - | | `vectorModel.avatar` | `string` | No | - | - | | `agentModel` | `object` | No | - | AI model details (empty if deleted; inactive models still return display metadata) | | `agentModel.pricing` | `object` | No | - | Tiered LLM pricing per million tokens; omitted if free | | `agentModel.pricing.tiers` | `object[]` | No | - | LLM pricing tier (lower bound derives from the previous tier upper bound). maxItems: 5 | | `agentModel.pricing.tiers[].maxInputTokensK` | `integer` | No | 32 | Upper input limit for this tier in thousands of tokens. Omit for unlimited. max: 9007199254740991 | | `agentModel.pricing.tiers[].inputPrice` | `number` | Yes | - | Credit price per million input tokens. min: 0 | | `agentModel.pricing.tiers[].outputPrice` | `number` | Yes | - | Credit price per million output tokens. min: 0 | | `agentModel.provider` | `string` | Yes | - | minLength: 1 | | `agentModel.model` | `string` | Yes | - | minLength: 1 | | `agentModel.name` | `string` | Yes | - | minLength: 1 | | `agentModel.scope` | `string` (enum) | Yes | `"system"` | Allowed values: `system` , `team` | | `agentModel.sortOrder` | `integer` | No | - | Display rank within the same scope (smaller numbers appear first). min: 0; max: 9007199254740991 | | `agentModel.tmbId` | `string \| null` | No | - | - | | `agentModel.teamId` | `string \| null` | No | - | - | | `agentModel.isActive` | `boolean` | No | - | - | | `agentModel.isUpcomingDeprecation` | `boolean` | No | - | Whether the model is scheduled for deprecation | | `agentModel.requestUrl` | `string` | No | - | - | | `agentModel.requestAuth` | `string` | No | - | - | | `agentModel.testMode` | `boolean` | No | - | - | | `agentModel.type` | `"llm"` | Yes | - | Fixed: `"llm"` | | `agentModel.config` | `object` | Yes | - | - | | `agentModel.config.maxContext` | `number` | Yes | - | - | | `agentModel.config.maxResponse` | `number` | Yes | - | - | | `agentModel.config.quoteMaxToken` | `number` | Yes | - | - | | `agentModel.config.maxTemperature` | `number \| null` | No | - | - | | `agentModel.config.showTopP` | `boolean` | No | - | - | | `agentModel.config.responseFormatList` | `string[]` | No | - | - | | `agentModel.config.showStopSign` | `boolean` | No | - | - | | `agentModel.config.censor` | `boolean` | No | - | - | | `agentModel.config.vision` | `boolean` | No | - | - | | `agentModel.config.audio` | `boolean` | No | - | - | | `agentModel.config.video` | `boolean` | No | - | - | | `agentModel.config.reasoning` | `boolean` | No | - | - | | `agentModel.config.reasoningEffort` | `boolean` | No | - | - | | `agentModel.config.functionCall` | `boolean` | No | - | - | | `agentModel.config.toolChoice` | `boolean` | No | - | - | | `agentModel.config.defaultSystemChatPrompt` | `string` | No | - | - | | `agentModel.config.defaultConfig` | `object` | No | - | - | | `agentModel.config.fieldMap` | `object` | No | - | - | | `agentModel.modelId` | `string` | Yes | - | - | | `agentModel.avatar` | `string` | No | - | - | | `vlmModel` | `object` | No | - | Vision-Language Model (VLM) | | `vlmModel.pricing` | `object` | No | - | Tiered LLM pricing per million tokens; omitted if free | | `vlmModel.pricing.tiers` | `object[]` | No | - | LLM pricing tier (lower bound derives from the previous tier upper bound). maxItems: 5 | | `vlmModel.pricing.tiers[].maxInputTokensK` | `integer` | No | 32 | Upper input limit for this tier in thousands of tokens. Omit for unlimited. max: 9007199254740991 | | `vlmModel.pricing.tiers[].inputPrice` | `number` | Yes | - | Credit price per million input tokens. min: 0 | | `vlmModel.pricing.tiers[].outputPrice` | `number` | Yes | - | Credit price per million output tokens. min: 0 | | `vlmModel.provider` | `string` | Yes | - | minLength: 1 | | `vlmModel.model` | `string` | Yes | - | minLength: 1 | | `vlmModel.name` | `string` | Yes | - | minLength: 1 | | `vlmModel.scope` | `string` (enum) | Yes | `"system"` | Allowed values: `system` , `team` | | `vlmModel.sortOrder` | `integer` | No | - | Display rank within the same scope (smaller numbers appear first). min: 0; max: 9007199254740991 | | `vlmModel.tmbId` | `string \| null` | No | - | - | | `vlmModel.teamId` | `string \| null` | No | - | - | | `vlmModel.isActive` | `boolean` | No | - | - | | `vlmModel.isUpcomingDeprecation` | `boolean` | No | - | Whether the model is scheduled for deprecation | | `vlmModel.requestUrl` | `string` | No | - | - | | `vlmModel.requestAuth` | `string` | No | - | - | | `vlmModel.testMode` | `boolean` | No | - | - | | `vlmModel.type` | `"llm"` | Yes | - | Fixed: `"llm"` | | `vlmModel.config` | `object` | Yes | - | - | | `vlmModel.config.maxContext` | `number` | Yes | - | - | | `vlmModel.config.maxResponse` | `number` | Yes | - | - | | `vlmModel.config.quoteMaxToken` | `number` | Yes | - | - | | `vlmModel.config.maxTemperature` | `number \| null` | No | - | - | | `vlmModel.config.showTopP` | `boolean` | No | - | - | | `vlmModel.config.responseFormatList` | `string[]` | No | - | - | | `vlmModel.config.showStopSign` | `boolean` | No | - | - | | `vlmModel.config.censor` | `boolean` | No | - | - | | `vlmModel.config.vision` | `boolean` | No | - | - | | `vlmModel.config.audio` | `boolean` | No | - | - | | `vlmModel.config.video` | `boolean` | No | - | - | | `vlmModel.config.reasoning` | `boolean` | No | - | - | | `vlmModel.config.reasoningEffort` | `boolean` | No | - | - | | `vlmModel.config.functionCall` | `boolean` | No | - | - | | `vlmModel.config.toolChoice` | `boolean` | No | - | - | | `vlmModel.config.defaultSystemChatPrompt` | `string` | No | - | - | | `vlmModel.config.defaultConfig` | `object` | No | - | - | | `vlmModel.config.fieldMap` | `object` | No | - | - | | `vlmModel.modelId` | `string` | Yes | - | - | | `vlmModel.avatar` | `string` | No | - | - | | `permission` | `object` | Yes | - | Serialized permission object JSON structure | | `permission.role` | `integer` | Yes | - | Permission role bitmask value. min: -9007199254740991; max: 9007199254740991 | | `permission.isOwner` | `boolean` | Yes | - | Whether the caller has owner permission | | `permission.hasManagePer` | `boolean` | Yes | - | Whether the caller has manage permission | | `permission.hasWritePer` | `boolean` | Yes | - | Whether the caller has write permission | | `permission.hasReadPer` | `boolean` | Yes | - | Whether the caller has read permission | | `permission.hasManageRole` | `boolean` | Yes | - | Whether manage role bit is set | | `permission.hasWriteRole` | `boolean` | Yes | - | Whether write role bit is set | | `permission.hasReadRole` | `boolean` | Yes | - | Whether read role bit is set | file: ./content/openapi/reference/dataset/list-v2.en.mdx url: https://doc.fastgpt.io/openapi/reference/dataset/list-v2 title: List Datasets (V2) last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "List Datasets (V2)", "seoTitle": "List Datasets (V2) - POST /api/core/dataset/listV2 | FastGPT OpenAPI", "description": "List accessible datasets and folders with pagination, ID lookup, keyword filtering, and optional collection file counts." } ## Endpoint Overview * **Method** : `POST` * **Path** : `/api/core/dataset/listV2` * **Module** : Datasets / Datasets * **Authentication** : `Authorization: Bearer `—Personal API Key (access scoped by team member permissions) (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E7%9F%A5%E8%AF%86%E5%BA%93%E7%AE%A1%E7%90%86/POST/core/dataset/listV2) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E7%9F%A5%E8%AF%86%E5%BA%93%E7%AE%A1%E7%90%86/POST/core/dataset/listV2` ) ## Description & Notes Queries accessible datasets with pagination or exact `datasetIds` lookup. When `datasetIds` is passed, `parentId` and pagination parameters are ignored while shared filters remain active. ## Request Parameters ### Request Body ( `application/json` ) #### Shared Parameters Across Branches | Field | Type | Required | Default | Constraints & Description | | --------------- | ----------------- | -------- | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `type` | `string \| array` | No | - | Dataset type filter | | `searchKey` | `string` | No | - | Search keyword matching dataset name and introduction | | `sort` | `string` (enum) | No | `"updateTimeDesc"` | Sort order; defaults to most recently updated descending. Allowed values: `updateTimeDesc` (Sort by update time descending (most recently modified first, default)), `createTimeDesc` (Sort by creation time descending (newest first)), `createTimeAsc` (Sort by creation time ascending (oldest first)) | | `tmbIds` | `string[]` | No | - | Filter by creator member IDs; an empty array returns an empty list | | `withAppCount` | `boolean` | No | - | Whether to count referencing published apps (default `false` ; visible to non-folder owners only) | | `withFileCount` | `boolean` | No | - | Whether to compute total non-folder collection count across all depths (default `false` ) | **Mutually Exclusive Branches ( `anyOf` )** * **Lookup by IDs** | Field | Type | Required | Default | Constraints & Description | | ------------ | ---------- | -------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `datasetIds` | `string[]` | Yes | - | Exact lookup by up to 500 dataset or folder IDs; takes precedence over pagination and strips `parentId` /pagination fields while keeping shared filters. minItems: 1; maxItems: 500 | * **Paginated Lookup** | Field | Type | Required | Default | Constraints & Description | | ---------- | ---------------- | -------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------- | | `parentId` | `string \| null` | No | - | Parent folder ID ( `null` or empty for root); omit to search across all readable datasets, or set to restrict search to a folder subtree | **Offset Pagination** : Specify the 0-based starting offset; when both `offset` and `pageNum` are provided, `offset` takes precedence. | Field | Type | Required | Default | Constraints & Description | | ---------- | --------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | `offset` | `integer` | Yes | - | **Mutually Exclusive Group: Pagination Parameters** . 0-based offset. min: 0; max: 9007199254740991 | | `pageSize` | `integer` | No | `20` | **Mutually Exclusive Group: Pagination Parameters** . Items per page. Defaults to 20, capped at 500 (larger values are clamped to 500). max: 500 | **Page-Number Pagination** : Paginate by page number (starts at page 1); `pageSize` controls items per page. | Field | Type | Required | Default | Constraints & Description | | ---------- | --------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | `pageNum` | `integer` | No | `1` | **Mutually Exclusive Group: Pagination Parameters** . 1-based page number; ignored when `offset` is provided. max: 9007199254740991 | | `pageSize` | `integer` | No | `20` | **Mutually Exclusive Group: Pagination Parameters** . Items per page. Defaults to 20, capped at 500 (larger values are clamped to 500). max: 500 | ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X POST "https://cloud.fastgpt.io/api/core/dataset/listV2" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ --data-raw '{ "datasetIds": [ "68ad85a7463006c963799a05" ] }' ``` ### Minimal Valid JSON Body ```json { "datasetIds": ["68ad85a7463006c963799a05"] } ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Successfully returned dataset list **Content-Type** : `application/json` | Field | Type | Required | Default | Constraints & Description | | ------------------------------------------ | ---------------- | -------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `total` | `number` | Yes | `0` | - | | `list` | `object[]` | Yes | `[]` | - | | `list[]._id` | `string` | Yes | - | Dataset ID. pattern: `^[0-9a-fA-F]{24}$` | | `list[].tmbId` | `string` | Yes | - | Team member ID. pattern: `^[0-9a-fA-F]{24}$` | | `list[].avatar` | `string` | Yes | `"/icon/logo.svg"` | Avatar | | `list[].createTime` | `string` | Yes | - | Creation time | | `list[].updateTime` | `string` | Yes | - | Update time | | `list[].name` | `string` | Yes | - | Name | | `list[].intro` | `string` | Yes | - | Introduction | | `list[].type` | `string` (enum) | Yes | - | Dataset type. Allowed values: `folder` , `dataset` , `websiteDataset` , `externalFile` , `apiDataset` , `feishu` , `yuque` , `dingtalk` | | `list[].permission` | `object` | Yes | - | Serialized permission object JSON structure | | `list[].permission.role` | `integer` | Yes | - | Permission role bitmask value. min: -9007199254740991; max: 9007199254740991 | | `list[].permission.isOwner` | `boolean` | Yes | - | Whether the caller has owner permission | | `list[].permission.hasManagePer` | `boolean` | Yes | - | Whether the caller has manage permission | | `list[].permission.hasWritePer` | `boolean` | Yes | - | Whether the caller has write permission | | `list[].permission.hasReadPer` | `boolean` | Yes | - | Whether the caller has read permission | | `list[].permission.hasManageRole` | `boolean` | Yes | - | Whether manage role bit is set | | `list[].permission.hasWriteRole` | `boolean` | Yes | - | Whether write role bit is set | | `list[].permission.hasReadRole` | `boolean` | Yes | - | Whether read role bit is set | | `list[].appCount` | `integer` | No | - | Count of published apps referencing this dataset (returned only to non-folder owners when enabled). min: 0; max: 9007199254740991 | | `list[].fileCount` | `integer` | No | - | Total non-folder collection count across all depths (unfiltered by file permissions; returned only when `withFileCount` is requested on non-folder datasets). min: 0; max: 9007199254740991 | | `list[].vectorModel` | `object` | No | - | Embedding model info (empty for folders or deleted models; inactive models still return display metadata) | | `list[].vectorModel.pricing` | `object` | No | - | Credit price per fixed billing unit; omitted if free | | `list[].vectorModel.pricing.unitPrice` | `number` | No | - | Composite credit price per million units (tokens/TTS) or per 60 seconds (STT). min: 0 | | `list[].vectorModel.provider` | `string` | Yes | - | minLength: 1 | | `list[].vectorModel.model` | `string` | Yes | - | minLength: 1 | | `list[].vectorModel.name` | `string` | Yes | - | minLength: 1 | | `list[].vectorModel.scope` | `string` (enum) | Yes | `"system"` | Allowed values: `system` , `team` | | `list[].vectorModel.sortOrder` | `integer` | No | - | Display rank within the same scope (smaller numbers appear first). min: 0; max: 9007199254740991 | | `list[].vectorModel.tmbId` | `string \| null` | No | - | - | | `list[].vectorModel.teamId` | `string \| null` | No | - | - | | `list[].vectorModel.isActive` | `boolean` | No | - | - | | `list[].vectorModel.isUpcomingDeprecation` | `boolean` | No | - | Whether the model is scheduled for deprecation | | `list[].vectorModel.requestUrl` | `string` | No | - | - | | `list[].vectorModel.requestAuth` | `string` | No | - | - | | `list[].vectorModel.testMode` | `boolean` | No | - | - | | `list[].vectorModel.type` | `"embedding"` | Yes | - | Fixed: `"embedding"` | | `list[].vectorModel.config` | `object` | Yes | - | - | | `list[].vectorModel.config.defaultToken` | `number` | Yes | - | - | | `list[].vectorModel.config.maxToken` | `number` | Yes | - | - | | `list[].vectorModel.config.weight` | `number` | Yes | `0` | - | | `list[].vectorModel.config.hidden` | `boolean` | No | - | - | | `list[].vectorModel.config.vision` | `boolean` | No | - | - | | `list[].vectorModel.config.normalization` | `boolean` | No | - | - | | `list[].vectorModel.config.batchSize` | `number` | No | - | - | | `list[].vectorModel.config.defaultConfig` | `object` | No | - | - | | `list[].vectorModel.config.dbConfig` | `object` | No | - | - | | `list[].vectorModel.config.queryConfig` | `object` | No | - | - | | `list[].vectorModel.modelId` | `string` | Yes | - | - | | `list[].vectorModel.avatar` | `string` | No | - | - | | `list[].inheritPermission` | `boolean` | Yes | - | Whether permissions are inherited from parent | | `list[].private` | `boolean` | No | - | Whether access is private to the owner | | `list[].folderAccessMode` | `string` (enum) | No | - | Folder access mode; `navigate` allows traversing readable descendants without granting direct read permission. Allowed values: `read` , `navigate` | | `list[].sourceMember` | `object` | No | - | Source member | | `list[].sourceMember.name` | `string` | Yes | - | Member name | | `list[].sourceMember.avatar` | `string \| null` | No | - | Member avatar | | `list[].sourceMember.status` | `string` (enum) | Yes | - | Member status. Allowed values: `active` , `leave` , `forbidden` | file: ./content/openapi/reference/dataset/update.en.mdx url: https://doc.fastgpt.io/openapi/reference/dataset/update title: Update Dataset last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "Update Dataset", "seoTitle": "Update Dataset - PUT /api/core/dataset/update | FastGPT OpenAPI", "description": "Update dataset name, introduction, model settings, website sync rules, PDF parse options, or move it to another folder." } ## Endpoint Overview * **Method** : `PUT` * **Path** : `/api/core/dataset/update` * **Module** : Datasets / Datasets * **Authentication** : `Authorization: Bearer `—Personal API Key (access scoped by team member permissions) (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E7%9F%A5%E8%AF%86%E5%BA%93%E7%AE%A1%E7%90%86/PUT/core/dataset/update) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E7%9F%A5%E8%AF%86%E5%BA%93%E7%AE%A1%E7%90%86/PUT/core/dataset/update` ) ## Description & Notes Update dataset metadata, model settings, sync configuration, or move it to another folder. ## Request Parameters ### Request Body ( `application/json` ) | Field | Type | Required | Default | Constraints & Description | | ----------------------------------------------- | ---------------- | -------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | `string` | Yes | - | Dataset ID. pattern: `^[0-9a-fA-F]{24}$` | | `parentId` | `string \| null` | No | - | Parent folder ID; pass `null` to move to the root directory | | `name` | `string` | No | - | Dataset name | | `avatar` | `string` | No | - | Dataset avatar URL | | `intro` | `string` | No | - | Dataset introduction | | `agentModelId` | `string` | No | - | Dataset Agent model ID; omitted leaves unchanged, cannot be cleared. minLength: 1 | | `agentModel` | `string` | No | - | **Deprecated** . Legacy dataset Agent model identifier; used only when `agentModelId` is omitted. minLength: 1 | | `vlmModelId` | `string \| null` | No | - | VLM model ID; omitted leaves unchanged, `null` or empty string clears it | | `vlmModel` | `string \| null` | No | - | **Deprecated** . Legacy VLM model identifier; used only when `vlmModelId` is omitted ( `null` or empty string clears it) | | `websiteConfig` | `object` | No | - | Site dataset configuration | | `websiteConfig.url` | `string` | Yes | - | Site URL | | `websiteConfig.selector` | `string` | Yes | - | CSS selector for site scraping | | `externalReadUrl` | `string` | No | - | External source URL | | `apiDatasetServer` | `object` | No | - | Third-party dataset server configuration (API / Lark / Yuque / DingTalk) | | `apiDatasetServer.apiServer` | `object` | No | - | API dataset server configuration | | `apiDatasetServer.apiServer.baseUrl` | `string` | Yes | - | - | | `apiDatasetServer.apiServer.authorization` | `string` | No | - | - | | `apiDatasetServer.apiServer.basePath` | `string` | No | - | - | | `apiDatasetServer.feishuServer` | `object` | No | - | Lark (Feishu) server configuration | | `apiDatasetServer.feishuServer.appId` | `string` | Yes | - | - | | `apiDatasetServer.feishuServer.appSecret` | `string` | No | - | - | | `apiDatasetServer.feishuServer.folderToken` | `string` | Yes | - | - | | `apiDatasetServer.yuqueServer` | `object` | No | - | Yuque server configuration | | `apiDatasetServer.yuqueServer.userId` | `string` | Yes | - | - | | `apiDatasetServer.yuqueServer.token` | `string` | No | - | - | | `apiDatasetServer.yuqueServer.basePath` | `string` | No | - | - | | `apiDatasetServer.dingtalkServer` | `object` | No | - | DingTalk dataset configuration | | `apiDatasetServer.dingtalkServer.appKey` | `string` | Yes | - | - | | `apiDatasetServer.dingtalkServer.appSecret` | `string` | No | - | - | | `apiDatasetServer.dingtalkServer.userId` | `string` | Yes | - | - | | `apiDatasetServer.dingtalkServer.operatorId` | `string` | No | - | - | | `apiDatasetServer.dingtalkServer.workspaceId` | `string` | No | - | - | | `apiDatasetServer.dingtalkServer.rootNodeId` | `string` | No | - | - | | `apiDatasetServer.dingtalkServer.workspaceName` | `string` | No | - | - | | `autoSync` | `boolean` | No | - | Whether auto-sync is enabled | | `chunkSettings` | `object` | No | - | Chunking configuration | | `chunkSettings.trainingType` | `string` (enum) | No | - | Training mode. Allowed values: `chunk` , `qa` , `imageParse` , `backup` , `template` , `auto` | | `chunkSettings.chunkTriggerType` | `string` (enum) | No | - | Chunk trigger mode. Allowed values: `minSize` , `forceChunk` , `maxSize` | | `chunkSettings.chunkTriggerMinSize` | `number` | No | - | Minimum size threshold to trigger chunking | | `chunkSettings.dataEnhanceCollectionName` | `boolean` | No | - | Prepend collection name to chunks | | `chunkSettings.imageIndex` | `boolean` | No | - | Enable image indexing | | `chunkSettings.autoIndexes` | `boolean` | No | - | Auto-generate vector indexes | | `chunkSettings.indexPrefixTitle` | `boolean` | No | - | Prefix title for indexes | | `chunkSettings.chunkSettingMode` | `string` (enum) | No | - | Chunk setting preset ( `auto` , `custom` , or `intelligent` ). Allowed values: `auto` , `custom` , `intelligent` | | `chunkSettings.chunkSplitMode` | `string` (enum) | No | - | Chunk splitting mode. Allowed values: `paragraph` , `size` , `char` | | `chunkSettings.paragraphChunkAIMode` | `string` (enum) | No | - | AI paragraph chunking mode. Allowed values: `auto` , `force` , `forbid` | | `chunkSettings.paragraphChunkDeep` | `number` | No | - | Paragraph heading split depth | | `chunkSettings.paragraphChunkMinSize` | `number` | No | - | Minimum paragraph chunk size | | `chunkSettings.chunkSize` | `number` | No | - | Target chunk size | | `chunkSettings.chunkSplitter` | `string` | No | - | Custom primary chunk separator | | `chunkSettings.indexSize` | `number` | No | - | Vector index chunk size | | `chunkSettings.qaPrompt` | `string` | No | - | Custom prompt for Q\&A extraction | | `sangforFileParseConfig` | `object` | No | - | External PDF parsing switches (headers/footers, appendix, image OCR, chart-to-table); applies only to `customPdfParse` for newly parsed files | | `sangforFileParseConfig.keep_header_footer` | `boolean` | No | - | Whether to keep page headers and footers (default `false` , strips headers/footers) | | `sangforFileParseConfig.keep_appendix` | `boolean` | No | - | Whether to keep appendix sections (default `true` ) | | `sangforFileParseConfig.image_analysis` | `boolean` | No | - | Whether to retain OCR/image recognition results including stamps (default `false` ) | | `sangforFileParseConfig.chart_analysis` | `boolean` | No | - | Whether to keep chart-to-table extraction results alongside original images (default `false` ) | ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X PUT "https://cloud.fastgpt.io/api/core/dataset/update" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ --data-raw '{ "id": "68ad85a7463006c963799a05" }' ``` ### Minimal Valid JSON Body ```json { "id": "68ad85a7463006c963799a05" } ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Successfully updated dataset Returns the standard FastGPT success envelope ( `{ "code": 200, "statusText": "", "message": "", "data": ... }` ). The exact `data` payload schema is not declared in this OpenAPI contract; refer to the status description above or inspect runtime responses. file: ./content/openapi/reference/model/catalog.en.mdx url: https://doc.fastgpt.io/openapi/reference/model/catalog title: Get Available Model Catalog last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "Get Available Model Catalog", "seoTitle": "Get Available Model Catalog - GET /api/core/ai/model/catalog | FastGPT OpenAPI", "description": "Retrieve all models, providers, and default model IDs available to the caller with optional version caching and custom sorting." } ## Endpoint Overview * **Method** : `GET` * **Path** : `/api/core/ai/model/catalog` * **Module** : Core Features / Models * **Authentication** : `Authorization: Bearer `—Personal API Key (access scoped by team member permissions) (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E6%A8%A1%E5%9E%8B%E7%AE%A1%E7%90%86/GET/core/ai/model/catalog) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E6%A8%A1%E5%9E%8B%E7%AE%A1%E7%90%86/GET/core/ai/model/catalog` ) ## Description & Notes Returns available models, providers, and effective default model IDs for the authenticated member or share-link identity in a single request, with content version negotiation. Passing `orderBy=custom` orders by own team models, shared team models, and system models sorted by `rank` ; omitting preserves runtime order. Members may pass `includeSourceMember=true` to attach creator details (always returning the full catalog; ignored for share links). ## Request Parameters ### Query Parameters | Field | Type | Required | Default | Constraints & Description | | --------------------- | ---------- | -------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------- | | `version` | `string` | No | - | Client-cached catalog version hash. minLength: 1 | | `includeSourceMember` | `boolean` | No | - | Attach source member metadata (members only; always returns the full catalog without version cache) | | `orderBy` | `"custom"` | No | - | Catalog display sorting: `custom` orders own team, shared team, and system models by rank; omit to keep runtime order. Fixed: `"custom"` | | `outLinkAuthData` | `string` | No | - | Share-link auth payload used to evaluate permissions via the link publisher identity | ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X GET "https://cloud.fastgpt.io/api/core/ai/model/catalog" \ -H "Authorization: Bearer YOUR_API_KEY" ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Returns the full catalog when the version changes or `includeSourceMember=true` ; otherwise returns only `version` **Content-Type** : `application/json` | Field | Type | Required | Default | Constraints & Description | | -------------------------------------- | ---------- | -------- | ------- | ------------------------------------------------------------------------------------------------ | | `version` | `string` | Yes | - | Current model catalog version hash | | `data` | `object` | No | - | Full catalog payload (omitted when client version matches and creator details are not requested) | | `data.models` | `object[]` | Yes | - | - | | `data.providers` | `object[]` | Yes | - | - | | `data.providers[].provider` | `string` | Yes | - | Model provider identifier | | `data.providers[].value` | `object` | Yes | - | - | | `data.providers[].value.en` | `string` | Yes | - | - | | `data.providers[].value.zh-CN` | `string` | Yes | - | - | | `data.providers[].value.zh-Hant` | `string` | Yes | - | - | | `data.providers[].avatar` | `string` | Yes | - | Model provider icon URL | | `data.defaultModelIds` | `object` | Yes | - | - | | `data.defaultModelIds.llm` | `string` | No | - | - | | `data.defaultModelIds.embedding` | `string` | No | - | - | | `data.defaultModelIds.tts` | `string` | No | - | - | | `data.defaultModelIds.stt` | `string` | No | - | - | | `data.defaultModelIds.rerank` | `string` | No | - | - | | `data.defaultModelIds.datasetTextLLM` | `string` | No | - | - | | `data.defaultModelIds.datasetImageLLM` | `string` | No | - | - | | `data.defaultModelIds.chatTitleLLM` | `string` | No | - | - | file: ./content/openapi/reference/model/list.en.mdx url: https://doc.fastgpt.io/openapi/reference/model/list title: List Public System Models last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "List Public System Models", "seoTitle": "List Public System Models - GET /api/core/ai/model/list | FastGPT OpenAPI", "description": "Fetch active public system models and pricing metadata for pricing tables or public catalogs without requiring authentication." } ## Endpoint Overview * **Method** : `GET` * **Path** : `/api/core/ai/model/list` * **Module** : Core Features / Models * **Authentication** : No authentication required (public endpoint) (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E6%A8%A1%E5%9E%8B%E7%AE%A1%E7%90%86/GET/core/ai/model/list) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E6%A8%A1%E5%9E%8B%E7%AE%A1%E7%90%86/GET/core/ai/model/list` ) ## Description & Notes Return minimal active system model and pricing metadata for public pricing pages without authentication. ## Request Parameters This endpoint does not require request parameters or a request body. ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X GET "https://cloud.fastgpt.io/api/core/ai/model/list" ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Successfully returned public system model list **Content-Type** : `application/json` | Field | Type | Required | Default | Constraints & Description | | --------------------------- | ---------- | -------- | ------- | ------------------------- | | `models` | `object[]` | Yes | - | - | | `providers` | `object[]` | Yes | - | - | | `providers[].provider` | `string` | Yes | - | Model provider identifier | | `providers[].value` | `object` | Yes | - | - | | `providers[].value.en` | `string` | Yes | - | - | | `providers[].value.zh-CN` | `string` | Yes | - | - | | `providers[].value.zh-Hant` | `string` | Yes | - | - | | `providers[].avatar` | `string` | Yes | - | Model provider icon URL | #### Polymorphic Field: `models` * **Variant 1** ( `type="llm"` ): `type` , `pricing` , `config` , `name` , `provider` , `testMode` * **Variant 2** ( `type="embedding"` ): `type` , `pricing` , `config` , `name` , `provider` , `testMode` * **Variant 3** ( `type="rerank"` ): `type` , `pricing` , `config` , `name` , `provider` , `testMode` * **Variant 4** ( `type="tts"` ): `type` , `pricing` , `name` , `provider` , `testMode` * **Variant 5** ( `type="stt"` ): `type` , `pricing` , `name` , `provider` , `testMode` file: ./content/openapi/reference/model/summary.en.mdx url: https://doc.fastgpt.io/openapi/reference/model/summary title: Get Model Display Summaries last_updated: 2026-11-19T17:16:49+08:00 meta: { "title": "Get Model Display Summaries", "seoTitle": "Get Model Display Summaries - POST /api/core/ai/model/summary | FastGPT OpenAPI", "description": "Batch retrieve model display names, icons, types, and availability status for the current identity or app baseline via API Key." } ## Endpoint Overview * **Method** : `POST` * **Path** : `/api/core/ai/model/summary` * **Module** : Core Features / Models * **Authentication** : `Authorization: Bearer `—Personal API Key (access scoped by team member permissions) (see [API Getting Started](https://doc.fastgpt.io/openapi/intro) ) * **Interactive Try-It-Out** : [Open in Scalar API Explorer](https://cloud.fastgpt.io/apidoc/systemopenapi#tag/%E6%A8%A1%E5%9E%8B%E7%AE%A1%E7%90%86/POST/core/ai/model/summary) (self-hosted instances: replace the origin with `/apidoc/systemopenapi#tag/%E6%A8%A1%E5%9E%8B%E7%AE%A1%E7%90%86/POST/core/ai/model/summary` ) ## Description & Notes Return model names, icons, types, and availability status for the current identity or app baseline without execution credentials. ## Request Parameters ### Request Body ( `application/json` ) | Field | Type | Required | Default | Constraints & Description | | ---------------------------- | ---------- | -------- | ------- | ----------------------------------------------------------------------------------------------------- | | `modelIds` | `string[]` | Yes | - | Stable model IDs to look up (max 100). minItems: 1; maxItems: 100 | | `appId` | `string` | No | - | Optional application ID; treats models in the app baseline as permitted. pattern: `^[0-9a-fA-F]{24}$` | | `outLinkAuthData` | `object` | No | - | Share-link auth payload; evaluates model permissions under the publisher identity | | `outLinkAuthData.shareId` | `string` | Yes | - | Share link ID. minLength: 1 | | `outLinkAuthData.outLinkUid` | `string` | Yes | - | External share user ID. minLength: 1 | ## Request Examples Replace `YOUR_API_KEY` and placeholder IDs before running. Self-hosted users should replace the base URL with `/api` . ### cURL Example ```bash curl --fail-with-body -X POST "https://cloud.fastgpt.io/api/core/ai/model/summary" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ --data-raw '{ "modelIds": [ "68ad85a7463006c963799a01" ] }' ``` ### Minimal Valid JSON Body ```json { "modelIds": ["68ad85a7463006c963799a01"] } ``` ## Response Schema & Examples Successful `/api/*` calls return the standard FastGPT envelope `{ "code": 200, "statusText": "", "message": "", "data": ... }` , where `data` matches the `200` schema below (when a payload schema is declared; otherwise refer to the status description for runtime `data` semantics). ### HTTP 200 Display status entries for active, inactive, deprecated, or unauthorized models **Content-Type** : `application/json` | Field | Type | Required | Default | Constraints & Description | | -------- | ---------- | -------- | ------- | ------------------------------------------------- | | `models` | `object[]` | Yes | - | Model display summaries returned in request order | #### Polymorphic Field: `models` * **Variant 1** ( `status="deleted"` ): `status` , `modelId` , `isUpcomingDeprecation` * **Variant 2** : `type` , `name` , `avatar` , `status` , `modelId` , `isUpcomingDeprecation` file: ./content/openapi/sdk/go.en.mdx url: https://doc.fastgpt.io/openapi/sdk/go title: Go SDK last_updated: 2026-12-01T16:49:37+08:00 meta: { "title": "Go SDK", "description": "Use the official FastGPT Go SDK (Go 1.24+, zero third-party dependencies) for SSE chat, interactive Workflows, and Datasets." } > **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): `/apidoc/systemopenapi` **Compatibility: Go 1.24 or later for FastGPT System OpenAPI.** `github.com/fastgpt-apps/fastgpt-go` (`package fastgpt`) is the official Go SDK for FastGPT System OpenAPI. Built with **zero third-party dependencies** purely on the Go 1.24 standard library (`net/http`, `encoding/json`, `iter.Seq2`, `context.AfterFunc`, `log/slog`), its models and service tree are deterministically generated from the System OpenAPI IR and cover all 47 System OpenAPI operations plus dual-mode chat streaming. > If you only need basic OpenAI-compatible chat calls, see the [API Quick Start](https://doc.fastgpt.io/openapi/intro). Use the official Go SDK when integrating streaming chat, interactive Workflows, Dataset processing, batch archive downloads, or App logs in Go services. ## Installation and Module Path * Runtime: **Go 1.24+** * Third-party dependencies: none * Module path: `github.com/fastgpt-apps/fastgpt-go` Install the published beta pre-release explicitly with `v0.1.0-beta.1` (omitting the tag before GA resolves to the `v0.0.1` placeholder): ```bash # Install the published beta pre-release explicitly go get github.com/fastgpt-apps/fastgpt-go@v0.1.0-beta.1 ``` Optional environment variables supported as fallbacks: | Variable | Purpose | Default / Fallback | | ------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------------- | | `FASTGPT_BASE_URL` | FastGPT server origin (with or without `/api`, normalized automatically) | Used when `WithBaseURL` is omitted; falls back to `https://cloud.fastgpt.cn` | | `FASTGPT_API_KEY` | Personal API key or App API key | Read when `WithAPIKey`, `WithAPIKeyProvider`, and `WithRequestAPIKey` are unset | ## Quick Start and Client Configuration ```go package main import ( "context" "fmt" "log" "os" fastgpt "github.com/fastgpt-apps/fastgpt-go" ) func main() { ctx := context.Background() client := fastgpt.NewClient( fastgpt.WithBaseURL(os.Getenv("FASTGPT_BASE_URL")), fastgpt.WithAPIKey(os.Getenv("FASTGPT_API_KEY")), fastgpt.WithDefaultAppID(os.Getenv("FASTGPT_APP_ID")), // optional for App API keys ) completion, err := client.Chat.CompletionsV2(ctx, fastgpt.ChatCompletionsV2Params{ ChatID: fastgpt.String("chat_001"), Messages: fastgpt.Some([]fastgpt.ChatMessage{ fastgpt.UserMessage("Summarize today's release notes."), }), }) if err != nil { log.Fatal(err) } if len(completion.Choices) > 0 { text, _ := completion.Choices[0].Message.Content.Text() fmt.Println(text) } } ``` * **Key scopes**: Chat, chat-management, and App log (`Apps.Logs`) endpoints accept both Personal API keys and App API keys (`WithDefaultAppID` is optional for App API keys because the server binds the App automatically). `Datasets` and `Models.Catalog` require a Personal API key, while `Models.List` returns public system models without requiring a key. ### Common `ClientOption` helpers | Option | Purpose | Default | | ------------------------- | ------------------------------------------------------------------------------------------ | ------------------------------------------------ | | `WithBaseURL(url)` | Set server base URL (auto-normalized to `/api`) | `FASTGPT_BASE_URL` or `https://cloud.fastgpt.cn` | | `WithAPIKey(key)` | Set a static API key | `FASTGPT_API_KEY` | | `WithAPIKeyProvider(fn)` | Resolve credentials dynamically per request for key rotation | `nil` | | `WithDefaultAppID(appID)` | Default `appId` injected on App-scoped operations | `""` | | `WithIdentity(identity)` | Default caller identity context | `nil` | | `WithTimeout(d)` | Full-attempt timeout for JSON calls; handshake-only for SSE and binary downloads | `60 * time.Second` | | `WithMaxRetries(n)` | Retry cap for idempotent `GET` requests on `408`/`429`/`502`/`503`/`504` or network errors | `2` | | `WithDefaultHeader(k, v)` | Add a default HTTP header to every request | None | | `WithHTTPClient(hc)` | Supply a custom `*http.Client` | `&http.Client{}` | | `WithHooks(hooks)` | Register `OnRequest`, `OnResponse`, and `OnError` hooks | None | | `WithLogger(logger)` | Attach `*slog.Logger` with automatic secret redaction | `nil` | ## Identity Isolation, Derived Clients, and Per-Request Overrides ### Derived clients (`WithIdentity` / `WithOptions`) Both `client.WithIdentity(...)` and `client.WithOptions(...)` **share the parent client's `*http.Client` connection pool**, making it cheap to derive scoped clients per tenant or end user: ```go // 1. Track external end users via CustomUID (App API key or Personal API key) userClient := client.WithIdentity(fastgpt.IdentityCustomUID("tenant-01:user-42")) histories, err := userClient.Chat.Histories.List(ctx, fastgpt.ChatHistoriesListParams{ PageSize: fastgpt.Int(20), }) // 2. Act on behalf of a team member with Personal API key and AuthProxy enabled memberClient := client.WithIdentity(fastgpt.IdentityAuthProxy(fastgpt.AuthProxyByUsername("alice"))) ``` `CustomUID` and `AuthProxy` (as well as `TmbID` and `Username` inside `AuthProxy`) are mutually exclusive and fail fast with `ErrBadRequest` before sending a request. See [Identity Proxy](https://doc.fastgpt.io/openapi/identity-proxy) for server-side setup. ### Per-request overrides (`RequestOption`) Every resource method accepts `opts ...RequestOption` to override configuration or inspect raw HTTP responses: ```go var raw fastgpt.RawResponse detail, err := client.Datasets.Detail( ctx, fastgpt.DatasetsDetailParams{ID: "68ad85a7463006c963799a05"}, fastgpt.WithRequestAPIKey(os.Getenv("FASTGPT_PERSONAL_KEY")), fastgpt.WithRequestTimeout(10*time.Second), fastgpt.WithRequestMaxRetries(0), fastgpt.WithRawResponse(&raw), ) if err == nil { fmt.Println(detail.Name, raw.StatusCode, raw.RequestID) } ``` Available options: `WithRequestHeader`, `WithRequestTimeout`, `WithRequestMaxRetries`, `WithRequestAPIKey`, `WithRequestAppID`, `WithRequestIdentity`, and `WithRawResponse`. ## Tri-State Optional Fields (`Opt[T]`) and Sealed Unions ### Tri-state `Opt[T]` Using Go 1.24 `json:",omitzero"`, `fastgpt.Opt[T]` cleanly separates omitted keys, explicit zero values (`false`, `0`, `""`), and explicit JSON `null`: * **Omitted**: Leave the field unset (zero `Opt[T]{}`; `IsZero()` returns `true`). * **Explicit value**: Use `fastgpt.String(...)`, `fastgpt.Bool(...)`, `fastgpt.Int(...)`, `fastgpt.Float64(...)`, or generic `fastgpt.Some(val)`. * **Explicit `null`**: Use `fastgpt.Null[T]()` (`IsNull()` returns `true`). * **Reading values**: Inspect via `.Get() (T, bool)` or `.Or(fallback)`. ### Sealed unions and constructors * **Request unions**: Mutually exclusive request parameters expose typed constructors that strip disallowed fields—for example `fastgpt.DeleteCollectionByID(id)`, `fastgpt.DeleteCollectionsByIDs(ids...)`, `fastgpt.DeleteCollectionsByAPIFiles(datasetID, apiFileIDs...)`, and message constructors (`fastgpt.SystemMessage`, `UserMessage`, `AssistantMessage`, `ToolMessage`). * **Response unions**: Polymorphic response types preserve `RawJSON` alongside variant helpers such as `AsApp()`, `AsLLM()`, `Text()`, and `Parts()` so unknown future variants degrade safely. ## Resource Tree | Service Field | Coverage | | ----------------- | ----------------------------------------------------------------------------------------------------------------------- | | `client.Chat` | `CompletionsV2`, `CompletionsV2Stream`, `Stop`, `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` is split into non-streaming `CompletionsV2` and streaming `CompletionsV2Stream`. ### Iterating SSE events with Go 1.24 `iter.Seq2` ```go stream, err := userClient.Chat.CompletionsV2Stream(ctx, fastgpt.ChatCompletionsV2Params{ ChatID: fastgpt.String("chat_001"), Messages: fastgpt.Some([]fastgpt.ChatMessage{fastgpt.UserMessage("Summarize today's Workflow logs.")}), Detail: fastgpt.Bool(true), }) if err != nil { log.Fatal(err) } defer stream.Close() for ev, err := range stream.Events() { if err != nil { log.Fatal(err) } switch e := ev.(type) { case fastgpt.ChatSSEAnswerEvent: fmt.Print(e.TextDelta) case fastgpt.ChatSSEFlowNodeStatusEvent: fmt.Printf("\n[Node] %s (%s)\n", e.Name, e.Status) } } summary, err := stream.FinalResult() if err != nil { log.Fatal(err) } fmt.Printf("\nTitle=%q Quotes=%d\n", summary.ChatTitle, len(summary.Quotes)) ``` ### Consumer ownership rules `ChatStream` enforces exclusive consumer ownership to prevent concurrent frame stealing: * Use `for ev, err := range stream.Events()` (or call `stream.FinalResult()` / `stream.FinalText()` directly). * If using manual `for stream.Next() { ev := stream.Current() }` followed by `stream.Err()`, **do not call `FinalResult()` / `FinalText()` while `Next()` is still active**—doing so immediately returns `ErrBadRequest`. Finish draining `Next()` or call `stream.Close()` first. ## 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: ```go if userClient.Chat.Interactive.IsInteractivePending(completion) { outer := userClient.Chat.Interactive.ExtractInteractive(completion) prompt := userClient.Chat.Interactive.UnwrapInteractive(outer) switch { case fastgpt.IsUserSelectInteractive(prompt): _, err = userClient.Chat.Interactive.ReplyUserSelect(ctx, fastgpt.ReplyUserSelectParams{ ChatID: "chat_001", Value: prompt.UserSelect.UserSelectOptions[0].Value, }) case fastgpt.IsUserInputInteractive(prompt): _, err = userClient.Chat.Interactive.ReplyUserForm(ctx, fastgpt.ReplyUserFormParams{ ChatID: "chat_001", Values: map[string]any{"project": "FastGPT", "priority": "P0"}, }) } } ``` ## Datasets, Streaming Downloads, and Auto-Pagination ### Multipart file uploads ```go created, err := client.Datasets.Collections.CreateByLocalFile(ctx, fastgpt.DatasetsCollectionsCreateByLocalFileParams{ DatasetID: "68ad85a7463006c963799a05", TrainingType: fastgpt.String("chunk"), File: fastgpt.FileUpload{ Filename: "handbook.md", ContentType: "text/markdown", Bytes: markdownBytes, }, }) ``` ### Streaming archive download (`*BinaryStream`) `BatchDownload` returns `*fastgpt.BinaryStream` (implementing `io.ReadCloser` and `io.WriterTo`, plus `.Bytes()`, `.ContentType()`, `.ContentLength()`, and `.Response()`), streaming ZIP bytes without buffering the entire archive in memory. The transport disables SDK retries, `net/http` keep-alive replays, and unfollowed-redirect masking so single-use tickets are never consumed twice or confused with HTML error pages: ```go ticketRes, err := client.Datasets.Collections.GetDownloadTicket(ctx, fastgpt.DatasetsCollectionsGetDownloadTicketParams{ DatasetID: "68ad85a7463006c963799a05", CollectionIDs: []string{created.CollectionID}, }) if err != nil { log.Fatal(err) } dlStream, err := client.Datasets.Collections.BatchDownload(ctx, fastgpt.DatasetsCollectionsBatchDownloadParams{ Ticket: ticketRes.Ticket, }) if err != nil { log.Fatal(err) } defer dlStream.Close() outFile, err := os.Create("collections.zip") if err != nil { log.Fatal(err) } defer outFile.Close() if _, err := io.Copy(outFile, dlStream); err != nil { log.Fatal(err) } ``` ### Automatic pagination (`*Pager[T]`) Paginated endpoints provide `*AutoPaging` methods supporting `.All()`, `.Pages()`, `.Collect()`, and manual `Next()` / `Current()` / `Err()`, bounded via `WithPageSize`, `WithMaxPages`, `WithMaxItems`, and `WithPagerRequestOptions`: ```go // 1. Offset auto-pagination across Chunks for chunk, err := range client.Datasets.Data.ListAutoPaging( ctx, fastgpt.DatasetsDataListParams{CollectionID: created.CollectionID}, fastgpt.WithPageSize(50), fastgpt.WithMaxItems(500), ).All() { if err != nil { log.Fatal(err) } fmt.Println(chunk.ID_, chunk.Q) } // 2. Cursor auto-pagination for App chat logs (POST /core/app/logs/search) logs, err := client.Apps.Logs.SearchAutoPaging( ctx, fastgpt.AppsLogsSearchParams{ DateStart: "2026-01-01T00:00:00.000Z", DateEnd: "2026-01-31T23:59:59.999Z", }, fastgpt.WithMaxPages(5), ).Collect() ``` ## Observability and Structured Errors Every SDK error is an `*fastgpt.APIError` compatible with `errors.Is` and `errors.As`. Messages, URLs, causes, hooks, and `slog` output automatically redact API keys and URL query secrets (`ticket`, `token`, `apiKey`): ```go client := fastgpt.NewClient( fastgpt.WithAPIKey(os.Getenv("FASTGPT_API_KEY")), fastgpt.WithLogger(slog.Default()), fastgpt.WithHooks(fastgpt.Hooks{ OnRequest: func(_ context.Context, r fastgpt.RequestHookContext) { log.Printf("-> %s %s (attempt %d)", r.Method, r.URL, r.Attempt) }, OnResponse: func(_ context.Context, r fastgpt.ResponseHookContext) { log.Printf("<- %d reqId=%s (%s)", r.StatusCode, r.RequestID, r.Duration) }, OnError: func(_ context.Context, e fastgpt.ErrorHookContext) { log.Printf("!! %s: %v", e.OperationID, e.Error) }, }), ) if _, err := client.Chat.Histories.List(ctx, fastgpt.ChatHistoriesListParams{}); err != nil { var apiErr *fastgpt.APIError _ = errors.As(err, &apiErr) switch { case errors.Is(err, fastgpt.ErrAuth): // 401 / 403 / server code 514 (unAuthApiKey) case errors.Is(err, fastgpt.ErrConflict): // 409 / chatIsGenerating: inspect apiErr.ChatGeneratingConflict() case errors.Is(err, fastgpt.ErrRateLimit): // 429 / tooManyRequest / uploadFileIntervalLimit case errors.Is(err, fastgpt.ErrTimeout): // Handshake or non-streaming read timeout case errors.Is(err, fastgpt.ErrNetwork): // Transport failure or SSE stream ended before [DONE] case errors.Is(err, fastgpt.ErrAborted): // Caller context canceled or stream closed early } } ``` Sentinel error kinds: `ErrAPI` (matched by all `*APIError` values), `ErrAuth`, `ErrBadRequest`, `ErrNotFound`, `ErrConflict`, `ErrRateLimit`, `ErrServer`, `ErrTimeout`, `ErrNetwork`, and `ErrAborted`. file: ./content/openapi/sdk/java.en.mdx url: https://doc.fastgpt.io/openapi/sdk/java title: Java SDK last_updated: 2026-12-01T16:49:37+08:00 meta: { "title": "Java SDK", "description": "Use the official FastGPT Java 17 SDK for sync and async chat, SSE streaming, interactive Workflows, and Datasets." } > **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): `/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 io.github.fastgpt-apps fastgpt-sdk 0.1.0-beta.1 ``` 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` 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` | `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 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`) and Resource Tree ### Tri-state `JsonField` Request parameter builders use `JsonField` to distinguish omitted keys (`JsonField.ofMissing()`), explicit JSON `null` (`*Null()` / `JsonField.ofNull()`), and explicit zero values (`false`, `0`, `""`). Workflow `variables` and JSON `Map` 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` 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` 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`) 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 | file: ./content/openapi/sdk/python.en.mdx url: https://doc.fastgpt.io/openapi/sdk/python title: Python SDK last_updated: 2026-12-01T16:49:37+08:00 meta: { "title": "Python SDK", "description": "Use the official FastGPT Python SDK (fastgpt-sdk) with sync and async clients for chat, Datasets, logs, and models." } > **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): `/apidoc/systemopenapi` **Compatibility: Python >= 3.10 for FastGPT System OpenAPI.** `fastgpt-sdk` (import package `fastgpt_sdk`) is the official Python SDK for FastGPT System OpenAPI. Built on `httpx` and Pydantic v2, it provides matching synchronous (`FastGPT`) and asynchronous (`AsyncFastGPT`) clients deterministically generated from the System OpenAPI IR across 47 endpoints: chat completions, SSE streaming, interactive Workflow resumption, Datasets and Collections, App logs, and model catalogs. > If you only need basic OpenAI-compatible chat calls, you can use the official OpenAI Python SDK directly—see the [API Quick Start](https://doc.fastgpt.io/openapi/intro). Use `fastgpt-sdk` when you need typed Datasets, interactive Workflows, chat history management, App logs, or strict request validation. ## Installation and Requirements * Runtime: **Python 3.10 or later** * Core dependencies: `httpx`, `pydantic >= 2.7` The `0.1.0b1` pre-release of `fastgpt-sdk` is published on PyPI—enable pre-releases when installing: ```bash pip install --pre fastgpt-sdk # or with uv uv add --prerelease=allow fastgpt-sdk ``` The SDK reads these optional environment variables: | Variable | Purpose | Default / Fallback | | ------------------ | ------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------- | | `FASTGPT_BASE_URL` | FastGPT server origin (with or without `/api`, normalized automatically) | Used when `base_url` is omitted; falls back to `https://cloud.fastgpt.cn` | | `FASTGPT_API_KEY` | Personal API key or App API key | Used when neither `api_key` nor `request_options` provides a key | | `FASTGPT_APP_ID` | Default App ID | Read explicitly by your code via `os.environ.get("FASTGPT_APP_ID")` for `default_app_id` | ## Quick Start and Authentication ### Synchronous client (`FastGPT`) Use `FastGPT` as a context manager to close its underlying HTTP pool cleanly on exit: ```python import os from fastgpt_sdk import FastGPT with FastGPT( base_url=os.environ.get("FASTGPT_BASE_URL", "https://cloud.fastgpt.cn"), api_key=os.environ.get("FASTGPT_API_KEY"), default_app_id=os.environ.get("FASTGPT_APP_ID"), # optional for App API keys ) as client: completion = client.chat.completions_v2( chat_id="chat_001", messages=[{"role": "user", "content": "Summarize today's release notes."}], ) print(completion.choices[0].message.content) ``` ### Asynchronous client (`AsyncFastGPT`) `AsyncFastGPT` mirrors the synchronous resource tree and Pydantic models for async frameworks such as FastAPI: ```python import asyncio import os from fastgpt_sdk import AsyncFastGPT async def main() -> None: async with AsyncFastGPT( base_url=os.environ.get("FASTGPT_BASE_URL", "https://cloud.fastgpt.cn"), api_key=os.environ.get("FASTGPT_API_KEY"), default_app_id=os.environ.get("FASTGPT_APP_ID"), ) as client: completion = await client.chat.completions_v2( chat_id="chat_001", messages=[{"role": "user", "content": "Summarize today's release notes."}], detail=True, ) print(completion.choices) asyncio.run(main()) ``` ### Personal API keys vs. App API keys * **App API key (v4.18.0+)**: Bound to a single App on the server, so `default_app_id` 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 `default_app_id` or pass `app_id` directly to an App-scoped method to target a specific App. `models.list` queries public system models without requiring a key. * **Credential rotation**: Pass a callable (`Callable[[], str]` for sync, sync or `async` callable for async) as `api_key` to resolve fresh tokens on every request. ### Client constructor options | Parameter | Type | Default | Description | | ----------------- | ------------------------------------------- | ------------------- | ---------------------------------------------------------------------------------------------- | | `base_url` | `str \| None` | `None` | FastGPT instance URL, normalized to end with `/api` | | `api_key` | `str \| Callable \| None` | `None` | Static API key or per-request credential provider | | `default_app_id` | `str \| None` | `None` | Default `appId` injected into App-scoped endpoints | | `identity` | `FastGPTIdentity \| Mapping \| None` | `None` | Default caller identity (`custom_uid` or `auth_proxy`) | | `timeout` | `float \| httpx.Timeout \| None` | `60.0` | Request timeout in seconds (or `httpx.Timeout`) | | `max_retries` | `int \| None` | `2` (`GET` retries) | Retry limit for idempotent `GET` requests on `408`/`429`/`502`/`503`/`504` or transport errors | | `default_headers` | `Mapping[str, str] \| None` | `None` | Default HTTP headers attached to every request | | `hooks` | `FastGPTHooks \| None` | `None` | Request, response, and error observability hooks | | `logger` | `FastGPTLogger \| LogLevel \| None` | `None` | Built-in redacted log level or custom logger | | `http_client` | `httpx.Client \| httpx.AsyncClient \| None` | `None` | Custom `httpx` client instance | ## Caller Identity Isolation and Per-Request Overrides ### Derived clients per end user (`with_identity`) Keep one shared parent client in your backend and derive lightweight per-request or per-user clients with `with_identity`. Derived clients reuse the parent's `httpx` connection pool and automatically inject identity fields into JSON bodies or query parameters per endpoint contract: ```python # 1. End-user tracking with custom_uid (App API key or Personal API key) user_client = client.with_identity(custom_uid="tenant-01:user-42") histories = user_client.chat.histories.list(page_size=20) # 2. Acting as a team member with Personal API key and auth_proxy enabled member_client = client.with_identity(auth_proxy={"username": "alice"}) ``` `custom_uid` and `auth_proxy` are strictly mutually exclusive; passing both raises a validation error before sending any request. See [Identity Proxy](https://doc.fastgpt.io/openapi/identity-proxy) for server-side rules. ### Derived config and per-call options (`with_options` / `request_options`) * `client.with_options(...)`: Creates a derived client with overridden defaults (`timeout`, `api_key`, `default_app_id`, `max_retries`, etc.) while sharing the parent's connection pool. * `request_options`: Overrides `api_key`, `timeout`, `max_retries`, `headers`, or—on identity-enabled endpoints such as chat and chat-management—`custom_uid` or `auth_proxy` for a single method call. To switch the target App on an App-scoped endpoint when using a **Personal API key**, pass `app_id="..."` directly as a method argument (App API keys remain bound to one App on the server). ```python detail = client.datasets.detail( id="68ad85a7463006c963799a05", request_options={ "api_key": os.environ["FASTGPT_PERSONAL_KEY"], "timeout": 10.0, "max_retries": 0, }, ) # Pass custom_uid on identity-enabled chat calls; Personal API keys can also pass app_id reply = client.chat.completions_v2( app_id="68ad85a7463006c963799a01", # Personal API key only; omit for App API keys chat_id="chat_001", messages=[{"role": "user", "content": "Hello"}], request_options={"custom_uid": "tenant-01:user-42"}, ) ``` ## Resource Tree and Input Styles The client exposes four domain resource trees with full static type annotations: | Resource Path | Capabilities | | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | | `client.chat` | `/v2/chat/completions` sync & SSE streaming, `stop`, Workflow interactive continuation (`interactive`), plus `histories`, `records`, and `feedbacks` | | `client.datasets` | Dataset lifecycle, hybrid `search`, `collections` (local file, link, text, batch archive download), and `data` Chunk management | | `client.apps` | `apps.logs` cursor search (`search`), usage charts, totals, and user lists | | `client.models` | Public system model list (`list`), model `catalog` (Personal API key), and `summary` | Every method accepts three equivalent input styles (pass either a positional payload or keyword arguments, never both): 1. **Pythonic keyword arguments**: e.g., `client.datasets.list(page_size=20, search_key="handbook")`. 2. **Typed Pydantic models**: import request classes from `fastgpt_sdk.generated.models`. 3. **Plain dicts**: accepts both `snake_case` and OpenAPI `camelCase` keys and rejects conflicting aliases for the same field. For optional tri-state fields, `NOT_GIVEN` omits the key from JSON, while `None` serializes an explicit `null` (use `is_given(...)` for type narrowing). ## Chat Completions and SSE Streaming `/v2/chat/completions` is exposed as separate `completions_v2` (non-streaming JSON) and `completions_v2_stream` (typed SSE stream) methods. ### Synchronous streaming ```python with user_client.chat.completions_v2_stream( chat_id="chat_001", messages=[{"role": "user", "content": "Summarize today's Workflow logs."}], detail=True, ) as stream: for event in stream: if event.type == "answer": print(event.text_delta, end="", flush=True) elif event.type == "flowNodeStatus": print(f"\n[Node] {event.name}: {event.status}") summary = stream.final_result() print("\nCitations:", len(summary.quotes), "Interactive:", summary.interactive) ``` ### Asynchronous streaming ```python async with await async_user_client.chat.completions_v2_stream( chat_id="chat_001", messages=[{"role": "user", "content": "Summarize today's Workflow logs."}], detail=True, ) as stream: async for event in stream: if event.type == "answer": print(event.text_delta, end="", flush=True) full_text = await stream.final_text() ``` ### `ChatStream` and `AsyncChatStream` helpers * `final_result()`: Consumes remaining events if needed and returns `ChatStreamFinalResult` with aggregated `text`, `reasoning_text`, `chat_title`, `quotes`, `interactive`, and completion state. * `final_text()`: Drains remaining events and returns the final assistant text string. * Context managers (`with` / `async with`) shield cleanup against async cancellation and close the underlying HTTP stream on early `break`. ## Resuming Interactive Workflows When a Workflow pauses at a selection or form input node, the response or stream summary contains an `interactive` payload. Use `client.chat.interactive` to detect, unwrap, and reply—see [Interactive Nodes & Variables](https://doc.fastgpt.io/openapi/interactive-and-variables) for full protocol details: ```python if user_client.chat.interactive.is_pending(completion): prompt = user_client.chat.interactive.unwrap( user_client.chat.interactive.extract(completion) ) if prompt.type == "userSelect": next_res = user_client.chat.interactive.reply_user_select( chat_id="chat_001", value=prompt.params.user_select_options[0].value, ) elif prompt.type == "userInput": next_res = user_client.chat.interactive.reply_user_form( chat_id="chat_001", values={"project": "FastGPT", "priority": "P0"}, ) ``` On `AsyncFastGPT`, `async_client.chat.interactive` provides async `reply_user_select` and `reply_user_form` methods with the same signature. ## Datasets, File Uploads, and Auto-Pagination ### Local file uploads (Multipart) `create_by_local_file` accepts `bytes`, `bytearray`, `pathlib.Path`, a readable binary stream, or a `(filename, content, content_type)` tuple and encodes both `file` and `data` parts into `multipart/form-data`: ```python from pathlib import Path created = client.datasets.collections.create_by_local_file( dataset_id="68ad85a7463006c963799a05", training_type="chunk", file=("handbook.md", Path("./handbook.md").read_bytes(), "text/markdown"), ) print("Created Collection ID:", created.collection_id) ``` ### Batch archive download Downloading Collections as a ZIP uses a two-step ticket flow. `batch_download` marks the request non-retryable (`retryable=False`) so transient transport retries never burn a single-use ticket: ```python ticket_res = client.datasets.collections.get_download_ticket( dataset_id="68ad85a7463006c963799a05", collection_ids=[created.collection_id], ) zip_bytes = client.datasets.collections.batch_download(ticket=ticket_res.ticket) Path("./collections.zip").write_bytes(zip_bytes) ``` ### Automatic pagination (`*_auto_paging`) Offset, page-number, and cursor endpoints provide auto-paging iterables supporting item iteration (`for item in pager` / `async for item in pager`), page batches (`.pages()`), list collection (`.to_list()`), and `max_items` / `max_pages` bounds: ```python # 1. Offset auto-pagination across Chunks in a Collection for chunk in client.datasets.data.list_auto_paging( collection_id=created.collection_id, page_size=50, max_items=500, ): print(chunk.id_, chunk.q) # 2. Cursor auto-pagination for App chat logs (POST /core/app/logs/search) for log in client.apps.logs.search_auto_paging( date_start="2026-01-01T00:00:00.000Z", date_end="2026-01-31T23:59:59.999Z", max_pages=5, ): print(log.chat_id, log.title) ``` ## Raw Responses, Observability, and Errors ### Inspecting raw HTTP metadata Prefix any resource tree with `with_raw_response` to receive `APIResponse[T]` with `status_code`, `headers`, `request_id`, and `.parse()`: ```python raw = client.with_raw_response.models.list() models_res = raw.parse() print(raw.status_code, raw.request_id, len(models_res.models)) ``` ### Hooks, logging, and automatic redaction `FastGPTHooks` and `logger` automatically redact `Authorization` headers, `fastgpt-` / `openapi-` prefixed keys, custom credentials, and URL tokens (`ticket`, `token`, `apiKey`) across logs, exceptions, and URLs: ```python from fastgpt_sdk import FastGPT, FastGPTHooks hooks = FastGPTHooks( on_request=lambda ctx: print("->", ctx.method, ctx.url, ctx.attempt), on_response=lambda ctx: print("<-", ctx.status_code, ctx.request_id, f"{ctx.duration_ms:.1f}ms"), on_error=lambda ctx: print("!!", ctx.operation_id, ctx.error), ) client = FastGPT(api_key=os.environ["FASTGPT_API_KEY"], logger="warn", hooks=hooks) ``` ### Exception hierarchy Transport failures, HTTP `4xx`/`5xx` statuses, legacy HTTP `200` error envelopes, and SSE error frames all map onto subclasses of `FastGPTError`: | Exception Class | Trigger Condition | | ------------------------ | --------------------------------------------------------------------------- | | `FastGPTAuthError` | HTTP `401` / `403`, server code `514`, `unAuth*` status, or missing API key | | `FastGPTBadRequestError` | Other `4xx` validation errors or local precondition checks | | `FastGPTNotFoundError` | HTTP `404` / `410` or `*UnExist` / `*NotFound` errors | | `FastGPTConflictError` | HTTP `409` or `chatIsGenerating` when a Session turn is still generating | | `FastGPTRateLimitError` | HTTP `429` or `tooManyRequest` / `uploadFileIntervalLimit` | | `FastGPTServerError` | `5xx` server errors | | `FastGPTTimeoutError` | Connect, handshake, or response body timeout | | `FastGPTNetworkError` | Socket errors or truncated SSE stream before `[DONE]` | file: ./content/openapi/sdk/typescript.en.mdx url: https://doc.fastgpt.io/openapi/sdk/typescript title: TypeScript SDK last_updated: 2026-12-02T10:14:48+08:00 meta: { "title": "TypeScript SDK", "description": "Use the official FastGPT TypeScript SDK (@fastgpt/sdk) with zero runtime dependencies for chat, SSE streaming, interactive Workflows, and Datasets." } > **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): `/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`, 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` | `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` | `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`), 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` 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 = 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); } } ``` file: ./content/plugin/debugging-and-publishing.en.mdx url: https://doc.fastgpt.io/plugin/debugging-and-publishing title: Debugging, packing, and publishing last_updated: 2026-12-01T18:08:29+08:00 meta: { "title": "Debugging, packing, and publishing", "description": "Validate tool plugins locally, connect them to FastGPT, and build packages for distribution" } This guide covers tool plugins created with `@fastgpt-plugin/cli` and `@fastgpt-plugin/sdk-factory`. Prepare an implemented [tool or Toolkit](https://doc.fastgpt.io/plugin/system-tool-development) before starting. Model presets follow their own [validation workflow](https://doc.fastgpt.io/plugin/model-presets#validation). Remote debugging requires a FastGPT environment with plugin debugging enabled. Self-hosted operators can follow the [remote debug suite configuration](https://doc.fastgpt.io/self-host/config/remote-debug-suite). Use a CLI version compatible with your plugin service. ## 1. Local mock debugging Install dependencies in the plugin directory first: ```bash cd packages/tools/my-tool pnpm install ``` View plugin and debuggable tool information: ```bash pnpx @fastgpt-plugin/cli debug . ``` Run one single-tool debug invocation: ```bash pnpx @fastgpt-plugin/cli debug . --run --input '{"query":"hello"}' --secrets '{"apiKey":"test"}' ``` Run a child tool in a Toolkit: ```bash pnpx @fastgpt-plugin/cli debug . --run --tool search --input '{"query":"hello"}' --secrets '{"apiKey":"test"}' ``` Use files when input, secrets, or system variables are large: ```bash pnpx @fastgpt-plugin/cli debug . --run --input-file input.json --secrets-file secrets.json --system-var-file system-var.json ``` Local debug boundaries: * `ctx.invoke.uploadFile()` uses a local mock implementation and defaults to `.fastgpt-plugin-debug/uploads`. * Host capabilities that require real platform authorization and billing—such as `ctx.invoke.createModelClient()`—are not mocked in local debug and fail with an unsupported error; use **FastGPT remote debugging** below to verify them. * Local debug quickly validates plugin logic and schemas. * Local debug does not simulate the production child-process pool, real Node.js IPC, network environment, server timeout, or queue scheduling. * Before listing an official plugin, install it manually in a test environment and complete end-to-end testing. > - For plugins that use reverse model invocation (`model:invoke`), **all** CLI commands—`build`, `check`, `pack`, and interactive, non-interactive, or saved-connection `dev` runs—currently require `@fastgpt-plugin/cli@0.2.2-beta.1` (paired with `@fastgpt-plugin/sdk-factory@1.2.0-beta.4`) and a FastGPT test environment with `model:invoke` support. The default `@fastgpt-plugin/cli@0.2.1` rejects `permission: ['model:invoke']` during `build`/`check` and lacks remote `chatCompletion` support. > - Pure debug calls without a `usageId` return model responses without creating billing records; to verify billing, trigger the tool through a workflow or conversation path that records usage, or install the `.pkg` package in a test environment. ## 2. FastGPT remote debugging Remote debugging connects a locally developed plugin to a FastGPT test environment. The FastGPT page authenticates the user and generates a debug link, while the CLI uses that link to create a WSS debug channel. Debug plugins are visible only to the developer running that session. Before using it, confirm that the test environment has deployed the FastGPT Plugin service and Connection Gateway, and that your local machine can reach the Gateway WSS endpoint returned by the test environment. ### 2.1 Generate a debug link 1. Sign in to the FastGPT test environment. 2. Open **Studio → System Tools** and click **Local Debug**. ![System Tools local debug entry](https://cdn.jsdelivr.net/gh/labring/fastgpt-img@main/optimized/current/system-tool-debug-entry.png.webp) 3. In the modal, click Generate Link and copy the debug link. 4. If a debug session already exists, click Refresh Link to generate a new connection key; the old link becomes invalid. ![Local debug dialog before generating a link](https://cdn.jsdelivr.net/gh/labring/fastgpt-img@main/optimized/current/system-tool-debug-dialog.png.webp) The debug link is only for connecting your local CLI to the test environment. Do not commit it to code repositories, documentation examples, or chat logs. ### 2.2 Start a local remote-debug session Run this command in a plugin directory or a workspace that contains multiple plugin directories: ```bash pnpx @fastgpt-plugin/cli dev ``` If your plugin uses reverse model invocation (`model:invoke`), use `@fastgpt-plugin/cli@0.2.2-beta.1` for all `dev` commands below (interactive, `--no-interactive`, `--watch`, and saved-connection runs) against a test environment whose FastGPT main and Plugin services include `model:invoke` support: ```bash pnpx @fastgpt-plugin/cli@0.2.2-beta.1 dev ``` After startup, paste the debug link copied from FastGPT into the TUI. The CLI exchanges the connection key from the link for a short-lived WSS connect token, then mounts local plugins to the FastGPT debug channel. Scripts and Agents can use non-interactive mode: ```bash pnpx @fastgpt-plugin/cli@0.2.2-beta.1 dev --no-interactive \ --connect "https://fastgpt.example.com/api/plugin/debug-channel/connection-key/exchange?connectionKey=fpg_dbg_..." ``` When passing only a raw connection key, tell the CLI where the exchange endpoint is: ```bash FASTGPT_PLUGIN_DEBUG_CONNECT_URL=https://fastgpt.example.com/api/plugin/debug-channel/connection-key/exchange \ pnpx @fastgpt-plugin/cli@0.2.2-beta.1 dev --no-interactive --connect "fpg_dbg_..." ``` After `--connect` connects successfully, it saves the connection key so later `pnpx @fastgpt-plugin/cli dev` runs (or `pnpx @fastgpt-plugin/cli@0.2.2-beta.1 dev` for `model:invoke` plugins) can reuse the local config. In the TUI, press `c` to enter and save a new debug link or connection key. ### Watch plugin directories When no plugin directory is passed, `dev` auto-discovers plugins from the current directory. If the current directory contains `index.ts`, it is used as the plugin entry; otherwise, the CLI scans one level of child directories for `index.ts`. You can also pass one or more plugin directories explicitly: ```bash pnpx @fastgpt-plugin/cli dev ./plugins/getTime ./plugins/dbops --watch ``` `--watch` reloads local plugins and recreates the remote-debug session after local file changes. The CLI reconnects by default when disconnected; use `--no-reconnect` to disable automatic reconnect. ### 2.3 Verify in FastGPT After the CLI reports that remote debugging is ready, return to the FastGPT test environment: 1. Check the debug plugin on the **Studio → System Tools** page. 2. Select the debug tool in an app, workflow, or Agent. 3. Fill in secrets and input parameters, then start a real invocation. 4. Check local handler logs and errors in the CLI terminal. The debug tool `source` is bound to the currently signed-in member, so other members do not see that debug plugin by default. ### Troubleshooting Remote Debugging | Symptom | Cause | Action | | ----------------------------------------------------------- | ------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | WSS connection fails or times out | Connection Key or network routing | Click **Refresh Link** in FastGPT, and verify connectivity and firewall rules from your dev machine to the Gateway port | | Debug tool does not appear in FastGPT | Debug account and channel binding | A debug tool is visible only to the member who generated the debug link; verify the signed-in account matches the CLI key | | `Input validation error` | Zod schema constraints | Check required fields, types, minimum values, and string constraints in `inputSchema`, then adjust test inputs | | Secret values are empty | `ctx.secrets` delivery | Confirm the secrets are filled in the tool configuration of the app, workflow, or Agent, or passed via `--secrets` / `--secrets-file` in local CLI | | Reverse model call is rejected or returns `model_not_found` | `manifest.permission` or model input | Confirm `permission: ['model:invoke']` is declared, the model field uses `Model` (`format: 'modelId'`), and an active FastGPT `modelId` (not a raw upstream model name) is passed | ### 2.4 End the debug session Press `Ctrl+C` in the local terminal to close the current CLI debug session; press `Ctrl+C` again to force exit. The End Debugging action in FastGPT revokes the current member's debug channel and removes the debug plugin entry from the page. If the debug link is exposed, the signed-in member changes, or authorization needs to be renewed, use Refresh Link to generate a new link. ## 3. Build, check, and pack Generated plugin projects normally support these commands from the plugin directory (for plugins using `model:invoke`, keep `@fastgpt-plugin/cli@0.2.2-beta.1` in `package.json` `devDependencies` and use the versioned `check` command below): ```bash pnpm run test pnpm run build pnpx @fastgpt-plugin/cli@0.2.2-beta.1 check --entry . --output ./dist pnpm run pack ``` You can also pass directories explicitly (`build --output` resolves relative to the current working directory, while `check --output` and `pack --dist` resolve relative to `--entry`): ```bash pnpx @fastgpt-plugin/cli@0.2.2-beta.1 build --entry packages/tools/my-tool --output packages/tools/my-tool/dist --minify pnpx @fastgpt-plugin/cli@0.2.2-beta.1 check --entry packages/tools/my-tool --output ./dist pnpx @fastgpt-plugin/cli@0.2.2-beta.1 pack --entry packages/tools/my-tool --dist ./dist --output packages/tools/my-tool/out ``` Packaging produces a `.pkg` file for installation and publishing. Inspect its artifacts using the [package and SDK reference](https://doc.fastgpt.io/plugin/package-reference#build-artifacts). ## 4. Verification checklist Before submitting, confirm: * `index.ts` default export is correct. * `manifest.pluginId`, `manifest.version`, Chinese and English names, and descriptions are complete. * Toolkit `children[].id` values are stable and unique. * `inputSchema` covers all user inputs and includes required type and range constraints. * `outputSchema` matches handler return values. * `secretSchema` covers all secret configuration and sensitive fields set `isSecret: true`. * `manifest.permission` follows least privilege: declare `file-upload:allow` for file uploads, and declare `model:invoke` with a `Model` (`format: 'modelId'`) input field for reverse model invocation. * External API success, failure, empty response, timeout, and auth failure are handled. * Error messages help locate issues and do not leak secrets or sensitive responses. * `pnpm run test` passes, or the reason it cannot be tested is documented. * `build`, `check`, and `pack` pass. * Icons and schemas in `dist/manifest.json` are as expected. * Remote debugging completes a real invocation in the test environment, or the reason remote debugging is not needed for this change is documented. * `.pkg` can be installed in a test environment and complete a real invocation. ## 5. Publishing workflow ### Community Plugins Community plugins usually start by creating and pushing an independent GitHub repository from the plugin directory: ```bash cd packages/tools/my-tool git init git add . git commit -m "feat: add my-tool plugin" gh repo create --public --source=. --remote=origin --push ``` Then return to the `fastgpt-community-plugins` repository, submit the submodule or reference update, and open a PR to `labring/fastgpt-community-plugins`. ### Official Plugins Official plugins require: 1. Code review. 2. Build, check, test, and package. 3. Manual `.pkg` installation in a test environment. 4. Complete functional testing, including external APIs, secret configuration, error paths, and concurrent calls. 5. Pre-listing security checks, focusing on SSRF, secret leakage, arbitrary file access, command execution, and dependency risk. ### Business Plugins Business plugins are released to private repositories. Manage versions, secrets, installation packages, and acceptance records according to the customer delivery process. Security boundaries for external APIs, customer private addresses, and account secrets should be recorded separately. For private delivery, use [team installation](https://doc.fastgpt.io/plugin/team-installation) or ask a root administrator to [install the system tool](https://doc.fastgpt.io/guide/build/tools/system-plugins/upload_system_tool). file: ./content/plugin/intro.en.mdx url: https://doc.fastgpt.io/plugin/intro title: Plugin development overview last_updated: 2026-11-17T14:28:28+08:00 meta: { "title": "Plugin development overview", "description": "Choose a FastGPT extension path and understand tool plugins, model presets, SDKs, and delivery formats" } > This document applies to FastGPT Plugin v1.0.0 and later. Plugin development is part of the FastGPT developer documentation. Choose a guide based on the capability you want to deliver: | Goal | Start here | Delivery format | | ------------------------------------- | ---------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | | Build your first tool plugin | [Quick start](https://doc.fastgpt.io/plugin/quick-start) | Verify locally and generate a `.pkg` tool package | | Implement a tool or Toolkit | [Tool development guide](https://doc.fastgpt.io/plugin/system-tool-development) | SDK definitions, debugging, building, and packaging | | Configure or build content moderation | [Content moderation guide](https://doc.fastgpt.io/plugin/moderation) | Admin policy configuration and `defineModeration()` `.pkg` packages | | Add model or provider presets | [Model preset guide](https://doc.fastgpt.io/plugin/model-presets) | Update static configuration in the plugin repository and submit the changes | | Develop Agent Skills | [Skill development tutorial](https://doc.fastgpt.io/guide/build/skill/development) | Author code in sandbox and bind to Agent | To install existing plugins, see [team installation and management](https://doc.fastgpt.io/plugin/team-installation). System administrators (users signed in with the `root` account, with the **Admin** entry at the bottom-left of the sidebar) can use [system tool management](https://doc.fastgpt.io/guide/build/tools/system-plugins/upload_system_tool) and [plugin runtime configuration](https://doc.fastgpt.io/plugin/runtime). Recommended development baseline: FastGPT v4.15.0+, FastGPT Plugin v1.0.0+, Node.js 22 (`>= 22.23.2`), pnpm 10. ## Background [FastGPT Plugin](https://github.com/labring/fastgpt-plugin) maintains the plugin service, SDKs, and CLI in a dedicated repository so plugins can evolve with their own versions. Tool authors create projects with the CLI, implement capabilities with the SDK, and deliver built packages to FastGPT. ## Design Goals * Independent iteration: maintain plugin source, versions, and publishing channels separately. * Clear development paths: use the CLI and SDK from project creation through debugging and packaging. * Runtime isolation: let the plugin service manage execution environments, process pools, and request scheduling. * Resource-specific development: give each resource its own declarations, validation, and delivery workflow. ## Core Concepts | Term | Meaning | | -------------- | ------------------------------------------------------------------------------------------------ | | Plugin | A resource that extends FastGPT; its development steps depend on the resource type. | | Tool | An API or computation exposed for Workflows and Agents to call. | | Toolkit | Multiple child tools in one plugin with shared metadata and secret configuration. | | Plugin package | The `.pkg` delivery file used to install and version tool plugins. | | Model preset | Static provider, capability, and default-parameter configuration supplied by the plugin service. | | Marketplace | A discovery and publishing channel for official and community plugins. | | Runtime | The backend that runs plugin code and manages resources; the default is `local-pool`. | | Pod | A plugin worker process in `local-pool`. | ## Repository Structure Plugin authors primarily use these entry points: | Path | Responsibility | | ------------------------------------------------- | ---------------------------------------------------------------------- | | `apps/cli/` | Create, debug, build, check, and pack commands | | `sdk/factory/` | Author SDK for tools, Toolkits, schemas, and handlers | | `sdk/client/` | Client SDK used by the FastGPT main service to call the plugin service | | `apps/server/` | Plugin server startup and HTTP interfaces | | `packages/infrastructure/src/static-data/models/` | Model and provider presets | For internal layers and dependencies, see the [FastGPT Plugin architecture](https://github.com/labring/fastgpt-plugin/blob/main/docs/dev/architecture.md). ## Repository Responsibilities | Repository | Maintained content | | --------------------------- | ----------------------------------------------------- | | `labring/fastgpt-plugin` | Plugin service, CLI, SDKs, runtime, and model presets | | `fastgpt-official-plugins` | Officially maintained or reviewed tool plugins | | `fastgpt-community-plugins` | Community-contributed tool plugins | | `fastgpt-business-plugins` | Private, customer-specific, and commercial plugins | ## Marketplace And Usage Boundaries After verification, tool authors follow the [publishing workflow](https://doc.fastgpt.io/plugin/debugging-and-publishing#publishing-workflow) for community, official, or private distribution. A team can also install a delivered `.pkg` directly. For discovery, permission review, and installation, see [install from Marketplace](https://doc.fastgpt.io/plugin/team-installation#install-from-marketplace). ## Plugin Installation And Management | Scope | Responsible role | Guide | | ------------------------------------------------------------ | ------------------------------------- | ---------------------------------------------------------------------------------------------------- | | Team installation, updates, and removal | Team administrator or owner | [Install and manage team plugins](https://doc.fastgpt.io/plugin/team-installation) | | System-wide installation and configuration | System administrator (`root` account) | [System tool management](https://doc.fastgpt.io/guide/build/tools/system-plugins/upload_system_tool) | | Runtime capacity, environment variables, and troubleshooting | Deployment operator | [Plugin runtime configuration](https://doc.fastgpt.io/plugin/runtime) | ### Localized Plugin Metadata When you provide `{ en, 'zh-CN' }` locale objects in `manifest` and schemas along with localized README files (`README.zh-CN.md`, `README.en.md`), the FastGPT UI displays the active locale and falls back to Simplified Chinese and then English. ## Packaging and Runtime Tool plugins are delivered as `.pkg` packages and executed in the plugin service's `local-pool` process pool. See [package and SDK reference](https://doc.fastgpt.io/plugin/package-reference) for build artifacts and SDK entry points, and [plugin runtime configuration](https://doc.fastgpt.io/plugin/runtime#local-pool-runtime) for worker pool capacity and environment variables. ## Development And Distribution Start tool development with [your first tool](https://doc.fastgpt.io/plugin/quick-start), then continue to [debugging, packing, and publishing](https://doc.fastgpt.io/plugin/debugging-and-publishing). Model presets are contributed as static repository configuration; follow the [model preset guide](https://doc.fastgpt.io/plugin/model-presets) to validate those changes. ## References * [FastGPT Plugin](https://github.com/labring/fastgpt-plugin) * [FastGPT Plugin System Design](https://github.com/labring/fastgpt-plugin/blob/main/docs/dev/design.md) * [FastGPT Plugin Architecture](https://github.com/labring/fastgpt-plugin/blob/main/docs/dev/architecture.md) * [System Plugin Development Guide](https://github.com/labring/fastgpt-plugin/blob/main/docs/dev/how-to-devlop-plugin.en.md) file: ./content/plugin/model-presets.en.mdx url: https://doc.fastgpt.io/plugin/model-presets title: Add Model Presets last_updated: 2026-11-12T14:01:38+08:00 meta: { "title": "Add Model Presets", "description": "Configure and maintain built-in provider and model presets inside the FastGPT plugin repository." } Model presets are maintained in the `fastgpt-plugin` repository. They provide FastGPT with built-in model providers, model lists, model capabilities, and default request parameters. After FastGPT loads these static presets, users can select the corresponding models in model configuration, AIProxy channels, and plugin-related features. This page follows the plugin system code structure for version 1.0 and later. The old `modules/model/*` paths are no longer the primary maintenance entry point. Contribute this extension by updating static configuration and submitting repository changes. Follow the [validation](#validation) steps on this page. ## Related Directories ```text packages/infrastructure/src/static-data/models/ ├── index.ts ├── model-static.ts ├── providers.ts ├── type.ts ├── channel-avatar/ └── provider/ └── {Provider}/ ├── index.ts └── logo.svg ``` * `provider/{Provider}/index.ts`: model presets for one provider. * `index.ts`: exports static model presets, provider lists, and channel declarations. * `model-static.ts`: registers all providers and builds `staticModelList`. * `providers.ts`: maintains provider display names in `ModelProviderMap` and AIProxy channels in `aiproxyChannels`. * `type.ts`: defines schemas for provider configs and model presets. * `provider/{Provider}/logo.svg`: provider logo. * `channel-avatar/`: AIProxy channel avatars. ## Add a Model to an Existing Provider ### 1. Confirm the provider is registered First check `packages/infrastructure/src/static-data/models/index.ts` and make sure the provider is imported and included in `staticModelProviderConfigs`: ```ts import openai from './provider/OpenAI'; export const staticModelProviderConfigs = [openai]; ``` If you are only adding a model to an existing provider, you do not need to change `index.ts`. ### 2. Update the provider model list Open the provider file, for example: ```text packages/infrastructure/src/static-data/models/provider/OpenAI/index.ts ``` Add the model to the `list` array. Prefer cloning the closest model from the same provider, type, and family, then adjust the fields based on official documentation. Examples for all five model types: ```ts import { ModelTypeEnum, type ProviderConfigType } from '../../type'; const ttsVoices = [ { label: 'Default voice', value: 'default' } ]; const models: ProviderConfigType = { provider: 'ExampleProvider', list: [ { type: ModelTypeEnum.llm, model: 'example-chat', maxContext: 128000, maxTokens: 16384, quoteMaxToken: 120000, maxTemperature: 1, responseFormatList: ['text', 'json_schema'], vision: true, reasoning: false, reasoningEffort: false, toolChoice: true }, { type: ModelTypeEnum.embedding, model: 'example-embedding', defaultToken: 512, maxToken: 8192, normalization: true }, { type: ModelTypeEnum.rerank, model: 'example-rerank', maxToken: 8192 }, { type: ModelTypeEnum.tts, model: 'example-tts', voices: ttsVoices }, { type: ModelTypeEnum.stt, model: 'example-stt' } ] }; export default models; ``` Common fields: | Field | Description | | -------------------- | ------------------------------------------------------------------------------ | | `type` | Model type from `ModelTypeEnum`: `llm`, `embedding`, `rerank`, `tts`, or `stt` | | `model` | Actual model ID used in requests | | `name` | Optional display name; defaults to `model` when omitted | | `maxContext` | Maximum LLM context length | | `maxTokens` | Maximum LLM output length | | `quoteMaxToken` | Maximum token budget FastGPT can use for cited Dataset content | | `maxTemperature` | Maximum temperature; use `null` when the model does not support temperature | | `responseFormatList` | Supported response formats, such as `text`, `json_object`, and `json_schema` | | `vision` | Whether vision input is supported | | `reasoning` | Whether this is a reasoning model | | `reasoningEffort` | Whether reasoning effort can be configured | | `toolChoice` | Whether tool choice is supported | | `fieldMap` | Field-name mapping for non-standard OpenAI-compatible APIs | | `defaultConfig` | Default request parameters sent with the model request | | `defaultToken` | Default chunk token count for Embedding models | | `maxToken` | Maximum input token count for Embedding/Rerank models | | `normalization` | Whether Embedding vectors should be normalized | | `voices` | Available voice list for TTS models | `index.ts` automatically adds the following when building `staticModelList`: * `provider`: from the current provider config. * `name`: defaults to `model` when not explicitly set. * Some default LLM capability switches, such as Dataset processing, classification, extraction, tool calling, and evaluation. ### 3. Do not rely on model names alone Before adding or changing a model, verify it against official model docs, official model-list APIs, or official pricing/model pages. Do not rely on search results, third-party blogs, or aggregator pages as proof that a model exists. Recommended rules: * Model presets support five model types: `llm`, `embedding`, `rerank`, `tts`, and `stt`. Choose the type based on the model's real capabilities and fill in the fields required by that type's schema. * Do not remove preview, experimental, or dated models just because a stable-looking sibling exists. Remove them only when official docs mark them as deprecated, retired, unavailable, or no longer recommended. * For open catalogs such as OpenRouter, Ollama, HuggingFace, and Other, avoid deleting local placeholders or models users may customize. * Preserve the existing ordering style in each provider file. Newer or more capable models are usually placed first. ## Add a New Model Provider Only add a provider directory when you need to support a completely new provider. ### 1. Create the provider directory Create a directory under `provider/` using the provider identifier: ```text packages/infrastructure/src/static-data/models/provider/NewProvider/ ├── index.ts └── logo.svg ``` `logo.svg` is the model provider avatar. When the plugin service initializes static model assets, it uploads `provider/{Provider}/logo.svg` as `models/{Provider}/logo`, and the `/models/get-providers` API returns that URL as the provider `avatar`. Basic `index.ts` structure: ```ts import { ModelTypeEnum, type ProviderConfigType } from '../../type'; const models: ProviderConfigType = { provider: 'NewProvider', list: [ { type: ModelTypeEnum.llm, model: 'new-provider-chat', maxContext: 128000, maxTokens: 8192, quoteMaxToken: 120000, maxTemperature: 1, responseFormatList: ['text'], vision: false, reasoning: false, reasoningEffort: false, toolChoice: true } ] }; export default models; ``` ### 2. Register the provider Import it in `packages/infrastructure/src/static-data/models/index.ts` and add it to `staticModelProviderConfigs`: ```ts import newProvider from './provider/NewProvider'; export const staticModelProviderConfigs: ProviderConfigType[] = [newProvider]; ``` ### 3. Add provider display names Add multilingual display names to `ModelProviderMap` in `packages/infrastructure/src/static-data/models/providers.ts`: ```ts NewProvider: { en: 'NewProvider', 'zh-CN': '新供应商', 'zh-Hant': '新供應商' } ``` If you do not add the provider to `ModelProviderMap`, the system falls back to the raw `provider` string as its display name. Formal providers should include multilingual display names. ## Add an AIProxy Protocol Adding an AIProxy protocol is not the same as adding a model provider: * Model provider: decides which `provider` owns the model presets, maintains the model list and model capabilities, and uses `provider/{Provider}/logo.svg` as its avatar. * AIProxy protocol: decides whether the protocol appears in the AIProxy channel list. AIProxy routes requests to the corresponding adaptor by `channelId`, and FastGPT uses `channel-avatar/{avatar}.svg` as the channel avatar. If you are only adding model presets, you may not need to add an AIProxy protocol. Maintain `aiproxyChannels` only when FastGPT needs to display that protocol in the AIProxy channel list. ### 1. Check AIProxy protocols and get channelId The `channelId` must match the `ChannelType` value defined in [`core/model/chtype.go`](https://github.com/labring/aiproxy/blob/main/core/model/chtype.go) in the AIProxy repository. Do not guess the `channelId` from the provider name. Run this in the AIProxy repository: ```bash rg -n "ChannelType.*=" core/model/chtype.go ``` Examples: | AIProxy type | ID | FastGPT `channelId` | | ------------------------- | ---- | ------------------- | | `ChannelTypeOpenAI` | `1` | `1` | | `ChannelTypeAnthropic` | `14` | `14` | | `ChannelTypeAli` | `17` | `17` | | `ChannelTypeGoogleGemini` | `24` | `24` | | `ChannelTypeDeepseek` | `36` | `36` | | `ChannelTypeDoubao` | `40` | `40` | | `ChannelTypeSiliconflow` | `43` | `43` | | `ChannelTypeAntLing` | `54` | `54` | Use the current `core/model/chtype.go` file on the AIProxy main branch as the source of truth. ### 2. Add the protocol declaration in fastgpt-plugin After confirming AIProxy supports the protocol, add an entry to `aiproxyChannels` in `packages/infrastructure/src/static-data/models/providers.ts`: ```ts export const aiproxyChannels: AIProxyChannelsType = [ { channelId: 54, name: { en: 'Ant Ling', 'zh-CN': '蚂蚁百灵', 'zh-Hant': '螞蟻百靈' }, avatar: 'antling', website: 'https://ant-ling.com' } ]; ``` Field reference: | Field | Description | | ----------- | ---------------------------------------------------------------------- | | `channelId` | Numeric AIProxy `ChannelType` ID. It must match `core/model/chtype.go` | | `name` | Multilingual display name in the FastGPT channel list | | `avatar` | Channel avatar filename without the extension | | `website` | Official website URL of the channel provider | Also add the avatar file under `channel-avatar/`: ```text packages/infrastructure/src/static-data/models/channel-avatar/antling.svg ``` The `avatar` value must match the filename under `channel-avatar/`. Supported avatar extensions are `svg`, `png`, `jpeg`, `webp`, and `jpg`. If AIProxy does not support the protocol yet, add the `ChannelType` and adaptor in the AIProxy repository first, and confirm the adaptor is imported in [`core/relay/adaptors/register.go`](https://github.com/labring/aiproxy/blob/main/core/relay/adaptors/register.go). The FastGPT plugin side only declares channel display data; it does not implement AIProxy adaptor logic. ## Validation After updating presets, run at least: ```bash pnpm typecheck ``` If you changed many providers, model schemas, or static asset loading logic, also run: ```bash pnpm test ``` Before submitting, review the diff under `packages/infrastructure/src/static-data/models/` and make sure no unrelated provider models were removed, model types are correct, and the new provider logo or `channel-avatar` file is included. ## Loading And End-to-End Verification In FastGPT After source validation, load and verify the model preset in FastGPT: 1. **Restart plugin service**: Update and restart the `fastgpt-plugin` deployment to load the new static presets. In self-hosted environments, restart the `fastgpt-plugin` container. 2. **Create model from template**: Sign in to FastGPT with the `root` system administrator account, go to **Admin → (Commercial Edition: System Resources →) System Models**, and click **New Model → Create from Template** on the **Model Config** tab. 3. **Select new preset**: Search and check the newly added model preset in the **Select Model Template** modal table and confirm to import its default context window and max token limits. 4. **Configure model channel**: Switch to the **Model provider** tab (or click **Configure Model Channel** when prompted) to add or edit an AIProxy channel with the API Key, Base URL, and model mapping. 5. **Verify request execution**: Open any Chat Agent or debugging window, select the configured model, and send a test prompt to verify streaming responses. file: ./content/plugin/moderation.en.mdx url: https://doc.fastgpt.io/plugin/moderation title: Content moderation guide last_updated: 2026-11-17T14:28:28+08:00 meta: { "title": "Content moderation guide", "description": "Overview of FastGPT content moderation architecture, admin policy settings, runtime checkpoints, handling strategies, and custom plugin extension." } > This guide applies to FastGPT v4.18.0 and later. If you are upgrading from the legacy commercial built-in censor, also see the [Content moderation upgrade and migration guide](https://doc.fastgpt.io/self-host/migration/content-moderation). FastGPT implements content moderation as a dedicated `moderation` Plugin type managed by the `fastgpt-plugin` service. Platform administrators can configure moderation providers, active checkpoints, suspected-risk handling, and exception fallback policies in one console, while developers can build adapter Plugins with `@fastgpt-plugin/sdk-factory` to integrate internal safety gateways or third-party moderation APIs. ## Architecture and Responsibilities Content moderation separates platform policy orchestration from provider-specific API adaptation: | Component | Responsibilities | | -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **FastGPT Main Service** | Admin policy UI, AES-256-GCM secret encryption, three runtime moderation checkpoints, streaming buffer truncation, moderation records (`system_moderation_records`), and admin audit logging | | **FastGPT Plugin Service** | Package installation and versioning for `moderation` Plugins, isolated worker pools (`local-pool`), and synchronous text checks via `GET /moderation` and `POST /moderation/check` | | **Moderation Plugin** | Adapter implemented with `defineModeration()` that calls upstream or local rules and normalizes responses into four-tier `verdict` values and `hits` | Key design boundaries: * **Single active Plugin**: You can install and keep saved credentials for multiple moderation Plugins, but only one **Active Service** can be enabled at a time to avoid conflicting provider criteria. * **Synchronous text moderation**: The current release focuses on synchronous text moderation (`input.content`) with optional streaming session tracking; asynchronous image, audio, or video callbacks are not included. * **Console access**: **Admin Console > Content Moderation > Moderation Policy** (`/admin/moderation/policy`) is available to `root` administrators on deployments with an activated Commercial Edition license. ## 1. Usage and Admin Configuration ### 1.1 Install and Configure a Moderation Plugin Sign in as a `root` administrator and open **Admin Console > Content Moderation > Moderation Policy** (`/admin/moderation/policy`): 1. Turn on **Enable Content Moderation** (disabled by default). 2. Add a moderation Plugin from the service panel: * **Add from Marketplace**: Opens the Marketplace filtered by moderation Plugins (`/config/tool/marketplace?type=moderation`), where you can install official Plugins including **Baidu** (`baidu`), **Alibaba Cloud** (`aliyun`), **Tencent Cloud** (`tencent`), **Keyword** (`keyword`), and **Legacy Custom Moderation** (`legacy-custom-censor`; see the [Content moderation upgrade and migration guide](https://doc.fastgpt.io/self-host/migration/content-moderation) for legacy protocol adaptation). * **Install from Local**: Upload a `.pkg` archive or `.zip` bundle built locally or delivered offline. 3. Click **Configure Parameters** next to a Plugin and fill in the fields declared by its `secretSchema`: * Fields marked `isSecret: true` are encrypted with AES-256-GCM on the server and masked in API responses and UI forms. * Before persisting, FastGPT sends a fixed non-sensitive test string through the Plugin to verify connectivity. If the probe returns `verdict: 'error'` or fails, the save is rejected so invalid credentials do not overwrite working settings. 4. Activation and uninstallation rules: * When no Plugin is enabled yet, **the first configured Plugin is activated automatically**. * Click **Enable** on any other configured Plugin to switch the active service mutually exclusively. * Uninstalling a Plugin is a soft delete that preserves saved credentials so reinstalling the Plugin restores your configuration. If other moderation Plugins are installed, switch away from the active Plugin before uninstalling it. Uninstalling the last moderation Plugin automatically disables content moderation. ### 1.2 Moderation Stages (Hooks) Once content moderation is enabled, all three checkpoints are enabled by default and can be toggled independently: | Stage | Trigger Timing | Scope | Behavior on Block | | -------------------------------- | ------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | | **User Input** (`userInput`) | Before workflow scheduling or any node executes | Current user query (`query` / `userChatInput`), custom global Variables, and dynamic form inputs | Throws an error immediately and stops execution with zero model token usage; client apps can roll back optimistic chat bubbles | | **Model Input** (`modelInput`) | Before LLM invocation in AI Chat, Tool Call (`toolCall`), and Agent nodes | Assembled current-turn context sent to the LLM: system prompts, current user message, Dataset citations, and parsed file text from the current turn (**chat history and earlier-turn files are exempt**) | Fails the model node directly without calling the LLM or incurring model billing | | **Final Output** (`finalOutput`) | Before delivering text responses or tool call arguments | AI text replies, Specified Reply nodes, User Select prompts, Form Input prompts, and model-generated tool call arguments | Blocks non-streaming replies outright; buffers streaming output by interval and aborts generation on violation | Additional runtime notes: * **In-loop tool response masking**: Inside Agent and ToolCall loops, tool execution responses (including tools, child workflows, built-in Dataset search, and file reading) are moderated whenever either `modelInput` or `finalOutput` is enabled. Violations replace the tool output with a standardized masked message (`该信息因内容审核不通过,无法返回`) so the Agent can continue reasoning without aborting the entire loop. * **Streaming buffer window**: Instead of checking isolated tokens (which can split sensitive phrases across chunks), FastGPT accumulates streamed text and checks the cumulative text every **Streaming Check Interval** characters. On a block, FastGPT immediately stops emitting chunks, aborts the upstream model stream, and discards unrendered text. ### 1.3 Handling Strategy Under **Handling Strategy**, configure three global behaviors: | Setting | Default | Options and Impact | | ---------------------------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | **Streaming Check Interval** | `100` chars/check | Positive integer (`>= 1`). Smaller values reduce client buffering latency at higher request volume and cost; larger values reduce moderation calls with slightly longer buffering | | **Suspected Risk** | `Block and Log` | Action when a Plugin returns `verdict: 'suspected'`: **Block and Log** (`blockAndLog`) or **Pass and Log** (`passAndLog`) | | **Service Exception** | `Pass Unmoderated Content` | Fallback when a Plugin returns `verdict: 'error'`, is unavailable, or times out: **Pass Unmoderated Content** (`pass`, fail-open) or **Block Unmoderated Content** (`block`, fail-closed — apps become unavailable if moderation fails, so choose carefully) | Click **Save** at the top right to apply policy changes. Navigating to Marketplace or clicking **Enable** preserves unsaved draft changes on the policy page. ### 1.4 Online Testing and Compliance Records * **Moderation Test**: When moderation is enabled with an active Plugin, the test card at the bottom of the policy page lets you submit sample text and inspect the raw four-tier verdict, normalized hit labels with scores, highlighted keywords, and error messages directly from the Plugin. * **Chat Log Details**: Team members with write permission on an App can inspect per-node `moderationRecords` inside Chat Log execution details (showing stage, verdict, hit labels, keywords, and moderated content). * **Platform Audit and Persistent Records**: Admin lifecycle actions (install, save config, enable/switch, uninstall, and policy updates) are written to the team audit log. Every runtime moderation call is persisted asynchronously to `system_moderation_records` and can be queried via `/api/core/plugin/admin/moderation/records` or inspected at `/admin/moderation/records` by stage and verdict. ## 2. Custom Moderation Plugin Development To integrate an internal safety gateway or another third-party moderation service, you can build a custom `moderation` Plugin with the FastGPT Plugin toolchain: * **Setup, debugging, and publishing**: Prerequisites, project layout, local debugging, and `.pkg` packaging/publishing follow the same workflow as tool Plugins—see the [System Tool Development Guide](https://doc.fastgpt.io/plugin/system-tool-development) and [Debugging, packing, and publishing](https://doc.fastgpt.io/plugin/debugging-and-publishing). * **Scaffolding and contract**: Initialize a project with `npx @fastgpt-plugin/cli create my-moderation --type moderation`. Export `defineModeration()` with `defineModerationManifest()`, declare credentials and provider policy IDs via `secretSchema`, inspect synchronous text `input.content`, and return standardized `verdict` (`pass` / `block` / `suspected` / `error`) and `hits`. Catch upstream or network failures and return `ctx.moderationError('...')` instead of throwing. When building with Claude Code, Codex, or another coding agent, copy this prompt: ```plaintext Follow the official FastGPT plugin development Skill (https://raw.githubusercontent.com/labring/fastgpt-official-plugins/refs/heads/main/.agents/skills/develop-fastgpt-plugin/SKILL.md) and plugin docs to build a FastGPT `moderation` plugin for using `npx @fastgpt-plugin/cli create --type moderation`, including `defineModeration()`, `secretSchema`, unit tests, local debug verification, and `.pkg` packaging. ``` file: ./content/plugin/package-reference.en.mdx url: https://doc.fastgpt.io/plugin/package-reference title: Package and SDK reference last_updated: 2026-12-01T18:08:29+08:00 meta: { "title": "Package and SDK reference", "description": "Tool plugin build artifacts, author metadata and schema declarations, and SDK and CLI entry points" } This reference explains delivery files and code declarations for tool plugin authors. For commands, see [debugging, packing, and publishing](https://doc.fastgpt.io/plugin/debugging-and-publishing). For service capacity and environment variables, see [plugin runtime configuration](https://doc.fastgpt.io/plugin/runtime). Model presets use a separate [static configuration contribution workflow](https://doc.fastgpt.io/plugin/model-presets). ## Build artifacts A tool plugin's `index.ts` default export is a `defineTool()` or `defineToolSet()` definition. The CLI build typically produces: | File | Purpose | | -------------------- | ----------------------------------------------- | | `dist/index.js` | Executable tool build | | `dist/manifest.json` | Generated metadata and schemas | | Icon files | Main tool icon and optional Toolkit child icons | | `README.md` | Optional plugin documentation | | `assets/**` | Optional static resources | The `pack` command generates a `.pkg` installation file. Its output location follows the project's `pack` script or the CLI `--output` option. To update metadata or schemas, edit the source and rebuild the package. ## Metadata and schemas Authors maintain the following fields in SDK definitions. The CLI and SDK versions determine the generated Manifest structure. | Declaration | Purpose | | ------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------- | | `manifest.pluginId` | Stable identifier shared by the plugin's versions | | `manifest.version` | Semantic version used during installation and updates | | `manifest.name`, `manifest.description` | English and Chinese display names and descriptions | | `manifest.versionDescription` | Changes in this version | | `manifest.tags` | Plugin category tags | | `manifest.permission` | Host capability permissions required by the plugin (such as `file-upload:allow`, `model:invoke`, `userInfo:read`) | | `createToolHandler({ inputSchema })` | Input types, constraints, defaults, and UI field descriptions; pair with `Model` to render a model selector (`format: 'modelId'`) | | `createToolHandler({ outputSchema })` | Handler return types and field descriptions | | `createToolHandler({ secretSchema })`, `defineToolSet({ secretSchema })` | Secret configuration and sensitive field declarations (declared in handler for single tools, shared at top level for Toolkits) | | `defineToolSet({ children })` | Toolkit child IDs, names, descriptions, and handlers | Keep child tool IDs stable so configured Workflows can continue to reference them. Declare secrets through `secretSchema` and read them from `ctx.secrets` in handlers. See [icon requirements](https://doc.fastgpt.io/plugin/system-tool-development#5-icon-conventions) for icon names. The CLI uses `tool` and `tool-suite` to select project skeletons. Build artifacts and the plugin service provide the installed tool's type, child relationships, and display data. ## Runtime context capabilities When executing a handler, the SDK supplies the `ctx` runtime context with the following capabilities: | Property / Method | Purpose | Typical Use Case | | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- | | `ctx.secrets` | Decrypted secret values configured for the tool | Reading API keys, tokens, and trusted upstream endpoints | | `ctx.invoke.uploadFile()` | Uploads a file (`{ file, fileName, contentType }`) to the FastGPT host and returns `[result, err]` with `result.accessURL` (requires `file-upload:allow`) | Returning generated reports, images, or media artifacts | | `ctx.invoke.createModelClient()` | Creates a standard official `OpenAI` SDK client proxied through the host channel, supporting streaming/non-streaming `chat.completions.create()` and transparent billing (requires `model:invoke`) | Calling FastGPT-configured chat or vision models inside a tool | | `ctx.invoke.userInfo()` | Reads user information for the current invocation context and returns `[result, err]` (requires `userInfo:read`) | Tools that need to identify the invoking member | | `ctx.streamResponse()` | Streams text answer chunks (`{ type: 'answer' \| 'fastAnswer', content }`) to the caller | Streaming incremental text answers during execution | ## SDK and CLI entry points | Component | Audience | Responsibility | | ----------------------------- | -------------------------------------- | -------------------------------------------------------------------- | | `@fastgpt-plugin/sdk-factory` | Plugin authors | Define tools, Toolkits, handlers, schemas, and host capability calls | | `@fastgpt-plugin/cli` | Plugin authors | Create projects, debug locally and remotely, build, check, and pack | | `@fastgpt-plugin/sdk-client` | FastGPT service integration developers | Call plugin management and runtime interfaces | Use compatible versions declared by the target project. Consult the matching versions of the [SDK Factory documentation](https://github.com/labring/fastgpt-plugin/blob/main/sdk/factory/README.en.md) and [CLI documentation](https://github.com/labring/fastgpt-plugin/blob/main/apps/cli/README.en.md) for complete interfaces. ## Delivery and installation * Authors follow the [verification checklist](https://doc.fastgpt.io/plugin/debugging-and-publishing#verification-checklist) for builds, input/output behavior, and real calls in a test environment. * Team administrators follow the [team installation guide](https://doc.fastgpt.io/plugin/team-installation) to install, update, and remove plugins. * Root administrators follow the [system tool management guide](https://doc.fastgpt.io/guide/build/tools/system-plugins/upload_system_tool) for system-wide delivery. file: ./content/plugin/quick-start.en.mdx url: https://doc.fastgpt.io/plugin/quick-start title: Quick start: create your first tool plugin last_updated: 2026-11-12T14:01:38+08:00 meta: { "title": "Quick start: create your first tool plugin", "description": "Create a greeting tool, validate its inputs and output, and build an installation package" } This guide walks you through the complete local workflow of building your first system tool plugin using `@fastgpt-plugin/cli` and `@fastgpt-plugin/sdk-factory`. ## Prerequisites Ensure your local development environment has: * **Node.js**: Node.js 22 (`>= 22.23.2`). * **pnpm**: pnpm 10. * **FastGPT**: v4.15.0 or later running instance. * **FastGPT Plugin**: v1.0.0 or later plugin service. * **Git**: For version control and code commits. ## Step 1: Create the Plugin Skeleton Initialize a single-tool plugin using the official CLI: ```bash pnpx @fastgpt-plugin/cli create hello-tool --type tool ``` The command generates the `hello-tool` project in your current directory with standard files: ```text hello-tool/ ├── index.ts # Core plugin logic entrypoint, exports defineTool by default ├── index.spec.ts # Unit test file ├── package.json # Build and test scripts ├── tsconfig.json # TypeScript configuration ├── vitest.config.ts # Unit testing configuration ├── logo.svg # Plugin icon ├── README.md # Default plugin documentation ├── README.zh-CN.md # Simplified Chinese documentation └── README.en.md # English documentation ``` Navigate into the directory and install dependencies: ```bash cd hello-tool pnpm install ``` ## Step 2: Implement Tool Logic and Schemas Open `index.ts` to define the tool metadata, input schema, output schema, and execution handler: ```ts import { createToolHandler, defineTool, type InputSchemaMetaType, type OutputSchemaMetaType } from '@fastgpt-plugin/sdk-factory'; import z from 'zod'; const handler = createToolHandler({ inputSchema: z.object({ name: z .string() .min(1) .default('FastGPT') .meta({ title: { en: 'User Name', 'zh-CN': '用户名称' }, description: { en: 'Name of the user to greet', 'zh-CN': '输入需要问候的用户名称' }, isToolParam: true } satisfies InputSchemaMetaType) }), outputSchema: z.object({ greeting: z.string().meta({ title: 'Greeting' } satisfies OutputSchemaMetaType) }), handler: async (input) => { return { greeting: `Hello, ${input.name}!` }; } }); export default defineTool({ manifest: { pluginId: 'hello-tool', version: '1.0.0', name: { en: 'Hello Tool', 'zh-CN': '问候工具' }, description: { en: 'Greet the user with a friendly message', 'zh-CN': '输出友好的问候信息' }, versionDescription: { en: 'Initial release', 'zh-CN': '初始版本' }, tags: ['tools'] }, handler }); ``` Key concepts: * `manifest.pluginId`: Globally unique plugin identifier, recommended in lowercase hyphenated format. * `manifest.name` and `manifest.description`: Bilingual text for English and Simplified Chinese, displayed in the FastGPT Studio according to user language preferences. * `inputSchema` and `outputSchema`: Zod schemas that declare input and output types, enriched with `.meta()` attributes for UI rendering. * `handler`: Business logic implementation whose returned values strictly conform to `outputSchema`. ## Step 3: Validate inputs Run these commands from the plugin directory to check the default value and the empty-string constraint: ```bash pnpx @fastgpt-plugin/cli debug . --run --input '{}' pnpx @fastgpt-plugin/cli debug . --run --input '{"name":""}' ``` The first call should return a result containing `"greeting": "Hello, FastGPT!"`. The second should report an input validation error because `name` requires at least one character. These cases cover the schema's default and invalid-input behavior. ## Step 4: Run Local Debugging Use the CLI debug command to simulate inputs and inspect runtime outputs directly: ```bash pnpx @fastgpt-plugin/cli debug . --run --input '{"name": "FastGPT User"}' ``` Check that the debug result contains this output: ```json { "greeting": "Hello, FastGPT User!" } ``` ## Step 5: Build and Pack After verification passes, execute the standard build and pack steps: ```bash pnpm run build pnpx @fastgpt-plugin/cli check --entry . --output ./dist pnpm run pack ``` The commands produce `hello-tool.pkg` in the plugin root directory by default (or in the directory passed to `--output`). See the [package and SDK reference](https://doc.fastgpt.io/plugin/package-reference#build-artifacts) for artifact details. ## Step 6: Install and Verify in FastGPT After generating the `.pkg` package, complete end-to-end acceptance in FastGPT: 1. **Install plugin**: * **Open-source Community Edition**: Sign in with the `root` system administrator account, go to **Admin → System Tools** in the bottom-left sidebar, click **New Tool → Install from Local** in the upper-right corner, upload `hello-tool.pkg`, and click **Confirm import**. * **Commercial Edition**: System administrators can import it under **Admin → System Resources → System Tools → New Tool → Install from Local**. When **Allow teams to upload plugins** is enabled under **Admin → System Config → Feature Flags**, a team administrator or owner can also import it under **Studio → System Tools → New Tool → Install from Local**. 2. **Configure application**: Open any Workflow or Chat Agent canvas, and add the newly installed "Hello Tool" (`hello-tool`) from the tool list. 3. **Verify execution result**: Send a test message in the debug preview to trigger the tool and inspect the node output in Run Details. A successful response contains: ```json { "greeting": "Hello, FastGPT!" } ``` This completes the full delivery lifecycle from scaffolding, schema validation, and packaging to live application invocation. ## Next Steps * Learn advanced tool specifications and toolkit patterns: [System Tool Development Guide](https://doc.fastgpt.io/plugin/system-tool-development) * Connect with a live FastGPT instance for remote debugging and distribution: [Debugging, Packing, and Publishing](https://doc.fastgpt.io/plugin/debugging-and-publishing) * Install the generated `.pkg` package into your team workspace: [Install and Manage Team Plugins](https://doc.fastgpt.io/plugin/team-installation) file: ./content/plugin/runtime.en.mdx url: https://doc.fastgpt.io/plugin/runtime title: Plugin runtime configuration last_updated: 2026-11-12T14:01:38+08:00 meta: { "title": "Plugin runtime configuration", "description": "local-pool parameters, scheduling boundaries, and environment variables for deployment administrators" } This reference is for FastGPT self-hosted administrators. The plugin service manages tool installation, worker processes, and request dispatch. The FastGPT server calls tools through that service. See [system tool management](https://doc.fastgpt.io/guide/build/tools/system-plugins/upload_system_tool) for installation and [remote debug suite configuration](https://doc.fastgpt.io/self-host/config/remote-debug-suite) for a development environment. ## `.pkg` Package Protocol System tools are installed and updated through `.pkg` files. Administrators receive the author's package and check its source, version, and compatibility with the target environment. ### Artifact Layout The plugin project's build and packaging workflow determines its artifacts and output location. See the [package and SDK reference](https://doc.fastgpt.io/plugin/package-reference#build-artifacts). ### Manifest Specification The build generates the Manifest. See [metadata and schemas](https://doc.fastgpt.io/plugin/package-reference#metadata-and-schemas) for author-maintained declarations. Changes to those declarations require a new build and installation package. ## local-pool Runtime FastGPT Plugin uses the `local-pool` process pool runtime by default. It manages Pod worker processes and request queues per plugin service. A Pod here means a worker process managed by the plugin runtime. ### Scheduling Pipeline 1. Dispatch requests to ready Pods with available concurrency capacity. 2. Start workers on demand when capacity is insufficient and the Pod count is below `maxPods`. 3. Queue requests when capacity is reached or startup backoff is active. 4. Continue processing queued requests as Pods release capacity or new workers become ready. 5. Requests can be rejected or time out when the queue reaches `maxQueueSize` or the wait exceeds `queueTimeout`. ### Per-Service Parameters System administrators can adjust these four fields under **Admin → (Commercial Edition: System Resources →) System Tools** by opening the target tool's configuration modal and switching to the **Runtime Configuration** tab. Use the current plugin service values shown in the configuration page, and test changes against host resources and the tool's external API rate limits. | Parameter | Constraint | Description | | --------------------------------------------------------------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------- | | Minimum worker nodes (`minPods`) | Nonnegative integer | Minimum Pods retained for the service | | Maximum worker nodes (`maxPods`) | Positive integer | Maximum Pods allowed for the service | | Pod timeout (`podTimeout`) | Positive integer, milliseconds | Per-request execution timeout inside a Pod (idle worker recycling wait time is controlled by `POOL_SERVICE_IDLE_TIMEOUT`) | | Max concurrent requests per Pod (`maxConcurrentRequestsPerPod`) | Positive integer | Maximum simultaneous requests handled by one Pod | `minPods` must be less than or equal to `maxPods`. Raising Pod counts and per-Pod concurrency increases resource use and can reach external service rate limits sooner. ## Global Environment Variables The plugin service process reads these variables for global capacity and service defaults. Supported variables and default values depend on the deployed FastGPT Plugin version. | Variable | Description | | ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | | `POOL_HEALTH_CHECK_INTERVAL` | Interval between Pod health checks in milliseconds | | `POOL_MAX_TOTAL_PODS` | Total Pod limit across plugin services in the server process | | `POOL_SERVICE_MIN_PODS` | Default minimum worker nodes per plugin service | | `POOL_SERVICE_MAX_PODS` | Default maximum worker nodes per plugin service | | `POOL_SERVICE_IDLE_TIMEOUT` | Idle Pod recycling wait time in milliseconds (controls when idle worker processes are terminated) | | `POOL_SERVICE_POD_TIMEOUT` | Default per-request Pod execution timeout in milliseconds | | `POOL_SERVICE_MAX_CONCURRENT_REQUESTS_PER_POD` | Default maximum concurrent requests per Pod | | `POOL_SERVICE_MAX_REQUESTS_PER_POD` | Maximum cumulative requests handled by one Pod | | `POOL_SERVICE_MAX_QUEUE_SIZE` | Maximum request queue capacity per plugin service | | `POOL_SERVICE_QUEUE_TIMEOUT` | Timeout for requests waiting for an available Pod, in milliseconds | | `POOL_SERVICE_STARTUP_RETRY_BASE_DELAY` | Base delay for Pod startup retry backoff, in milliseconds | | `POOL_SERVICE_STARTUP_RETRY_MAX_DELAY` | Maximum delay for Pod startup retry backoff, in milliseconds | | `POOL_SERVICE_POD_MAX_OLD_SPACE_SIZE_MB` | V8 old-space memory limit in MB per Pod worker process | | `POOL_SERVICE_POD_ALLOW_NET` | Whether Pod worker processes are allowed network access (defaults to `false`; enable when tools call external APIs) | | `POOL_SERVICE_POD_TERMINATION_GRACE_PERIOD` | Grace period in milliseconds before a Pod process is forcefully terminated | ## Failure Isolation and Circuit Breaking The plugin service manages worker failures, startup retries, and backoff. Begin troubleshooting with service logs to distinguish tool execution errors, worker startup failures, queue timeouts, and host capacity limits. For repeated startup failures, fix dependencies, plugin code, or the runtime environment before verifying recovery. The deployed service version determines retry and circuit-breaking policies. file: ./content/plugin/system-tool-development.en.mdx url: https://doc.fastgpt.io/plugin/system-tool-development title: System Tool Development Guide last_updated: 2026-12-01T18:08:29+08:00 meta: { "title": "System Tool Development Guide", "description": "Learn how to build FastGPT system tool plugins from scratch, define input/output schemas and secrets, implement handlers, and package releases." } ## Introduction This document targets system tool development after FastGPT v4.15.0. System tools use SDK definitions and are delivered to the FastGPT Plugin service as `.pkg` files for installation, updates, and runtime management. Model presets use a [static configuration contribution workflow](https://doc.fastgpt.io/plugin/model-presets). The currently stable system tool plugin types are: * Single tool: one plugin exposes one tool and is declared with `defineTool()`. * Toolkit: one plugin exposes multiple related child tools and is declared with `defineToolSet()`. System tool plugins run in the runtime provided by the FastGPT Plugin service. The FastGPT main service invokes tools through the plugin service, and plugin code uses `@fastgpt-plugin/sdk-factory` to describe input, output, secret configuration, and execution logic. ## Differences From The Legacy Mechanism 1. FastGPT and FastGPT Plugin remain separate services within a microservice architecture. 2. The plugin package protocol upgrades from the old built-in system tool directory to a unified `.pkg` format, making installation, version management, hot updates, and future plugin type expansion easier. 3. The plugin runtime is managed by the server. The current default runtime is `local-pool`, where each plugin version has its own process pool, queue, and runtime configuration. 4. Plugin metadata, input/output schemas, secret schemas, and icon assets are included in build artifacts for use by FastGPT pages, workflows, and Agents. 5. Tool development uses `@fastgpt-plugin/cli` and `@fastgpt-plugin/sdk-factory` to define schemas and build packages. ## Information To Collect Before Development Clarify these items before coding: | Information | Description | | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | | Plugin type | `tool` or `tool-suite`. | | Plugin ID | `pluginId`, globally stable and unique. Keep it unchanged after publishing. | | Child tool ID | Required for Toolkits. `children[].id` stays unchanged after publishing. | | Chinese and English names | `name.en` and `name.zh-CN`. | | Chinese and English descriptions | `description.en` and `description.zh-CN`. | | Inputs | Type, constraints, default value, UI title, and description for each field. | | Outputs | Type, meaning, and downstream usage for each field. | | Secrets | API Key, Base URL, username/password, and similar values, described through `secretSchema`. | | External API | Request method, auth method, timeout, rate limit, error response, and test account. | | File capability | Use `ctx.invoke.uploadFile()` and declare `file-upload:allow` when file upload is needed. | | Model invocation | Declare a model input with `Model`, add `model:invoke` to `manifest.permission`, and call models via `ctx.invoke.createModelClient()`. | | Streaming output | Use `ctx.streamResponse()` when streaming text answers to the user. | | Test cases | Include at least success, invalid parameters, auth failure, and upstream failure. | Missing information that affects plugin ID, auth method, billing, or listing security should be confirmed first. Other missing information can use reasonable defaults, with assumptions recorded in the submission notes. ## Developing With An Agent When using Claude Code, Codex, or another agent tool, copy this prompt: ```plaintext Develop a plugin using the following official FastGPT plugin development Skill: https://raw.githubusercontent.com/labring/fastgpt-official-plugins/refs/heads/main/.agents/skills/develop-fastgpt-plugin/SKILL.md Requirements: 1. Read and understand the complete Skill first, then follow its development workflow. 2. Before coding, collect the plugin name and type, Chinese and English names and descriptions, inputs and outputs, secrets, external APIs, expected behavior, error handling, and test cases. 3. If key requirements are missing, ask no more than three essential questions. When reasonable defaults are available, state the assumptions and continue. 4. Use `@fastgpt-plugin/cli` to create the plugin skeleton. Follow the repository's existing structure, naming, testing, and build conventions. 5. After implementation, run the required validation, including tests, build, plugin checks, and packaging. Explain anything that could not be validated. 6. In the final response, list changed files, validation results, remaining assumptions, and external API behavior that requires human confirmation. ``` When developing or maintaining SDK/CLI in the `fastgpt-plugin` repository, also refer to local skills: * `sdk/factory/skills/fastgpt-plugin-development/SKILL.md` * `sdk/factory/skills/fastgpt-system-tool-development/SKILL.md` * `sdk/factory/skills/fastgpt-sdk-factory/SKILL.md` ## 1. Prepare Environment Recommended environment: * Node.js 22 (`>= 22.23.2`). * `pnpm` 10; the `fastgpt-plugin` repository uses pnpm workspace. * Git. * GitHub CLI `gh`, used for forking, creating repositories, and submitting PRs. When developing community plugins, first fork and clone the community repository: ```bash gh repo fork labring/fastgpt-community-plugins --clone cd fastgpt-community-plugins pnpm install ``` When debugging the CLI or SDK in the `fastgpt-plugin` repository, install dependencies and build the CLI/SDK first: ```bash pnpm install pnpm build:sdk-factory pnpm build:cli ``` ## 2. Create Plugin Skeleton Single-tool plugin: ```bash pnpx @fastgpt-plugin/cli create my-tool --type tool --cwd packages/tools ``` Toolkit plugin: ```bash pnpx @fastgpt-plugin/cli create my-tool-suite --type tool-suite --cwd packages/tools ``` You can also enter the target directory and create interactively: ```bash pnpx @fastgpt-plugin/cli create ``` The CLI creates the plugin directory and common files: | File | Purpose | | ------------------ | --------------------------------------------------------------------------------------------------------------- | | `index.ts` | Plugin entry, default-exporting `defineTool()` or `defineToolSet()`. | | `index.spec.ts` | Unit test file. | | `package.json` | Plugin dependencies and `build`, `build:dev`, `check`, `dev`, `debug`, `debug:run`, `pack`, and `test` scripts. | | `tsconfig.json` | TypeScript config. | | `vitest.config.ts` | Test config. | | `README.md` | Default plugin documentation. | | `README.zh-CN.md` | Simplified Chinese plugin documentation. | | `README.en.md` | English plugin documentation. | | `logo.svg` | Main plugin icon. | ## 3. Implement Single Tool The system tool entry must default-export an SDK factory instance: ```ts import { createToolHandler, defineTool, type InputSchemaMetaType, type OutputSchemaMetaType, type SecretSchemaMetaType } from '@fastgpt-plugin/sdk-factory'; import z from 'zod'; const secretSchema = z.object({ apiKey: z .string() .min(1) .meta({ title: 'API Key', isSecret: true } satisfies SecretSchemaMetaType) }); const handler = createToolHandler({ inputSchema: z.object({ query: z .string() .min(1) .meta({ title: 'Query', description: 'Search keyword' } satisfies InputSchemaMetaType) }), outputSchema: z.object({ result: z.string().meta({ title: 'Result' } satisfies OutputSchemaMetaType) }), secretSchema, handler: async (input, ctx) => { return { result: input.query }; } }); export default defineTool({ manifest: { pluginId: 'example-search', version: '1.0.0', name: { en: 'Example Search', 'zh-CN': '示例搜索' }, description: { en: 'Search example data', 'zh-CN': '搜索示例数据' }, versionDescription: { en: 'Initial version', 'zh-CN': '初始版本' }, tags: ['tools'] }, handler }); ``` Core rules: * Keep `pluginId`, child tool `id`, input field names, and output field names stable after publishing. * Use `{ en, 'zh-CN' }` for `manifest.name`, `manifest.description`, and `versionDescription`. * Describe inputs, outputs, and secrets with Zod schemas. * Add `InputSchemaMetaType` to input fields and `OutputSchemaMetaType` to output fields. * Add `SecretSchemaMetaType` to secret fields and set `isSecret: true` for sensitive fields. * Handler return values must match `outputSchema`. * Convert external API errors into actionable messages and avoid exposing secrets, tokens, or complete sensitive responses. * Use `ctx.invoke.uploadFile()` with `file-upload:allow` declared in `manifest.permission` when host file upload is needed, and prefer preserving the returned `err`. * To call FastGPT platform models from a tool, declare `model:invoke` in `manifest.permission`, define a single model input with `Model` (`format: 'modelId'`, recommended `isToolParam: false`), and call `chat.completions.create()` through `ctx.invoke.createModelClient()`. * Use `ctx.streamResponse({ type: 'answer' | 'fastAnswer', content })` when streaming text answers to users. ## 4. Implement a Toolkit Use `defineToolSet()` for Toolkits. Put shared information in the top-level `manifest` and `secretSchema`, and declare each child tool's independent `id`, name, description, and handler in `children`. ```ts import { createToolHandler, defineToolSet, type InputSchemaMetaType, type OutputSchemaMetaType, type SecretSchemaMetaType } from '@fastgpt-plugin/sdk-factory'; import z from 'zod'; const secretSchema = z.object({ apiKey: z.string().meta({ title: 'API Key', isSecret: true } satisfies SecretSchemaMetaType) }); const searchHandler = createToolHandler({ inputSchema: z.object({ query: z.string().meta({ title: 'Query' } satisfies InputSchemaMetaType) }), outputSchema: z.object({ items: z.array(z.string()).meta({ title: 'Items' } satisfies OutputSchemaMetaType) }), secretSchema, handler: async (input) => ({ items: [input.query] }) }); const summaryHandler = createToolHandler({ inputSchema: z.object({ content: z.string().meta({ title: 'Content' } satisfies InputSchemaMetaType) }), outputSchema: z.object({ summary: z.string().meta({ title: 'Summary' } satisfies OutputSchemaMetaType) }), secretSchema, handler: async (input) => ({ summary: input.content.slice(0, 100) }) }); export default defineToolSet({ manifest: { pluginId: 'text-tools', version: '1.0.0', name: { en: 'Text Tools', 'zh-CN': '文本工具集' }, description: { en: 'Search and summarize text', 'zh-CN': '搜索和总结文本' } }, children: [ { id: 'search', name: { en: 'Search', 'zh-CN': '搜索' }, description: { en: 'Search text', 'zh-CN': '搜索文本' }, handler: searchHandler }, { id: 'summary', name: { en: 'Summary', 'zh-CN': '总结' }, description: { en: 'Summarize text', 'zh-CN': '总结文本' }, handler: summaryHandler } ], secretSchema }); ``` ## 5. Icon Conventions During build, the CLI scans icons in the plugin root and writes them into the built `manifest.json`. | Scenario | File name | | ------------------ | --------------------------------------------------------------------------- | | Main plugin icon | `logo.svg`, `logo.png`, `logo.jpg`, `logo.jpeg`, `logo.webp`, or `logo.gif` | | Toolkit child icon | `.logo.svg`, `.logo.png`, and similar names | Notes: * Put icon files in the plugin root. * The `` of a child icon must exactly match `children[].id`. * Keep only one extension for the same icon to avoid ambiguous scan results. * Child tools without their own icons reuse the main plugin icon by default. * After build, check the `icon` field in `dist/manifest.json`. ## 6. Key Development Recipes ### 6.1 Authenticated External API Requests When calling external third-party services requiring an API key, declare the secret field in `secretSchema` and extract it via `ctx.secrets` in the handler. Handle network and HTTP errors with actionable messages while keeping credentials omitted from logs and error text: ```ts import { createToolHandler, defineTool, type InputSchemaMetaType, type OutputSchemaMetaType, type SecretSchemaMetaType } from '@fastgpt-plugin/sdk-factory'; import z from 'zod'; const secretSchema = z.object({ apiKey: z .string() .min(1) .meta({ title: 'API Key', isSecret: true } satisfies SecretSchemaMetaType) }); const UPSTREAM_SEARCH_URL = 'https://api.example.com/v1/search'; const handler = createToolHandler({ inputSchema: z.object({ query: z .string() .min(1) .meta({ title: 'Query', description: 'Search keyword sent to the trusted upstream service' } satisfies InputSchemaMetaType) }), outputSchema: z.object({ status: z.string().meta({ title: 'Status' } satisfies OutputSchemaMetaType), data: z.any().meta({ title: 'Response Data' } satisfies OutputSchemaMetaType) }), secretSchema, handler: async (input, ctx) => { try { const requestUrl = new URL(UPSTREAM_SEARCH_URL); requestUrl.searchParams.set('q', input.query); const res = await fetch(requestUrl.toString(), { headers: { Authorization: `Bearer ${ctx.secrets.apiKey}`, 'Content-Type': 'application/json' } }); if (!res.ok) { throw new Error(`Upstream service returned status ${res.status}`); } const data = await res.json(); return { status: 'success', data }; } catch (err: any) { throw new Error(`External API request failed: ${err.message || 'unknown error'}`); } } }); ``` Keep the authenticated upstream endpoint fixed in a trusted server constant or controlled configuration so `ctx.secrets` credentials are sent only to verified hosts. ### 6.2 Host File Uploads And Artifact Return When a tool produces generated files (such as reports, exported images, or media) and returns them to FastGPT callers, invoke the host upload capability `ctx.invoke.uploadFile()`. The host stores the artifact and returns an accessible URL: ```ts handler: async (input, ctx) => { const content = Buffer.from( `Report for ${input.query}\nGenerated at ${new Date().toISOString()}` ); const [result, err] = await ctx.invoke.uploadFile({ file: content, fileName: 'report.txt', contentType: 'text/plain' }); if (err) { throw new Error(`Failed to upload generated file: ${err}`); } return { fileUrl: result.accessURL, filename: 'report.txt' }; }; ``` ### 6.3 Streaming Text Answer Output To stream text answer chunks directly to the conversation client during execution, call `ctx.streamResponse()` with `{ type: 'answer' | 'fastAnswer', content: string }`: ```ts handler: async (input, ctx) => { await ctx.streamResponse({ type: 'answer', content: 'Fetching remote resources...\n' }); // Execute processing logic await ctx.streamResponse({ type: 'answer', content: 'Processing complete.\n' }); return { result: 'Operation completed successfully' }; }; ``` ### 6.4 Side Effects And Repeated Invocation Handling FastGPT Workflows and Agents may call a tool multiple times during loop executions or retries. For operations with side effects (such as database writes, external charges, or messaging): * **Business idempotency**: Include a unique identifier (such as `requestId` or `orderId`) in the input schema, and enforce idempotency on the external service. * **State awareness**: Return existing outcomes for already completed external actions. * **Explicit timeouts**: Set bounded timeouts on requests, detect cancellation signals, and stop pending downstream work promptly. ### 6.5 Reverse Model Invocation (OpenAI SDK) When a tool needs to call a FastGPT-configured LLM during execution (for summarization, extraction, or reasoning), call `ctx.invoke.createModelClient()` to get a standard official `OpenAI` SDK client. The FastGPT host handles team model authorization, request proxying, and transparent real-time billing. > * Reverse model invocation currently requires `@fastgpt-plugin/sdk-factory@1.2.0-beta.4` and `@fastgpt-plugin/cli@0.2.2-beta.1` (the default npm `latest` releases do not yet include `Model`, `createModelClient()`, or remote `chatCompletion` debugging; run `pnpx @fastgpt-plugin/cli@0.2.2-beta.1 dev` for remote debugging), along with FastGPT main and FastGPT Plugin test services that include `model:invoke` support. > * Tool inputs support a **single model** parameter declared with the exported `Model` schema constant (`format: 'modelId'`). FastGPT automatically renders a model selector in Workflow tool nodes and Agent tool settings, and prevents Agents from fabricating or overriding the model parameter at runtime. > * Currently only `chat.completions` (covering LLMs and VLMs) is exposed. Pass the `modelId` provided by FastGPT in the `model` field; raw upstream model names are rejected. Complete example: ```ts import { createToolHandler, defineInputSchema, defineOutputSchema, defineTool, Model } from '@fastgpt-plugin/sdk-factory'; import z from 'zod'; const handler = createToolHandler({ inputSchema: defineInputSchema({ model: { type: Model, title: { en: 'Model', 'zh-CN': '模型' }, description: { en: 'FastGPT chat model used to summarize content', 'zh-CN': '用于总结内容的 FastGPT 对话模型' }, isToolParam: false }, content: { type: z.string().min(1), title: { en: 'Content', 'zh-CN': '待处理文本' }, isToolParam: true }, stream: { type: z.boolean().default(false).optional(), title: { en: 'Stream output', 'zh-CN': '流式输出' }, isToolParam: false } }), outputSchema: defineOutputSchema({ summary: { type: z.string(), title: { en: 'Summary', 'zh-CN': '总结结果' } } }), handler: async (input, ctx) => { const ai = ctx.invoke.createModelClient(); if (input.stream) { const stream = await ai.chat.completions.create({ model: input.model, messages: [ { role: 'system', content: 'Summarize the user text concisely.' }, { role: 'user', content: input.content } ], stream: true }); let summary = ''; for await (const chunk of stream) { const delta = chunk.choices[0]?.delta?.content ?? ''; if (delta) { summary += delta; ctx.streamResponse({ type: 'answer', content: delta }); } } return { summary }; } const completion = await ai.chat.completions.create({ model: input.model, messages: [ { role: 'system', content: 'Summarize the user text concisely.' }, { role: 'user', content: input.content } ] }); return { summary: completion.choices[0]?.message?.content ?? '' }; } }); export default defineTool({ manifest: { pluginId: 'text-summarizer', version: '1.0.0', name: { en: 'Text Summarizer', 'zh-CN': '文本总结器' }, description: { en: 'Summarize input text with a FastGPT model', 'zh-CN': '使用 FastGPT 平台模型总结输入文本' }, permission: ['model:invoke'] }, handler }); ``` Key notes: * **Permission declaration**: You must declare `'model:invoke'` in `manifest.permission`; otherwise both the plugin host and the FastGPT server block the call. * **Model selection and authorization**: Fields typed with `Model` render as model selectors in Workflows and Agents. FastGPT first verifies that the `modelId` exists and is active in the team model catalog (supporting both platform-enabled system models and team models owned by the current team; team ownership is enforced only for team models). If the model matches the active workflow's published resource snapshot, it inherits the publisher's authorization; otherwise FastGPT checks the running member's model `use` permission. Team AI points balance is checked for all resolved calls. * **Transparent billing**: Token usage and AI points from reverse model calls are billed in real time to the active conversation or workflow usage record (`usageId`) as separate line items attributed to the calling tool and model. When no `usageId` is present, standalone plugin billing records are created only for non-debug invocations—pure debug calls without a `usageId` return model responses without creating a billing record. Plugin handlers never access `usageId` or manage billing directly. ## 7. Debugging, Packaging, And Publishing Workflow After implementing your tool, follow the unified delivery path in [debugging, packing, and publishing](https://doc.fastgpt.io/plugin/debugging-and-publishing): 1. **Local debugging**: Use `pnpx @fastgpt-plugin/cli debug . --run` to verify schemas, defaults, and boundary inputs. See [local debugging](https://doc.fastgpt.io/plugin/debugging-and-publishing#local-debugging). 2. **Remote debugging**: Connect to your FastGPT test environment using `pnpx @fastgpt-plugin/cli dev`. See [remote debugging](https://doc.fastgpt.io/plugin/debugging-and-publishing#remote-debugging). 3. **Build and pack**: Run `pnpm run build`, `cli check`, and `pnpm run pack` to generate `.pkg` artifacts. See [build, check, and pack](https://doc.fastgpt.io/plugin/debugging-and-publishing#build-check-pack). 4. **Pre-submission verification**: Check items against the [verification checklist](https://doc.fastgpt.io/plugin/debugging-and-publishing#verification-checklist). 5. **Publishing channels**: Choose community distribution, official distribution, or private commercial delivery. See [publishing workflow](https://doc.fastgpt.io/plugin/debugging-and-publishing#publishing-workflow). ## Design and Versioning Guidelines ### How should I choose between `tool` and `tool-suite`? Use `tool` for a single capability. Use `tool-suite` for multiple capabilities that share authentication, the same upstream API, and strong business relevance, such as search, detail, and task creation in one plugin. ### How should plugin versions be managed? Use semantic versioning for `manifest.version`. Upgrade patch for compatible fixes, minor for compatible new features, and major when changing input/output fields, child tool IDs, or user configuration. Evaluate existing workflow compatibility before major changes. ### Can I put API keys in code or environment variables? Plugins should declare secrets through `secretSchema` and read them through `ctx.secrets`. Real secrets should not appear in code repositories, test snapshots, error logs, or README files. ### Is a test environment still needed after local debug passes? Yes. Local debug quickly validates plugin logic and schemas. Test environment validation confirms real installation, runtime, host reverse invocation, network, and permission behavior. ## References * [FastGPT Plugin Repository](https://github.com/labring/fastgpt-plugin) * [System Plugin Development Guide](https://github.com/labring/fastgpt-plugin/blob/main/docs/dev/how-to-devlop-plugin.en.md) * [SDK Factory Guide](https://github.com/labring/fastgpt-plugin/blob/main/sdk/factory/README.en.md) * [CLI Guide](https://github.com/labring/fastgpt-plugin/blob/main/apps/cli/README.en.md) file: ./content/plugin/team-installation.en.mdx url: https://doc.fastgpt.io/plugin/team-installation title: Install and Manage Team Plugins last_updated: 2026-11-12T14:01:38+08:00 meta: { "title": "Install and Manage Team Plugins", "description": "Install, update, and uninstall team plugins from Marketplace or local packages" } > Team plugins require a FastGPT Commercial Edition license and must be enabled by a system administrator under **Admin → System Config → Feature Flags → Allow teams to upload plugins** (disabled by default and unavailable in the open-source Community Edition). Team plugins are installed and managed by team administrators or owners and are available only within the current team. Team members can use installed plugins in workflows, Agents, and tool selectors. ## Scope Team plugins and system plugins are independent installations: * System administrators install and configure system plugins for use across teams. * Team administrators install team plugins for the current team. * The same plugin can exist as both a system plugin and a team plugin. Both entries are displayed, and the system entry carries a **System** label. * A team plugin does not inherit secrets, pricing, status, version, or other configuration from a system plugin with the same ID. * Teams cannot hide or change the visibility of system plugins. Team plugins can be updated or uninstalled and do not have a deprecation state. ## Roles * **System administrator**: A user signed in with the `root` account, with the **Admin** entry at the bottom-left of the sidebar, responsible for system-wide configuration and system plugins. * **Team owner**: The creator of the current team, holding full administrative permissions within the team by default. * **Team administrator**: A team member granted the **Admin** permission under **Account → Team → Permissions**. ## Prerequisites Before installing a plugin, confirm that: 1. Your account is a team administrator or team owner. Regular members can use installed plugins but cannot install, update, or uninstall them. 2. The system administrator has enabled **Allow teams to upload plugins** under **Admin → System Config → Feature Flags**. This toggle gates all team plugin installation methods; Marketplace installation, local uploads, and installation confirmation are rejected when it is disabled. 3. The deployment can access FastGPT Marketplace when installing from Marketplace. 4. For a local installation, you have a valid `.pkg` file or a `.zip` archive containing one or more `.pkg` files. The **New Tool** button in the upper-right corner is visible only when your account is a team administrator or owner and **Allow teams to upload plugins** is enabled. When the deployment disables the Marketplace (`disableMarketplace`), the menu shows only **Install from Local**. Authors preparing a custom package can follow [debugging, packing, and publishing](https://doc.fastgpt.io/plugin/debugging-and-publishing#build-check-pack). System administrators can follow [system tool management](https://doc.fastgpt.io/guide/build/tools/system-plugins/upload_system_tool) for system-wide installation. ## Install from Marketplace 1. Open **Studio → System Tools**. 2. Click **New Tool** in the upper-right corner and select **Install from Marketplace**. 3. Find a plugin by name, source, or category. You can enable the **Only show uninstalled** filter. 4. Open the plugin details and review its description and version information. 5. Select a version and click **Install** to continue. ![Team plugin Marketplace and tool installation entry](https://cdn.jsdelivr.net/gh/labring/fastgpt-img@main/optimized/current/team-plugin-marketplace.png.webp) After installation, the plugin appears in the team tool list and can be selected in workflows and Agents. Configure any required secrets or runtime parameters before use. ## Upload a Local Package When team plugin uploads are enabled, you can install plugins you developed yourself or obtained through other channels: 1. Open **Studio → System Tools**. 2. Click **New Tool** and select **Install from Local**. 3. In the **Import/update Plugin** dialog, select one or more `.pkg` files, or a `.zip` archive containing multiple `.pkg` files. 4. Wait for FastGPT to upload and inspect the packages. 5. Review the **Name, Tag, Intro, Status, and Action** columns in the parsed list. Failed files display an individual error and can be removed or retried. 6. Click **Confirm import**. Uploading and parsing only prepare an installation preview. The plugin is installed for the team after confirmation. ## Update a Plugin When Marketplace provides a newer version, an update option appears on the plugin card or details page: 1. Open the team Marketplace and locate the plugin. 2. Review the release notes and permission changes. 3. Select the target version and update the plugin. 4. Test workflows and Agents that use the plugin. For local packages, upload the target version again and confirm the installation. Team configuration remains independent from the system installation. Plugin updates may change input and output schemas, secret requirements, or runtime behavior. Validate updates in a test application before updating production workflows. ## Uninstall a Plugin A team administrator can click **Uninstall** from the tool card menu or details drawer, then enter the plugin name in the **Confirm uninstalling this team plugin?** dialog. Uninstalling: 1. Deletes the installation under the current team source from the plugin service. 2. Revokes future runtime access for the current team. 3. Removes the team plugin from new tool selection flows. Existing workflow and Agent nodes are not rewritten. They fail on their next run after the plugin is uninstalled. Reinstall the plugin from Marketplace or upload its package again to restore access. Uninstalling a team plugin does not affect a system plugin with the same ID or installations owned by other teams. ## System and Team Copies When the same plugin is installed at both levels: * The team entry appears before the system entry. * The system entry displays a **System** label next to its title. Hover over the label to read its explanation. * Workflows and Agents store the plugin source, so each copy can be selected and configured independently. * Uninstalling the team copy leaves the system copy available. Use clear internal conventions when both copies exist, especially when they have different versions or configuration. ## Security Recommendations * Install packages only from trusted sources and review plugin descriptions and secret requirements. * Apply your team's data security policy when a plugin accesses external URLs, accounts, or secrets. * Review release notes and test compatibility before upgrading. * Check workflow and Agent references before uninstalling a plugin. * For troubleshooting team plugin installation, permissions, and secret isolation, see [App, Chat, and Plugin FAQ](https://doc.fastgpt.io/guide/build/faq#team-plugin-installation-and-management).