Implement core infrastructure: - BaseClientMixin with retry logic and validation - FastGPTClient base class with httpx - ChatClient with 11 chat operation methods - AppClient for analytics and logs - Custom exceptions (APIError, AuthenticationError, etc.) - Package configuration (pyproject.toml, setup.py) - Documentation (README.md, CLAUDE.md) - Basic usage examples 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
6.6 KiB
CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
Project Overview
This is the FastGPT Python SDK, a Python client library for interacting with FastGPT's OpenAPI. The SDK is designed following the architecture patterns from the Dify Python SDK, adapted for FastGPT's API structure.
Key Design Principles
-
Base Client + Specialized Clients: A
FastGPTClientbase class handles HTTP communication, retry logic, error handling, and validation. Specialized clients (ChatClient,AppClient) inherit from it. -
Synchronous + Asynchronous: All clients have async variants using
httpx.AsyncClient. -
Context Manager Support: Clients should be usable with
withstatements for automatic resource cleanup. -
OpenAI-Compatible API: FastGPT's
/api/v1/chat/completionsendpoint is OpenAI-compatible, but with FastGPT-specific extensions.
API Architecture
FastGPT API Structure
- Base URL: User-configured (default:
http://localhost:3000) - Authentication:
Authorization: Bearer {api_key} - Chat Completions:
/api/v1/chat/completions(OpenAI-compatible) - Chat History:
/api/core/chat/*endpoints - App Analytics:
/api/proApi/core/app/logs/*endpoints
Key Concepts
- chatId: Identifier for a conversation window (similar to Dify's
conversation_id) - dataId: Identifier for a specific message within a chat
- appId: Application identifier (from FastGPT app details URL)
- variables: Template variables that replace
[key]placeholders in workflows - detail mode: When
detail=true, responses includeresponseDatawith module-level execution details
SSE Event Types
FastGPT uses Server-Sent Events with multiple event types:
answer- Main chat response contentfastAnswer- Quick reply contentflowNodeStatus- Workflow node status (running,completed,error)flowResponses- Complete node response data (module execution details)interactive- Interactive node (user input/form selection)updateVariables- Variable updates during executionerror- Error eventstoolCall,toolParams,toolResponse- Tool/agent operations
Project Structure
fastgpt-python-sdk/
├── fastgpt_client/
│ ├── __init__.py # Export all clients
│ ├── client.py # Base FastGPTClient
│ ├── async_client.py # AsyncFastGPTClient + async variants
│ ├── base_client.py # BaseClientMixin (retry, validation)
│ ├── chat_client.py # ChatClient (sync)
│ ├── app_client.py # AppClient for analytics/logs
│ ├── exceptions.py # Custom exceptions
│ └── utils/
│ ├── validation.py # Parameter validation
│ ├── response_parser.py # Parse SSE events
│ └── types.py # Type definitions
├── tests/
├── examples/
├── setup.py
├── pyproject.toml
└── README.md
Client Classes
FastGPTClient (Base)
- Uses
httpx.Clientfor connection pooling - Implements retry logic with configurable
max_retriesandretry_delay - Custom exceptions:
APIError,AuthenticationError,RateLimitError,ValidationError - Parameter validation via
_validate_params() - Methods:
_send_request(),_handle_error_response(),close()
ChatClient
Inherits from FastGPTClient. Key methods:
create_chat_completion()- Send messages (blocking/streaming), supportschatId,variables,detailget_chat_histories()- List chat histories for an appget_chat_init()- Get chat initialization infoget_chat_records()- Get messages for a specific chatget_record_detail()- Get execution details for a messageupdate_chat_history()- Update title or pin/unpindelete_chat_history()- Delete a chatclear_chat_histories()- Clear all historiesdelete_chat_record()- Delete a single messagesend_feedback()- Like/dislike a messageget_suggested_questions()- Generate suggested questions
AppClient
Inherits from FastGPTClient:
get_app_logs_chart()- Analytics data (users, chats, app metrics)get_app_info()- App metadata
Async Variants
AsyncFastGPTClient,AsyncChatClient,AsyncAppClient- All methods are
async defand useawait - Use
async withfor context manager support
Development Commands
# Install package in development mode
pip install -e .
# Run tests
pytest
# Run single test file
pytest tests/test_chat_client.py
# Run with coverage
pytest --cov=fastgpt_client
# Lint with ruff
ruff check fastgpt_client/
# Format with ruff
ruff format fastgpt_client/
Key Differences from Dify SDK
| Aspect | Dify SDK | FastGPT SDK |
|---|---|---|
| Chat ID | conversation_id |
chatId |
| Message input | inputs + query |
messages array (OpenAI format) |
| Variables | inputs dict |
variables dict + messages |
| Streaming events | Single data: type |
Multiple event: types |
| Detail mode | N/A | detail=true returns responseData |
| Response format | Custom Dify format | OpenAI-compatible (choices, usage) |
Request/Response Patterns
Chat Completion Request
{
"chatId": "optional_chat_id", # Omit for stateless, provide for context
"stream": false,
"detail": false,
"variables": {"key": "value"}, # Template variable substitution
"messages": [
{"role": "user", "content": "Hello"}
]
}
Chat Completion Response (blocking, detail=false)
OpenAI-compatible format with choices, usage, id, model.
Chat Completion Response (detail=true)
Includes responseData array with module execution details:
moduleName- Node namemoduleType- Node type (chatNode, datasetSearchNode, etc.)tokens,price,runningTimequoteList- Knowledge base citationscompleteMessages- Full context
Interactive Node Response
When workflow hits an interactive node:
{
"interactive": {
"type": "userSelect" | "userInput",
"params": {
"description": "...",
"userSelectOptions": [...], # for userSelect
"inputForm": [...] # for userInput
}
}
}
References
- FastGPT Chat API Documentation
- FastGPT App Logs Documentation
- Dify Python SDK (architecture reference)