mirror of
https://github.com/CJackHwang/ds2api.git
synced 2026-05-03 16:05:26 +08:00
Compare commits
15 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d496122840 | ||
|
|
35b99cdf4c | ||
|
|
85ac0d95a4 | ||
|
|
648b80bb7b | ||
|
|
ee0b7f08a0 | ||
|
|
d0b159fb8a | ||
|
|
d57f547bdb | ||
|
|
6a536c5c27 | ||
|
|
ce73814583 | ||
|
|
792d458ce0 | ||
|
|
392473722c | ||
|
|
baca42280f | ||
|
|
ba96554cc1 | ||
|
|
015ec6eb3c | ||
|
|
9626d6ccbd |
701
API.en.md
Normal file
701
API.en.md
Normal file
@@ -0,0 +1,701 @@
|
||||
# DS2API API Reference
|
||||
|
||||
Language: [中文](API.md) | [English](API.en.md)
|
||||
|
||||
This document describes all DS2API API endpoints.
|
||||
|
||||
---
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Basics](#basics)
|
||||
- [OpenAI-Compatible API](#openai-compatible-api)
|
||||
- [List Models](#list-models)
|
||||
- [Chat Completions](#chat-completions)
|
||||
- [Claude-Compatible API](#claude-compatible-api)
|
||||
- [Claude Model List](#claude-model-list)
|
||||
- [Claude Messages](#claude-messages)
|
||||
- [Token Counting](#token-counting)
|
||||
- [Admin API](#admin-api)
|
||||
- [Login](#login)
|
||||
- [Configuration](#configuration)
|
||||
- [Account Management](#account-management)
|
||||
- [Vercel Sync](#vercel-sync)
|
||||
- [Error Handling](#error-handling)
|
||||
- [Examples](#examples)
|
||||
|
||||
---
|
||||
|
||||
## Basics
|
||||
|
||||
| Item | Description |
|
||||
|-----|------|
|
||||
| **Base URL** | `https://your-domain.com` or `http://localhost:5001` |
|
||||
| **OpenAI auth** | `Authorization: Bearer <api-key>` |
|
||||
| **Claude auth** | `x-api-key: <api-key>` |
|
||||
| **Response format** | JSON |
|
||||
|
||||
---
|
||||
|
||||
## OpenAI-Compatible API
|
||||
|
||||
### List Models
|
||||
|
||||
```http
|
||||
GET /v1/models
|
||||
```
|
||||
|
||||
**Response example**:
|
||||
|
||||
```json
|
||||
{
|
||||
"object": "list",
|
||||
"data": [
|
||||
{"id": "deepseek-chat", "object": "model", "owned_by": "deepseek"},
|
||||
{"id": "deepseek-reasoner", "object": "model", "owned_by": "deepseek"},
|
||||
{"id": "deepseek-chat-search", "object": "model", "owned_by": "deepseek"},
|
||||
{"id": "deepseek-reasoner-search", "object": "model", "owned_by": "deepseek"}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Chat Completions
|
||||
|
||||
```http
|
||||
POST /v1/chat/completions
|
||||
Authorization: Bearer your-api-key
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
**Parameters**:
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
|-----|------|:----:|------|
|
||||
| `model` | string | ✅ | Model name (see below) |
|
||||
| `messages` | array | ✅ | Chat messages |
|
||||
| `stream` | boolean | ❌ | Stream responses (default `false`) |
|
||||
| `temperature` | number | ❌ | Temperature (0-2) |
|
||||
| `max_tokens` | number | ❌ | Max output tokens |
|
||||
| `tools` | array | ❌ | Tool definitions (Function Calling) |
|
||||
| `tool_choice` | string | ❌ | Tool selection strategy |
|
||||
|
||||
**Supported models**:
|
||||
|
||||
| Model | Reasoning | Search | Notes |
|
||||
|-----|:--------:|:------:|------|
|
||||
| `deepseek-chat` | ❌ | ❌ | Standard chat |
|
||||
| `deepseek-reasoner` | ✅ | ❌ | Reasoning mode with trace |
|
||||
| `deepseek-chat-search` | ❌ | ✅ | Search enhanced |
|
||||
| `deepseek-reasoner-search` | ✅ | ✅ | Reasoning + search |
|
||||
|
||||
**Basic request example**:
|
||||
|
||||
```json
|
||||
{
|
||||
"model": "deepseek-chat",
|
||||
"messages": [
|
||||
{"role": "system", "content": "You are a helpful assistant."},
|
||||
{"role": "user", "content": "Hello"}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Streaming request example**:
|
||||
|
||||
```json
|
||||
{
|
||||
"model": "deepseek-reasoner-search",
|
||||
"messages": [
|
||||
{"role": "user", "content": "What's in the news today?"}
|
||||
],
|
||||
"stream": true
|
||||
}
|
||||
```
|
||||
|
||||
**Streaming response format** (`stream: true`):
|
||||
|
||||
```
|
||||
data: {"id":"...","object":"chat.completion.chunk","choices":[{"delta":{"role":"assistant"},"index":0}]}
|
||||
|
||||
data: {"id":"...","object":"chat.completion.chunk","choices":[{"delta":{"reasoning_content":"Let me think..."},"index":0}]}
|
||||
|
||||
data: {"id":"...","object":"chat.completion.chunk","choices":[{"delta":{"content":"Based on search results..."},"index":0}]}
|
||||
|
||||
data: {"id":"...","object":"chat.completion.chunk","choices":[{"index":0,"finish_reason":"stop"}]}
|
||||
|
||||
data: [DONE]
|
||||
```
|
||||
|
||||
> **Note**: Reasoning models emit `reasoning_content` with the trace.
|
||||
|
||||
**Non-streaming response format** (`stream: false`):
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "chatcmpl-xxx",
|
||||
"object": "chat.completion",
|
||||
"created": 1738400000,
|
||||
"model": "deepseek-reasoner",
|
||||
"choices": [{
|
||||
"index": 0,
|
||||
"message": {
|
||||
"role": "assistant",
|
||||
"content": "Response text",
|
||||
"reasoning_content": "Reasoning trace (reasoner only)"
|
||||
},
|
||||
"finish_reason": "stop"
|
||||
}],
|
||||
"usage": {
|
||||
"prompt_tokens": 10,
|
||||
"completion_tokens": 50,
|
||||
"total_tokens": 60,
|
||||
"completion_tokens_details": {
|
||||
"reasoning_tokens": 20
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Tool Calling (Function Calling)
|
||||
|
||||
**Request example**:
|
||||
|
||||
```json
|
||||
{
|
||||
"model": "deepseek-chat",
|
||||
"messages": [{"role": "user", "content": "What's the weather in Beijing?"}],
|
||||
"tools": [{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"description": "Get the weather for a city",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"location": {"type": "string", "description": "City name"}
|
||||
},
|
||||
"required": ["location"]
|
||||
}
|
||||
}
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
**Response example**:
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "chatcmpl-xxx",
|
||||
"object": "chat.completion",
|
||||
"choices": [{
|
||||
"index": 0,
|
||||
"message": {
|
||||
"role": "assistant",
|
||||
"content": null,
|
||||
"tool_calls": [{
|
||||
"id": "call_xxx",
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": "{\"location\": \"Beijing\"}"
|
||||
}
|
||||
}]
|
||||
},
|
||||
"finish_reason": "tool_calls"
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Claude-Compatible API
|
||||
|
||||
### Claude Model List
|
||||
|
||||
```http
|
||||
GET /anthropic/v1/models
|
||||
```
|
||||
|
||||
**Response example**:
|
||||
|
||||
```json
|
||||
{
|
||||
"object": "list",
|
||||
"data": [
|
||||
{"id": "claude-sonnet-4-20250514", "object": "model", "owned_by": "anthropic"},
|
||||
{"id": "claude-sonnet-4-20250514-fast", "object": "model", "owned_by": "anthropic"},
|
||||
{"id": "claude-sonnet-4-20250514-slow", "object": "model", "owned_by": "anthropic"}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Model mapping**:
|
||||
|
||||
| Claude Model | Actual | Notes |
|
||||
|------------|--------|------|
|
||||
| `claude-sonnet-4-20250514` | deepseek-chat | Standard mode |
|
||||
| `claude-sonnet-4-20250514-fast` | deepseek-chat | Fast mode |
|
||||
| `claude-sonnet-4-20250514-slow` | deepseek-reasoner | Reasoning mode |
|
||||
|
||||
---
|
||||
|
||||
### Claude Messages
|
||||
|
||||
```http
|
||||
POST /anthropic/v1/messages
|
||||
x-api-key: your-api-key
|
||||
Content-Type: application/json
|
||||
anthropic-version: 2023-06-01
|
||||
```
|
||||
|
||||
**Parameters**:
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
|-----|------|:----:|------|
|
||||
| `model` | string | ✅ | Model name |
|
||||
| `max_tokens` | integer | ✅ | Max output tokens |
|
||||
| `messages` | array | ✅ | Chat messages |
|
||||
| `stream` | boolean | ❌ | Stream responses (default `false`) |
|
||||
| `system` | string | ❌ | System prompt |
|
||||
| `temperature` | number | ❌ | Temperature |
|
||||
|
||||
**Request example**:
|
||||
|
||||
```json
|
||||
{
|
||||
"model": "claude-sonnet-4-20250514",
|
||||
"max_tokens": 1024,
|
||||
"messages": [
|
||||
{"role": "user", "content": "Hello, please introduce yourself."}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Non-streaming response**:
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "msg_xxx",
|
||||
"type": "message",
|
||||
"role": "assistant",
|
||||
"content": [{
|
||||
"type": "text",
|
||||
"text": "Hello! I'm an AI assistant..."
|
||||
}],
|
||||
"model": "claude-sonnet-4-20250514",
|
||||
"stop_reason": "end_turn",
|
||||
"usage": {
|
||||
"input_tokens": 10,
|
||||
"output_tokens": 50
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Streaming response** (SSE):
|
||||
|
||||
```
|
||||
event: message_start
|
||||
data: {"type":"message_start","message":{"id":"msg_xxx","type":"message","role":"assistant","model":"claude-sonnet-4-20250514"}}
|
||||
|
||||
event: content_block_start
|
||||
data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}
|
||||
|
||||
event: content_block_delta
|
||||
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hello"}}
|
||||
|
||||
event: content_block_stop
|
||||
data: {"type":"content_block_stop","index":0}
|
||||
|
||||
event: message_delta
|
||||
data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":50}}
|
||||
|
||||
event: message_stop
|
||||
data: {"type":"message_stop"}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Token Counting
|
||||
|
||||
```http
|
||||
POST /anthropic/v1/messages/count_tokens
|
||||
x-api-key: your-api-key
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
**Request example**:
|
||||
|
||||
```json
|
||||
{
|
||||
"model": "claude-sonnet-4-20250514",
|
||||
"messages": [
|
||||
{"role": "user", "content": "Hello"}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Response example**:
|
||||
|
||||
```json
|
||||
{
|
||||
"input_tokens": 5
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Admin API
|
||||
|
||||
All admin endpoints (except login) require `Authorization: Bearer <jwt-token>`.
|
||||
|
||||
### Login
|
||||
|
||||
```http
|
||||
POST /admin/login
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
**Request body**:
|
||||
|
||||
```json
|
||||
{
|
||||
"key": "your-admin-key"
|
||||
}
|
||||
```
|
||||
|
||||
**Response**:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"token": "jwt-token-string",
|
||||
"expires_in": 86400
|
||||
}
|
||||
```
|
||||
|
||||
> Tokens are valid for 24 hours by default.
|
||||
|
||||
---
|
||||
|
||||
### Configuration
|
||||
|
||||
#### Get configuration
|
||||
|
||||
```http
|
||||
GET /admin/config
|
||||
Authorization: Bearer <jwt-token>
|
||||
```
|
||||
|
||||
**Response**:
|
||||
|
||||
```json
|
||||
{
|
||||
"keys": ["api-key-1", "api-key-2"],
|
||||
"accounts": [
|
||||
{
|
||||
"email": "user@example.com",
|
||||
"password": "***",
|
||||
"token": "session-token"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
#### Update configuration
|
||||
|
||||
```http
|
||||
POST /admin/config
|
||||
Authorization: Bearer <jwt-token>
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
**Request body**:
|
||||
|
||||
```json
|
||||
{
|
||||
"keys": ["new-api-key"],
|
||||
"accounts": [...]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Account Management
|
||||
|
||||
#### Add account
|
||||
|
||||
```http
|
||||
POST /admin/accounts
|
||||
Authorization: Bearer <jwt-token>
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
**Request body**:
|
||||
|
||||
```json
|
||||
{
|
||||
"email": "user@example.com",
|
||||
"password": "password123"
|
||||
}
|
||||
```
|
||||
|
||||
#### Batch import accounts
|
||||
|
||||
```http
|
||||
POST /admin/accounts/batch
|
||||
Authorization: Bearer <jwt-token>
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
**Request body**:
|
||||
|
||||
```json
|
||||
{
|
||||
"accounts": [
|
||||
{"email": "user1@example.com", "password": "pass1"},
|
||||
{"email": "user2@example.com", "password": "pass2"}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
#### Test one account
|
||||
|
||||
```http
|
||||
POST /admin/accounts/test
|
||||
Authorization: Bearer <jwt-token>
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
**Request body**:
|
||||
|
||||
```json
|
||||
{
|
||||
"email": "user@example.com"
|
||||
}
|
||||
```
|
||||
|
||||
#### Test all accounts
|
||||
|
||||
```http
|
||||
POST /admin/accounts/test-all
|
||||
Authorization: Bearer <jwt-token>
|
||||
```
|
||||
|
||||
#### Queue status
|
||||
|
||||
```http
|
||||
GET /admin/queue/status
|
||||
Authorization: Bearer <jwt-token>
|
||||
```
|
||||
|
||||
**Response**:
|
||||
|
||||
```json
|
||||
{
|
||||
"total_accounts": 5,
|
||||
"healthy_accounts": 4,
|
||||
"queue_size": 10,
|
||||
"accounts": [
|
||||
{
|
||||
"email": "user@example.com",
|
||||
"status": "healthy",
|
||||
"last_used": "2026-02-01T12:00:00Z"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Vercel Sync
|
||||
|
||||
```http
|
||||
POST /admin/vercel/sync
|
||||
Authorization: Bearer <jwt-token>
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
**Request body** (first sync only):
|
||||
|
||||
```json
|
||||
{
|
||||
"vercel_token": "your-vercel-token",
|
||||
"project_id": "your-project-id"
|
||||
}
|
||||
```
|
||||
|
||||
> After a successful first sync, credentials are stored for future syncs.
|
||||
|
||||
**Response**:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "Configuration synced to Vercel"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Error Handling
|
||||
|
||||
All error responses follow this structure:
|
||||
|
||||
```json
|
||||
{
|
||||
"error": {
|
||||
"message": "Error description",
|
||||
"type": "error_type",
|
||||
"code": "error_code"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Common error codes**:
|
||||
|
||||
| HTTP Status | Error Type | Description |
|
||||
|:----------:|---------|------|
|
||||
| 400 | `invalid_request_error` | Invalid request parameters |
|
||||
| 401 | `authentication_error` | Missing or invalid API key |
|
||||
| 403 | `permission_denied` | Insufficient permissions |
|
||||
| 429 | `rate_limit_error` | Too many requests |
|
||||
| 500 | `internal_error` | Internal server error |
|
||||
| 503 | `service_unavailable` | No available accounts |
|
||||
|
||||
---
|
||||
|
||||
## Examples
|
||||
|
||||
### Python (OpenAI SDK)
|
||||
|
||||
```python
|
||||
from openai import OpenAI
|
||||
|
||||
client = OpenAI(
|
||||
api_key="your-api-key",
|
||||
base_url="https://your-domain.com/v1"
|
||||
)
|
||||
|
||||
# Basic chat
|
||||
response = client.chat.completions.create(
|
||||
model="deepseek-chat",
|
||||
messages=[{"role": "user", "content": "Hello"}]
|
||||
)
|
||||
print(response.choices[0].message.content)
|
||||
|
||||
# Streaming + reasoning
|
||||
for chunk in client.chat.completions.create(
|
||||
model="deepseek-reasoner",
|
||||
messages=[{"role": "user", "content": "Explain relativity"}],
|
||||
stream=True
|
||||
):
|
||||
delta = chunk.choices[0].delta
|
||||
if hasattr(delta, 'reasoning_content') and delta.reasoning_content:
|
||||
print(f"[Reasoning] {delta.reasoning_content}", end="")
|
||||
if delta.content:
|
||||
print(delta.content, end="")
|
||||
```
|
||||
|
||||
### Python (Anthropic SDK)
|
||||
|
||||
```python
|
||||
import anthropic
|
||||
|
||||
client = anthropic.Anthropic(
|
||||
api_key="your-api-key",
|
||||
base_url="https://your-domain.com/anthropic"
|
||||
)
|
||||
|
||||
response = client.messages.create(
|
||||
model="claude-sonnet-4-20250514",
|
||||
max_tokens=1024,
|
||||
messages=[{"role": "user", "content": "Hello"}]
|
||||
)
|
||||
print(response.content[0].text)
|
||||
```
|
||||
|
||||
### cURL
|
||||
|
||||
```bash
|
||||
# OpenAI format
|
||||
curl https://your-domain.com/v1/chat/completions \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Authorization: Bearer your-api-key" \
|
||||
-d '{
|
||||
"model": "deepseek-chat",
|
||||
"messages": [{"role": "user", "content": "Hello"}]
|
||||
}'
|
||||
|
||||
# Claude format
|
||||
curl https://your-domain.com/anthropic/v1/messages \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "x-api-key: your-api-key" \
|
||||
-H "anthropic-version: 2023-06-01" \
|
||||
-d '{
|
||||
"model": "claude-sonnet-4-20250514",
|
||||
"max_tokens": 1024,
|
||||
"messages": [{"role": "user", "content": "Hello"}]
|
||||
}'
|
||||
```
|
||||
|
||||
### JavaScript / TypeScript
|
||||
|
||||
```javascript
|
||||
// OpenAI format - streaming request
|
||||
const response = await fetch('https://your-domain.com/v1/chat/completions', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': 'Bearer your-api-key'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: 'deepseek-chat-search',
|
||||
messages: [{ role: 'user', content: 'What is in the news today?' }],
|
||||
stream: true
|
||||
})
|
||||
});
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
|
||||
const chunk = decoder.decode(value);
|
||||
const lines = chunk.split('\n').filter(line => line.startsWith('data: '));
|
||||
|
||||
for (const line of lines) {
|
||||
const data = line.slice(6);
|
||||
if (data === '[DONE]') continue;
|
||||
|
||||
const json = JSON.parse(data);
|
||||
const content = json.choices?.[0]?.delta?.content;
|
||||
if (content) process.stdout.write(content);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Node.js (OpenAI SDK)
|
||||
|
||||
```javascript
|
||||
import OpenAI from 'openai';
|
||||
|
||||
const client = new OpenAI({
|
||||
apiKey: 'your-api-key',
|
||||
baseURL: 'https://your-domain.com/v1'
|
||||
});
|
||||
|
||||
const stream = await client.chat.completions.create({
|
||||
model: 'deepseek-reasoner',
|
||||
messages: [{ role: 'user', content: 'Explain black holes' }],
|
||||
stream: true
|
||||
});
|
||||
|
||||
for await (const chunk of stream) {
|
||||
const content = chunk.choices[0]?.delta?.content;
|
||||
if (content) process.stdout.write(content);
|
||||
}
|
||||
```
|
||||
2
API.md
2
API.md
@@ -1,5 +1,7 @@
|
||||
# DS2API 接口文档
|
||||
|
||||
语言 / Language: [中文](API.md) | [English](API.en.md)
|
||||
|
||||
本文档详细介绍 DS2API 提供的所有 API 端点。
|
||||
|
||||
---
|
||||
|
||||
94
CONTRIBUTING.en.md
Normal file
94
CONTRIBUTING.en.md
Normal file
@@ -0,0 +1,94 @@
|
||||
# Contributing Guide
|
||||
|
||||
Language: [中文](CONTRIBUTING.md) | [English](CONTRIBUTING.en.md)
|
||||
|
||||
Thank you for contributing to DS2API!
|
||||
|
||||
## Development Setup
|
||||
|
||||
### Backend
|
||||
|
||||
```bash
|
||||
# 1. Clone the repo
|
||||
git clone https://github.com/CJackHwang/ds2api.git
|
||||
cd ds2api
|
||||
|
||||
# 2. Create a virtual environment (recommended)
|
||||
python -m venv venv
|
||||
source venv/bin/activate # Windows: venv\Scripts\activate
|
||||
|
||||
# 3. Install dependencies
|
||||
pip install -r requirements.txt
|
||||
|
||||
# 4. Configure
|
||||
cp config.example.json config.json
|
||||
# Edit config.json
|
||||
|
||||
# 5. Run
|
||||
python dev.py
|
||||
```
|
||||
|
||||
### Frontend (WebUI)
|
||||
|
||||
```bash
|
||||
cd webui
|
||||
npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
WebUI language packs live in `webui/src/locales/`. Add new locale JSON files there.
|
||||
|
||||
## Code Standards
|
||||
|
||||
- **Python**: Follow PEP 8, use 4-space indentation
|
||||
- **JavaScript/React**: Use 4-space indentation and function components
|
||||
- **Commit messages**: Use semantic prefixes (e.g. `feat:`, `fix:`, `docs:`)
|
||||
|
||||
## Submitting a PR
|
||||
|
||||
1. Fork this repo
|
||||
2. Create a feature branch (`git checkout -b feature/xxx`)
|
||||
3. Commit your changes (`git commit -m 'feat: add xxx'`)
|
||||
4. Push your branch (`git push origin feature/xxx`)
|
||||
5. Open a Pull Request
|
||||
|
||||
## WebUI Build
|
||||
|
||||
> **Important**: After modifying `webui/`, **no manual build is required**.
|
||||
|
||||
When a PR is merged into `main`, GitHub Actions will automatically:
|
||||
1. Build the WebUI
|
||||
2. Commit build artifacts to `static/admin/`
|
||||
|
||||
If you need a local build (for testing):
|
||||
```bash
|
||||
./scripts/build-webui.sh
|
||||
```
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
ds2api/
|
||||
├── app.py # FastAPI entrypoint
|
||||
├── dev.py # Development server
|
||||
├── core/ # Core modules
|
||||
│ ├── auth.py # Account auth & rotation
|
||||
│ ├── config.py # Configuration management
|
||||
│ ├── deepseek.py # DeepSeek API calls
|
||||
│ ├── models.py # Model definitions
|
||||
│ ├── pow.py # PoW calculations
|
||||
│ └── sse_parser.py # SSE parsing
|
||||
├── routes/ # API routes
|
||||
│ ├── openai.py # OpenAI-compatible endpoints
|
||||
│ ├── claude.py # Claude-compatible endpoints
|
||||
│ ├── home.py # Landing page routes
|
||||
│ └── admin/ # Admin endpoints
|
||||
├── webui/ # React WebUI source
|
||||
├── static/admin/ # WebUI build output (auto-generated)
|
||||
└── scripts/ # Helper scripts
|
||||
```
|
||||
|
||||
## Reporting Issues
|
||||
|
||||
- Use [GitHub Issues](https://github.com/CJackHwang/ds2api/issues)
|
||||
- Provide detailed reproduction steps and logs
|
||||
@@ -1,5 +1,7 @@
|
||||
# 贡献指南
|
||||
|
||||
语言 / Language: [中文](CONTRIBUTING.md) | [English](CONTRIBUTING.en.md)
|
||||
|
||||
感谢你对 DS2API 的贡献!
|
||||
|
||||
## 开发环境设置
|
||||
@@ -34,6 +36,8 @@ npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
WebUI 语言包位于 `webui/src/locales/`,新增语言请在此处添加对应 JSON 文件。
|
||||
|
||||
## 代码规范
|
||||
|
||||
- **Python**: 遵循 PEP 8,使用 4 空格缩进
|
||||
|
||||
410
DEPLOY.en.md
Normal file
410
DEPLOY.en.md
Normal file
@@ -0,0 +1,410 @@
|
||||
# DS2API Deployment Guide
|
||||
|
||||
Language: [中文](DEPLOY.md) | [English](DEPLOY.en.md)
|
||||
|
||||
This document covers all supported DS2API deployment methods.
|
||||
|
||||
---
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Vercel Deployment (Recommended)](#vercel-deployment-recommended)
|
||||
- [Docker Deployment (Recommended)](#docker-deployment-recommended)
|
||||
- [Local Development](#local-development)
|
||||
- [Production Deployment](#production-deployment)
|
||||
- [FAQ](#faq)
|
||||
|
||||
---
|
||||
|
||||
## Vercel Deployment (Recommended)
|
||||
|
||||
### One-click deployment
|
||||
|
||||
[](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FCJackHwang%2Fds2api&env=DS2API_ADMIN_KEY&envDescription=Admin%20console%20access%20key%20%28required%29&envLink=https%3A%2F%2Fgithub.com%2FCJackHwang%2Fds2api%23environment-variables&project-name=ds2api&repository-name=ds2api)
|
||||
|
||||
### Steps
|
||||
|
||||
1. **Click the deploy button**
|
||||
- Sign in to GitHub
|
||||
- Authorize Vercel access
|
||||
|
||||
2. **Set environment variables**
|
||||
- `DS2API_ADMIN_KEY`: Admin console password (**required**)
|
||||
|
||||
3. **Wait for deployment**
|
||||
- Vercel builds and deploys automatically
|
||||
- You will receive a deployment URL
|
||||
|
||||
4. **Configure accounts**
|
||||
- Visit `https://your-project.vercel.app/admin`
|
||||
- Log in with the admin key
|
||||
- Add DeepSeek accounts
|
||||
- Set custom API keys
|
||||
|
||||
5. **Sync configuration**
|
||||
- Click "Sync to Vercel"
|
||||
- The first sync requires a Vercel token and project ID
|
||||
- After sync, the configuration is persisted
|
||||
|
||||
### Get Vercel credentials
|
||||
|
||||
**Vercel token**:
|
||||
1. Visit https://vercel.com/account/tokens
|
||||
2. Click "Create Token"
|
||||
3. Set a name and expiration
|
||||
4. Copy the token
|
||||
|
||||
**Project ID**:
|
||||
1. Open your Vercel project
|
||||
2. Go to Settings → General
|
||||
3. Copy the "Project ID"
|
||||
|
||||
---
|
||||
|
||||
## Local Development
|
||||
|
||||
### Requirements
|
||||
|
||||
- Python 3.9+
|
||||
- Node.js 18+ (WebUI development)
|
||||
- pip
|
||||
|
||||
### Quick start
|
||||
|
||||
```bash
|
||||
# 1. Clone the repo
|
||||
git clone https://github.com/CJackHwang/ds2api.git
|
||||
cd ds2api
|
||||
|
||||
# 2. Install Python dependencies
|
||||
pip install -r requirements.txt
|
||||
|
||||
# 3. Configure accounts
|
||||
cp config.example.json config.json
|
||||
# Edit config.json and fill in DeepSeek account info
|
||||
|
||||
# 4. Start the service
|
||||
python dev.py
|
||||
```
|
||||
|
||||
### Config example
|
||||
|
||||
```json
|
||||
{
|
||||
"keys": ["my-api-key-1", "my-api-key-2"],
|
||||
"accounts": [
|
||||
{
|
||||
"email": "your-email@example.com",
|
||||
"password": "your-password",
|
||||
"token": ""
|
||||
},
|
||||
{
|
||||
"mobile": "12345678901",
|
||||
"password": "your-password",
|
||||
"token": ""
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Notes**:
|
||||
- `keys`: Custom API keys for calling the service
|
||||
- `accounts`: DeepSeek Web accounts
|
||||
- Supports `email` or `mobile` login
|
||||
- Leave `token` blank; it will be fetched automatically
|
||||
|
||||
### WebUI development
|
||||
|
||||
```bash
|
||||
# Enter the WebUI directory
|
||||
cd webui
|
||||
|
||||
# Install dependencies
|
||||
npm install
|
||||
|
||||
# Start the dev server
|
||||
npm run dev
|
||||
```
|
||||
|
||||
The WebUI dev server runs on `http://localhost:5173` and proxies API requests to `http://localhost:5001`.
|
||||
|
||||
### WebUI build
|
||||
|
||||
Build artifacts are located in `static/admin/`.
|
||||
|
||||
**Automatic build (recommended)**:
|
||||
- Vercel builds the WebUI during deployment (see `vercel.json` `buildCommand`)
|
||||
- The GitHub Actions WebUI build workflow is disabled
|
||||
- `static/admin/` build artifacts are no longer committed
|
||||
|
||||
**Manual build**:
|
||||
```bash
|
||||
# Option 1: use script
|
||||
./scripts/build-webui.sh
|
||||
|
||||
# Option 2: run directly
|
||||
cd webui
|
||||
npm install
|
||||
npm run build
|
||||
```
|
||||
|
||||
> **Contributor note**: No manual build is required after modifying WebUI; Vercel deploys will build it automatically.
|
||||
|
||||
---
|
||||
|
||||
## Docker Deployment (Recommended)
|
||||
|
||||
Docker uses a **non-invasive, decoupled design**:
|
||||
- Dockerfile executes standard Python steps and avoids hardcoded project configs
|
||||
- WebUI is built during image build (for non-Vercel deployments)
|
||||
- Configuration lives in environment variables and `.env`
|
||||
- **Rebuild the image to update code without touching Docker config**
|
||||
|
||||
### Quick start (Docker Compose)
|
||||
|
||||
```bash
|
||||
# 1. Copy the environment template
|
||||
cp .env.example .env
|
||||
# Edit .env with DS2API_ADMIN_KEY and DS2API_CONFIG_JSON
|
||||
|
||||
# 2. Start the service
|
||||
docker-compose up -d
|
||||
|
||||
# 3. Check logs
|
||||
docker-compose logs -f
|
||||
|
||||
# 4. Rebuild after code updates
|
||||
docker-compose up -d --build
|
||||
```
|
||||
|
||||
### Mount a config file
|
||||
|
||||
To use `config.json` instead of environment variables:
|
||||
|
||||
```yaml
|
||||
# docker-compose.yml
|
||||
services:
|
||||
ds2api:
|
||||
build: .
|
||||
ports:
|
||||
- "5001:5001"
|
||||
environment:
|
||||
- DS2API_ADMIN_KEY=your-admin-key
|
||||
volumes:
|
||||
- ./config.json:/app/config.json:ro
|
||||
restart: unless-stopped
|
||||
```
|
||||
|
||||
### Docker CLI deployment
|
||||
|
||||
```bash
|
||||
# Build the image
|
||||
docker build -t ds2api:latest .
|
||||
|
||||
# Run with env variables
|
||||
docker run -d \
|
||||
--name ds2api \
|
||||
-p 5001:5001 \
|
||||
-e DS2API_ADMIN_KEY=your-admin-key \
|
||||
-e DS2API_CONFIG_JSON='{"keys":["api-key"],"accounts":[...]}' \
|
||||
--restart unless-stopped \
|
||||
ds2api:latest
|
||||
|
||||
# Or mount a config file
|
||||
docker run -d \
|
||||
--name ds2api \
|
||||
-p 5001:5001 \
|
||||
-e DS2API_ADMIN_KEY=your-admin-key \
|
||||
-v $(pwd)/config.json:/app/config.json:ro \
|
||||
--restart unless-stopped \
|
||||
ds2api:latest
|
||||
```
|
||||
|
||||
### Development mode (hot reload)
|
||||
|
||||
```bash
|
||||
# Use the dev compose file to enable hot reload
|
||||
docker-compose -f docker-compose.dev.yml up
|
||||
```
|
||||
|
||||
Development mode:
|
||||
- Source code is mounted into the container
|
||||
- Log level set to DEBUG
|
||||
- Reads local `config.json`
|
||||
|
||||
### Maintenance commands
|
||||
|
||||
```bash
|
||||
# Check container status
|
||||
docker-compose ps
|
||||
|
||||
# View logs
|
||||
docker-compose logs -f ds2api
|
||||
|
||||
# Restart
|
||||
docker-compose restart
|
||||
|
||||
# Stop
|
||||
docker-compose down
|
||||
|
||||
# Full rebuild (clear cache)
|
||||
docker-compose down
|
||||
docker-compose build --no-cache
|
||||
docker-compose up -d
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Production Deployment
|
||||
|
||||
### Using systemd (Linux)
|
||||
|
||||
1. **Create the service file**
|
||||
|
||||
```bash
|
||||
sudo nano /etc/systemd/system/ds2api.service
|
||||
```
|
||||
|
||||
```ini
|
||||
[Unit]
|
||||
Description=DS2API Service
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=www-data
|
||||
WorkingDirectory=/opt/ds2api
|
||||
ExecStart=/usr/bin/python3 app.py
|
||||
Restart=always
|
||||
RestartSec=10
|
||||
Environment=PORT=5001
|
||||
Environment=DS2API_ADMIN_KEY=your-admin-key
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
```
|
||||
|
||||
2. **Start the service**
|
||||
|
||||
```bash
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl enable ds2api
|
||||
sudo systemctl start ds2api
|
||||
```
|
||||
|
||||
3. **Check status**
|
||||
|
||||
```bash
|
||||
sudo systemctl status ds2api
|
||||
sudo journalctl -u ds2api -f
|
||||
```
|
||||
|
||||
### Nginx reverse proxy
|
||||
|
||||
```nginx
|
||||
server {
|
||||
listen 80;
|
||||
server_name api.yourdomain.com;
|
||||
|
||||
# SSL configuration (recommended)
|
||||
# listen 443 ssl http2;
|
||||
# ssl_certificate /path/to/cert.pem;
|
||||
# ssl_certificate_key /path/to/key.pem;
|
||||
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:5001;
|
||||
proxy_http_version 1.1;
|
||||
|
||||
# Disable buffering for SSE
|
||||
proxy_buffering off;
|
||||
proxy_cache off;
|
||||
|
||||
# Connection settings
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
|
||||
# SSE timeouts
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
|
||||
# Chunked transfer
|
||||
chunked_transfer_encoding on;
|
||||
tcp_nopush on;
|
||||
tcp_nodelay on;
|
||||
keepalive_timeout 120;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## FAQ
|
||||
|
||||
### Q: What if account validation fails?
|
||||
|
||||
**A**: Check the following:
|
||||
1. Confirm the DeepSeek account password is correct
|
||||
2. Ensure the account is not banned or requires verification
|
||||
3. Log in once in a browser
|
||||
4. Check logs for detailed errors
|
||||
|
||||
### Q: Streaming responses disconnect?
|
||||
|
||||
**A**:
|
||||
1. Check Nginx / reverse proxy config and ensure `proxy_buffering` is off
|
||||
2. Increase `proxy_read_timeout`
|
||||
3. Verify network stability
|
||||
|
||||
### Q: Configuration lost after Vercel deploy?
|
||||
|
||||
**A**:
|
||||
1. Ensure you clicked "Sync to Vercel"
|
||||
2. Verify the Vercel token is valid and unexpired
|
||||
3. Ensure the project ID is correct
|
||||
|
||||
### Q: How to update to the latest version?
|
||||
|
||||
**Local deployment**:
|
||||
```bash
|
||||
git pull origin main
|
||||
pip install -r requirements.txt
|
||||
# Restart the service
|
||||
```
|
||||
|
||||
**Docker deployment**:
|
||||
```bash
|
||||
# Pull the latest code
|
||||
git pull origin main
|
||||
|
||||
# Rebuild and start (Docker config unchanged)
|
||||
docker-compose up -d --build
|
||||
```
|
||||
|
||||
**Vercel deployment**:
|
||||
- The project auto-syncs from GitHub
|
||||
- Or trigger a redeploy in the Vercel console
|
||||
|
||||
### Q: How do I view logs?
|
||||
|
||||
**Local dev**:
|
||||
```bash
|
||||
# Set log level
|
||||
export LOG_LEVEL=DEBUG
|
||||
python dev.py
|
||||
```
|
||||
|
||||
**Vercel**:
|
||||
- Vercel console → Project → Deployments → Logs
|
||||
|
||||
### Q: Token counting is inaccurate?
|
||||
|
||||
**A**: DS2API uses a heuristic estimate (characters / 4). The official OpenAI tokenizer may differ, so treat it as a reference only.
|
||||
|
||||
---
|
||||
|
||||
## Get Help
|
||||
|
||||
- **GitHub Issues**: https://github.com/CJackHwang/ds2api/issues
|
||||
- **Docs**: https://github.com/CJackHwang/ds2api
|
||||
@@ -1,5 +1,7 @@
|
||||
# DS2API 部署指南
|
||||
|
||||
语言 / Language: [中文](DEPLOY.md) | [English](DEPLOY.en.md)
|
||||
|
||||
本文档详细介绍 DS2API 的各种部署方式。
|
||||
|
||||
---
|
||||
|
||||
@@ -6,13 +6,14 @@
|
||||
[](version.txt)
|
||||
[](DEPLOY.md#docker-部署推荐)
|
||||
|
||||
语言 / Language: [中文](README.MD) | [English](README.en.md)
|
||||
|
||||
将 DeepSeek 免费对话版转换为 **OpenAI & Claude 兼容 API**,支持多账号轮询、自动 Token 刷新、可视化管理界面。
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
|
||||
|
||||
@@ -22,6 +23,7 @@
|
||||
- 🚀 **多账号轮询** - Round-Robin 负载均衡,支持高并发场景
|
||||
- 🔐 **Token 自动刷新** - 过期自动重新登录,无需手动维护
|
||||
- 🌐 **WebUI 管理** - 可视化添加账号、测试 API、同步 Vercel 配置
|
||||
- 🌍 **多语言切换** - WebUI 内置中英双语,可随时切换
|
||||
- 🔍 **联网搜索** - 支持 DeepSeek 原生搜索增强模式
|
||||
- 🧠 **深度思考** - 支持推理模式,输出思考过程
|
||||
- 🛠️ **工具调用** - 兼容 OpenAI Function Calling 格式
|
||||
|
||||
233
README.en.md
Normal file
233
README.en.md
Normal file
@@ -0,0 +1,233 @@
|
||||
# DS2API
|
||||
|
||||
[](LICENSE)
|
||||

|
||||

|
||||
[](version.txt)
|
||||
[](DEPLOY.md#docker-deployment-recommended)
|
||||
|
||||
Language: [中文](README.MD) | [English](README.en.md)
|
||||
|
||||
Convert DeepSeek Web into an **OpenAI & Claude compatible API**, with multi-account rotation, automatic token refresh, and a visual admin console.
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
## ✨ Features
|
||||
|
||||
- 🔄 **Dual-protocol support** - OpenAI and Claude (Anthropic) compatible APIs
|
||||
- 🚀 **Multi-account rotation** - Round-robin load balancing for high concurrency
|
||||
- 🔐 **Automatic token refresh** - Re-auth on expiry without manual maintenance
|
||||
- 🌐 **WebUI management** - Add accounts, test APIs, and sync Vercel settings visually
|
||||
- 🌍 **Language toggle** - Built-in Chinese and English UI switcher
|
||||
- 🔍 **Web search** - DeepSeek native search enhancement mode
|
||||
- 🧠 **Deep reasoning** - Reasoning mode with trace output
|
||||
- 🛠️ **Tool calling** - OpenAI Function Calling compatible
|
||||
- ☁️ **One-click Vercel deploy** - No server required
|
||||
|
||||
## 📋 Model Support
|
||||
|
||||
### OpenAI compatible endpoint (`/v1/chat/completions`)
|
||||
|
||||
| Model | Reasoning | Search | Notes |
|
||||
|-----|:--------:|:------:|------|
|
||||
| `deepseek-chat` | ❌ | ❌ | Standard chat |
|
||||
| `deepseek-reasoner` | ✅ | ❌ | Reasoning (shows trace) |
|
||||
| `deepseek-chat-search` | ❌ | ✅ | Web search mode |
|
||||
| `deepseek-reasoner-search` | ✅ | ✅ | Reasoning + search |
|
||||
|
||||
### Claude compatible endpoint (`/anthropic/v1/messages`)
|
||||
|
||||
| Model | Notes |
|
||||
|-----|------|
|
||||
| `claude-sonnet-4-20250514` | Maps to deepseek-chat (standard) |
|
||||
| `claude-sonnet-4-20250514-fast` | Maps to deepseek-chat (fast) |
|
||||
| `claude-sonnet-4-20250514-slow` | Maps to deepseek-reasoner (reasoning) |
|
||||
|
||||
> **Tip**: The Claude endpoint actually calls DeepSeek and returns Anthropic-format responses.
|
||||
|
||||
## 🚀 Quick Start
|
||||
|
||||
### Option 1: Vercel deployment (recommended)
|
||||
|
||||
[](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FCJackHwang%2Fds2api&env=DS2API_ADMIN_KEY&envDescription=Admin%20console%20access%20key%20%28required%29&envLink=https%3A%2F%2Fgithub.com%2FCJackHwang%2Fds2api%23environment-variables&project-name=ds2api&repository-name=ds2api)
|
||||
|
||||
1. Click the button above and set `DS2API_ADMIN_KEY`
|
||||
2. After deployment, visit `/admin`
|
||||
3. Add DeepSeek accounts and custom API keys
|
||||
4. Click "Sync to Vercel" to persist configuration
|
||||
|
||||
> **First sync validates accounts and stores tokens automatically.**
|
||||
|
||||
### Option 2: Local development
|
||||
|
||||
```bash
|
||||
# 1. Clone the repo
|
||||
git clone https://github.com/CJackHwang/ds2api.git
|
||||
cd ds2api
|
||||
|
||||
# 2. Install dependencies
|
||||
pip install -r requirements.txt
|
||||
|
||||
# 3. Configure accounts
|
||||
cp config.example.json config.json
|
||||
# Edit config.json to add DeepSeek account info
|
||||
|
||||
# 4. Start the service
|
||||
python dev.py
|
||||
```
|
||||
|
||||
Visit `http://localhost:5001` after startup.
|
||||
|
||||
## ⚙️ Configuration
|
||||
|
||||
### Environment variables
|
||||
|
||||
| Variable | Description | Required |
|
||||
|-----|------|:----:|
|
||||
| `DS2API_ADMIN_KEY` | Admin console password | Required on Vercel |
|
||||
| `DS2API_CONFIG_JSON` | Config JSON or Base64 | Optional |
|
||||
| `VERCEL_TOKEN` | Vercel API token (for sync) | Optional |
|
||||
| `VERCEL_PROJECT_ID` | Vercel project ID | Optional |
|
||||
| `PORT` | Service port (default 5001) | Optional |
|
||||
|
||||
### Config file format (`config.json`)
|
||||
|
||||
```json
|
||||
{
|
||||
"keys": ["your-api-key-1", "your-api-key-2"],
|
||||
"accounts": [
|
||||
{
|
||||
"email": "user@example.com",
|
||||
"password": "your-password",
|
||||
"token": ""
|
||||
},
|
||||
{
|
||||
"mobile": "12345678901",
|
||||
"password": "your-password",
|
||||
"token": ""
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
> **Notes**:
|
||||
> - `keys`: Custom API keys for calling this service
|
||||
> - `accounts`: DeepSeek Web accounts (email or mobile)
|
||||
> - `token`: Leave blank; DS2API will fetch and refresh automatically
|
||||
|
||||
## 📡 API Usage
|
||||
|
||||
See **[API.md](API.md)** for full API documentation.
|
||||
|
||||
### Quick examples
|
||||
|
||||
**List models**:
|
||||
```bash
|
||||
curl http://localhost:5001/v1/models
|
||||
```
|
||||
|
||||
**OpenAI-compatible call**:
|
||||
```bash
|
||||
curl http://localhost:5001/v1/chat/completions \
|
||||
-H "Authorization: Bearer your-api-key" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"model": "deepseek-chat",
|
||||
"messages": [{"role": "user", "content": "Hello"}],
|
||||
"stream": true
|
||||
}'
|
||||
```
|
||||
|
||||
**Claude-compatible call**:
|
||||
```bash
|
||||
curl http://localhost:5001/anthropic/v1/messages \
|
||||
-H "x-api-key: your-api-key" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "anthropic-version: 2023-06-01" \
|
||||
-d '{
|
||||
"model": "claude-sonnet-4-20250514",
|
||||
"max_tokens": 1024,
|
||||
"messages": [{"role": "user", "content": "Hello"}]
|
||||
}'
|
||||
```
|
||||
|
||||
### Python SDK usage
|
||||
|
||||
```python
|
||||
from openai import OpenAI
|
||||
|
||||
client = OpenAI(
|
||||
api_key="your-api-key",
|
||||
base_url="http://localhost:5001/v1"
|
||||
)
|
||||
|
||||
response = client.chat.completions.create(
|
||||
model="deepseek-reasoner",
|
||||
messages=[{"role": "user", "content": "Explain quantum entanglement"}],
|
||||
stream=True
|
||||
)
|
||||
|
||||
for chunk in response:
|
||||
if chunk.choices[0].delta.content:
|
||||
print(chunk.choices[0].delta.content, end="")
|
||||
```
|
||||
|
||||
## 🔧 Deployment Notes
|
||||
|
||||
### Nginx reverse proxy
|
||||
|
||||
```nginx
|
||||
location / {
|
||||
proxy_pass http://localhost:5001;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Connection "";
|
||||
proxy_buffering off;
|
||||
proxy_cache off;
|
||||
chunked_transfer_encoding on;
|
||||
tcp_nopush on;
|
||||
tcp_nodelay on;
|
||||
keepalive_timeout 120;
|
||||
}
|
||||
```
|
||||
|
||||
### Option 3: Docker deployment
|
||||
|
||||
```bash
|
||||
# 1. Clone the repo and enter the directory
|
||||
git clone https://github.com/CJackHwang/ds2api.git
|
||||
cd ds2api
|
||||
|
||||
# 2. Configure environment variables
|
||||
cp .env.example .env
|
||||
# Edit .env and fill in DS2API_ADMIN_KEY and DS2API_CONFIG_JSON
|
||||
|
||||
# 3. Start the service
|
||||
docker-compose up -d
|
||||
|
||||
# 4. Check logs
|
||||
docker-compose logs -f
|
||||
```
|
||||
|
||||
> **Docker advantage**: Zero-intrusion design; update the main code with `docker-compose up -d --build` without changing Docker configuration. See [DEPLOY.md](DEPLOY.md#docker-deployment-recommended).
|
||||
|
||||
## ⚠️ Disclaimer
|
||||
|
||||
**This project is based on reverse engineering and stability is not guaranteed.**
|
||||
|
||||
- For learning and research only. **No commercial use or public service is allowed.**
|
||||
- For production, use the official [DeepSeek API](https://platform.deepseek.com/)
|
||||
- You assume all risks from using this project
|
||||
|
||||
## 📜 Acknowledgements
|
||||
|
||||
This project is based on the following open-source projects:
|
||||
|
||||
- [iidamie/deepseek2api](https://github.com/iidamie/deepseek2api)
|
||||
- [LLM-Red-Team/deepseek-free-api](https://github.com/LLM-Red-Team/deepseek-free-api)
|
||||
|
||||
## 📊 Star History
|
||||
|
||||
[](https://star-history.com/#CJackHwang/ds2api&Date)
|
||||
36
core/auth.py
36
core/auth.py
@@ -58,17 +58,35 @@ def get_queue_status() -> dict:
|
||||
# ----------------------------------------------------------------------
|
||||
# 账号选择与释放 - 轮询(Round-Robin)策略
|
||||
# ----------------------------------------------------------------------
|
||||
def choose_new_account(exclude_ids=None):
|
||||
def choose_new_account(exclude_ids=None, target_id=None):
|
||||
"""轮询选择策略:
|
||||
1. 使用线程锁保证并发安全
|
||||
2. 优先选择队首的有 token 账号
|
||||
3. 从队列头部取出账号(FIFO)
|
||||
4. 请求完成后调用 release_account 将账号放回队尾
|
||||
2. 如果指定了 target_id,优先尝试获取该账号
|
||||
3. 优先选择队首的有 token 账号
|
||||
4. 从队列头部取出账号(FIFO)
|
||||
5. 请求完成后调用 release_account 将账号放回队尾
|
||||
"""
|
||||
if exclude_ids is None:
|
||||
exclude_ids = []
|
||||
|
||||
with _queue_lock:
|
||||
# 0. 如果指定了目标账号,优先尝试获取
|
||||
if target_id:
|
||||
for i in range(len(account_queue)):
|
||||
acc = account_queue[i]
|
||||
acc_id = get_account_identifier(acc)
|
||||
if acc_id == target_id:
|
||||
selected = account_queue.pop(i)
|
||||
in_use_accounts[acc_id] = selected
|
||||
logger.info(f"[choose_new_account] 指定选择: {acc_id} | 队列剩余: {len(account_queue)}")
|
||||
return selected
|
||||
# 如果队列中没找到,且不在 in_use 中,说明账号不存在
|
||||
if target_id not in in_use_accounts:
|
||||
logger.warning(f"[choose_new_account] 指定账号不存在: {target_id}")
|
||||
else:
|
||||
logger.warning(f"[choose_new_account] 指定账号正忙: {target_id}")
|
||||
return None
|
||||
|
||||
# 第一轮:优先选择已有 token 的账号
|
||||
for i in range(len(account_queue)):
|
||||
acc = account_queue[i]
|
||||
@@ -145,11 +163,17 @@ def determine_mode_and_token(request: Request):
|
||||
if caller_key in config_keys:
|
||||
request.state.use_config_token = True
|
||||
request.state.tried_accounts = [] # 初始化已尝试账号
|
||||
selected_account = choose_new_account()
|
||||
|
||||
target_account = request.headers.get("X-Ds2-Target-Account")
|
||||
selected_account = choose_new_account(target_id=target_account)
|
||||
|
||||
if not selected_account:
|
||||
detail_msg = "No accounts configured or all accounts are busy."
|
||||
if target_account:
|
||||
detail_msg = f"Target account {target_account} is busy or not found."
|
||||
raise HTTPException(
|
||||
status_code=429,
|
||||
detail="No accounts configured or all accounts are busy.",
|
||||
detail=detail_msg,
|
||||
)
|
||||
if not selected_account.get("token", "").strip():
|
||||
try:
|
||||
|
||||
@@ -32,9 +32,14 @@ logger = logging.getLogger("ds2api")
|
||||
|
||||
# -------------------------- 初始化 tokenizer --------------------------
|
||||
chat_tokenizer_dir = resolve_path("DS2API_TOKENIZER_DIR", "")
|
||||
# 抑制 Mistral tokenizer regex 警告(不影响 DeepSeek tokenization)
|
||||
_tf_logger = logging.getLogger("transformers")
|
||||
_tf_log_level = _tf_logger.level
|
||||
_tf_logger.setLevel(logging.ERROR)
|
||||
tokenizer = transformers.AutoTokenizer.from_pretrained(
|
||||
chat_tokenizer_dir, trust_remote_code=True
|
||||
)
|
||||
_tf_logger.setLevel(_tf_log_level)
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 配置文件的读写函数
|
||||
|
||||
@@ -255,6 +255,26 @@ def parse_sse_chunk_for_content(
|
||||
return ([], True, new_fragment_type)
|
||||
contents.extend(result)
|
||||
|
||||
# 处理字典值(初始响应 chunk,包含 response.fragments)
|
||||
elif isinstance(v_value, dict):
|
||||
response_obj = v_value.get("response", v_value)
|
||||
fragments = response_obj.get("fragments", [])
|
||||
if isinstance(fragments, list):
|
||||
for frag in fragments:
|
||||
if isinstance(frag, dict):
|
||||
frag_type = frag.get("type", "").upper()
|
||||
frag_content = frag.get("content", "")
|
||||
if frag_type == "THINK" or frag_type == "THINKING":
|
||||
new_fragment_type = "thinking"
|
||||
if frag_content:
|
||||
contents.append((frag_content, "thinking"))
|
||||
elif frag_type == "RESPONSE":
|
||||
new_fragment_type = "text"
|
||||
if frag_content:
|
||||
contents.append((frag_content, "text"))
|
||||
elif frag_content:
|
||||
contents.append((frag_content, ptype))
|
||||
|
||||
return (contents, False, new_fragment_type)
|
||||
|
||||
|
||||
|
||||
@@ -122,6 +122,49 @@ async def delete_key(key: str, _: bool = Depends(verify_admin)):
|
||||
# ----------------------------------------------------------------------
|
||||
# 账号管理
|
||||
# ----------------------------------------------------------------------
|
||||
@router.get("/accounts")
|
||||
async def list_accounts(
|
||||
page: int = 1,
|
||||
page_size: int = 10,
|
||||
_: bool = Depends(verify_admin)
|
||||
):
|
||||
"""获取账号列表(分页,倒序,密码脱敏)"""
|
||||
accounts = CONFIG.get("accounts", [])
|
||||
total = len(accounts)
|
||||
|
||||
# 倒序排列
|
||||
accounts = list(reversed(accounts))
|
||||
|
||||
# 计算分页
|
||||
page = max(1, page)
|
||||
page_size = max(1, min(100, page_size)) # 限制每页最多 100 条
|
||||
total_pages = (total + page_size - 1) // page_size if total > 0 else 1
|
||||
|
||||
start = (page - 1) * page_size
|
||||
end = start + page_size
|
||||
page_accounts = accounts[start:end]
|
||||
|
||||
# 脱敏处理
|
||||
safe_accounts = []
|
||||
for acc in page_accounts:
|
||||
safe_acc = {
|
||||
"email": acc.get("email", ""),
|
||||
"mobile": acc.get("mobile", ""),
|
||||
"has_password": bool(acc.get("password")),
|
||||
"has_token": bool(acc.get("token")),
|
||||
"token_preview": acc.get("token", "")[:20] + "..." if acc.get("token") else "",
|
||||
}
|
||||
safe_accounts.append(safe_acc)
|
||||
|
||||
return JSONResponse(content={
|
||||
"items": safe_accounts,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
"total_pages": total_pages,
|
||||
})
|
||||
|
||||
|
||||
@router.post("/accounts")
|
||||
async def add_account(request: Request, _: bool = Depends(verify_admin)):
|
||||
"""添加账号"""
|
||||
|
||||
@@ -2,8 +2,10 @@
|
||||
"""Admin Vercel 模块 - Vercel 同步和部署"""
|
||||
import asyncio
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import time as _time
|
||||
|
||||
import httpx
|
||||
from fastapi import APIRouter, HTTPException, Request, Depends
|
||||
@@ -23,6 +25,19 @@ VERCEL_PROJECT_ID = os.getenv("VERCEL_PROJECT_ID", "")
|
||||
VERCEL_TEAM_ID = os.getenv("VERCEL_TEAM_ID", "")
|
||||
|
||||
|
||||
def _compute_config_hash() -> str:
|
||||
"""计算可同步配置的指纹哈希(仅包含 keys 和 accounts)"""
|
||||
syncable = {
|
||||
"keys": CONFIG.get("keys", []),
|
||||
"accounts": [
|
||||
{k: v for k, v in acc.items() if k != "token"}
|
||||
for acc in CONFIG.get("accounts", [])
|
||||
],
|
||||
}
|
||||
raw = json.dumps(syncable, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
|
||||
return hashlib.md5(raw.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# API 测试(通过本地 API)
|
||||
# ----------------------------------------------------------------------
|
||||
@@ -228,6 +243,10 @@ async def sync_to_vercel(request: Request, _: bool = Depends(verify_admin)):
|
||||
|
||||
if deploy_resp.status_code in [200, 201]:
|
||||
deploy_data = deploy_resp.json()
|
||||
# 记录同步哈希和时间
|
||||
CONFIG["_vercel_sync_hash"] = _compute_config_hash()
|
||||
CONFIG["_vercel_sync_time"] = int(_time.time())
|
||||
save_config(CONFIG)
|
||||
result = {
|
||||
"success": True,
|
||||
"message": "配置已同步,正在重新部署...",
|
||||
@@ -240,6 +259,10 @@ async def sync_to_vercel(request: Request, _: bool = Depends(verify_admin)):
|
||||
result["saved_credentials"] = saved_credentials
|
||||
return JSONResponse(content=result)
|
||||
|
||||
# 环境变量已更新,但无法自动触发重新部署
|
||||
CONFIG["_vercel_sync_hash"] = _compute_config_hash()
|
||||
CONFIG["_vercel_sync_time"] = int(_time.time())
|
||||
save_config(CONFIG)
|
||||
result = {
|
||||
"success": True,
|
||||
"message": "配置已同步到 Vercel,请手动触发重新部署",
|
||||
@@ -259,6 +282,25 @@ async def sync_to_vercel(request: Request, _: bool = Depends(verify_admin)):
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 同步状态查询
|
||||
# ----------------------------------------------------------------------
|
||||
@router.get("/vercel/status")
|
||||
async def get_vercel_sync_status(_: bool = Depends(verify_admin)):
|
||||
"""检查当前配置与上次同步到 Vercel 的配置是否一致"""
|
||||
last_hash = CONFIG.get("_vercel_sync_hash", "")
|
||||
last_time = CONFIG.get("_vercel_sync_time", 0)
|
||||
current_hash = _compute_config_hash()
|
||||
|
||||
synced = bool(last_hash and last_hash == current_hash)
|
||||
|
||||
return JSONResponse(content={
|
||||
"synced": synced,
|
||||
"last_sync_time": last_time if last_time else None,
|
||||
"has_synced_before": bool(last_hash),
|
||||
})
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 导出配置
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
@@ -314,7 +314,7 @@ Remember: Output ONLY the JSON, no other text. The response must start with {{ a
|
||||
deepseek_resp.close()
|
||||
except Exception:
|
||||
pass
|
||||
cleanup_account(request)
|
||||
# 注意:不在此处调用 cleanup_account,由外层 finally 统一处理
|
||||
|
||||
return StreamingResponse(
|
||||
claude_sse_stream(),
|
||||
|
||||
174
routes/openai.py
174
routes/openai.py
@@ -194,6 +194,7 @@ IMPORTANT: If calling tools, output ONLY the JSON. The response must start with
|
||||
last_content_time = time.time() # 最后收到有效内容的时间
|
||||
keepalive_count = 0 # 连续 keepalive 计数
|
||||
has_content = False # 是否收到过内容
|
||||
stream_finished = False # 是否已发送过结束标记
|
||||
|
||||
def process_data():
|
||||
"""处理 DeepSeek SSE 数据流 - 使用 sse_parser 模块"""
|
||||
@@ -343,6 +344,7 @@ IMPORTANT: If calling tools, output ONLY the JSON. The response must start with
|
||||
yield f"data: {json.dumps(finish_chunk, ensure_ascii=False)}\n\n"
|
||||
yield "data: [DONE]\n\n"
|
||||
last_send_time = current_time
|
||||
stream_finished = True
|
||||
break
|
||||
|
||||
new_choices = []
|
||||
@@ -391,8 +393,8 @@ IMPORTANT: If calling tools, output ONLY the JSON. The response must start with
|
||||
except queue.Empty:
|
||||
continue
|
||||
|
||||
# 如果是超时退出,也发送结束标记
|
||||
if has_content:
|
||||
# 如果是超时退出且尚未发送结束标记,补发结束标记
|
||||
if has_content and not stream_finished:
|
||||
prompt_tokens = len(final_prompt) // 4
|
||||
thinking_tokens = len(final_thinking) // 4
|
||||
completion_tokens = len(final_text) // 4
|
||||
@@ -435,8 +437,7 @@ IMPORTANT: If calling tools, output ONLY the JSON. The response must start with
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"[sse_stream] 异常: {e}")
|
||||
finally:
|
||||
cleanup_account(request)
|
||||
# 注意:不在此处调用 cleanup_account,由外层 finally 统一处理
|
||||
|
||||
return StreamingResponse(
|
||||
sse_stream(),
|
||||
@@ -453,107 +454,84 @@ IMPORTANT: If calling tools, output ONLY the JSON. The response must start with
|
||||
|
||||
def collect_data():
|
||||
nonlocal result
|
||||
ptype = "text"
|
||||
current_fragment_type = "thinking" if thinking_enabled else "text"
|
||||
try:
|
||||
for raw_line in deepseek_resp.iter_lines():
|
||||
try:
|
||||
line = raw_line.decode("utf-8")
|
||||
except Exception as e:
|
||||
logger.warning(f"[chat_completions] 解码失败: {e}")
|
||||
if ptype == "thinking":
|
||||
think_list.append("解码失败,请稍候再试")
|
||||
else:
|
||||
text_list.append("解码失败,请稍候再试")
|
||||
chunk = parse_deepseek_sse_line(raw_line)
|
||||
if not chunk:
|
||||
continue
|
||||
if chunk.get("type") == "done":
|
||||
data_queue.put(None)
|
||||
break
|
||||
if not line:
|
||||
continue
|
||||
if line.startswith("data:"):
|
||||
data_str = line[5:].strip()
|
||||
if data_str == "[DONE]":
|
||||
data_queue.put(None)
|
||||
break
|
||||
try:
|
||||
chunk = json.loads(data_str)
|
||||
if "v" in chunk:
|
||||
v_value = chunk["v"]
|
||||
if "p" in chunk and chunk.get("p") == "response/search_status":
|
||||
continue
|
||||
if "p" in chunk and chunk.get("p") == "response/thinking_content":
|
||||
ptype = "thinking"
|
||||
elif "p" in chunk and chunk.get("p") == "response/content":
|
||||
ptype = "text"
|
||||
if isinstance(v_value, str):
|
||||
if search_enabled and v_value.startswith("[citation:"):
|
||||
continue
|
||||
if ptype == "thinking":
|
||||
think_list.append(v_value)
|
||||
else:
|
||||
text_list.append(v_value)
|
||||
elif isinstance(v_value, list):
|
||||
for item in v_value:
|
||||
if item.get("p") == "status" and item.get("v") == "FINISHED":
|
||||
final_reasoning = "".join(think_list)
|
||||
final_content = "".join(text_list)
|
||||
prompt_tokens = len(final_prompt) // 4
|
||||
reasoning_tokens = len(final_reasoning) // 4
|
||||
completion_tokens = len(final_content) // 4
|
||||
|
||||
# 检测工具调用
|
||||
detected_tools = []
|
||||
finish_reason = "stop"
|
||||
if has_tools:
|
||||
detected_tools = parse_tool_calls(final_content, [{"name": t.get("function", t).get("name")} for t in tools_requested])
|
||||
if detected_tools:
|
||||
finish_reason = "tool_calls"
|
||||
|
||||
# 构建 message 对象
|
||||
message_obj = {
|
||||
"role": "assistant",
|
||||
"content": final_content if not detected_tools else None,
|
||||
}
|
||||
# 只有启用思考模式时才包含 reasoning_content
|
||||
if thinking_enabled and final_reasoning:
|
||||
message_obj["reasoning_content"] = final_reasoning
|
||||
# 添加工具调用
|
||||
if detected_tools:
|
||||
tool_calls_data = format_openai_tool_calls(detected_tools)
|
||||
message_obj["tool_calls"] = tool_calls_data
|
||||
message_obj["content"] = None
|
||||
|
||||
result = {
|
||||
"id": completion_id,
|
||||
"object": "chat.completion",
|
||||
"created": created_time,
|
||||
"model": model,
|
||||
"choices": [{
|
||||
"index": 0,
|
||||
"message": message_obj,
|
||||
"finish_reason": finish_reason,
|
||||
}],
|
||||
"usage": {
|
||||
"prompt_tokens": prompt_tokens,
|
||||
"completion_tokens": reasoning_tokens + completion_tokens,
|
||||
"total_tokens": prompt_tokens + reasoning_tokens + completion_tokens,
|
||||
"completion_tokens_details": {"reasoning_tokens": reasoning_tokens},
|
||||
},
|
||||
}
|
||||
data_queue.put("DONE")
|
||||
return
|
||||
except Exception as e:
|
||||
logger.warning(f"[collect_data] 无法解析: {data_str}, 错误: {e}")
|
||||
if ptype == "thinking":
|
||||
think_list.append("解析失败,请稍候再试")
|
||||
try:
|
||||
contents, is_finished, new_fragment_type = parse_sse_chunk_for_content(
|
||||
chunk, thinking_enabled, current_fragment_type
|
||||
)
|
||||
current_fragment_type = new_fragment_type
|
||||
if is_finished:
|
||||
final_reasoning = "".join(think_list)
|
||||
final_content = "".join(text_list)
|
||||
prompt_tokens = len(final_prompt) // 4
|
||||
reasoning_tokens = len(final_reasoning) // 4
|
||||
completion_tokens = len(final_content) // 4
|
||||
|
||||
# 检测工具调用
|
||||
detected_tools = []
|
||||
finish_reason = "stop"
|
||||
if has_tools:
|
||||
detected_tools = parse_tool_calls(final_content, [{"name": t.get("function", t).get("name")} for t in tools_requested])
|
||||
if detected_tools:
|
||||
finish_reason = "tool_calls"
|
||||
|
||||
# 构建 message 对象
|
||||
message_obj = {
|
||||
"role": "assistant",
|
||||
"content": final_content if not detected_tools else None,
|
||||
}
|
||||
# 只有启用思考模式时才包含 reasoning_content
|
||||
if thinking_enabled and final_reasoning:
|
||||
message_obj["reasoning_content"] = final_reasoning
|
||||
# 添加工具调用
|
||||
if detected_tools:
|
||||
tool_calls_data = format_openai_tool_calls(detected_tools)
|
||||
message_obj["tool_calls"] = tool_calls_data
|
||||
message_obj["content"] = None
|
||||
|
||||
result = {
|
||||
"id": completion_id,
|
||||
"object": "chat.completion",
|
||||
"created": created_time,
|
||||
"model": model,
|
||||
"choices": [{
|
||||
"index": 0,
|
||||
"message": message_obj,
|
||||
"finish_reason": finish_reason,
|
||||
}],
|
||||
"usage": {
|
||||
"prompt_tokens": prompt_tokens,
|
||||
"completion_tokens": reasoning_tokens + completion_tokens,
|
||||
"total_tokens": prompt_tokens + reasoning_tokens + completion_tokens,
|
||||
"completion_tokens_details": {"reasoning_tokens": reasoning_tokens},
|
||||
},
|
||||
}
|
||||
data_queue.put("DONE")
|
||||
return
|
||||
|
||||
for content_text, content_type in contents:
|
||||
if should_filter_citation(content_text, search_enabled):
|
||||
continue
|
||||
if content_type == "thinking":
|
||||
think_list.append(content_text)
|
||||
else:
|
||||
text_list.append("解析失败,请稍候再试")
|
||||
data_queue.put(None)
|
||||
break
|
||||
text_list.append(content_text)
|
||||
except Exception as e:
|
||||
logger.warning(f"[collect_data] 无法解析: {chunk}, 错误: {e}")
|
||||
text_list.append("解析失败,请稍候再试")
|
||||
data_queue.put(None)
|
||||
break
|
||||
except Exception as e:
|
||||
logger.warning(f"[collect_data] 错误: {e}")
|
||||
if ptype == "thinking":
|
||||
think_list.append("处理失败,请稍候再试")
|
||||
else:
|
||||
text_list.append("处理失败,请稍候再试")
|
||||
text_list.append("处理失败,请稍候再试")
|
||||
data_queue.put(None)
|
||||
finally:
|
||||
deepseek_resp.close()
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
|
||||
@@ -6,16 +6,16 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
|
||||
<!-- SEO Meta Tags -->
|
||||
<title>DS2API - DeepSeek API 管理面板</title>
|
||||
<meta name="description" content="DS2API 管理面板 - 轻松管理 DeepSeek 账号、测试 API、同步 Vercel 配置" />
|
||||
<meta name="keywords" content="DeepSeek, API, OpenAI, 管理面板, DS2API" />
|
||||
<title>DS2API - 管理面板 / Admin Console</title>
|
||||
<meta name="description" content="DS2API 管理面板:管理 DeepSeek 账号、测试 API、同步 Vercel 配置 / Admin console for accounts, API tests, and Vercel sync." />
|
||||
<meta name="keywords" content="DeepSeek, API, OpenAI, 管理面板, admin console, DS2API" />
|
||||
<meta name="author" content="CJackHwang" />
|
||||
<meta name="robots" content="noindex, nofollow" />
|
||||
|
||||
<!-- Open Graph / Social -->
|
||||
<meta property="og:type" content="website" />
|
||||
<meta property="og:title" content="DS2API - DeepSeek API 管理面板" />
|
||||
<meta property="og:description" content="轻松管理 DeepSeek 账号、测试 API、同步 Vercel 配置" />
|
||||
<meta property="og:title" content="DS2API - 管理面板 / Admin Console" />
|
||||
<meta property="og:description" content="Manage DeepSeek accounts, test the API, and sync Vercel configuration." />
|
||||
<meta property="og:site_name" content="DS2API" />
|
||||
|
||||
<!-- PWA / Mobile -->
|
||||
@@ -39,4 +39,4 @@
|
||||
<script type="module" src="/src/main.jsx"></script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
</html>
|
||||
|
||||
@@ -25,19 +25,22 @@ import BatchImport from './components/BatchImport'
|
||||
import VercelSync from './components/VercelSync'
|
||||
import Login from './components/Login'
|
||||
import LandingPage from './components/LandingPage'
|
||||
|
||||
const NAV_ITEMS = [
|
||||
{ id: 'accounts', label: '账号管理', icon: Users, description: '管理 DeepSeek 账号池' },
|
||||
{ id: 'test', label: 'API 测试', icon: Server, description: '测试 API 连接与响应' },
|
||||
{ id: 'import', label: '批量导入', icon: Upload, description: '批量导入账号配置' },
|
||||
{ id: 'vercel', label: 'Vercel 同步', icon: Cloud, description: '同步配置到 Vercel' },
|
||||
]
|
||||
import LanguageToggle from './components/LanguageToggle'
|
||||
import { useI18n } from './i18n'
|
||||
|
||||
function Dashboard({ token, onLogout, config, fetchConfig, showMessage, message }) {
|
||||
const { t } = useI18n()
|
||||
const [activeTab, setActiveTab] = useState('accounts')
|
||||
const [sidebarOpen, setSidebarOpen] = useState(false)
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
const navItems = [
|
||||
{ id: 'accounts', label: t('nav.accounts.label'), icon: Users, description: t('nav.accounts.desc') },
|
||||
{ id: 'test', label: t('nav.test.label'), icon: Server, description: t('nav.test.desc') },
|
||||
{ id: 'import', label: t('nav.import.label'), icon: Upload, description: t('nav.import.desc') },
|
||||
{ id: 'vercel', label: t('nav.vercel.label'), icon: Cloud, description: t('nav.vercel.desc') },
|
||||
]
|
||||
|
||||
const authFetch = async (url, options = {}) => {
|
||||
const headers = {
|
||||
...options.headers,
|
||||
@@ -47,7 +50,7 @@ function Dashboard({ token, onLogout, config, fetchConfig, showMessage, message
|
||||
|
||||
if (res.status === 401) {
|
||||
onLogout()
|
||||
throw new Error('认证已过期,请重新登录')
|
||||
throw new Error(t('auth.expired'))
|
||||
}
|
||||
return res
|
||||
}
|
||||
@@ -87,11 +90,14 @@ function Dashboard({ token, onLogout, config, fetchConfig, showMessage, message
|
||||
</div>
|
||||
<span>DS2API</span>
|
||||
</div>
|
||||
<p className="text-[10px] text-muted-foreground mt-2 font-semibold tracking-[0.1em] uppercase opacity-60 px-1">在线管理面板</p>
|
||||
<div className="flex items-center justify-between mt-2">
|
||||
<p className="text-[10px] text-muted-foreground font-semibold tracking-[0.1em] uppercase opacity-60 px-1">{t('sidebar.onlineAdminConsole')}</p>
|
||||
<LanguageToggle />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<nav className="flex-1 px-3 space-y-1 overflow-y-auto pt-2">
|
||||
{NAV_ITEMS.map((item) => {
|
||||
{navItems.map((item) => {
|
||||
const Icon = item.icon
|
||||
const isActive = activeTab === item.id
|
||||
return (
|
||||
@@ -119,19 +125,19 @@ function Dashboard({ token, onLogout, config, fetchConfig, showMessage, message
|
||||
<div className="p-4 border-t border-border bg-card">
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between text-sm px-1">
|
||||
<span className="text-muted-foreground font-semibold text-[10px] uppercase tracking-wider">系统状态</span>
|
||||
<span className="text-muted-foreground font-semibold text-[10px] uppercase tracking-wider">{t('sidebar.systemStatus')}</span>
|
||||
<span className="flex items-center gap-1.5 text-[10px] font-bold text-emerald-500 bg-emerald-500/10 px-2 py-0.5 rounded-full border border-emerald-500/20">
|
||||
<span className="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse"></span>
|
||||
在线
|
||||
{t('sidebar.statusOnline')}
|
||||
</span>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<div className="bg-background rounded-lg p-3 border border-border shadow-sm">
|
||||
<div className="text-[9px] text-muted-foreground font-bold uppercase tracking-wider mb-0.5 opacity-70">账号</div>
|
||||
<div className="text-[9px] text-muted-foreground font-bold uppercase tracking-wider mb-0.5 opacity-70">{t('sidebar.accounts')}</div>
|
||||
<div className="text-lg font-bold text-foreground leading-tight">{config.accounts?.length || 0}</div>
|
||||
</div>
|
||||
<div className="bg-background rounded-lg p-3 border border-border shadow-sm">
|
||||
<div className="text-[9px] text-muted-foreground font-bold uppercase tracking-wider mb-0.5 opacity-70">密钥</div>
|
||||
<div className="text-[9px] text-muted-foreground font-bold uppercase tracking-wider mb-0.5 opacity-70">{t('sidebar.keys')}</div>
|
||||
<div className="text-lg font-bold text-foreground">{config.keys?.length || 0}</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -140,7 +146,7 @@ function Dashboard({ token, onLogout, config, fetchConfig, showMessage, message
|
||||
className="w-full h-10 flex items-center justify-center gap-2 rounded-lg border border-border text-xs font-medium text-muted-foreground hover:bg-destructive/10 hover:text-destructive hover:border-destructive/20 transition-all"
|
||||
>
|
||||
<LogOut className="w-3.5 h-3.5" />
|
||||
退出登录
|
||||
{t('sidebar.signOut')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -154,22 +160,25 @@ function Dashboard({ token, onLogout, config, fetchConfig, showMessage, message
|
||||
</div>
|
||||
<span className="font-semibold text-sm">DS2API</span>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setSidebarOpen(true)}
|
||||
className="p-2 -mr-2 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<Menu className="w-5 h-5" />
|
||||
</button>
|
||||
<div className="flex items-center gap-2">
|
||||
<LanguageToggle />
|
||||
<button
|
||||
onClick={() => setSidebarOpen(true)}
|
||||
className="p-2 -mr-2 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<Menu className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="flex-1 overflow-auto bg-background p-4 lg:p-10">
|
||||
<div className="max-w-6xl mx-auto space-y-4 lg:space-y-6">
|
||||
<div className="hidden lg:block mb-8">
|
||||
<h1 className="text-3xl font-bold tracking-tight mb-2">
|
||||
{NAV_ITEMS.find(n => n.id === activeTab)?.label}
|
||||
{navItems.find(n => n.id === activeTab)?.label}
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
{NAV_ITEMS.find(n => n.id === activeTab)?.description}
|
||||
{navItems.find(n => n.id === activeTab)?.description}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -195,6 +204,7 @@ function Dashboard({ token, onLogout, config, fetchConfig, showMessage, message
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
const { t } = useI18n()
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
const [config, setConfig] = useState({ keys: [], accounts: [] })
|
||||
@@ -207,7 +217,7 @@ export default function App() {
|
||||
const isAdminRoute = location.pathname.startsWith('/admin') || isProduction
|
||||
|
||||
useEffect(() => {
|
||||
// 只在 admin 路由时检查登录状态
|
||||
// Only check auth status on admin routes.
|
||||
if (!isAdminRoute) {
|
||||
setAuthChecking(false)
|
||||
return
|
||||
@@ -248,8 +258,8 @@ export default function App() {
|
||||
setConfig(data)
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('获取配置失败:', e)
|
||||
showMessage('error', e.message)
|
||||
console.error('Failed to fetch config:', e)
|
||||
showMessage('error', t('errors.fetchConfig', { error: e.message }))
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
@@ -278,13 +288,13 @@ export default function App() {
|
||||
sessionStorage.removeItem('ds2api_token_expires')
|
||||
}
|
||||
|
||||
// 在 admin 路由时,等待认证检查完成
|
||||
// Wait for auth checks on admin routes.
|
||||
if (isAdminRoute && authChecking) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-background">
|
||||
<div className="flex flex-col items-center gap-4">
|
||||
<div className="w-8 h-8 border-4 border-primary border-t-transparent rounded-full animate-spin"></div>
|
||||
<p className="text-muted-foreground animate-pulse">正在检查登录状态...</p>
|
||||
<p className="text-muted-foreground animate-pulse">{t('auth.checking')}</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -8,11 +8,16 @@ import {
|
||||
Server,
|
||||
ShieldCheck,
|
||||
Copy,
|
||||
Check
|
||||
Check,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
ChevronDown
|
||||
} from 'lucide-react'
|
||||
import clsx from 'clsx'
|
||||
import { useI18n } from '../i18n'
|
||||
|
||||
export default function AccountManager({ config, onRefresh, onMessage, authFetch }) {
|
||||
const { t } = useI18n()
|
||||
const [showAddKey, setShowAddKey] = useState(false)
|
||||
const [showAddAccount, setShowAddAccount] = useState(false)
|
||||
const [newKey, setNewKey] = useState('')
|
||||
@@ -23,9 +28,36 @@ export default function AccountManager({ config, onRefresh, onMessage, authFetch
|
||||
const [testingAll, setTestingAll] = useState(false)
|
||||
const [batchProgress, setBatchProgress] = useState({ current: 0, total: 0, results: [] })
|
||||
const [queueStatus, setQueueStatus] = useState(null)
|
||||
const [keysExpanded, setKeysExpanded] = useState(false)
|
||||
|
||||
// 分页状态
|
||||
const [accounts, setAccounts] = useState([])
|
||||
const [page, setPage] = useState(1)
|
||||
const [pageSize] = useState(10)
|
||||
const [totalPages, setTotalPages] = useState(1)
|
||||
const [totalAccounts, setTotalAccounts] = useState(0)
|
||||
const [loadingAccounts, setLoadingAccounts] = useState(false)
|
||||
|
||||
const apiFetch = authFetch || fetch
|
||||
|
||||
const fetchAccounts = async (targetPage = page) => {
|
||||
setLoadingAccounts(true)
|
||||
try {
|
||||
const res = await apiFetch(`/admin/accounts?page=${targetPage}&page_size=${pageSize}`)
|
||||
if (res.ok) {
|
||||
const data = await res.json()
|
||||
setAccounts(data.items || [])
|
||||
setTotalPages(data.total_pages || 1)
|
||||
setTotalAccounts(data.total || 0)
|
||||
setPage(data.page || 1)
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to fetch accounts:', e)
|
||||
} finally {
|
||||
setLoadingAccounts(false)
|
||||
}
|
||||
}
|
||||
|
||||
const fetchQueueStatus = async () => {
|
||||
try {
|
||||
const res = await apiFetch('/admin/queue/status')
|
||||
@@ -39,6 +71,7 @@ export default function AccountManager({ config, onRefresh, onMessage, authFetch
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
fetchAccounts()
|
||||
fetchQueueStatus()
|
||||
const interval = setInterval(fetchQueueStatus, 5000)
|
||||
return () => clearInterval(interval)
|
||||
@@ -54,39 +87,39 @@ export default function AccountManager({ config, onRefresh, onMessage, authFetch
|
||||
body: JSON.stringify({ key: newKey.trim() }),
|
||||
})
|
||||
if (res.ok) {
|
||||
onMessage('success', 'API 密钥添加成功')
|
||||
onMessage('success', t('accountManager.addKeySuccess'))
|
||||
setNewKey('')
|
||||
setShowAddKey(false)
|
||||
onRefresh()
|
||||
} else {
|
||||
const data = await res.json()
|
||||
onMessage('error', data.detail || 'Failed to add')
|
||||
onMessage('error', data.detail || t('messages.failedToAdd'))
|
||||
}
|
||||
} catch (e) {
|
||||
onMessage('error', '网络错误')
|
||||
onMessage('error', t('messages.networkError'))
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const deleteKey = async (key) => {
|
||||
if (!confirm('确定要删除此 API 密钥吗?')) return
|
||||
if (!confirm(t('accountManager.deleteKeyConfirm'))) return
|
||||
try {
|
||||
const res = await apiFetch(`/admin/keys/${encodeURIComponent(key)}`, { method: 'DELETE' })
|
||||
if (res.ok) {
|
||||
onMessage('success', 'Deleted successfully')
|
||||
onMessage('success', t('messages.deleted'))
|
||||
onRefresh()
|
||||
} else {
|
||||
onMessage('error', 'Delete failed')
|
||||
onMessage('error', t('messages.deleteFailed'))
|
||||
}
|
||||
} catch (e) {
|
||||
onMessage('error', 'Network error')
|
||||
onMessage('error', t('messages.networkError'))
|
||||
}
|
||||
}
|
||||
|
||||
const addAccount = async () => {
|
||||
if (!newAccount.password || (!newAccount.email && !newAccount.mobile)) {
|
||||
onMessage('error', 'Password and Email/Mobile are required')
|
||||
onMessage('error', t('accountManager.requiredFields'))
|
||||
return
|
||||
}
|
||||
setLoading(true)
|
||||
@@ -97,33 +130,35 @@ export default function AccountManager({ config, onRefresh, onMessage, authFetch
|
||||
body: JSON.stringify(newAccount),
|
||||
})
|
||||
if (res.ok) {
|
||||
onMessage('success', '账号添加成功')
|
||||
onMessage('success', t('accountManager.addAccountSuccess'))
|
||||
setNewAccount({ email: '', mobile: '', password: '' })
|
||||
setShowAddAccount(false)
|
||||
fetchAccounts(1) // 添加后回到第一页
|
||||
onRefresh()
|
||||
} else {
|
||||
const data = await res.json()
|
||||
onMessage('error', data.detail || 'Failed to add')
|
||||
onMessage('error', data.detail || t('messages.failedToAdd'))
|
||||
}
|
||||
} catch (e) {
|
||||
onMessage('error', '网络错误')
|
||||
onMessage('error', t('messages.networkError'))
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const deleteAccount = async (id) => {
|
||||
if (!confirm('确定要删除此账号吗?')) return
|
||||
if (!confirm(t('accountManager.deleteAccountConfirm'))) return
|
||||
try {
|
||||
const res = await apiFetch(`/admin/accounts/${encodeURIComponent(id)}`, { method: 'DELETE' })
|
||||
if (res.ok) {
|
||||
onMessage('success', 'Deleted successfully')
|
||||
onMessage('success', t('messages.deleted'))
|
||||
fetchAccounts() // 刷新当前页
|
||||
onRefresh()
|
||||
} else {
|
||||
onMessage('error', 'Delete failed')
|
||||
onMessage('error', t('messages.deleteFailed'))
|
||||
}
|
||||
} catch (e) {
|
||||
onMessage('error', 'Network error')
|
||||
onMessage('error', t('messages.networkError'))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -136,28 +171,32 @@ export default function AccountManager({ config, onRefresh, onMessage, authFetch
|
||||
body: JSON.stringify({ identifier }),
|
||||
})
|
||||
const data = await res.json()
|
||||
onMessage(data.success ? 'success' : 'error', `${identifier}: ${data.success ? `Success (${data.response_time}ms)` : data.message}`)
|
||||
const statusMessage = data.success
|
||||
? t('apiTester.testSuccess', { account: identifier, time: data.response_time })
|
||||
: `${identifier}: ${data.message}`
|
||||
onMessage(data.success ? 'success' : 'error', statusMessage)
|
||||
fetchAccounts() // 刷新当前页
|
||||
onRefresh()
|
||||
} catch (e) {
|
||||
onMessage('error', 'Test failed: ' + e.message)
|
||||
onMessage('error', t('accountManager.testFailed', { error: e.message }))
|
||||
} finally {
|
||||
setTesting(prev => ({ ...prev, [identifier]: false }))
|
||||
}
|
||||
}
|
||||
|
||||
const testAllAccounts = async () => {
|
||||
if (!confirm('测试所有账号的 API 连通性?')) return
|
||||
const accounts = config.accounts || []
|
||||
if (accounts.length === 0) return
|
||||
if (!confirm(t('accountManager.testAllConfirm'))) return
|
||||
const allAccounts = config.accounts || []
|
||||
if (allAccounts.length === 0) return
|
||||
|
||||
setTestingAll(true)
|
||||
setBatchProgress({ current: 0, total: accounts.length, results: [] })
|
||||
setBatchProgress({ current: 0, total: allAccounts.length, results: [] })
|
||||
|
||||
let successCount = 0
|
||||
const results = []
|
||||
|
||||
for (let i = 0; i < accounts.length; i++) {
|
||||
const acc = accounts[i]
|
||||
for (let i = 0; i < allAccounts.length; i++) {
|
||||
const acc = allAccounts[i]
|
||||
const id = acc.email || acc.mobile
|
||||
|
||||
try {
|
||||
@@ -173,10 +212,11 @@ export default function AccountManager({ config, onRefresh, onMessage, authFetch
|
||||
results.push({ id, success: false, message: e.message })
|
||||
}
|
||||
|
||||
setBatchProgress({ current: i + 1, total: accounts.length, results: [...results] })
|
||||
setBatchProgress({ current: i + 1, total: allAccounts.length, results: [...results] })
|
||||
}
|
||||
|
||||
onMessage('success', `Completed: ${successCount}/${accounts.length} available`)
|
||||
onMessage('success', t('accountManager.testAllCompleted', { success: successCount, total: allAccounts.length }))
|
||||
fetchAccounts() // 刷新当前页
|
||||
onRefresh()
|
||||
setTestingAll(false)
|
||||
}
|
||||
@@ -191,30 +231,30 @@ export default function AccountManager({ config, onRefresh, onMessage, authFetch
|
||||
<div className="absolute right-0 top-0 p-4 opacity-5 group-hover:opacity-10 transition-opacity">
|
||||
<CheckCircle2 className="w-16 h-16" />
|
||||
</div>
|
||||
<p className="text-xs font-medium text-muted-foreground uppercase tracking-widest">可用</p>
|
||||
<p className="text-xs font-medium text-muted-foreground uppercase tracking-widest">{t('accountManager.available')}</p>
|
||||
<div className="mt-2 flex items-baseline gap-2">
|
||||
<span className="text-3xl font-bold text-foreground">{queueStatus.available}</span>
|
||||
<span className="text-xs text-muted-foreground">个账号</span>
|
||||
<span className="text-xs text-muted-foreground">{t('accountManager.accountsUnit')}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-card border border-border rounded-xl p-4 flex flex-col justify-between shadow-sm relative overflow-hidden group">
|
||||
<div className="absolute right-0 top-0 p-4 opacity-5 group-hover:opacity-10 transition-opacity">
|
||||
<Server className="w-16 h-16" />
|
||||
</div>
|
||||
<p className="text-xs font-medium text-muted-foreground uppercase tracking-widest">正在使用</p>
|
||||
<p className="text-xs font-medium text-muted-foreground uppercase tracking-widest">{t('accountManager.inUse')}</p>
|
||||
<div className="mt-2 flex items-baseline gap-2">
|
||||
<span className="text-3xl font-bold text-foreground">{queueStatus.in_use}</span>
|
||||
<span className="text-xs text-muted-foreground">线程</span>
|
||||
<span className="text-xs text-muted-foreground">{t('accountManager.threadsUnit')}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-card border border-border rounded-xl p-4 flex flex-col justify-between shadow-sm relative overflow-hidden group">
|
||||
<div className="absolute right-0 top-0 p-4 opacity-5 group-hover:opacity-10 transition-opacity">
|
||||
<ShieldCheck className="w-16 h-16" />
|
||||
</div>
|
||||
<p className="text-xs font-medium text-muted-foreground uppercase tracking-widest">账号池总数</p>
|
||||
<p className="text-xs font-medium text-muted-foreground uppercase tracking-widest">{t('accountManager.totalPool')}</p>
|
||||
<div className="mt-2 flex items-baseline gap-2">
|
||||
<span className="text-3xl font-bold text-foreground">{queueStatus.total}</span>
|
||||
<span className="text-xs text-muted-foreground">个账号</span>
|
||||
<span className="text-xs text-muted-foreground">{t('accountManager.accountsUnit')}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -223,82 +263,93 @@ export default function AccountManager({ config, onRefresh, onMessage, authFetch
|
||||
|
||||
{/* API Keys Section */}
|
||||
<div className="bg-card border border-border rounded-xl overflow-hidden shadow-sm">
|
||||
<div className="p-6 border-b border-border flex flex-col md:flex-row md:items-center justify-between gap-4">
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold">API 密钥</h2>
|
||||
<p className="text-sm text-muted-foreground">管理 API 访问密钥池</p>
|
||||
<div
|
||||
className="p-6 flex flex-col md:flex-row md:items-center justify-between gap-4 cursor-pointer select-none hover:bg-muted/30 transition-colors"
|
||||
onClick={() => setKeysExpanded(!keysExpanded)}
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<ChevronDown className={clsx(
|
||||
"w-5 h-5 text-muted-foreground transition-transform duration-200",
|
||||
keysExpanded ? "rotate-0" : "-rotate-90"
|
||||
)} />
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold">{t('accountManager.apiKeysTitle')}</h2>
|
||||
<p className="text-sm text-muted-foreground">{t('accountManager.apiKeysDesc')} ({config.keys?.length || 0})</p>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setShowAddKey(true)}
|
||||
onClick={(e) => { e.stopPropagation(); setShowAddKey(true) }}
|
||||
className="flex items-center gap-2 px-4 py-2 bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 transition-colors font-medium text-sm shadow-sm"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
添加密钥
|
||||
{t('accountManager.addKey')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="divide-y divide-border">
|
||||
{config.keys?.length > 0 ? (
|
||||
config.keys.map((key, i) => (
|
||||
<div key={i} className="p-4 flex items-center justify-between hover:bg-muted/50 transition-colors group">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="font-mono text-sm bg-muted/50 px-3 py-1 rounded inline-block">
|
||||
{key.slice(0, 16)}****
|
||||
{keysExpanded && (
|
||||
<div className="divide-y divide-border border-t border-border">
|
||||
{config.keys?.length > 0 ? (
|
||||
config.keys.map((key, i) => (
|
||||
<div key={i} className="p-4 flex items-center justify-between hover:bg-muted/50 transition-colors group">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="font-mono text-sm bg-muted/50 px-3 py-1 rounded inline-block">
|
||||
{key.slice(0, 16)}****
|
||||
</div>
|
||||
{copiedKey === key && (
|
||||
<span className="text-xs text-green-500 animate-pulse">{t('accountManager.copied')}</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<button
|
||||
onClick={() => {
|
||||
navigator.clipboard.writeText(key)
|
||||
setCopiedKey(key)
|
||||
setTimeout(() => setCopiedKey(null), 2000)
|
||||
}}
|
||||
className="p-2 text-muted-foreground hover:text-primary hover:bg-primary/10 rounded-md transition-colors opacity-0 group-hover:opacity-100"
|
||||
title={t('accountManager.copyKeyTitle')}
|
||||
>
|
||||
{copiedKey === key ? <Check className="w-4 h-4 text-green-500" /> : <Copy className="w-4 h-4" />}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => deleteKey(key)}
|
||||
className="p-2 text-muted-foreground hover:text-destructive hover:bg-destructive/10 rounded-md transition-colors opacity-0 group-hover:opacity-100"
|
||||
title={t('accountManager.deleteKeyTitle')}
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
{copiedKey === key && (
|
||||
<span className="text-xs text-green-500 animate-pulse">已复制</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<button
|
||||
onClick={() => {
|
||||
navigator.clipboard.writeText(key)
|
||||
setCopiedKey(key)
|
||||
setTimeout(() => setCopiedKey(null), 2000)
|
||||
}}
|
||||
className="p-2 text-muted-foreground hover:text-primary hover:bg-primary/10 rounded-md transition-colors opacity-0 group-hover:opacity-100"
|
||||
title="复制密钥"
|
||||
>
|
||||
{copiedKey === key ? <Check className="w-4 h-4 text-green-500" /> : <Copy className="w-4 h-4" />}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => deleteKey(key)}
|
||||
className="p-2 text-muted-foreground hover:text-destructive hover:bg-destructive/10 rounded-md transition-colors opacity-0 group-hover:opacity-100"
|
||||
title="删除密钥"
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
) : (
|
||||
<div className="p-8 text-center text-muted-foreground">未找到 API 密钥</div>
|
||||
)}
|
||||
</div>
|
||||
))
|
||||
) : (
|
||||
<div className="p-8 text-center text-muted-foreground">{t('accountManager.noApiKeys')}</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Accounts Section */}
|
||||
<div className="bg-card border border-border rounded-xl overflow-hidden shadow-sm">
|
||||
<div className="p-6 border-b border-border flex flex-col md:flex-row md:items-center justify-between gap-4">
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold">DeepSeek 账号</h2>
|
||||
<p className="text-sm text-muted-foreground">管理 DeepSeek 账号池</p>
|
||||
<h2 className="text-lg font-semibold">{t('accountManager.accountsTitle')}</h2>
|
||||
<p className="text-sm text-muted-foreground">{t('accountManager.accountsDesc')}</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<button
|
||||
onClick={testAllAccounts}
|
||||
disabled={testingAll || !config.accounts?.length}
|
||||
disabled={testingAll || totalAccounts === 0}
|
||||
className="flex items-center px-3 py-2 bg-secondary text-secondary-foreground rounded-lg hover:bg-secondary/80 transition-colors text-xs font-medium border border-border disabled:opacity-50"
|
||||
>
|
||||
{testingAll ? <span className="animate-spin mr-2">⟳</span> : <Play className="w-3 h-3 mr-2" />}
|
||||
测试全部
|
||||
{t('accountManager.testAll')}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setShowAddAccount(true)}
|
||||
className="flex items-center gap-2 px-4 py-2 bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 transition-colors font-medium text-sm shadow-sm"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
添加账号
|
||||
{t('accountManager.addAccount')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -307,7 +358,7 @@ export default function AccountManager({ config, onRefresh, onMessage, authFetch
|
||||
{testingAll && batchProgress.total > 0 && (
|
||||
<div className="p-4 border-b border-border bg-muted/30">
|
||||
<div className="flex items-center justify-between text-sm mb-2">
|
||||
<span className="font-medium">正在测试所有账号...</span>
|
||||
<span className="font-medium">{t('accountManager.testingAllAccounts')}</span>
|
||||
<span className="text-muted-foreground">{batchProgress.current} / {batchProgress.total}</span>
|
||||
</div>
|
||||
<div className="w-full bg-muted rounded-full h-2 overflow-hidden mb-4">
|
||||
@@ -332,8 +383,10 @@ export default function AccountManager({ config, onRefresh, onMessage, authFetch
|
||||
)}
|
||||
|
||||
<div className="divide-y divide-border">
|
||||
{config.accounts?.length > 0 ? (
|
||||
config.accounts.map((acc, i) => {
|
||||
{loadingAccounts ? (
|
||||
<div className="p-8 text-center text-muted-foreground">{t('actions.loading')}</div>
|
||||
) : accounts.length > 0 ? (
|
||||
accounts.map((acc, i) => {
|
||||
const id = acc.email || acc.mobile
|
||||
return (
|
||||
<div key={i} className="p-4 flex flex-col md:flex-row md:items-center justify-between gap-4 hover:bg-muted/50 transition-colors">
|
||||
@@ -345,7 +398,7 @@ export default function AccountManager({ config, onRefresh, onMessage, authFetch
|
||||
<div className="min-w-0">
|
||||
<div className="font-medium truncate">{id}</div>
|
||||
<div className="flex items-center gap-2 text-xs text-muted-foreground mt-0.5">
|
||||
<span>{acc.has_token ? '已建立会话' : '需重新登录'}</span>
|
||||
<span>{acc.has_token ? t('accountManager.sessionActive') : t('accountManager.reauthRequired')}</span>
|
||||
{acc.token_preview && (
|
||||
<span className="font-mono bg-muted px-1.5 py-0.5 rounded text-[10px]">
|
||||
{acc.token_preview}
|
||||
@@ -360,7 +413,7 @@ export default function AccountManager({ config, onRefresh, onMessage, authFetch
|
||||
disabled={testing[id]}
|
||||
className="px-2 lg:px-3 py-1 lg:py-1.5 text-[10px] lg:text-xs font-medium border border-border rounded-md hover:bg-secondary transition-colors disabled:opacity-50"
|
||||
>
|
||||
{testing[id] ? '正在测试...' : '测试'}
|
||||
{testing[id] ? t('actions.testing') : t('actions.test')}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => deleteAccount(id)}
|
||||
@@ -373,9 +426,35 @@ export default function AccountManager({ config, onRefresh, onMessage, authFetch
|
||||
)
|
||||
})
|
||||
) : (
|
||||
<div className="p-8 text-center text-muted-foreground">未找到任何账号</div>
|
||||
<div className="p-8 text-center text-muted-foreground">{t('accountManager.noAccounts')}</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 分页控件 */}
|
||||
{totalPages > 1 && (
|
||||
<div className="p-4 border-t border-border flex items-center justify-between">
|
||||
<div className="text-sm text-muted-foreground">
|
||||
{t('accountManager.pageInfo', { current: page, total: totalPages, count: totalAccounts })}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
onClick={() => fetchAccounts(page - 1)}
|
||||
disabled={page <= 1 || loadingAccounts}
|
||||
className="p-2 border border-border rounded-md hover:bg-secondary transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<ChevronLeft className="w-4 h-4" />
|
||||
</button>
|
||||
<span className="text-sm font-medium px-2">{page} / {totalPages}</span>
|
||||
<button
|
||||
onClick={() => fetchAccounts(page + 1)}
|
||||
disabled={page >= totalPages || loadingAccounts}
|
||||
className="p-2 border border-border rounded-md hover:bg-secondary transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<ChevronRight className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Modals */}
|
||||
@@ -384,19 +463,19 @@ export default function AccountManager({ config, onRefresh, onMessage, authFetch
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4 animate-in fade-in">
|
||||
<div className="bg-card w-full max-w-md rounded-xl border border-border shadow-2xl overflow-hidden animate-in zoom-in-95">
|
||||
<div className="p-4 border-b border-border flex justify-between items-center">
|
||||
<h3 className="font-semibold">添加 API 密钥</h3>
|
||||
<h3 className="font-semibold">{t('accountManager.modalAddKeyTitle')}</h3>
|
||||
<button onClick={() => setShowAddKey(false)} className="text-muted-foreground hover:text-foreground">
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="p-6 space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1.5">新密钥值</label>
|
||||
<label className="block text-sm font-medium mb-1.5">{t('accountManager.newKeyLabel')}</label>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
type="text"
|
||||
className="input-field bg-[#09090b] flex-1"
|
||||
placeholder="输入自定义 API 密钥"
|
||||
placeholder={t('accountManager.newKeyPlaceholder')}
|
||||
value={newKey}
|
||||
onChange={e => setNewKey(e.target.value)}
|
||||
autoFocus
|
||||
@@ -406,15 +485,15 @@ export default function AccountManager({ config, onRefresh, onMessage, authFetch
|
||||
onClick={() => setNewKey('sk-' + crypto.randomUUID().replace(/-/g, ''))}
|
||||
className="px-3 py-2 bg-secondary text-secondary-foreground rounded-lg hover:bg-secondary/80 transition-colors text-sm font-medium border border-border whitespace-nowrap"
|
||||
>
|
||||
生成
|
||||
{t('accountManager.generate')}
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground mt-1.5">点击「生成」自动创建随机密钥</p>
|
||||
<p className="text-xs text-muted-foreground mt-1.5">{t('accountManager.generateHint')}</p>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<button onClick={() => setShowAddKey(false)} className="px-4 py-2 rounded-lg border border-border hover:bg-secondary transition-colors text-sm font-medium">取消</button>
|
||||
<button onClick={() => setShowAddKey(false)} className="px-4 py-2 rounded-lg border border-border hover:bg-secondary transition-colors text-sm font-medium">{t('actions.cancel')}</button>
|
||||
<button onClick={addKey} disabled={loading} className="px-4 py-2 bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 transition-colors text-sm font-medium disabled:opacity-50">
|
||||
{loading ? '添加中...' : '添加密钥'}
|
||||
{loading ? t('accountManager.addKeyLoading') : t('accountManager.addKeyAction')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -428,14 +507,14 @@ export default function AccountManager({ config, onRefresh, onMessage, authFetch
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4 animate-in fade-in">
|
||||
<div className="bg-card w-full max-w-md rounded-xl border border-border shadow-2xl overflow-hidden animate-in zoom-in-95">
|
||||
<div className="p-4 border-b border-border flex justify-between items-center">
|
||||
<h3 className="font-semibold">添加 DeepSeek 账号</h3>
|
||||
<h3 className="font-semibold">{t('accountManager.modalAddAccountTitle')}</h3>
|
||||
<button onClick={() => setShowAddAccount(false)} className="text-muted-foreground hover:text-foreground">
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="p-6 space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1.5">邮箱 (可选)</label>
|
||||
<label className="block text-sm font-medium mb-1.5">{t('accountManager.emailOptional')}</label>
|
||||
<input
|
||||
type="email"
|
||||
className="input-field"
|
||||
@@ -445,7 +524,7 @@ export default function AccountManager({ config, onRefresh, onMessage, authFetch
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1.5">手机号 (可选)</label>
|
||||
<label className="block text-sm font-medium mb-1.5">{t('accountManager.mobileOptional')}</label>
|
||||
<input
|
||||
type="text"
|
||||
className="input-field"
|
||||
@@ -455,19 +534,19 @@ export default function AccountManager({ config, onRefresh, onMessage, authFetch
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1.5">密码 <span className="text-destructive">*</span></label>
|
||||
<label className="block text-sm font-medium mb-1.5">{t('accountManager.passwordLabel')} <span className="text-destructive">*</span></label>
|
||||
<input
|
||||
type="password"
|
||||
className="input-field bg-[#09090b]"
|
||||
placeholder="账号密码"
|
||||
placeholder={t('accountManager.passwordPlaceholder')}
|
||||
value={newAccount.password}
|
||||
onChange={e => setNewAccount({ ...newAccount, password: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<button onClick={() => setShowAddAccount(false)} className="px-4 py-2 rounded-lg border border-border hover:bg-secondary transition-colors text-sm font-medium">取消</button>
|
||||
<button onClick={() => setShowAddAccount(false)} className="px-4 py-2 rounded-lg border border-border hover:bg-secondary transition-colors text-sm font-medium">{t('actions.cancel')}</button>
|
||||
<button onClick={addAccount} disabled={loading} className="px-4 py-2 bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 transition-colors text-sm font-medium disabled:opacity-50">
|
||||
{loading ? '添加中...' : '添加账号'}
|
||||
{loading ? t('accountManager.addAccountLoading') : t('accountManager.addAccountAction')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, useRef } from 'react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import {
|
||||
Send,
|
||||
Square,
|
||||
@@ -14,20 +14,18 @@ import {
|
||||
ChevronDown,
|
||||
ShieldCheck,
|
||||
Terminal,
|
||||
Zap
|
||||
Zap,
|
||||
ToggleLeft,
|
||||
ToggleRight
|
||||
} from 'lucide-react'
|
||||
import clsx from 'clsx'
|
||||
|
||||
const MODELS = [
|
||||
{ id: "deepseek-chat", name: "deepseek-chat", icon: MessageSquare, desc: "非思考模型", color: "text-amber-500" },
|
||||
{ id: "deepseek-reasoner", name: "deepseek-reasoner", icon: Cpu, desc: "思考模型", color: "text-amber-600" },
|
||||
{ id: "deepseek-chat-search", name: "deepseek-chat-search", icon: SearchIcon, desc: "非思考模型 (带搜索)", color: "text-cyan-500" },
|
||||
{ id: "deepseek-reasoner-search", name: "deepseek-reasoner-search", icon: SearchIcon, desc: "思考模型 (带搜索)", color: "text-cyan-600" },
|
||||
];
|
||||
import { useI18n } from '../i18n'
|
||||
|
||||
export default function ApiTester({ config, onMessage, authFetch }) {
|
||||
const { t } = useI18n()
|
||||
const [model, setModel] = useState('deepseek-chat')
|
||||
const [message, setMessage] = useState('Hello, please introduce yourself in one sentence.')
|
||||
const defaultMessage = t('apiTester.defaultMessage')
|
||||
const [message, setMessage] = useState(defaultMessage)
|
||||
const [apiKey, setApiKey] = useState('')
|
||||
const [selectedAccount, setSelectedAccount] = useState('')
|
||||
const [response, setResponse] = useState(null)
|
||||
@@ -35,13 +33,21 @@ export default function ApiTester({ config, onMessage, authFetch }) {
|
||||
const [streamingContent, setStreamingContent] = useState('')
|
||||
const [streamingThinking, setStreamingThinking] = useState('')
|
||||
const [isStreaming, setIsStreaming] = useState(false)
|
||||
const [streamingMode, setStreamingMode] = useState(true)
|
||||
const abortControllerRef = useRef(null)
|
||||
const defaultMessageRef = useRef(defaultMessage)
|
||||
|
||||
const [sidebarOpen, setSidebarOpen] = useState(false)
|
||||
const [configExpanded, setConfigExpanded] = useState(false)
|
||||
|
||||
const apiFetch = authFetch || fetch
|
||||
const accounts = config.accounts || []
|
||||
const models = [
|
||||
{ id: "deepseek-chat", name: "deepseek-chat", icon: MessageSquare, desc: t('apiTester.models.chat'), color: "text-amber-500" },
|
||||
{ id: "deepseek-reasoner", name: "deepseek-reasoner", icon: Cpu, desc: t('apiTester.models.reasoner'), color: "text-amber-600" },
|
||||
{ id: "deepseek-chat-search", name: "deepseek-chat-search", icon: SearchIcon, desc: t('apiTester.models.chatSearch'), color: "text-cyan-500" },
|
||||
{ id: "deepseek-reasoner-search", name: "deepseek-reasoner-search", icon: SearchIcon, desc: t('apiTester.models.reasonerSearch'), color: "text-cyan-600" },
|
||||
]
|
||||
|
||||
const stopGeneration = () => {
|
||||
if (abortControllerRef.current) {
|
||||
@@ -52,7 +58,7 @@ export default function ApiTester({ config, onMessage, authFetch }) {
|
||||
setIsStreaming(false)
|
||||
}
|
||||
|
||||
const directTest = async () => {
|
||||
const runTest = async () => {
|
||||
if (loading) return
|
||||
|
||||
setLoading(true)
|
||||
@@ -66,81 +72,90 @@ export default function ApiTester({ config, onMessage, authFetch }) {
|
||||
try {
|
||||
const key = apiKey || (config.keys?.[0] || '')
|
||||
if (!key) {
|
||||
onMessage('error', '请提供 API 密钥')
|
||||
onMessage('error', t('apiTester.missingApiKey'))
|
||||
setLoading(false)
|
||||
setIsStreaming(false)
|
||||
return
|
||||
}
|
||||
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${key}`,
|
||||
}
|
||||
if (selectedAccount) {
|
||||
headers['X-Ds2-Target-Account'] = selectedAccount
|
||||
}
|
||||
|
||||
const res = await fetch('/v1/chat/completions', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${key}`,
|
||||
},
|
||||
headers,
|
||||
body: JSON.stringify({
|
||||
model,
|
||||
messages: [{ role: 'user', content: message }],
|
||||
stream: true,
|
||||
stream: streamingMode,
|
||||
}),
|
||||
signal: abortControllerRef.current.signal,
|
||||
})
|
||||
|
||||
if (!res.ok) {
|
||||
const data = await res.json()
|
||||
setResponse({ success: false, error: data.error?.message || '请求失败' })
|
||||
onMessage('error', data.error?.message || '请求失败')
|
||||
const data = await res.json().catch(() => ({}))
|
||||
const errorMsg = data.error?.message || t('apiTester.requestFailed')
|
||||
setResponse({ success: false, error: errorMsg })
|
||||
onMessage('error', errorMsg)
|
||||
setLoading(false)
|
||||
setIsStreaming(false)
|
||||
return
|
||||
}
|
||||
|
||||
setResponse({ success: true, status_code: res.status })
|
||||
if (streamingMode) {
|
||||
setResponse({ success: true, status_code: res.status })
|
||||
|
||||
const reader = res.body.getReader()
|
||||
const decoder = new TextDecoder()
|
||||
let buffer = ''
|
||||
const reader = res.body.getReader()
|
||||
const decoder = new TextDecoder()
|
||||
let buffer = ''
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) break
|
||||
while (true) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) break
|
||||
|
||||
buffer += decoder.decode(value, { stream: true })
|
||||
const lines = buffer.split('\n')
|
||||
buffer = lines.pop() || ''
|
||||
buffer += decoder.decode(value, { stream: true })
|
||||
const lines = buffer.split('\n')
|
||||
buffer = lines.pop() || ''
|
||||
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim()
|
||||
if (!trimmed || !trimmed.startsWith('data: ')) continue
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim()
|
||||
if (!trimmed || !trimmed.startsWith('data: ')) continue
|
||||
|
||||
const dataStr = trimmed.slice(6)
|
||||
if (dataStr === '[DONE]') continue
|
||||
const dataStr = trimmed.slice(6)
|
||||
if (dataStr === '[DONE]') continue
|
||||
|
||||
try {
|
||||
const json = JSON.parse(dataStr)
|
||||
console.log('[ApiTester] Parsed JSON:', json)
|
||||
const choice = json.choices?.[0]
|
||||
if (choice?.delta) {
|
||||
const delta = choice.delta
|
||||
console.log('[ApiTester] Delta:', delta)
|
||||
if (delta.reasoning_content) {
|
||||
setStreamingThinking(prev => prev + delta.reasoning_content)
|
||||
}
|
||||
if (delta.content) {
|
||||
console.log('[ApiTester] Content:', delta.content)
|
||||
setStreamingContent(prev => prev + delta.content)
|
||||
try {
|
||||
const json = JSON.parse(dataStr)
|
||||
const choice = json.choices?.[0]
|
||||
if (choice?.delta) {
|
||||
const delta = choice.delta
|
||||
if (delta.reasoning_content) {
|
||||
setStreamingThinking(prev => prev + delta.reasoning_content)
|
||||
}
|
||||
if (delta.content) {
|
||||
setStreamingContent(prev => prev + delta.content)
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Invalid JSON hunk:', dataStr, e)
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Invalid JSON hunk:', dataStr, e)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const data = await res.json()
|
||||
setResponse({ success: true, status_code: res.status, ...data })
|
||||
onMessage('success', t('apiTester.testSuccess', { account: selectedAccount || 'Auto', time: 'N/A' }))
|
||||
}
|
||||
} catch (e) {
|
||||
if (e.name === 'AbortError') {
|
||||
onMessage('info', '已停止生成')
|
||||
onMessage('info', t('messages.generationStopped'))
|
||||
} else {
|
||||
onMessage('error', '网络错误: ' + e.message)
|
||||
onMessage('error', t('apiTester.networkError', { error: e.message }))
|
||||
setResponse({ error: e.message, success: false })
|
||||
}
|
||||
} finally {
|
||||
@@ -150,251 +165,235 @@ export default function ApiTester({ config, onMessage, authFetch }) {
|
||||
}
|
||||
}
|
||||
|
||||
const sendTest = async () => {
|
||||
if (selectedAccount) {
|
||||
setLoading(true)
|
||||
setResponse(null)
|
||||
try {
|
||||
const res = await apiFetch('/admin/accounts/test', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
identifier: selectedAccount,
|
||||
model,
|
||||
message,
|
||||
}),
|
||||
})
|
||||
const data = await res.json()
|
||||
setResponse({
|
||||
success: data.success,
|
||||
status_code: res.status,
|
||||
response: data,
|
||||
account: selectedAccount,
|
||||
})
|
||||
if (data.success) {
|
||||
onMessage('success', `${selectedAccount}: 测试成功 (${data.response_time}ms)`)
|
||||
} else {
|
||||
onMessage('error', `${selectedAccount}: ${data.message}`)
|
||||
}
|
||||
} catch (e) {
|
||||
onMessage('error', '网络错误: ' + e.message)
|
||||
setResponse({ error: e.message })
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
return
|
||||
}
|
||||
useEffect(() => {
|
||||
setMessage((prev) => (prev === defaultMessageRef.current ? defaultMessage : prev))
|
||||
defaultMessageRef.current = defaultMessage
|
||||
}, [defaultMessage])
|
||||
|
||||
directTest()
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col lg:grid lg:grid-cols-12 gap-6 h-[calc(100vh-140px)]">
|
||||
{/* Configuration Panel */}
|
||||
<div className={clsx(
|
||||
"lg:col-span-3 flex flex-col transition-all duration-300 ease-in-out z-20",
|
||||
configExpanded ? "h-auto" : "h-14 lg:h-full"
|
||||
)}>
|
||||
<div className="bg-card border border-border rounded-xl flex flex-col h-full shadow-sm">
|
||||
{/* Mobile Toggle Header */}
|
||||
<button
|
||||
onClick={() => setConfigExpanded(!configExpanded)}
|
||||
className="lg:hidden flex items-center justify-between p-4 w-full bg-muted/20 hover:bg-muted/30 transition-colors"
|
||||
>
|
||||
<div className="flex items-center gap-2.5 font-medium text-sm text-foreground">
|
||||
<div className="p-1.5 rounded-md bg-transparent text-foreground">
|
||||
<Terminal className="w-4 h-4" />
|
||||
</div>
|
||||
<span>配置</span>
|
||||
</div>
|
||||
<div className={clsx("transition-transform duration-300 text-muted-foreground", configExpanded ? "rotate-180" : "")}>
|
||||
<ChevronDown className="w-4 h-4" />
|
||||
</div>
|
||||
</button>
|
||||
|
||||
<div className={clsx(
|
||||
"p-4 space-y-6 overflow-y-auto custom-scrollbar flex-1",
|
||||
!configExpanded && "hidden lg:block"
|
||||
)}>
|
||||
<div className="space-y-3">
|
||||
<label className="text-[11px] font-semibold text-muted-foreground uppercase tracking-wider ml-0.5">模型</label>
|
||||
<div className="grid grid-cols-1 gap-2">
|
||||
{MODELS.map(m => {
|
||||
const Icon = m.icon
|
||||
return (
|
||||
<button
|
||||
key={m.id}
|
||||
onClick={() => setModel(m.id)}
|
||||
className={clsx(
|
||||
"group relative flex items-start gap-3 p-3 rounded-lg border text-left transition-all duration-200",
|
||||
model === m.id
|
||||
? "bg-secondary border-primary/50 shadow-sm"
|
||||
: "bg-transparent border-transparent hover:bg-muted"
|
||||
)}
|
||||
>
|
||||
<div className={clsx(
|
||||
"p-1.5 rounded-md shrink-0 transition-colors",
|
||||
model === m.id ? m.color : "text-muted-foreground group-hover:text-foreground"
|
||||
)}>
|
||||
<Icon className="w-4 h-4" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className={clsx("font-medium text-sm", model === m.id ? "text-foreground" : "text-foreground/80")}>
|
||||
{m.name}
|
||||
</div>
|
||||
<div className="text-[11px] text-muted-foreground mt-0.5">{m.desc}</div>
|
||||
</div>
|
||||
{model === m.id && (
|
||||
<div className={clsx("absolute top-3 right-3", m.color)}>
|
||||
<div className="w-1.5 h-1.5 rounded-full bg-current" />
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="text-[11px] font-semibold text-muted-foreground uppercase tracking-wider ml-0.5">账号策略</label>
|
||||
<div className="relative">
|
||||
<select
|
||||
className="w-full h-10 pl-3 pr-8 bg-secondary border border-border rounded-lg text-sm appearance-none focus:outline-none focus:ring-1 focus:ring-ring focus:border-ring transition-all cursor-pointer hover:bg-muted"
|
||||
value={selectedAccount}
|
||||
onChange={e => setSelectedAccount(e.target.value)}
|
||||
>
|
||||
<option value="" className="bg-popover text-popover-foreground">🎲 随机切换 (支持流式预览)</option>
|
||||
{accounts.map((acc, i) => (
|
||||
<option key={i} value={acc.email || acc.mobile} className="bg-popover text-popover-foreground">
|
||||
👤 {acc.email || acc.mobile}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<ChevronDown className="absolute right-2.5 top-3 w-4 h-4 text-muted-foreground pointer-events-none" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="text-[11px] font-semibold text-muted-foreground uppercase tracking-wider ml-0.5">API 密钥 (可选)</label>
|
||||
<input
|
||||
type="password"
|
||||
className="w-full h-10 px-3 bg-muted/30 border border-border rounded-lg text-sm font-mono placeholder:text-muted-foreground/40 focus:outline-none focus:ring-1 focus:ring-ring focus:border-ring transition-all"
|
||||
placeholder={config.keys?.[0] ? `默认: ...${config.keys[0].slice(-6)}` : '输入自定义密钥'}
|
||||
value={apiKey}
|
||||
onChange={e => setApiKey(e.target.value)}
|
||||
/>
|
||||
return (
|
||||
<div className="flex flex-col lg:grid lg:grid-cols-12 gap-6 h-[calc(100vh-140px)]">
|
||||
{/* Configuration Panel */}
|
||||
<div className={clsx(
|
||||
"lg:col-span-3 flex flex-col transition-all duration-300 ease-in-out z-20",
|
||||
configExpanded ? "h-auto" : "h-14 lg:h-full"
|
||||
)}>
|
||||
<div className="bg-card border border-border rounded-xl flex flex-col h-full shadow-sm">
|
||||
{/* Mobile Toggle Header */}
|
||||
<button
|
||||
onClick={() => setConfigExpanded(!configExpanded)}
|
||||
className="lg:hidden flex items-center justify-between p-4 w-full bg-muted/20 hover:bg-muted/30 transition-colors"
|
||||
>
|
||||
<div className="flex items-center gap-2.5 font-medium text-sm text-foreground">
|
||||
<div className="p-1.5 rounded-md bg-transparent text-foreground">
|
||||
<Terminal className="w-4 h-4" />
|
||||
</div>
|
||||
<span>{t('apiTester.config')}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Chat Interface */}
|
||||
<div className="lg:col-span-9 flex flex-col bg-card border border-border rounded-xl shadow-sm overflow-hidden min-h-0 flex-1 relative">
|
||||
|
||||
{/* Messages Area */}
|
||||
<div className="flex-1 overflow-y-auto p-4 lg:p-6 space-y-8 custom-scrollbar scroll-smooth">
|
||||
{/* User Message */}
|
||||
<div className="flex gap-4 max-w-4xl mx-auto flex-row-reverse group">
|
||||
<div className="w-8 h-8 rounded-lg bg-secondary flex items-center justify-center shrink-0 border border-border">
|
||||
<User className="w-4 h-4 text-muted-foreground" />
|
||||
</div>
|
||||
<div className="space-y-1 max-w-[85%] lg:max-w-[75%]">
|
||||
<div className="bg-primary text-primary-foreground rounded-2xl rounded-tr-sm px-5 py-3 text-sm leading-relaxed shadow-sm">
|
||||
{message}
|
||||
</div>
|
||||
</div>
|
||||
<div className={clsx("transition-transform duration-300 text-muted-foreground", configExpanded ? "rotate-180" : "")}>
|
||||
<ChevronDown className="w-4 h-4" />
|
||||
</div>
|
||||
</button>
|
||||
|
||||
{/* AI Response */}
|
||||
{(response || isStreaming) && (
|
||||
<div className="flex gap-4 max-w-4xl mx-auto animate-in fade-in slide-in-from-bottom-2 duration-300">
|
||||
<div className={clsx(
|
||||
"w-8 h-8 rounded-lg flex items-center justify-center shrink-0 border border-border",
|
||||
response?.success !== false ? "bg-muted" : "bg-destructive/10 border-destructive/20"
|
||||
)}>
|
||||
<Bot className={clsx("w-4 h-4", response?.success !== false ? "text-foreground" : "text-destructive")} />
|
||||
</div>
|
||||
<div className="space-y-3 flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-semibold text-sm text-foreground">
|
||||
DeepSeek
|
||||
</span>
|
||||
{response && (
|
||||
<span className={clsx(
|
||||
"text-[10px] px-1.5 py-0.5 rounded-sm border uppercase font-medium tracking-wider",
|
||||
response.success ? "border-emerald-500/20 text-emerald-500 bg-emerald-500/10" : "border-destructive/20 text-destructive bg-destructive/10"
|
||||
<div className={clsx(
|
||||
"p-4 space-y-6 overflow-y-auto custom-scrollbar flex-1",
|
||||
!configExpanded && "hidden lg:block"
|
||||
)}>
|
||||
<div className="space-y-3">
|
||||
<label className="text-[11px] font-semibold text-muted-foreground uppercase tracking-wider ml-0.5">{t('apiTester.modelLabel')}</label>
|
||||
<div className="grid grid-cols-1 gap-2">
|
||||
{models.map(m => {
|
||||
const Icon = m.icon
|
||||
return (
|
||||
<button
|
||||
key={m.id}
|
||||
onClick={() => setModel(m.id)}
|
||||
className={clsx(
|
||||
"group relative flex items-start gap-3 p-3 rounded-lg border text-left transition-all duration-200",
|
||||
model === m.id
|
||||
? "bg-secondary border-primary/50 shadow-sm"
|
||||
: "bg-transparent border-transparent hover:bg-muted"
|
||||
)}
|
||||
>
|
||||
<div className={clsx(
|
||||
"p-1.5 rounded-md shrink-0 transition-colors",
|
||||
model === m.id ? m.color : "text-muted-foreground group-hover:text-foreground"
|
||||
)}>
|
||||
{response.status_code || '错误'}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{(streamingThinking || response?.response?.thinking) && (
|
||||
<div className="text-xs bg-secondary/50 border border-border rounded-lg p-3 space-y-1.5">
|
||||
<div className="flex items-center gap-1.5 text-muted-foreground">
|
||||
<Zap className="w-3.5 h-3.5" />
|
||||
<span className="font-medium">思维链过程</span>
|
||||
<Icon className="w-4 h-4" />
|
||||
</div>
|
||||
<div className="whitespace-pre-wrap leading-relaxed text-muted-foreground font-mono text-[11px] max-h-60 overflow-y-auto custom-scrollbar pl-5 border-l-2 border-border/50">
|
||||
{streamingThinking || response?.response?.thinking}
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className={clsx("font-medium text-sm", model === m.id ? "text-foreground" : "text-foreground/80")}>
|
||||
{m.name}
|
||||
</div>
|
||||
<div className="text-[11px] text-muted-foreground mt-0.5">{m.desc}</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="text-sm leading-7 text-foreground whitespace-pre-wrap">
|
||||
{!selectedAccount ? (
|
||||
streamingContent || (response?.error && <span className="text-destructive font-medium">{response.error}</span>)
|
||||
) : (
|
||||
response?.response?.message || <span className="text-muted-foreground italic">正在生成响应...</span>
|
||||
)}
|
||||
{isStreaming && <span className="inline-block w-1.5 h-4 bg-primary ml-1 align-middle animate-pulse" />}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Input Area */}
|
||||
<div className="p-4 lg:p-6 border-t border-border bg-card">
|
||||
<div className="max-w-4xl mx-auto relative group">
|
||||
<textarea
|
||||
className="w-full bg-[#09090b] border border-border rounded-xl pl-4 pr-12 py-3 text-sm focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all resize-none custom-scrollbar placeholder:text-muted-foreground/50 text-foreground shadow-inner"
|
||||
placeholder="输入消息..."
|
||||
rows={1}
|
||||
style={{ minHeight: '52px' }}
|
||||
value={message}
|
||||
onChange={e => setMessage(e.target.value)}
|
||||
onKeyDown={e => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault()
|
||||
sendTest()
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<div className="absolute right-2 bottom-2">
|
||||
{loading && isStreaming ? (
|
||||
<button
|
||||
onClick={stopGeneration}
|
||||
className="p-2 text-muted-foreground hover:text-destructive transition-colors"
|
||||
>
|
||||
<Square className="w-4 h-4 fill-current" />
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
onClick={sendTest}
|
||||
disabled={loading || !message.trim()}
|
||||
className="p-2 text-primary hover:text-primary/80 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
{loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Send className="w-4 h-4" />}
|
||||
</button>
|
||||
)}
|
||||
{model === m.id && (
|
||||
<div className={clsx("absolute top-3 right-3", m.color)}>
|
||||
<div className="w-1.5 h-1.5 rounded-full bg-current" />
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
<div className="max-w-4xl mx-auto mt-3 flex justify-center">
|
||||
<span className="text-[10px] text-muted-foreground/40 font-medium">DeepSeek 管理员界面</span>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="text-[11px] font-semibold text-muted-foreground uppercase tracking-wider ml-0.5">{t('apiTester.streamMode')}</label>
|
||||
<button
|
||||
onClick={() => setStreamingMode(!streamingMode)}
|
||||
className={clsx(
|
||||
"w-full flex items-center justify-between px-3 py-2 rounded-lg border transition-all duration-200",
|
||||
streamingMode
|
||||
? "bg-primary/10 border-primary/50 text-foreground"
|
||||
: "bg-background border-border text-muted-foreground hover:bg-muted/50"
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className={clsx("p-1.5 rounded-md", streamingMode ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground")}>
|
||||
<Zap className="w-4 h-4" />
|
||||
</div>
|
||||
<span className="text-sm font-medium">{t('apiTester.streamMode')}</span>
|
||||
</div>
|
||||
{streamingMode ? <ToggleRight className="w-5 h-5 text-primary" /> : <ToggleLeft className="w-5 h-5 text-muted-foreground" />}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="text-[11px] font-semibold text-muted-foreground uppercase tracking-wider ml-0.5">{t('apiTester.accountSelector')}</label>
|
||||
<div className="relative">
|
||||
<select
|
||||
className="w-full h-10 pl-3 pr-8 bg-secondary border border-border rounded-lg text-sm appearance-none focus:outline-none focus:ring-1 focus:ring-ring focus:border-ring transition-all cursor-pointer hover:bg-muted"
|
||||
value={selectedAccount}
|
||||
onChange={e => setSelectedAccount(e.target.value)}
|
||||
>
|
||||
<option value="" className="bg-popover text-popover-foreground">{t('apiTester.autoRandom')}</option>
|
||||
{accounts.map((acc, i) => (
|
||||
<option key={i} value={acc.email || acc.mobile} className="bg-popover text-popover-foreground">
|
||||
👤 {acc.email || acc.mobile}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<ChevronDown className="absolute right-2.5 top-3 w-4 h-4 text-muted-foreground pointer-events-none" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="text-[11px] font-semibold text-muted-foreground uppercase tracking-wider ml-0.5">{t('apiTester.apiKeyOptional')}</label>
|
||||
<input
|
||||
type="password"
|
||||
className="w-full h-10 px-3 bg-muted/30 border border-border rounded-lg text-sm font-mono placeholder:text-muted-foreground/40 focus:outline-none focus:ring-1 focus:ring-ring focus:border-ring transition-all"
|
||||
placeholder={config.keys?.[0] ? t('apiTester.apiKeyDefault', { suffix: config.keys[0].slice(-6) }) : t('apiTester.apiKeyPlaceholder')}
|
||||
value={apiKey}
|
||||
onChange={e => setApiKey(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
{/* Chat Interface */}
|
||||
<div className="lg:col-span-9 flex flex-col bg-card border border-border rounded-xl shadow-sm overflow-hidden min-h-0 flex-1 relative">
|
||||
|
||||
{/* Messages Area */}
|
||||
<div className="flex-1 overflow-y-auto p-4 lg:p-6 space-y-8 custom-scrollbar scroll-smooth">
|
||||
{/* User Message */}
|
||||
<div className="flex gap-4 max-w-4xl mx-auto flex-row-reverse group">
|
||||
<div className="w-8 h-8 rounded-lg bg-secondary flex items-center justify-center shrink-0 border border-border">
|
||||
<User className="w-4 h-4 text-muted-foreground" />
|
||||
</div>
|
||||
<div className="space-y-1 max-w-[85%] lg:max-w-[75%]">
|
||||
<div className="bg-primary text-primary-foreground rounded-2xl rounded-tr-sm px-5 py-3 text-sm leading-relaxed shadow-sm">
|
||||
{message}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* AI Response */}
|
||||
{(response || isStreaming) && (
|
||||
<div className="flex gap-4 max-w-4xl mx-auto animate-in fade-in slide-in-from-bottom-2 duration-300">
|
||||
<div className={clsx(
|
||||
"w-8 h-8 rounded-lg flex items-center justify-center shrink-0 border border-border",
|
||||
response?.success !== false ? "bg-muted" : "bg-destructive/10 border-destructive/20"
|
||||
)}>
|
||||
<Bot className={clsx("w-4 h-4", response?.success !== false ? "text-foreground" : "text-destructive")} />
|
||||
</div>
|
||||
<div className="space-y-3 flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-semibold text-sm text-foreground">
|
||||
DeepSeek
|
||||
</span>
|
||||
{response && (
|
||||
<span className={clsx(
|
||||
"text-[10px] px-1.5 py-0.5 rounded-sm border uppercase font-medium tracking-wider",
|
||||
response.success ? "border-emerald-500/20 text-emerald-500 bg-emerald-500/10" : "border-destructive/20 text-destructive bg-destructive/10"
|
||||
)}>
|
||||
{response.status_code || t('apiTester.statusError')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{(streamingThinking || response?.choices?.[0]?.message?.reasoning_content) && (
|
||||
<div className="text-xs bg-secondary/50 border border-border rounded-lg p-3 space-y-1.5">
|
||||
<div className="flex items-center gap-1.5 text-muted-foreground">
|
||||
<Zap className="w-3.5 h-3.5" />
|
||||
<span className="font-medium">{t('apiTester.reasoningTrace')}</span>
|
||||
</div>
|
||||
<div className="whitespace-pre-wrap leading-relaxed text-muted-foreground font-mono text-[11px] max-h-60 overflow-y-auto custom-scrollbar pl-5 border-l-2 border-border/50">
|
||||
{streamingThinking || response?.choices?.[0]?.message?.reasoning_content}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="text-sm leading-7 text-foreground whitespace-pre-wrap">
|
||||
{streamingContent || response?.choices?.[0]?.message?.content || (response?.error && <span className="text-destructive font-medium">{response.error}</span>) || (loading && <span className="text-muted-foreground italic">{t('apiTester.generating')}</span>)}
|
||||
{isStreaming && <span className="inline-block w-1.5 h-4 bg-primary ml-1 align-middle animate-pulse" />}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Input Area */}
|
||||
<div className="p-4 lg:p-6 border-t border-border bg-card">
|
||||
<div className="max-w-4xl mx-auto relative group">
|
||||
<textarea
|
||||
className="w-full bg-[#09090b] border border-border rounded-xl pl-4 pr-12 py-3 text-sm focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all resize-none custom-scrollbar placeholder:text-muted-foreground/50 text-foreground shadow-inner"
|
||||
placeholder={t('apiTester.enterMessage')}
|
||||
rows={1}
|
||||
style={{ minHeight: '52px' }}
|
||||
value={message}
|
||||
onChange={e => setMessage(e.target.value)}
|
||||
onKeyDown={e => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault()
|
||||
runTest()
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<div className="absolute right-2 bottom-2">
|
||||
{loading && isStreaming ? (
|
||||
<button
|
||||
onClick={stopGeneration}
|
||||
className="p-2 text-muted-foreground hover:text-destructive transition-colors"
|
||||
>
|
||||
<Square className="w-4 h-4 fill-current" />
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
onClick={runTest}
|
||||
disabled={loading || !message.trim()}
|
||||
className="p-2 text-primary hover:text-primary/80 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
{loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Send className="w-4 h-4" />}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="max-w-4xl mx-auto mt-3 flex justify-center">
|
||||
<span className="text-[10px] text-muted-foreground/40 font-medium">{t('apiTester.adminConsoleLabel')}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,68 +1,69 @@
|
||||
import { useState } from 'react'
|
||||
import { FileCode, Download, Upload, Copy, Check, AlertTriangle } from 'lucide-react'
|
||||
import clsx from 'clsx'
|
||||
|
||||
const TEMPLATES = {
|
||||
full: {
|
||||
name: '全量配置模板',
|
||||
desc: '包含密钥、账号及模型映射',
|
||||
config: {
|
||||
keys: ["your-api-key-1", "your-api-key-2"],
|
||||
accounts: [
|
||||
{ email: "user1@example.com", password: "password1", token: "" },
|
||||
{ email: "user2@example.com", password: "password2", token: "" },
|
||||
{ mobile: "+8613800138001", password: "password3", token: "" }
|
||||
],
|
||||
claude_model_mapping: {
|
||||
fast: "deepseek-chat",
|
||||
slow: "deepseek-reasoner"
|
||||
}
|
||||
}
|
||||
},
|
||||
email_only: {
|
||||
name: '仅邮箱账号',
|
||||
desc: '批量导入邮箱格式账号',
|
||||
config: {
|
||||
keys: ["your-api-key"],
|
||||
accounts: [
|
||||
{ email: "account1@example.com", password: "pass1", token: "" },
|
||||
{ email: "account2@example.com", password: "pass2", token: "" },
|
||||
{ email: "account3@example.com", password: "pass3", token: "" }
|
||||
]
|
||||
}
|
||||
},
|
||||
mobile_only: {
|
||||
name: '仅手机号账号',
|
||||
desc: '批量导入手机号格式账号',
|
||||
config: {
|
||||
keys: ["your-api-key"],
|
||||
accounts: [
|
||||
{ mobile: "+8613800000001", password: "pass1", token: "" },
|
||||
{ mobile: "+8613800000002", password: "pass2", token: "" },
|
||||
{ mobile: "+8613800000003", password: "pass3", token: "" }
|
||||
]
|
||||
}
|
||||
},
|
||||
keys_only: {
|
||||
name: '仅 API 密钥',
|
||||
desc: '仅添加 API 访问密钥',
|
||||
config: {
|
||||
keys: ["key-1", "key-2", "key-3"]
|
||||
}
|
||||
}
|
||||
}
|
||||
import { useI18n } from '../i18n'
|
||||
|
||||
export default function BatchImport({ onRefresh, onMessage, authFetch }) {
|
||||
const { t } = useI18n()
|
||||
const [jsonInput, setJsonInput] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [result, setResult] = useState(null)
|
||||
const [copied, setCopied] = useState(false)
|
||||
|
||||
const apiFetch = authFetch || fetch
|
||||
const templates = {
|
||||
full: {
|
||||
name: t('batchImport.templates.full.name'),
|
||||
desc: t('batchImport.templates.full.desc'),
|
||||
config: {
|
||||
keys: ["your-api-key-1", "your-api-key-2"],
|
||||
accounts: [
|
||||
{ email: "user1@example.com", password: "password1", token: "" },
|
||||
{ email: "user2@example.com", password: "password2", token: "" },
|
||||
{ mobile: "+8613800138001", password: "password3", token: "" }
|
||||
],
|
||||
claude_model_mapping: {
|
||||
fast: "deepseek-chat",
|
||||
slow: "deepseek-reasoner"
|
||||
}
|
||||
}
|
||||
},
|
||||
email_only: {
|
||||
name: t('batchImport.templates.emailOnly.name'),
|
||||
desc: t('batchImport.templates.emailOnly.desc'),
|
||||
config: {
|
||||
keys: ["your-api-key"],
|
||||
accounts: [
|
||||
{ email: "account1@example.com", password: "pass1", token: "" },
|
||||
{ email: "account2@example.com", password: "pass2", token: "" },
|
||||
{ email: "account3@example.com", password: "pass3", token: "" }
|
||||
]
|
||||
}
|
||||
},
|
||||
mobile_only: {
|
||||
name: t('batchImport.templates.mobileOnly.name'),
|
||||
desc: t('batchImport.templates.mobileOnly.desc'),
|
||||
config: {
|
||||
keys: ["your-api-key"],
|
||||
accounts: [
|
||||
{ mobile: "+8613800000001", password: "pass1", token: "" },
|
||||
{ mobile: "+8613800000002", password: "pass2", token: "" },
|
||||
{ mobile: "+8613800000003", password: "pass3", token: "" }
|
||||
]
|
||||
}
|
||||
},
|
||||
keys_only: {
|
||||
name: t('batchImport.templates.keysOnly.name'),
|
||||
desc: t('batchImport.templates.keysOnly.desc'),
|
||||
config: {
|
||||
keys: ["key-1", "key-2", "key-3"]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const handleImport = async () => {
|
||||
if (!jsonInput.trim()) {
|
||||
onMessage('error', '请输入 JSON 配置内容')
|
||||
onMessage('error', t('batchImport.enterJson'))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -70,7 +71,7 @@ export default function BatchImport({ onRefresh, onMessage, authFetch }) {
|
||||
try {
|
||||
config = JSON.parse(jsonInput)
|
||||
} catch (e) {
|
||||
onMessage('error', '无效的 JSON 格式')
|
||||
onMessage('error', t('messages.invalidJson'))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -85,23 +86,23 @@ export default function BatchImport({ onRefresh, onMessage, authFetch }) {
|
||||
const data = await res.json()
|
||||
if (res.ok) {
|
||||
setResult(data)
|
||||
onMessage('success', `导入成功: ${data.imported_keys} 个密钥, ${data.imported_accounts} 个账号`)
|
||||
onMessage('success', t('batchImport.importSuccess', { keys: data.imported_keys, accounts: data.imported_accounts }))
|
||||
onRefresh()
|
||||
} else {
|
||||
onMessage('error', data.detail || '导入失败')
|
||||
onMessage('error', data.detail || t('messages.importFailed'))
|
||||
}
|
||||
} catch (e) {
|
||||
onMessage('error', '网络错误')
|
||||
onMessage('error', t('messages.networkError'))
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const loadTemplate = (key) => {
|
||||
const tpl = TEMPLATES[key]
|
||||
const tpl = templates[key]
|
||||
if (tpl) {
|
||||
setJsonInput(JSON.stringify(tpl.config, null, 2))
|
||||
onMessage('info', `已加载模板: ${tpl.name}`)
|
||||
onMessage('info', t('batchImport.templateLoaded', { name: tpl.name }))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -111,10 +112,10 @@ export default function BatchImport({ onRefresh, onMessage, authFetch }) {
|
||||
if (res.ok) {
|
||||
const data = await res.json()
|
||||
setJsonInput(JSON.stringify(JSON.parse(data.json), null, 2))
|
||||
onMessage('success', '当前配置已加载')
|
||||
onMessage('success', t('batchImport.currentConfigLoaded'))
|
||||
}
|
||||
} catch (e) {
|
||||
onMessage('error', '获取配置失败')
|
||||
onMessage('error', t('batchImport.fetchConfigFailed'))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,10 +127,10 @@ export default function BatchImport({ onRefresh, onMessage, authFetch }) {
|
||||
await navigator.clipboard.writeText(data.base64)
|
||||
setCopied(true)
|
||||
setTimeout(() => setCopied(false), 2000)
|
||||
onMessage('success', 'Base64 配置已复制到剪贴板')
|
||||
onMessage('success', t('batchImport.copySuccess'))
|
||||
}
|
||||
} catch (e) {
|
||||
onMessage('error', '复制失败')
|
||||
onMessage('error', t('messages.copyFailed'))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -140,10 +141,10 @@ export default function BatchImport({ onRefresh, onMessage, authFetch }) {
|
||||
<div className="bg-card border border-border rounded-xl p-5 shadow-sm">
|
||||
<h3 className="font-semibold flex items-center gap-2 mb-4">
|
||||
<FileCode className="w-4 h-4 text-primary" />
|
||||
快速模板
|
||||
{t('batchImport.quickTemplates')}
|
||||
</h3>
|
||||
<div className="space-y-3">
|
||||
{Object.entries(TEMPLATES).map(([key, tpl]) => (
|
||||
{Object.entries(templates).map(([key, tpl]) => (
|
||||
<button
|
||||
key={key}
|
||||
onClick={() => loadTemplate(key)}
|
||||
@@ -159,20 +160,20 @@ export default function BatchImport({ onRefresh, onMessage, authFetch }) {
|
||||
<div className="bg-linear-to-br from-primary/10 to-transparent border border-primary/20 rounded-xl p-5 shadow-sm">
|
||||
<h3 className="font-semibold flex items-center gap-2 mb-2 text-primary">
|
||||
<Download className="w-4 h-4" />
|
||||
数据导出
|
||||
{t('batchImport.dataExport')}
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground mb-4">
|
||||
获取配置的 Base64 字符串,用于 Vercel 环境变量。
|
||||
{t('batchImport.dataExportDesc')}
|
||||
</p>
|
||||
<button
|
||||
onClick={copyBase64}
|
||||
className="w-full flex items-center justify-center gap-2 py-2.5 bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 transition-all font-medium text-sm shadow-sm"
|
||||
>
|
||||
{copied ? <Check className="w-4 h-4" /> : <Copy className="w-4 h-4" />}
|
||||
{copied ? '已复制' : '复制 Base64 配置'}
|
||||
{copied ? t('batchImport.copied') : t('batchImport.copyBase64')}
|
||||
</button>
|
||||
<p className="text-[10px] text-muted-foreground mt-2 text-center">
|
||||
变量名: <code className="bg-background px-1 py-0.5 rounded border border-border">DS2API_CONFIG_JSON</code>
|
||||
{t('batchImport.variableName')}: <code className="bg-background px-1 py-0.5 rounded border border-border">DS2API_CONFIG_JSON</code>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -182,14 +183,14 @@ export default function BatchImport({ onRefresh, onMessage, authFetch }) {
|
||||
<div className="p-4 border-b border-border flex items-center justify-between bg-muted/20">
|
||||
<h3 className="font-semibold flex items-center gap-2">
|
||||
<Upload className="w-4 h-4 text-primary" />
|
||||
JSON 编辑器
|
||||
{t('batchImport.jsonEditor')}
|
||||
</h3>
|
||||
<div className="flex gap-2">
|
||||
<button onClick={handleExport} className="px-3 py-1.5 bg-secondary text-secondary-foreground rounded-lg hover:bg-secondary/80 transition-colors text-xs font-medium border border-border">
|
||||
加载当前配置
|
||||
{t('batchImport.loadCurrentConfig')}
|
||||
</button>
|
||||
<button onClick={handleImport} disabled={loading} className="px-3 py-1.5 bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 transition-colors text-xs font-medium disabled:opacity-50">
|
||||
{loading ? '正在导入...' : '应用配置'}
|
||||
{loading ? t('batchImport.importing') : t('batchImport.applyConfig')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -217,10 +218,10 @@ export default function BatchImport({ onRefresh, onMessage, authFetch }) {
|
||||
)}
|
||||
<div>
|
||||
<h4 className={clsx("font-medium", result.imported_keys || result.imported_accounts ? "text-emerald-500" : "text-destructive")}>
|
||||
导入操作已完成
|
||||
{t('batchImport.importComplete')}
|
||||
</h4>
|
||||
<p className="text-sm opacity-80 mt-1">
|
||||
成功导入了 {result.imported_keys} 个 API 密钥,并更新了 {result.imported_accounts} 个账号。
|
||||
{t('batchImport.importSummary', { keys: result.imported_keys, accounts: result.imported_accounts })}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import React from 'react'
|
||||
import { useI18n } from '../i18n'
|
||||
import LanguageToggle from './LanguageToggle'
|
||||
|
||||
const LandingPage = ({ onEnter }) => {
|
||||
const { t } = useI18n()
|
||||
return (
|
||||
<div className="landing-container min-h-screen relative overflow-hidden flex flex-col items-center justify-center p-6 text-center">
|
||||
{/* Animated Background Elements - using Tailwind with some custom CSS in styles.css if needed,
|
||||
@@ -84,6 +87,10 @@ const LandingPage = ({ onEnter }) => {
|
||||
<div className="blob" style={{ top: '10%', left: '15%' }} />
|
||||
<div className="blob" style={{ bottom: '10%', right: '15%', animationDelay: '-5s' }} />
|
||||
|
||||
<div className="absolute top-6 right-6 z-20">
|
||||
<LanguageToggle />
|
||||
</div>
|
||||
|
||||
<div className="landing-content">
|
||||
<header className="mb-12">
|
||||
<h1 className="logo-text">DS2API</h1>
|
||||
@@ -97,14 +104,14 @@ const LandingPage = ({ onEnter }) => {
|
||||
onClick={onEnter}
|
||||
className="btn-premium text-white px-8 py-3 rounded-xl font-bold transition-all flex items-center gap-2"
|
||||
>
|
||||
<span>🎛️</span> 管理面板
|
||||
<span>🎛️</span> {t('landing.adminConsole')}
|
||||
</button>
|
||||
<a
|
||||
href="/v1/models"
|
||||
target="_blank"
|
||||
className="glass-card text-white px-8 py-3 rounded-xl font-semibold transition-all flex items-center gap-2"
|
||||
>
|
||||
<span>📡</span> API 状态
|
||||
<span>📡</span> {t('landing.apiStatus')}
|
||||
</a>
|
||||
<a
|
||||
href="https://github.com/CJackHwang/ds2api"
|
||||
@@ -117,10 +124,10 @@ const LandingPage = ({ onEnter }) => {
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-6 text-left">
|
||||
{[
|
||||
{ icon: '🚀', title: '全面兼容', desc: '适配 OpenAI 与 Claude 格式' },
|
||||
{ icon: '⚖️', title: '负载均衡', desc: '智能轮询,稳定高效' },
|
||||
{ icon: '🧠', title: '深度思考', desc: '支持推理过程输出' },
|
||||
{ icon: '🔍', title: '联网搜索', desc: '集成原生网页搜索能力' },
|
||||
{ icon: '🚀', title: t('landing.features.compatibility.title'), desc: t('landing.features.compatibility.desc') },
|
||||
{ icon: '⚖️', title: t('landing.features.loadBalancing.title'), desc: t('landing.features.loadBalancing.desc') },
|
||||
{ icon: '🧠', title: t('landing.features.reasoning.title'), desc: t('landing.features.reasoning.desc') },
|
||||
{ icon: '🔍', title: t('landing.features.search.title'), desc: t('landing.features.search.desc') },
|
||||
].map((feature, idx) => (
|
||||
<div key={idx} className="glass-card p-6 rounded-2xl">
|
||||
<span className="text-2xl mb-4 block">{feature.icon}</span>
|
||||
|
||||
18
webui/src/components/LanguageToggle.jsx
Normal file
18
webui/src/components/LanguageToggle.jsx
Normal file
@@ -0,0 +1,18 @@
|
||||
import { useI18n } from '../i18n'
|
||||
|
||||
export default function LanguageToggle({ className = '' }) {
|
||||
const { lang, setLang, t } = useI18n()
|
||||
const nextLang = lang === 'zh' ? 'en' : 'zh'
|
||||
const label = nextLang === 'zh' ? t('language.chinese') : t('language.english')
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setLang(nextLang)}
|
||||
className={`text-xs font-semibold px-2 py-1 rounded-md border border-border bg-secondary/50 text-muted-foreground hover:text-foreground hover:bg-secondary transition-colors ${className}`}
|
||||
title={t('language.label')}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -1,8 +1,11 @@
|
||||
import { useState } from 'react'
|
||||
import { Key, ArrowRight, ShieldCheck, Lock, Check } from 'lucide-react'
|
||||
import clsx from 'clsx'
|
||||
import { useI18n } from '../i18n'
|
||||
import LanguageToggle from './LanguageToggle'
|
||||
|
||||
export default function Login({ onLogin, onMessage }) {
|
||||
const { t } = useI18n()
|
||||
const [adminKey, setAdminKey] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [remember, setRemember] = useState(true)
|
||||
@@ -32,10 +35,10 @@ export default function Login({ onLogin, onMessage }) {
|
||||
onMessage('warning', data.message)
|
||||
}
|
||||
} else {
|
||||
onMessage('error', data.detail || '登录失败')
|
||||
onMessage('error', data.detail || t('login.signInFailed'))
|
||||
}
|
||||
} catch (e) {
|
||||
onMessage('error', '网络错误: ' + e.message)
|
||||
onMessage('error', t('login.networkError', { error: e.message }))
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
@@ -43,6 +46,9 @@ export default function Login({ onLogin, onMessage }) {
|
||||
|
||||
return (
|
||||
<div className="min-h-screen w-full flex flex-col items-center justify-center p-4 bg-background text-foreground">
|
||||
<div className="absolute top-6 right-6">
|
||||
<LanguageToggle />
|
||||
</div>
|
||||
|
||||
<div className="w-full max-w-[400px] relative z-10 animate-in fade-in zoom-in-95 duration-200">
|
||||
<div className="w-full bg-card border border-border rounded-xl p-8 shadow-sm">
|
||||
@@ -50,13 +56,13 @@ export default function Login({ onLogin, onMessage }) {
|
||||
<div className="inline-flex items-center justify-center w-12 h-12 rounded-xl bg-primary/10 text-primary mb-2">
|
||||
<Lock className="w-6 h-6" />
|
||||
</div>
|
||||
<h1 className="text-3xl font-bold tracking-tight text-foreground">欢迎回来</h1>
|
||||
<p className="text-sm text-muted-foreground/80">请输入管理员密钥以继续</p>
|
||||
<h1 className="text-3xl font-bold tracking-tight text-foreground">{t('login.welcome')}</h1>
|
||||
<p className="text-sm text-muted-foreground/80">{t('login.subtitle')}</p>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleLogin} className="space-y-5 animate-in fade-in slide-in-from-bottom-4 duration-700 delay-150">
|
||||
<div className="space-y-2">
|
||||
<label className="text-xs font-semibold text-muted-foreground uppercase tracking-widest ml-1">管理员密钥</label>
|
||||
<label className="text-xs font-semibold text-muted-foreground uppercase tracking-widest ml-1">{t('login.adminKeyLabel')}</label>
|
||||
<div className="relative group">
|
||||
<div className="absolute inset-y-0 left-0 pl-3.5 flex items-center pointer-events-none text-muted-foreground group-focus-within:text-primary transition-colors">
|
||||
<Key className="w-4 h-4" />
|
||||
@@ -64,7 +70,7 @@ export default function Login({ onLogin, onMessage }) {
|
||||
<input
|
||||
type="password"
|
||||
className="w-full bg-[#09090b] border border-border rounded-xl pl-10 pr-4 py-3 text-sm focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all placeholder:text-muted-foreground/30 text-foreground"
|
||||
placeholder="输入您的管理员密钥..."
|
||||
placeholder={t('login.adminKeyPlaceholder')}
|
||||
value={adminKey}
|
||||
onChange={e => setAdminKey(e.target.value)}
|
||||
autoFocus
|
||||
@@ -81,10 +87,10 @@ export default function Login({ onLogin, onMessage }) {
|
||||
checked={remember}
|
||||
onChange={e => setRemember(e.target.checked)}
|
||||
/>
|
||||
<div className="w-4.5 h-4.5 bg-secondary border border-border rounded-md peer-checked:bg-primary peer-checked:border-primary transition-all shadow-sm"></div>
|
||||
<Check className="absolute w-3 h-3 text-primary-foreground opacity-0 peer-checked:opacity-100 left-0.5 transition-opacity" />
|
||||
<div className="w-[18px] h-[18px] bg-secondary border border-border rounded-md peer-checked:bg-primary peer-checked:border-primary transition-all shadow-sm"></div>
|
||||
<Check className="absolute inset-0 m-auto w-3 h-3 text-primary-foreground opacity-0 peer-checked:opacity-100 transition-opacity stroke-[3]" />
|
||||
</div>
|
||||
<span className="text-xs font-medium text-muted-foreground group-hover:text-foreground transition-colors">记住登录状态</span>
|
||||
<span className="text-xs font-medium text-muted-foreground group-hover:text-foreground transition-colors">{t('login.rememberSession')}</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
@@ -97,7 +103,7 @@ export default function Login({ onLogin, onMessage }) {
|
||||
<div className="w-5 h-5 border-2 border-primary-foreground/30 border-t-primary-foreground rounded-full animate-spin" />
|
||||
) : (
|
||||
<div className="flex items-center gap-2">
|
||||
<span>登录</span>
|
||||
<span>{t('login.signIn')}</span>
|
||||
<ArrowRight className="w-4 h-4" />
|
||||
</div>
|
||||
)}
|
||||
@@ -107,13 +113,13 @@ export default function Login({ onLogin, onMessage }) {
|
||||
<div className="mt-6 pt-6 border-t border-border flex justify-center">
|
||||
<div className="flex items-center gap-1.5 text-[10px] text-muted-foreground/60 font-medium tracking-wide uppercase">
|
||||
<ShieldCheck className="w-3 h-3" />
|
||||
<span>安全连接</span>
|
||||
<span>{t('login.secureConnection')}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-8 text-center">
|
||||
<p className="text-[10px] text-muted-foreground/30 font-mono text-center">DS2API 管理员门户</p>
|
||||
<p className="text-[10px] text-muted-foreground/30 font-mono text-center">{t('login.adminPortal')}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,16 +1,32 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { Cloud, ArrowRight, ExternalLink, Info, CheckCircle2, XCircle } from 'lucide-react'
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { Cloud, ArrowRight, ExternalLink, Info, CheckCircle2, XCircle, RefreshCw } from 'lucide-react'
|
||||
import clsx from 'clsx'
|
||||
import { useI18n } from '../i18n'
|
||||
|
||||
export default function VercelSync({ onMessage, authFetch }) {
|
||||
const { t } = useI18n()
|
||||
const [vercelToken, setVercelToken] = useState('')
|
||||
const [projectId, setProjectId] = useState('')
|
||||
const [teamId, setTeamId] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [result, setResult] = useState(null)
|
||||
const [preconfig, setPreconfig] = useState(null)
|
||||
const [syncStatus, setSyncStatus] = useState(null)
|
||||
|
||||
const apiFetch = authFetch || fetch
|
||||
|
||||
const fetchSyncStatus = useCallback(async () => {
|
||||
try {
|
||||
const res = await apiFetch('/admin/vercel/status')
|
||||
if (res.ok) {
|
||||
const data = await res.json()
|
||||
setSyncStatus(data)
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to fetch sync status:', e)
|
||||
}
|
||||
}, [apiFetch])
|
||||
|
||||
useEffect(() => {
|
||||
const loadPreconfig = async () => {
|
||||
try {
|
||||
@@ -26,17 +42,21 @@ export default function VercelSync({ onMessage, authFetch }) {
|
||||
}
|
||||
}
|
||||
loadPreconfig()
|
||||
}, [])
|
||||
fetchSyncStatus()
|
||||
// Poll every 15s to detect config changes
|
||||
const interval = setInterval(fetchSyncStatus, 15000)
|
||||
return () => clearInterval(interval)
|
||||
}, [fetchSyncStatus])
|
||||
|
||||
const handleSync = async () => {
|
||||
const tokenToUse = preconfig?.has_token && !vercelToken ? '__USE_PRECONFIG__' : vercelToken
|
||||
|
||||
if (!tokenToUse && !preconfig?.has_token) {
|
||||
onMessage('error', '需要 Vercel 访问令牌')
|
||||
onMessage('error', t('vercel.tokenRequired'))
|
||||
return
|
||||
}
|
||||
if (!projectId) {
|
||||
onMessage('error', '需要项目 ID')
|
||||
onMessage('error', t('vercel.projectRequired'))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -56,12 +76,13 @@ export default function VercelSync({ onMessage, authFetch }) {
|
||||
if (res.ok) {
|
||||
setResult({ ...data, success: true })
|
||||
onMessage('success', data.message)
|
||||
fetchSyncStatus()
|
||||
} else {
|
||||
setResult({ ...data, success: false })
|
||||
onMessage('error', data.detail || '同步失败')
|
||||
onMessage('error', data.detail || t('vercel.syncFailed'))
|
||||
}
|
||||
} catch (e) {
|
||||
onMessage('error', '网络错误')
|
||||
onMessage('error', t('vercel.networkError'))
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
@@ -72,28 +93,56 @@ export default function VercelSync({ onMessage, authFetch }) {
|
||||
{/* Configuration Form */}
|
||||
<div className="bg-card border border-border rounded-xl shadow-sm p-6 space-y-6">
|
||||
<div className="border-b border-border pb-6">
|
||||
<h2 className="text-xl font-semibold flex items-center gap-2">
|
||||
<Cloud className="w-6 h-6 text-primary" />
|
||||
Vercel 部署
|
||||
</h2>
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-xl font-semibold flex items-center gap-2">
|
||||
<Cloud className="w-6 h-6 text-primary" />
|
||||
{t('vercel.title')}
|
||||
</h2>
|
||||
{syncStatus && (
|
||||
<div className={clsx(
|
||||
"flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full border transition-colors",
|
||||
syncStatus.synced
|
||||
? "text-emerald-500 bg-emerald-500/10 border-emerald-500/20"
|
||||
: syncStatus.has_synced_before
|
||||
? "text-amber-500 bg-amber-500/10 border-amber-500/20"
|
||||
: "text-muted-foreground bg-muted/50 border-border"
|
||||
)}>
|
||||
<span className={clsx(
|
||||
"w-1.5 h-1.5 rounded-full",
|
||||
syncStatus.synced ? "bg-emerald-500" : syncStatus.has_synced_before ? "bg-amber-500 animate-pulse" : "bg-muted-foreground"
|
||||
)} />
|
||||
{syncStatus.synced
|
||||
? t('vercel.statusSynced')
|
||||
: syncStatus.has_synced_before
|
||||
? t('vercel.statusNotSynced')
|
||||
: t('vercel.statusNeverSynced')}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-muted-foreground text-sm mt-1">
|
||||
将当前密钥和账号配置直接同步到 Vercel 环境变量中。
|
||||
{t('vercel.description')}
|
||||
</p>
|
||||
{syncStatus?.last_sync_time && (
|
||||
<p className="text-xs text-muted-foreground/60 mt-1.5 flex items-center gap-1">
|
||||
<RefreshCw className="w-3 h-3" />
|
||||
{t('vercel.lastSyncTime', { time: new Date(syncStatus.last_sync_time * 1000).toLocaleString() })}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium flex items-center justify-between">
|
||||
Vercel 访问令牌
|
||||
{t('vercel.tokenLabel')}
|
||||
<a href="https://vercel.com/account/tokens" target="_blank" rel="noopener noreferrer" className="text-xs text-primary hover:underline flex items-center gap-1">
|
||||
获取令牌 <ExternalLink className="w-3 h-3" />
|
||||
{t('vercel.getToken')} <ExternalLink className="w-3 h-3" />
|
||||
</a>
|
||||
</label>
|
||||
<div className="relative">
|
||||
<input
|
||||
type="password"
|
||||
className="w-full h-10 px-3 bg-background border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-ring focus:border-ring transition-all pr-10"
|
||||
placeholder={preconfig?.has_token ? "正在使用预配置的令牌" : "输入 Vercel 访问令牌"}
|
||||
placeholder={preconfig?.has_token ? t('vercel.tokenPlaceholderPreconfig') : t('vercel.tokenPlaceholder')}
|
||||
value={vercelToken}
|
||||
onChange={e => setVercelToken(e.target.value)}
|
||||
/>
|
||||
@@ -106,7 +155,7 @@ export default function VercelSync({ onMessage, authFetch }) {
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium">项目 ID</label>
|
||||
<label className="text-sm font-medium">{t('vercel.projectIdLabel')}</label>
|
||||
<input
|
||||
type="text"
|
||||
className="w-full h-10 px-3 bg-background border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-ring focus:border-ring transition-all"
|
||||
@@ -114,12 +163,12 @@ export default function VercelSync({ onMessage, authFetch }) {
|
||||
value={projectId}
|
||||
onChange={e => setProjectId(e.target.value)}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">可在项目设置 (Project Settings) → 常规 (General) 中找到</p>
|
||||
<p className="text-xs text-muted-foreground">{t('vercel.projectIdHint')}</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium flex items-center gap-2">
|
||||
团队 ID <span className="text-xs text-muted-foreground font-normal">(可选)</span>
|
||||
{t('vercel.teamIdLabel')} <span className="text-xs text-muted-foreground font-normal">({t('vercel.optional')})</span>
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
@@ -140,16 +189,16 @@ export default function VercelSync({ onMessage, authFetch }) {
|
||||
{loading ? (
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="w-4 h-4 border-2 border-current border-t-transparent rounded-full animate-spin" />
|
||||
正在同步...
|
||||
{t('vercel.syncing')}
|
||||
</span>
|
||||
) : (
|
||||
<span className="flex items-center gap-2">
|
||||
同步并重新部署 <ArrowRight className="w-4 h-4" />
|
||||
{t('vercel.syncRedeploy')} <ArrowRight className="w-4 h-4" />
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
<p className="text-xs text-center text-muted-foreground mt-4">
|
||||
这将触发 Vercel 的重新部署,大约需要 30-60 秒。
|
||||
{t('vercel.redeployHint')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -170,14 +219,14 @@ export default function VercelSync({ onMessage, authFetch }) {
|
||||
)}
|
||||
<div className="space-y-1">
|
||||
<h3 className={`font-semibold text-lg ${result.success ? 'text-emerald-500' : 'text-destructive'}`}>
|
||||
{result.success ? '同步成功' : '同步失败'}
|
||||
{result.success ? t('vercel.syncSucceeded') : t('vercel.syncFailedLabel')}
|
||||
</h3>
|
||||
<p className="text-sm opacity-90">{result.message}</p>
|
||||
|
||||
{result.deployment_url && (
|
||||
<div className="pt-3 mt-3 border-t border-emerald-500/20">
|
||||
<a href={`https://${result.deployment_url}`} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-1 text-sm font-medium hover:underline">
|
||||
访问部署地址 <ExternalLink className="w-3 h-3" />
|
||||
{t('vercel.openDeployment')} <ExternalLink className="w-3 h-3" />
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
@@ -189,24 +238,26 @@ export default function VercelSync({ onMessage, authFetch }) {
|
||||
<div className="bg-secondary/20 border border-border rounded-xl p-6">
|
||||
<h3 className="font-semibold flex items-center gap-2 mb-4">
|
||||
<Info className="w-5 h-5 text-primary" />
|
||||
工作原理
|
||||
{t('vercel.howItWorks')}
|
||||
</h3>
|
||||
<ul className="space-y-4">
|
||||
<li className="flex gap-3">
|
||||
<span className="shrink-0 w-6 h-6 rounded-full bg-background border border-border flex items-center justify-center text-xs font-bold text-muted-foreground">1</span>
|
||||
<p className="text-sm text-muted-foreground">当前配置 (密钥和账号) 被导出为 JSON 字符串。</p>
|
||||
<p className="text-sm text-muted-foreground">{t('vercel.steps.one')}</p>
|
||||
</li>
|
||||
<li className="flex gap-3">
|
||||
<span className="shrink-0 w-6 h-6 rounded-full bg-background border border-border flex items-center justify-center text-xs font-bold text-muted-foreground">2</span>
|
||||
<p className="text-sm text-muted-foreground">JSON 被编码为 Base64 以确保格式兼容性。</p>
|
||||
<p className="text-sm text-muted-foreground">{t('vercel.steps.two')}</p>
|
||||
</li>
|
||||
<li className="flex gap-3">
|
||||
<span className="shrink-0 w-6 h-6 rounded-full bg-background border border-border flex items-center justify-center text-xs font-bold text-muted-foreground">3</span>
|
||||
<p className="text-sm text-muted-foreground">更新 Vercel 项目中的 <code className="bg-background px-1 py-0.5 rounded border border-border text-xs">DS2API_CONFIG_JSON</code> 环境变量。</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('vercel.steps.three')} <code className="bg-background px-1 py-0.5 rounded border border-border text-xs">DS2API_CONFIG_JSON</code>
|
||||
</p>
|
||||
</li>
|
||||
<li className="flex gap-3">
|
||||
<span className="shrink-0 w-6 h-6 rounded-full bg-background border border-border flex items-center justify-center text-xs font-bold text-muted-foreground">4</span>
|
||||
<p className="text-sm text-muted-foreground">触发重新部署以应用新的环境变量。</p>
|
||||
<p className="text-sm text-muted-foreground">{t('vercel.steps.four')}</p>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
62
webui/src/i18n.jsx
Normal file
62
webui/src/i18n.jsx
Normal file
@@ -0,0 +1,62 @@
|
||||
import { createContext, useContext, useEffect, useMemo, useState } from 'react'
|
||||
import en from './locales/en.json'
|
||||
import zh from './locales/zh.json'
|
||||
|
||||
const STORAGE_KEY = 'ds2api_lang'
|
||||
const translations = { en, zh }
|
||||
|
||||
const I18nContext = createContext({
|
||||
lang: 'zh',
|
||||
setLang: () => {},
|
||||
t: (key) => key,
|
||||
})
|
||||
|
||||
const getBrowserLang = () => {
|
||||
if (typeof navigator === 'undefined') return 'zh'
|
||||
return navigator.language?.toLowerCase().startsWith('zh') ? 'zh' : 'en'
|
||||
}
|
||||
|
||||
const getValue = (obj, key) => {
|
||||
if (!obj) return undefined
|
||||
return key.split('.').reduce((acc, part) => (acc ? acc[part] : undefined), obj)
|
||||
}
|
||||
|
||||
const formatMessage = (message, vars) => {
|
||||
if (!vars) return message
|
||||
return message.replace(/\{(\w+)\}/g, (match, key) => {
|
||||
if (Object.prototype.hasOwnProperty.call(vars, key)) {
|
||||
return vars[key]
|
||||
}
|
||||
return match
|
||||
})
|
||||
}
|
||||
|
||||
export const I18nProvider = ({ children }) => {
|
||||
const [lang, setLang] = useState(() => {
|
||||
if (typeof localStorage === 'undefined') return getBrowserLang()
|
||||
return localStorage.getItem(STORAGE_KEY) || getBrowserLang()
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof localStorage !== 'undefined') {
|
||||
localStorage.setItem(STORAGE_KEY, lang)
|
||||
}
|
||||
if (typeof document !== 'undefined') {
|
||||
document.documentElement.lang = lang === 'zh' ? 'zh-CN' : 'en'
|
||||
}
|
||||
}, [lang])
|
||||
|
||||
const t = useMemo(() => {
|
||||
return (key, vars) => {
|
||||
const value = getValue(translations[lang], key) ?? getValue(translations.en, key) ?? key
|
||||
if (typeof value !== 'string') return value
|
||||
return formatMessage(value, vars)
|
||||
}
|
||||
}, [lang])
|
||||
|
||||
const contextValue = useMemo(() => ({ lang, setLang, t }), [lang, t])
|
||||
|
||||
return <I18nContext.Provider value={contextValue}>{children}</I18nContext.Provider>
|
||||
}
|
||||
|
||||
export const useI18n = () => useContext(I18nContext)
|
||||
237
webui/src/locales/en.json
Normal file
237
webui/src/locales/en.json
Normal file
@@ -0,0 +1,237 @@
|
||||
{
|
||||
"language": {
|
||||
"label": "Language",
|
||||
"english": "English",
|
||||
"chinese": "中文"
|
||||
},
|
||||
"nav": {
|
||||
"accounts": {
|
||||
"label": "Account Management",
|
||||
"desc": "Manage the DeepSeek account pool"
|
||||
},
|
||||
"test": {
|
||||
"label": "API Test",
|
||||
"desc": "Test API connectivity and responses"
|
||||
},
|
||||
"import": {
|
||||
"label": "Batch Import",
|
||||
"desc": "Bulk import account configuration"
|
||||
},
|
||||
"vercel": {
|
||||
"label": "Vercel Sync",
|
||||
"desc": "Sync configuration to Vercel"
|
||||
}
|
||||
},
|
||||
"sidebar": {
|
||||
"onlineAdminConsole": "Online Admin Console",
|
||||
"systemStatus": "System Status",
|
||||
"statusOnline": "Online",
|
||||
"accounts": "Accounts",
|
||||
"keys": "Keys",
|
||||
"signOut": "Sign out"
|
||||
},
|
||||
"auth": {
|
||||
"expired": "Authentication expired. Please sign in again.",
|
||||
"checking": "Checking authentication status..."
|
||||
},
|
||||
"errors": {
|
||||
"fetchConfig": "Failed to fetch configuration: {error}"
|
||||
},
|
||||
"actions": {
|
||||
"cancel": "Cancel",
|
||||
"add": "Add",
|
||||
"delete": "Delete",
|
||||
"copy": "Copy",
|
||||
"generate": "Generate",
|
||||
"test": "Test",
|
||||
"testing": "Testing...",
|
||||
"loading": "Loading..."
|
||||
},
|
||||
"messages": {
|
||||
"deleted": "Deleted successfully",
|
||||
"deleteFailed": "Delete failed",
|
||||
"failedToAdd": "Failed to add",
|
||||
"networkError": "Network error.",
|
||||
"requestFailed": "Request failed.",
|
||||
"generationStopped": "Generation stopped.",
|
||||
"invalidJson": "Invalid JSON format.",
|
||||
"importFailed": "Import failed.",
|
||||
"copyFailed": "Copy failed."
|
||||
},
|
||||
"landing": {
|
||||
"adminConsole": "Admin Console",
|
||||
"apiStatus": "API Status",
|
||||
"features": {
|
||||
"compatibility": {
|
||||
"title": "Full Compatibility",
|
||||
"desc": "OpenAI & Claude format support"
|
||||
},
|
||||
"loadBalancing": {
|
||||
"title": "Load Balancing",
|
||||
"desc": "Smart rotation with stable throughput"
|
||||
},
|
||||
"reasoning": {
|
||||
"title": "Deep Reasoning",
|
||||
"desc": "Expose reasoning traces when enabled"
|
||||
},
|
||||
"search": {
|
||||
"title": "Web Search",
|
||||
"desc": "Integrated native web search"
|
||||
}
|
||||
}
|
||||
},
|
||||
"accountManager": {
|
||||
"addKeySuccess": "API key added successfully.",
|
||||
"addAccountSuccess": "Account added successfully.",
|
||||
"requiredFields": "Password and email/mobile are required.",
|
||||
"deleteKeyConfirm": "Are you sure you want to delete this API key?",
|
||||
"deleteAccountConfirm": "Are you sure you want to delete this account?",
|
||||
"testAllConfirm": "Test API connectivity for all accounts?",
|
||||
"testAllCompleted": "Completed: {success}/{total} available",
|
||||
"testFailed": "Test failed: {error}",
|
||||
"available": "Available",
|
||||
"inUse": "In use",
|
||||
"totalPool": "Total pool",
|
||||
"accountsUnit": "accounts",
|
||||
"threadsUnit": "threads",
|
||||
"apiKeysTitle": "API Keys",
|
||||
"apiKeysDesc": "Manage the API access key pool",
|
||||
"addKey": "Add key",
|
||||
"copied": "Copied",
|
||||
"copyKeyTitle": "Copy key",
|
||||
"deleteKeyTitle": "Delete key",
|
||||
"noApiKeys": "No API keys found.",
|
||||
"accountsTitle": "DeepSeek Accounts",
|
||||
"accountsDesc": "Manage the DeepSeek account pool",
|
||||
"testAll": "Test all",
|
||||
"addAccount": "Add account",
|
||||
"testingAllAccounts": "Testing all accounts...",
|
||||
"sessionActive": "Session active",
|
||||
"reauthRequired": "Re-auth required",
|
||||
"noAccounts": "No accounts found.",
|
||||
"modalAddKeyTitle": "Add API key",
|
||||
"newKeyLabel": "New key value",
|
||||
"newKeyPlaceholder": "Enter a custom API key",
|
||||
"generate": "Generate",
|
||||
"generateHint": "Click Generate to create a random key.",
|
||||
"addKeyLoading": "Adding...",
|
||||
"addKeyAction": "Add key",
|
||||
"modalAddAccountTitle": "Add DeepSeek account",
|
||||
"emailOptional": "Email (optional)",
|
||||
"mobileOptional": "Mobile (optional)",
|
||||
"passwordLabel": "Password",
|
||||
"passwordPlaceholder": "Account password",
|
||||
"addAccountLoading": "Adding...",
|
||||
"addAccountAction": "Add account",
|
||||
"pageInfo": "Page {current}/{total}, {count} accounts total"
|
||||
},
|
||||
"apiTester": {
|
||||
"defaultMessage": "Hello, please introduce yourself in one sentence.",
|
||||
"models": {
|
||||
"chat": "Non-reasoning model",
|
||||
"reasoner": "Reasoning model",
|
||||
"chatSearch": "Non-reasoning model (with search)",
|
||||
"reasonerSearch": "Reasoning model (with search)"
|
||||
},
|
||||
"missingApiKey": "Please provide an API key.",
|
||||
"requestFailed": "Request failed.",
|
||||
"networkError": "Network error: {error}",
|
||||
"testSuccess": "{account}: Test successful ({time}ms)",
|
||||
"config": "Configuration",
|
||||
"modelLabel": "Model",
|
||||
"streamMode": "Streaming",
|
||||
"accountSelector": "Account",
|
||||
"autoRandom": "🤖 Auto / Random",
|
||||
"apiKeyOptional": "API Key (optional)",
|
||||
"apiKeyDefault": "Default: ...{suffix}",
|
||||
"apiKeyPlaceholder": "Enter a custom key",
|
||||
"statusError": "Error",
|
||||
"reasoningTrace": "Reasoning Trace",
|
||||
"generating": "Generating response...",
|
||||
"enterMessage": "Enter a message...",
|
||||
"adminConsoleLabel": "DeepSeek admin console"
|
||||
},
|
||||
"batchImport": {
|
||||
"templates": {
|
||||
"full": {
|
||||
"name": "Full configuration template",
|
||||
"desc": "Includes keys, accounts, and model mapping"
|
||||
},
|
||||
"emailOnly": {
|
||||
"name": "Email-only accounts",
|
||||
"desc": "Batch import accounts using email login"
|
||||
},
|
||||
"mobileOnly": {
|
||||
"name": "Mobile-only accounts",
|
||||
"desc": "Batch import accounts using mobile login"
|
||||
},
|
||||
"keysOnly": {
|
||||
"name": "API keys only",
|
||||
"desc": "Add API access keys only"
|
||||
}
|
||||
},
|
||||
"enterJson": "Please provide JSON configuration content.",
|
||||
"importSuccess": "Import successful: {keys} keys, {accounts} accounts",
|
||||
"templateLoaded": "Template loaded: {name}",
|
||||
"currentConfigLoaded": "Current configuration loaded.",
|
||||
"fetchConfigFailed": "Failed to fetch configuration.",
|
||||
"copySuccess": "Base64 configuration copied to clipboard.",
|
||||
"quickTemplates": "Quick Templates",
|
||||
"dataExport": "Data Export",
|
||||
"dataExportDesc": "Copy the Base64-encoded configuration for Vercel environment variables.",
|
||||
"copyBase64": "Copy Base64 config",
|
||||
"copied": "Copied",
|
||||
"variableName": "Variable name",
|
||||
"jsonEditor": "JSON Editor",
|
||||
"loadCurrentConfig": "Load current config",
|
||||
"applyConfig": "Apply config",
|
||||
"importing": "Importing...",
|
||||
"importComplete": "Import complete",
|
||||
"importSummary": "Imported {keys} API keys and updated {accounts} accounts."
|
||||
},
|
||||
"login": {
|
||||
"welcome": "Welcome back",
|
||||
"subtitle": "Enter your admin key to continue",
|
||||
"adminKeyLabel": "Admin key",
|
||||
"adminKeyPlaceholder": "Enter your admin key...",
|
||||
"rememberSession": "Remember this session",
|
||||
"signIn": "Sign in",
|
||||
"secureConnection": "Secure connection",
|
||||
"adminPortal": "DS2API admin portal",
|
||||
"signInFailed": "Sign-in failed.",
|
||||
"networkError": "Network error: {error}"
|
||||
},
|
||||
"vercel": {
|
||||
"tokenRequired": "Vercel access token is required.",
|
||||
"projectRequired": "Project ID is required.",
|
||||
"syncFailed": "Sync failed.",
|
||||
"networkError": "Network error.",
|
||||
"title": "Vercel Deployment",
|
||||
"description": "Sync the current keys and accounts directly to Vercel environment variables.",
|
||||
"tokenLabel": "Vercel Access Token",
|
||||
"getToken": "Get token",
|
||||
"tokenPlaceholderPreconfig": "Using preconfigured token",
|
||||
"tokenPlaceholder": "Enter Vercel access token",
|
||||
"projectIdLabel": "Project ID",
|
||||
"projectIdHint": "Find it in Project Settings → General.",
|
||||
"teamIdLabel": "Team ID",
|
||||
"optional": "optional",
|
||||
"syncing": "Syncing...",
|
||||
"syncRedeploy": "Sync & redeploy",
|
||||
"redeployHint": "This triggers a Vercel redeploy and usually takes 30–60 seconds.",
|
||||
"syncSucceeded": "Sync succeeded",
|
||||
"syncFailedLabel": "Sync failed",
|
||||
"openDeployment": "Open deployment",
|
||||
"statusSynced": "Synced",
|
||||
"statusNotSynced": "Not synced",
|
||||
"statusNeverSynced": "Never synced",
|
||||
"lastSyncTime": "Last sync: {time}",
|
||||
"howItWorks": "How it works",
|
||||
"steps": {
|
||||
"one": "The current configuration (keys and accounts) is exported as JSON.",
|
||||
"two": "The JSON is Base64-encoded for safe formatting.",
|
||||
"three": "Update the env var in Vercel:",
|
||||
"four": "Trigger a redeploy to apply the updated environment variables."
|
||||
}
|
||||
}
|
||||
}
|
||||
237
webui/src/locales/zh.json
Normal file
237
webui/src/locales/zh.json
Normal file
@@ -0,0 +1,237 @@
|
||||
{
|
||||
"language": {
|
||||
"label": "语言",
|
||||
"english": "English",
|
||||
"chinese": "中文"
|
||||
},
|
||||
"nav": {
|
||||
"accounts": {
|
||||
"label": "账号管理",
|
||||
"desc": "管理 DeepSeek 账号池"
|
||||
},
|
||||
"test": {
|
||||
"label": "API 测试",
|
||||
"desc": "测试 API 连接与响应"
|
||||
},
|
||||
"import": {
|
||||
"label": "批量导入",
|
||||
"desc": "批量导入账号配置"
|
||||
},
|
||||
"vercel": {
|
||||
"label": "Vercel 同步",
|
||||
"desc": "同步配置到 Vercel"
|
||||
}
|
||||
},
|
||||
"sidebar": {
|
||||
"onlineAdminConsole": "在线管理面板",
|
||||
"systemStatus": "系统状态",
|
||||
"statusOnline": "在线",
|
||||
"accounts": "账号",
|
||||
"keys": "密钥",
|
||||
"signOut": "退出登录"
|
||||
},
|
||||
"auth": {
|
||||
"expired": "认证已过期,请重新登录",
|
||||
"checking": "正在检查登录状态..."
|
||||
},
|
||||
"errors": {
|
||||
"fetchConfig": "获取配置失败: {error}"
|
||||
},
|
||||
"actions": {
|
||||
"cancel": "取消",
|
||||
"add": "添加",
|
||||
"delete": "删除",
|
||||
"copy": "复制",
|
||||
"generate": "生成",
|
||||
"test": "测试",
|
||||
"testing": "正在测试...",
|
||||
"loading": "加载中..."
|
||||
},
|
||||
"messages": {
|
||||
"deleted": "删除成功",
|
||||
"deleteFailed": "删除失败",
|
||||
"failedToAdd": "添加失败",
|
||||
"networkError": "网络错误",
|
||||
"requestFailed": "请求失败",
|
||||
"generationStopped": "已停止生成",
|
||||
"invalidJson": "无效的 JSON 格式",
|
||||
"importFailed": "导入失败",
|
||||
"copyFailed": "复制失败"
|
||||
},
|
||||
"landing": {
|
||||
"adminConsole": "管理面板",
|
||||
"apiStatus": "API 状态",
|
||||
"features": {
|
||||
"compatibility": {
|
||||
"title": "全面兼容",
|
||||
"desc": "适配 OpenAI 与 Claude 格式"
|
||||
},
|
||||
"loadBalancing": {
|
||||
"title": "负载均衡",
|
||||
"desc": "智能轮询,稳定高效"
|
||||
},
|
||||
"reasoning": {
|
||||
"title": "深度思考",
|
||||
"desc": "支持推理过程输出"
|
||||
},
|
||||
"search": {
|
||||
"title": "联网搜索",
|
||||
"desc": "集成原生网页搜索能力"
|
||||
}
|
||||
}
|
||||
},
|
||||
"accountManager": {
|
||||
"addKeySuccess": "API 密钥添加成功",
|
||||
"addAccountSuccess": "账号添加成功",
|
||||
"requiredFields": "需要填写密码以及邮箱或手机号",
|
||||
"deleteKeyConfirm": "确定要删除此 API 密钥吗?",
|
||||
"deleteAccountConfirm": "确定要删除此账号吗?",
|
||||
"testAllConfirm": "测试所有账号的 API 连通性?",
|
||||
"testAllCompleted": "完成:{success}/{total} 可用",
|
||||
"testFailed": "测试失败: {error}",
|
||||
"available": "可用",
|
||||
"inUse": "正在使用",
|
||||
"totalPool": "账号池总数",
|
||||
"accountsUnit": "个账号",
|
||||
"threadsUnit": "线程",
|
||||
"apiKeysTitle": "API 密钥",
|
||||
"apiKeysDesc": "管理 API 访问密钥池",
|
||||
"addKey": "添加密钥",
|
||||
"copied": "已复制",
|
||||
"copyKeyTitle": "复制密钥",
|
||||
"deleteKeyTitle": "删除密钥",
|
||||
"noApiKeys": "未找到 API 密钥",
|
||||
"accountsTitle": "DeepSeek 账号",
|
||||
"accountsDesc": "管理 DeepSeek 账号池",
|
||||
"testAll": "测试全部",
|
||||
"addAccount": "添加账号",
|
||||
"testingAllAccounts": "正在测试所有账号...",
|
||||
"sessionActive": "已建立会话",
|
||||
"reauthRequired": "需重新登录",
|
||||
"noAccounts": "未找到任何账号",
|
||||
"modalAddKeyTitle": "添加 API 密钥",
|
||||
"newKeyLabel": "新密钥值",
|
||||
"newKeyPlaceholder": "输入自定义 API 密钥",
|
||||
"generate": "生成",
|
||||
"generateHint": "点击「生成」自动创建随机密钥",
|
||||
"addKeyLoading": "添加中...",
|
||||
"addKeyAction": "添加密钥",
|
||||
"modalAddAccountTitle": "添加 DeepSeek 账号",
|
||||
"emailOptional": "邮箱 (可选)",
|
||||
"mobileOptional": "手机号 (可选)",
|
||||
"passwordLabel": "密码",
|
||||
"passwordPlaceholder": "账号密码",
|
||||
"addAccountLoading": "添加中...",
|
||||
"addAccountAction": "添加账号",
|
||||
"pageInfo": "第 {current}/{total} 页,共 {count} 个账号"
|
||||
},
|
||||
"apiTester": {
|
||||
"defaultMessage": "你好,请用一句话介绍你自己。",
|
||||
"models": {
|
||||
"chat": "非思考模型",
|
||||
"reasoner": "思考模型",
|
||||
"chatSearch": "非思考模型 (带搜索)",
|
||||
"reasonerSearch": "思考模型 (带搜索)"
|
||||
},
|
||||
"missingApiKey": "请提供 API 密钥",
|
||||
"requestFailed": "请求失败",
|
||||
"networkError": "网络错误: {error}",
|
||||
"testSuccess": "{account}: 测试成功 ({time}ms)",
|
||||
"config": "配置",
|
||||
"modelLabel": "模型",
|
||||
"streamMode": "流式模式",
|
||||
"accountSelector": "选择账号",
|
||||
"autoRandom": "🤖 自动 / 随机",
|
||||
"apiKeyOptional": "API 密钥 (可选)",
|
||||
"apiKeyDefault": "默认: ...{suffix}",
|
||||
"apiKeyPlaceholder": "输入自定义密钥",
|
||||
"statusError": "错误",
|
||||
"reasoningTrace": "思维链过程",
|
||||
"generating": "正在生成响应...",
|
||||
"enterMessage": "输入消息...",
|
||||
"adminConsoleLabel": "DeepSeek 管理员界面"
|
||||
},
|
||||
"batchImport": {
|
||||
"templates": {
|
||||
"full": {
|
||||
"name": "全量配置模板",
|
||||
"desc": "包含密钥、账号及模型映射"
|
||||
},
|
||||
"emailOnly": {
|
||||
"name": "仅邮箱账号",
|
||||
"desc": "批量导入邮箱格式账号"
|
||||
},
|
||||
"mobileOnly": {
|
||||
"name": "仅手机号账号",
|
||||
"desc": "批量导入手机号格式账号"
|
||||
},
|
||||
"keysOnly": {
|
||||
"name": "仅 API 密钥",
|
||||
"desc": "仅添加 API 访问密钥"
|
||||
}
|
||||
},
|
||||
"enterJson": "请输入 JSON 配置内容",
|
||||
"importSuccess": "导入成功: {keys} 个密钥, {accounts} 个账号",
|
||||
"templateLoaded": "已加载模板: {name}",
|
||||
"currentConfigLoaded": "当前配置已加载",
|
||||
"fetchConfigFailed": "获取配置失败",
|
||||
"copySuccess": "Base64 配置已复制到剪贴板",
|
||||
"quickTemplates": "快速模板",
|
||||
"dataExport": "数据导出",
|
||||
"dataExportDesc": "获取配置的 Base64 字符串,用于 Vercel 环境变量。",
|
||||
"copyBase64": "复制 Base64 配置",
|
||||
"copied": "已复制",
|
||||
"variableName": "变量名",
|
||||
"jsonEditor": "JSON 编辑器",
|
||||
"loadCurrentConfig": "加载当前配置",
|
||||
"applyConfig": "应用配置",
|
||||
"importing": "正在导入...",
|
||||
"importComplete": "导入操作已完成",
|
||||
"importSummary": "成功导入了 {keys} 个 API 密钥,并更新了 {accounts} 个账号。"
|
||||
},
|
||||
"login": {
|
||||
"welcome": "欢迎回来",
|
||||
"subtitle": "请输入管理员密钥以继续",
|
||||
"adminKeyLabel": "管理员密钥",
|
||||
"adminKeyPlaceholder": "输入您的管理员密钥...",
|
||||
"rememberSession": "记住登录状态",
|
||||
"signIn": "登录",
|
||||
"secureConnection": "安全连接",
|
||||
"adminPortal": "DS2API 管理员门户",
|
||||
"signInFailed": "登录失败",
|
||||
"networkError": "网络错误: {error}"
|
||||
},
|
||||
"vercel": {
|
||||
"tokenRequired": "需要 Vercel 访问令牌",
|
||||
"projectRequired": "需要项目 ID",
|
||||
"syncFailed": "同步失败",
|
||||
"networkError": "网络错误",
|
||||
"title": "Vercel 部署",
|
||||
"description": "将当前密钥和账号配置直接同步到 Vercel 环境变量中。",
|
||||
"tokenLabel": "Vercel 访问令牌",
|
||||
"getToken": "获取令牌",
|
||||
"tokenPlaceholderPreconfig": "正在使用预配置的令牌",
|
||||
"tokenPlaceholder": "输入 Vercel 访问令牌",
|
||||
"projectIdLabel": "项目 ID",
|
||||
"projectIdHint": "可在项目设置 (Project Settings) → 常规 (General) 中找到",
|
||||
"teamIdLabel": "团队 ID",
|
||||
"optional": "可选",
|
||||
"syncing": "正在同步...",
|
||||
"syncRedeploy": "同步并重新部署",
|
||||
"redeployHint": "这将触发 Vercel 的重新部署,大约需要 30-60 秒。",
|
||||
"syncSucceeded": "同步成功",
|
||||
"syncFailedLabel": "同步失败",
|
||||
"openDeployment": "访问部署地址",
|
||||
"statusSynced": "已同步",
|
||||
"statusNotSynced": "未同步",
|
||||
"statusNeverSynced": "从未同步",
|
||||
"lastSyncTime": "上次同步: {time}",
|
||||
"howItWorks": "工作原理",
|
||||
"steps": {
|
||||
"one": "当前配置 (密钥和账号) 被导出为 JSON 字符串。",
|
||||
"two": "JSON 被编码为 Base64 以确保格式兼容性。",
|
||||
"three": "更新 Vercel 项目中的环境变量:",
|
||||
"four": "触发重新部署以应用新的环境变量。"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,14 +2,17 @@ import React from 'react'
|
||||
import ReactDOM from 'react-dom/client'
|
||||
import { BrowserRouter } from 'react-router-dom'
|
||||
import App from './App.jsx'
|
||||
import { I18nProvider } from './i18n'
|
||||
import './styles.css'
|
||||
|
||||
const basename = import.meta.env.MODE === 'production' ? '/admin' : '/'
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')).render(
|
||||
<React.StrictMode>
|
||||
<BrowserRouter basename={basename}>
|
||||
<App />
|
||||
</BrowserRouter>
|
||||
<I18nProvider>
|
||||
<BrowserRouter basename={basename}>
|
||||
<App />
|
||||
</BrowserRouter>
|
||||
</I18nProvider>
|
||||
</React.StrictMode>,
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user