add documents

This commit is contained in:
Xin Wang
2026-01-08 17:35:09 +08:00
parent 6a6d736991
commit f1bd12353a
21 changed files with 4268 additions and 0 deletions

View File

@@ -0,0 +1,126 @@
# Authentication
FastGPT API uses API keys for authentication. This guide covers how to securely manage and use your API keys with the SDK.
## API Key Format
FastGPT API keys typically start with `fastgpt-`:
```
fastgpt-xxxxxxxxxxxxxxxxxxxxxx
```
## Setting Your API Key
### Method 1: Directly in Code (Not Recommended)
```python
from fastgpt_client import ChatClient
client = ChatClient(api_key="fastgpt-xxxxx")
```
!!! warning
Never commit API keys to version control!
### Method 2: Environment Variables (Recommended)
Create a `.env` file:
```bash
API_KEY=fastgpt-xxxxx
BASE_URL=http://localhost:3000
```
Use `python-dotenv` to load it:
```python
import os
from dotenv import load_dotenv
from fastgpt_client import ChatClient
load_dotenv()
client = ChatClient(
api_key=os.getenv("API_KEY"),
base_url=os.getenv("BASE_URL")
)
```
Add `.env` to your `.gitignore`:
```
.env
```
### Method 3: System Environment Variables
Set the environment variable in your shell:
```bash
# Linux/macOS
export FASTGPT_API_KEY="fastgpt-xxxxx"
export FASTGPT_BASE_URL="http://localhost:3000"
# Windows (Command Prompt)
set FASTGPT_API_KEY=fastgpt-xxxxx
set FASTGPT_BASE_URL=http://localhost:3000
# Windows (PowerShell)
$env:FASTGPT_API_KEY="fastgpt-xxxxx"
$env:FASTGPT_BASE_URL="http://localhost:3000"
```
Then use it in Python:
```python
import os
from fastgpt_client import ChatClient
client = ChatClient(
api_key=os.getenv("FASTGPT_API_KEY"),
base_url=os.getenv("FASTGPT_BASE_URL", "http://localhost:3000")
)
```
## Base URL Configuration
The default base URL is `http://localhost:3000`. If you're using a different FastGPT instance:
```python
client = ChatClient(
api_key="fastgpt-xxxxx",
base_url="https://your-fastgpt-instance.com"
)
```
## Authentication Errors
If authentication fails, the SDK raises an `AuthenticationError`:
```python
from fastgpt_client import ChatClient
from fastgpt_client.exceptions import AuthenticationError
try:
with ChatClient(api_key="invalid-key") as client:
response = client.create_chat_completion(
messages=[{"role": "user", "content": "Hello"}]
)
except AuthenticationError as e:
print(f"Authentication failed: {e}")
```
## Security Best Practices
1. **Never expose API keys** in client-side code (browsers, mobile apps)
2. **Use environment variables** to store keys
3. **Rotate keys regularly** for production applications
4. **Use separate keys** for different environments (dev, staging, prod)
5. **Monitor usage** to detect unauthorized access
6. **Commit `.env` to `.gitignore`** to prevent accidental commits
## Next Steps
- [Quick Start](quick_start.md) - Start using the SDK
- [Error Handling](../advanced/error_handling.md) - Learn to handle errors properly

View File

@@ -0,0 +1,45 @@
# Installation
## Requirements
- Python 3.8 or higher
- A FastGPT API key
## Install with pip
```bash
pip install fastgpt-client
```
## Install for Development
If you want to contribute to the SDK or run tests:
```bash
# Clone the repository
git clone https://github.com/yourusername/fastgpt-python-sdk.git
cd fastgpt-python-sdk
# Install in development mode
pip install -e ".[dev]"
```
### Development Dependencies
The `[dev]` extra includes:
- `pytest` - Testing framework
- `ruff` - Linting and formatting
- `httpx` - HTTP client (already included)
- `python-dotenv` - Environment variable management
## Verify Installation
```python
from fastgpt_client import ChatClient, AppClient
print("FastGPT SDK installed successfully!")
```
## Next Steps
- [Quick Start Guide](quick_start.md) - Learn the basics
- [Authentication](authentication.md) - Set up your API key

View File

@@ -0,0 +1,147 @@
# Quick Start
This guide will help you get started with the FastGPT Python SDK in just a few minutes.
## 1. Get Your API Key
You'll need a FastGPT API key to use the SDK. You can obtain one from your FastGPT instance:
1. Log in to your FastGPT instance
2. Navigate to Settings → API Keys
3. Create a new API key
4. Copy the key (it will start with `fastgpt-`)
## 2. Basic Chat Completion
The simplest way to use the SDK is with a basic chat completion:
```python
from fastgpt_client import ChatClient
# Initialize the client
with ChatClient(
api_key="fastgpt-xxxxx",
base_url="http://localhost:3000"
) as client:
# Send a message
response = client.create_chat_completion(
messages=[{"role": "user", "content": "Hello! What's AI?"}],
stream=False
)
response.raise_for_status()
result = response.json()
# Print the response
print(result['choices'][0]['message']['content'])
```
## 3. Streaming Responses
For real-time responses, use streaming:
```python
import json
with ChatClient(api_key="fastgpt-xxxxx") as client:
response = client.create_chat_completion(
messages=[{"role": "user", "content": "Tell me a short story"}],
stream=True
)
for line in response.iter_lines():
if line.startswith("data:"):
data = line[5:].strip()
if data and data != "[DONE]":
chunk = json.loads(data)
if "choices" in chunk and chunk["choices"]:
delta = chunk["choices"][0].get("delta", {})
content = delta.get("content", "")
if content:
print(content, end="", flush=True)
```
## 4. Using Context (chatId)
To maintain a conversation across multiple requests, use `chatId`:
```python
with ChatClient(api_key="fastgpt-xxxxx") as client:
chat_id = "my_conversation_123"
# First message
response = client.create_chat_completion(
messages=[{"role": "user", "content": "What's AI?"}],
chatId=chat_id,
stream=False
)
# Second message (continues the conversation)
response = client.create_chat_completion(
messages=[{"role": "user", "content": "Tell me more"}],
chatId=chat_id, # Same chatId maintains context
stream=False
)
```
## 5. Using Variables
You can use template variables in your FastGPT workflows:
```python
with ChatClient(api_key="fastgpt-xxxxx") as client:
response = client.create_chat_completion(
messages=[{"role": "user", "content": "Hello [name]!"}],
variables={"name": "Alice"}, # Replaces [name] placeholder
stream=False
)
```
## 6. Get Chat Histories
Retrieve your chat histories:
```python
with ChatClient(api_key="fastgpt-xxxxx") as client:
histories = client.get_chat_histories(
appId="your-app-id",
offset=0,
pageSize=20,
source="api"
)
histories.raise_for_status()
data = histories.json()
for chat in data['data']['list']:
print(f"{chat['title']}: {chat['chatId']}")
```
## Environment Variables
For better security, use environment variables for your API key:
```bash
# .env file
API_KEY=fastgpt-xxxxx
BASE_URL=http://localhost:3000
```
```python
import os
from dotenv import load_dotenv
from fastgpt_client import ChatClient
load_dotenv()
with ChatClient(
api_key=os.getenv("API_KEY"),
base_url=os.getenv("BASE_URL")
) as client:
# Your code here
pass
```
## Next Steps
- [Authentication](authentication.md) - Learn more about securing your API key
- [API Reference](../api/overview.md) - Explore all available methods
- [Examples](../examples/basic_usage.md) - More usage examples