FastGPTFastGPT

Python SDK

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:

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. 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:

pip install --pre fastgpt-sdk
# or with uv
uv add --prerelease=allow fastgpt-sdk

The SDK reads these optional environment variables:

VariablePurposeDefault / Fallback
FASTGPT_BASE_URLFastGPT server origin (with or without /api, normalized automatically)Used when base_url is omitted; falls back to https://cloud.fastgpt.cn
FASTGPT_API_KEYPersonal API key or App API keyUsed when neither api_key nor request_options provides a key
FASTGPT_APP_IDDefault App IDRead 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:

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:

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

ParameterTypeDefaultDescription
base_urlstr | NoneNoneFastGPT instance URL, normalized to end with /api
api_keystr | Callable | NoneNoneStatic API key or per-request credential provider
default_app_idstr | NoneNoneDefault appId injected into App-scoped endpoints
identityFastGPTIdentity | Mapping | NoneNoneDefault caller identity (custom_uid or auth_proxy)
timeoutfloat | httpx.Timeout | None60.0Request timeout in seconds (or httpx.Timeout)
max_retriesint | None2 (GET retries)Retry limit for idempotent GET requests on 408/429/502/503/504 or transport errors
default_headersMapping[str, str] | NoneNoneDefault HTTP headers attached to every request
hooksFastGPTHooks | NoneNoneRequest, response, and error observability hooks
loggerFastGPTLogger | LogLevel | NoneNoneBuilt-in redacted log level or custom logger
http_clienthttpx.Client | httpx.AsyncClient | NoneNoneCustom 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:

# 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 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).
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 PathCapabilities
client.chat/v2/chat/completions sync & SSE streaming, stop, Workflow interactive continuation (interactive), plus histories, records, and feedbacks
client.datasetsDataset lifecycle, hybrid search, collections (local file, link, text, batch archive download), and data Chunk management
client.appsapps.logs cursor search (search), usage charts, totals, and user lists
client.modelsPublic 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

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

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 for full protocol details:

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:

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:

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:

# 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():

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:

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 ClassTrigger Condition
FastGPTAuthErrorHTTP 401 / 403, server code 514, unAuth* status, or missing API key
FastGPTBadRequestErrorOther 4xx validation errors or local precondition checks
FastGPTNotFoundErrorHTTP 404 / 410 or *UnExist / *NotFound errors
FastGPTConflictErrorHTTP 409 or chatIsGenerating when a Session turn is still generating
FastGPTRateLimitErrorHTTP 429 or tooManyRequest / uploadFileIntervalLimit
FastGPTServerError5xx server errors
FastGPTTimeoutErrorConnect, handshake, or response body timeout
FastGPTNetworkErrorSocket errors or truncated SSE stream before [DONE]
Edit on GitHub

Last updated