Initial commit: FastGPT Python SDK Phase 1
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>
This commit is contained in:
194
CLAUDE.md
Normal file
194
CLAUDE.md
Normal file
@@ -0,0 +1,194 @@
|
||||
# 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](https://github.com/langgenius/dify-python-sdk), adapted for FastGPT's API structure.
|
||||
|
||||
### Key Design Principles
|
||||
|
||||
1. **Base Client + Specialized Clients**: A `FastGPTClient` base class handles HTTP communication, retry logic, error handling, and validation. Specialized clients (`ChatClient`, `AppClient`) inherit from it.
|
||||
|
||||
2. **Synchronous + Asynchronous**: All clients have async variants using `httpx.AsyncClient`.
|
||||
|
||||
3. **Context Manager Support**: Clients should be usable with `with` statements for automatic resource cleanup.
|
||||
|
||||
4. **OpenAI-Compatible API**: FastGPT's `/api/v1/chat/completions` endpoint 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 include `responseData` with module-level execution details
|
||||
|
||||
### SSE Event Types
|
||||
|
||||
FastGPT uses Server-Sent Events with multiple event types:
|
||||
|
||||
- `answer` - Main chat response content
|
||||
- `fastAnswer` - Quick reply content
|
||||
- `flowNodeStatus` - 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 execution
|
||||
- `error` - Error events
|
||||
- `toolCall`, `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.Client` for connection pooling
|
||||
- Implements retry logic with configurable `max_retries` and `retry_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), supports `chatId`, `variables`, `detail`
|
||||
- `get_chat_histories()` - List chat histories for an app
|
||||
- `get_chat_init()` - Get chat initialization info
|
||||
- `get_chat_records()` - Get messages for a specific chat
|
||||
- `get_record_detail()` - Get execution details for a message
|
||||
- `update_chat_history()` - Update title or pin/unpin
|
||||
- `delete_chat_history()` - Delete a chat
|
||||
- `clear_chat_histories()` - Clear all histories
|
||||
- `delete_chat_record()` - Delete a single message
|
||||
- `send_feedback()` - Like/dislike a message
|
||||
- `get_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 def` and use `await`
|
||||
- Use `async with` for context manager support
|
||||
|
||||
## Development Commands
|
||||
|
||||
```bash
|
||||
# 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
|
||||
|
||||
```python
|
||||
{
|
||||
"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 name
|
||||
- `moduleType` - Node type (chatNode, datasetSearchNode, etc.)
|
||||
- `tokens`, `price`, `runningTime`
|
||||
- `quoteList` - Knowledge base citations
|
||||
- `completeMessages` - Full context
|
||||
|
||||
### Interactive Node Response
|
||||
|
||||
When workflow hits an interactive node:
|
||||
```python
|
||||
{
|
||||
"interactive": {
|
||||
"type": "userSelect" | "userInput",
|
||||
"params": {
|
||||
"description": "...",
|
||||
"userSelectOptions": [...], # for userSelect
|
||||
"inputForm": [...] # for userInput
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## References
|
||||
|
||||
- [FastGPT Chat API Documentation](https://doc.fastgpt.io/docs/introduction/development/openapi/chat)
|
||||
- [FastGPT App Logs Documentation](https://doc.fastgpt.io/docs/introduction/development/openapi/app)
|
||||
- [Dify Python SDK](https://github.com/langgenius/dify-python-sdk) (architecture reference)
|
||||
Reference in New Issue
Block a user