agnet step 1 add auth

This commit is contained in:
Jethro Lin 2024-12-04 11:24:47 +08:00
parent 7b376c2ed9
commit dca86354ba
15 changed files with 1961 additions and 3 deletions

View file

@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Services\Auth\TokenService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;
class AuthController extends Controller
{
public function __construct(
private readonly TokenService $tokenService
) {}
public function getAccessToken(Request $request): JsonResponse
{
try {
$validated = $request->validate([
'auth_token' => 'required|string',
]);
$authToken = $this->tokenService->validateAuthToken($validated['auth_token']);
if (!$authToken) {
return response()->json([
'error' => 'invalid_auth_token',
'message' => '认证令牌无效。',
], 401);
}
$accessToken = $this->tokenService->generateAccessToken($authToken);
return response()->json($accessToken);
} catch (ValidationException $e) {
return response()->json([
'error' => 'invalid_request',
'message' => '请求参数缺失。',
], 400);
} catch (\Exception $e) {
Log::error('Error generating access token', [
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
return response()->json([
'error' => 'server_error',
'message' => '服务器内部错误。',
], 500);
}
}
}

View file

@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace App\Http\Middleware;
use App\Services\Auth\TokenService;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class ValidateAccessToken
{
public function __construct(
private readonly TokenService $tokenService
) {}
public function handle(Request $request, Closure $next): Response
{
$bearerToken = $request->bearerToken();
if (!$bearerToken) {
return response()->json([
'error' => 'unauthorized',
'message' => '未授权,令牌无效或未提供。',
], 401);
}
$tokenData = $this->tokenService->validateAccessToken($bearerToken);
if (!$tokenData) {
return response()->json([
'error' => 'unauthorized',
'message' => '访问令牌无效或已过期。',
], 401);
}
// Add client information to the request for later use
$request->merge(['client_id' => $tokenData['client_id']]);
return $next($request);
}
}

37
app/Models/AuthToken.php Normal file
View file

@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class AuthToken extends Model
{
protected $table = 'auth_tokens';
protected $fillable = [
'client_id',
'token',
'expires_at',
];
protected $casts = [
'expires_at' => 'datetime',
];
public function client(): BelongsTo
{
return $this->belongsTo(Client::class);
}
public function isValid(): bool
{
if ($this->expires_at === null) {
return true;
}
return $this->expires_at->isFuture();
}
}

36
app/Models/Client.php Normal file
View file

@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Client extends Model
{
protected $table = 'clients';
protected $fillable = [
'name',
'llm_provider_id',
];
public function llmProvider(): BelongsTo
{
return $this->belongsTo(LlmProvider::class);
}
public function admins(): BelongsToMany
{
return $this->belongsToMany(Admin::class, 'admin_client')
->withTimestamp('assigned_at');
}
public function authTokens(): HasMany
{
return $this->hasMany(AuthToken::class);
}
}

View file

@ -2,7 +2,9 @@
namespace App\Providers;
use App\Http\Middleware\ValidateAccessToken;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Route;
class AppServiceProvider extends ServiceProvider
{
@ -19,6 +21,6 @@ public function register(): void
*/
public function boot(): void
{
//
Route::aliasMiddleware('auth.access_token', ValidateAccessToken::class);
}
}

View file

@ -0,0 +1,89 @@
<?php
declare(strict_types=1);
namespace App\Services\Auth;
use App\Models\AuthToken;
use App\Models\Client;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Str;
class TokenService
{
private const ACCESS_TOKEN_PREFIX = 'access_token:';
private const ACCESS_TOKEN_TTL = 3600; // 1 hour in seconds
public function generateAuthToken(Client $client, ?int $expiresInDays = null): AuthToken
{
$token = AuthToken::create([
'client_id' => $client->id,
'token' => Str::random(64),
'expires_at' => $expiresInDays ? now()->addDays($expiresInDays) : null,
]);
return $token;
}
public function generateAccessToken(AuthToken $authToken): array
{
$accessToken = Str::random(64);
$expiresAt = now()->addSeconds(self::ACCESS_TOKEN_TTL);
$tokenData = [
'client_id' => $authToken->client_id,
'expires_at' => $expiresAt->toIso8601String(),
];
Redis::setex(
self::ACCESS_TOKEN_PREFIX . $accessToken,
self::ACCESS_TOKEN_TTL,
json_encode($tokenData)
);
return [
'access_token' => $accessToken,
'expires_in' => self::ACCESS_TOKEN_TTL,
];
}
public function validateAuthToken(string $token): ?AuthToken
{
$authToken = AuthToken::where('token', $token)->first();
if (!$authToken || !$authToken->isValid()) {
return null;
}
return $authToken;
}
public function validateAccessToken(string $token): ?array
{
$tokenData = Redis::get(self::ACCESS_TOKEN_PREFIX . $token);
if (!$tokenData) {
return null;
}
$data = json_decode($tokenData, true);
$expiresAt = \DateTime::createFromFormat(\DateTime::ISO8601, $data['expires_at']);
if ($expiresAt < now()) {
$this->revokeAccessToken($token);
return null;
}
return $data;
}
public function revokeAccessToken(string $token): void
{
Redis::del(self::ACCESS_TOKEN_PREFIX . $token);
}
public function revokeAuthToken(AuthToken $authToken): void
{
$authToken->delete();
}
}

46
clear_and_cache.sh Normal file
View file

@ -0,0 +1,46 @@
#!/bin/bash
# 清除 Laravel 快取和重新快取設定
echo "Clearing Laravel caches..."
php artisan config:clear
if [ $? -eq 0 ]; then
echo "Config cache cleared successfully."
else
echo "Failed to clear config cache."
exit 1
fi
php artisan cache:clear
if [ $? -eq 0 ]; then
echo "Application cache cleared successfully."
else
echo "Failed to clear application cache."
exit 1
fi
php artisan route:clear
if [ $? -eq 0 ]; then
echo "Route cache cleared successfully."
else
echo "Failed to clear route cache."
exit 1
fi
php artisan view:clear
if [ $? -eq 0 ]; then
echo "View cache cleared successfully."
else
echo "Failed to clear view cache."
exit 1
fi
php artisan config:cache
if [ $? -eq 0 ]; then
echo "Config cache regenerated successfully."
else
echo "Failed to regenerate config cache."
exit 1
fi
echo "All Laravel cache operations completed successfully."

View file

@ -8,7 +8,8 @@
"require": {
"php": "^8.2",
"laravel/framework": "^11.31",
"laravel/tinker": "^2.9"
"laravel/tinker": "^2.9",
"predis/predis": "^2.3"
},
"require-dev": {
"fakerphp/faker": "^1.23",

63
composer.lock generated
View file

@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "626b9e7ddd47fb7eff9aaa53cce0c9ad",
"content-hash": "3c2add9f85c3cab994b57b6b8ff1eb72",
"packages": [
{
"name": "brick/math",
@ -2406,6 +2406,67 @@
],
"time": "2024-07-20T21:41:07+00:00"
},
{
"name": "predis/predis",
"version": "v2.3.0",
"source": {
"type": "git",
"url": "https://github.com/predis/predis.git",
"reference": "bac46bfdb78cd6e9c7926c697012aae740cb9ec9"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/predis/predis/zipball/bac46bfdb78cd6e9c7926c697012aae740cb9ec9",
"reference": "bac46bfdb78cd6e9c7926c697012aae740cb9ec9",
"shasum": ""
},
"require": {
"php": "^7.2 || ^8.0"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^3.3",
"phpstan/phpstan": "^1.9",
"phpunit/phpunit": "^8.0 || ^9.4"
},
"suggest": {
"ext-relay": "Faster connection with in-memory caching (>=0.6.2)"
},
"type": "library",
"autoload": {
"psr-4": {
"Predis\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Till Krüss",
"homepage": "https://till.im",
"role": "Maintainer"
}
],
"description": "A flexible and feature-complete Redis client for PHP.",
"homepage": "http://github.com/predis/predis",
"keywords": [
"nosql",
"predis",
"redis"
],
"support": {
"issues": "https://github.com/predis/predis/issues",
"source": "https://github.com/predis/predis/tree/v2.3.0"
},
"funding": [
{
"url": "https://github.com/sponsors/tillkruss",
"type": "github"
}
],
"time": "2024-11-21T20:00:02+00:00"
},
{
"name": "psr/clock",
"version": "1.0.0",

268
doc/db.md Normal file
View file

@ -0,0 +1,268 @@
# LLM API 转发平台数据库规格书
---
## 目录
1. [简介](#1-简介)
2. [数据库概览](#2-数据库概览)
3. [MySQL 数据库设计](#3-mysql-数据库设计)
- [3.1 管理员表admins](#31-管理员表admins)
- [3.2 客户用户表clients](#32-客户用户表clients)
- [3.3 LLM 提供商表llm_providers](#33-llm-提供商表llm_providers)
- [3.4 认证令牌表auth_tokens](#34-认证令牌表auth_tokens)
- [3.5 管理员与客户用户关联表admin_client](#35-管理员与客户用户关联表admin_client)
- [3.6 操作日志表operation_logs](#36-操作日志表operation_logs)
4. [Redis 缓存设计](#4-redis-缓存设计)
- [4.1 访问令牌存储](#41-访问令牌存储)
- [4.2 令牌注销机制](#42-令牌注销机制)
5. [数据库关系图](#5-数据库关系图)
6. [总结](#6-总结)
---
## 1. 简介
本规格书旨在基于之前的系统设计,详细设计 LLM API 转发平台的数据库结构。数据库采用 **MySQL** 作为主要的数据存储,**Redis** 用于缓存短期有效的访问令牌和支持动态注销功能。
---
## 2. 数据库概览
- **MySQL**持久化存储管理员、客户用户、LLM 提供商、认证令牌等信息。
- **Redis**:缓存短期访问令牌,实现高效验证和支持令牌的动态注销。
---
## 3. MySQL 数据库设计
### 3.1 管理员表(`admins`
**描述**:存储超级管理员和管理员的信息。
**字段**
| 字段名 | 数据类型 | 允许为空 | 默认值 | 描述 |
|-----------------|-----------------|----------|--------|----------------------|
| `id` | BIGINT UNSIGNED | 否 | 自增 | 主键 |
| `username` | VARCHAR(50) | 否 | | 用户名 |
| `password` | VARCHAR(255) | 否 | | 加密后的密码 |
| `email` | VARCHAR(100) | 是 | NULL | 邮箱 |
| `role` | ENUM('super', 'admin') | 否 | 'admin' | 角色,'super'为超级管理员,'admin'为管理员 |
| `created_at` | TIMESTAMP | 否 | 当前时间 | 创建时间 |
| `updated_at` | TIMESTAMP | 否 | 当前时间 | 更新时间 |
**索引**
- `UNIQUE INDEX``username`
- `INDEX``email`
### 3.2 客户用户表(`clients`
**描述**:存储客户用户的信息。
**字段**
| 字段名 | 数据类型 | 允许为空 | 默认值 | 描述 |
|-----------------------|-----------------|----------|--------|------------------------------|
| `id` | BIGINT UNSIGNED | 否 | 自增 | 主键 |
| `name` | VARCHAR(100) | 否 | | 客户用户名称 |
| `llm_provider_id` | BIGINT UNSIGNED | 否 | | 外键,关联到 `llm_providers.id` |
| `created_at` | TIMESTAMP | 否 | 当前时间 | 创建时间 |
| `updated_at` | TIMESTAMP | 否 | 当前时间 | 更新时间 |
**索引**
- `INDEX``llm_provider_id`
**外键约束**
- `llm_provider_id` 引用 `llm_providers.id`,级联更新和删除。
### 3.3 LLM 提供商表(`llm_providers`
**描述**:存储 LLM 提供商的信息。
**字段**
| 字段名 | 数据类型 | 允许为空 | 默认值 | 描述 |
|------------------|-----------------|----------|--------|------------------------------|
| `id` | BIGINT UNSIGNED | 否 | 自增 | 主键 |
| `name` | VARCHAR(100) | 否 | | 提供商名称 |
| `service_name` | VARCHAR(100) | 否 | | 服务名称,用于后端调用逻辑 |
| `api_url` | VARCHAR(255) | 否 | | 提供商的 API 接口地址 |
| `api_token` | VARCHAR(255) | 否 | | 调用提供商 API 所需的令牌 |
| `created_at` | TIMESTAMP | 否 | 当前时间 | 创建时间 |
| `updated_at` | TIMESTAMP | 否 | 当前时间 | 更新时间 |
**索引**
- `UNIQUE INDEX``name`
- `INDEX``service_name`
### 3.4 认证令牌表(`auth_tokens`
**描述**:存储客户用户的长期认证令牌。
**字段**
| 字段名 | 数据类型 | 允许为空 | 默认值 | 描述 |
|-----------------|-----------------|----------|--------|--------------------------------|
| `id` | BIGINT UNSIGNED | 否 | 自增 | 主键 |
| `client_id` | BIGINT UNSIGNED | 否 | | 外键,关联到 `clients.id` |
| `token` | CHAR(64) | 否 | | 认证令牌随机生成的64位字符串 |
| `expires_at` | TIMESTAMP | 是 | NULL | 过期时间NULL表示永久有效 |
| `created_at` | TIMESTAMP | 否 | 当前时间 | 创建时间 |
| `updated_at` | TIMESTAMP | 否 | 当前时间 | 更新时间 |
**索引**
- `UNIQUE INDEX``token`
- `INDEX``client_id`
**外键约束**
- `client_id` 引用 `clients.id`,级联删除。
### 3.5 管理员与客户用户关联表(`admin_client`
**描述**:存储管理员与客户用户的多对多关系。
**字段**
| 字段名 | 数据类型 | 允许为空 | 默认值 | 描述 |
|--------------|-----------------|----------|--------|-----------------------------|
| `admin_id` | BIGINT UNSIGNED | 否 | | 外键,关联到 `admins.id` |
| `client_id` | BIGINT UNSIGNED | 否 | | 外键,关联到 `clients.id` |
| `assigned_at`| TIMESTAMP | 否 | 当前时间 | 分配时间 |
**索引**
- `PRIMARY KEY`(`admin_id`, `client_id`)
- `INDEX``client_id`
**外键约束**
- `admin_id` 引用 `admins.id`,级联删除。
- `client_id` 引用 `clients.id`,级联删除。
### 3.6 操作日志表(`operation_logs`
**描述**:记录管理员和客户用户的操作日志。
**字段**
| 字段名 | 数据类型 | 允许为空 | 默认值 | 描述 |
|-----------------|-----------------|----------|--------|------------------------------|
| `id` | BIGINT UNSIGNED | 否 | 自增 | 主键 |
| `user_type` | ENUM('admin', 'client') | 否 | | 用户类型 |
| `user_id` | BIGINT UNSIGNED | 否 | | 用户ID关联管理员或客户用户 |
| `operation` | VARCHAR(255) | 否 | | 操作描述 |
| `ip_address` | VARCHAR(45) | 是 | NULL | IP地址支持IPv6 |
| `created_at` | TIMESTAMP | 否 | 当前时间 | 操作时间 |
**索引**
- `INDEX``user_type`, `user_id`
---
## 4. Redis 缓存设计
### 4.1 访问令牌存储
**描述**:存储客户用户的短期访问令牌,实现高效的令牌验证和自动过期。
- **Key 格式**`access_token:{token}`
- **Value 内容**:序列化的令牌信息,包括`client_id`、`expires_at`等。
**示例**
- **Key**`access_token:a1b2c3d4e5f6...`
- **Value**
```json
{
"client_id": 12345,
"expires_at": "2023-10-01T12:00:00Z"
}
```
- **过期策略**:设置 `TTL`,令牌将在 `expires_at` 到达时自动过期。
### 4.2 令牌注销机制
**描述**:支持访问令牌的即时注销,防止被滥用。
- **方案**:当需要注销令牌时,直接从 Redis 中删除对应的 `access_token:{token}` 键。
- **实现步骤**
1. 调用 Redis 的 `DEL` 命令删除指定的令牌键。
2. 后续的令牌验证中,如令牌不存在或已过期,则拒绝访问。
---
## 5. 数据库关系图
```
+----------------+ +----------------+ +----------------+
| admins | | clients | | llm_providers |
+----------------+ +----------------+ +----------------+
| id |<----->| id | | id |
| username | | name | | name |
| password | | llm_provider_id|<----->| service_name |
| role | | | | api_url |
+----------------+ +----------------+ | api_token |
^ ^ +----------------+
| |
| +---------------+
| |
+-----------------+
| admin_client |
+-----------------+
| admin_id |
| client_id |
+-----------------+
+----------------+
| auth_tokens |
+----------------+
| id |
| client_id |
| token |
+----------------+
```
**说明**
- `admins``clients` 之间是多对多关系,通过 `admin_client` 关联。
- `clients``llm_providers` 是多对一关系,`clients.llm_provider_id` 外键引用 `llm_providers.id`
- `clients``auth_tokens` 是一对多关系,一个客户用户可以有多个认证令牌。
---
## 6. 总结
以上是基于系统设计的数据库规格书,详细描述了 MySQL 中的表结构和 Redis 中的缓存设计。
- **MySQL**
- **管理员表**:存储超级管理员和管理员的信息。
- **客户用户表**:存储客户用户的信息,并绑定 LLM 提供商。
- **LLM 提供商表**:存储 LLM 提供商的配置和调用信息。
- **认证令牌表**:存储客户用户的长期认证令牌。
- **管理员与客户用户关联表**:实现管理员和客户用户的多对多关系。
- **操作日志表**:记录系统的操作日志,便于审计和追踪。
- **Redis**
- **访问令牌存储**:高效存储和验证短期访问令牌,支持自动过期和动态注销。
**注意事项**
- 所有涉及敏感信息的字段如密码、令牌、API Token在存储时应进行加密或哈希处理确保数据安全。
- 数据库的外键约束和索引设计应充分考虑性能和数据完整性。
- Redis 中的令牌管理应注意内存占用和过期策略,防止缓存过期造成的认证问题。
---
如有任何疑问或需要进一步的修改和完善,请随时联系数据库设计团队。

623
doc/llm_apiv1.txt Normal file
View file

@ -0,0 +1,623 @@
# LLM API 转发平台 API 开发文档
---
## 目录
1. [简介](#1-简介)
2. [认证与授权](#2-认证与授权)
- [2.1 认证令牌Auth Token](#21-认证令牌auth-token)
- [2.2 访问令牌Access Token](#22-访问令牌access-token)
3. [API 概览](#3-api-概览)
- [3.1 客户用户 API](#31-客户用户-api)
- [3.2 管理员 API](#32-管理员-api)
4. [API 详细说明](#4-api-详细说明)
- [4.1 认证 API](#41-认证-api)
- [4.1.1 获取访问令牌](#411-获取访问令牌)
- [4.2 客户用户 API](#42-客户用户-api)
- [4.2.1 发送提示词请求](#421-发送提示词请求)
- [4.3 管理员 API](#43-管理员-api)
- [4.3.1 LLM 提供商管理](#431-llm-提供商管理)
- [4.3.1.1 新增 LLM 提供商](#4311-新增-llm-提供商)
- [4.3.1.2 修改 LLM 提供商](#4312-修改-llm-提供商)
- [4.3.1.3 删除 LLM 提供商](#4313-删除-llm-提供商)
- [4.3.1.4 获取 LLM 提供商列表](#4314-获取-llm-提供商列表)
- [4.3.2 客户用户管理](#432-客户用户管理)
- [4.3.2.1 新增客户用户](#4321-新增客户用户)
- [4.3.2.2 修改客户用户](#4322-修改客户用户)
- [4.3.2.3 删除客户用户](#4323-删除客户用户)
- [4.3.2.4 获取客户用户列表](#4324-获取客户用户列表)
- [4.3.3 生成认证令牌](#433-生成认证令牌)
5. [请求与响应格式](#5-请求与响应格式)
- [5.1 通用请求头](#51-通用请求头)
- [5.2 响应格式](#52-响应格式)
6. [错误代码](#6-错误代码)
7. [安全性考虑](#7-安全性考虑)
8. [示例](#8-示例)
- [8.1 获取访问令牌示例](#81-获取访问令牌示例)
- [8.2 发送提示词请求示例](#82-发送提示词请求示例)
9. [结论](#9-结论)
---
## 1. 简介
本文档详细描述了 LLM API 转发平台的 API 接口规范,旨在指导开发者基于 Laravel、MySQL 和 Redis 技术栈,实现平台的 API 功能。平台提供了基于令牌的 LLM 调用服务,支持多层级管理员管理和 LLM 提供商的动态配置。
---
## 2. 认证与授权
平台采用基于令牌的认证机制,包括长期有效的**认证令牌Auth Token**和短期有效的**访问令牌Access Token**。
### 2.1 认证令牌Auth Token
- **用途**:客户用户使用认证令牌获取访问令牌。
- **特点**
- 由管理员生成并分发给客户用户。
- 长期有效,或由管理员设定过期时间。
### 2.2 访问令牌Access Token
- **用途**:客户用户使用访问令牌访问受保护的 API 接口。
- **特点**
- 由客户用户使用认证令牌获取。
- 短期有效(如 1 小时),存储在 Redis 中,支持自动过期和动态注销。
---
## 3. API 概览
### 3.1 客户用户 API
- **获取访问令牌**
- `POST /api/auth/token`
- **发送提示词请求**
- `POST /api/llm/request`
### 3.2 管理员 API
- **LLM 提供商管理**
- 新增 LLM 提供商:`POST /api/admin/llm-providers`
- 修改 LLM 提供商:`PUT /api/admin/llm-providers/{id}`
- 删除 LLM 提供商:`DELETE /api/admin/llm-providers/{id}`
- 获取 LLM 提供商列表:`GET /api/admin/llm-providers`
- **客户用户管理**
- 新增客户用户:`POST /api/admin/clients`
- 修改客户用户:`PUT /api/admin/clients/{id}`
- 删除客户用户:`DELETE /api/admin/clients/{id}`
- 获取客户用户列表:`GET /api/admin/clients`
- **生成认证令牌**
- `POST /api/admin/clients/{id}/auth-token`
---
## 4. API 详细说明
### 4.1 认证 API
#### 4.1.1 获取访问令牌
- **URL**`/api/auth/token`
- **方法**`POST`
- **描述**:使用认证令牌获取短期访问令牌。
**请求参数**
- **Header**
- `Content-Type: application/json`
- **Body**
```json
{
"auth_token": "string"
}
```
- `auth_token`(必填):管理员分发的认证令牌。
**响应示例**
- **成功**
```json
{
"access_token": "string",
"expires_in": 3600
}
```
- `access_token`:短期访问令牌。
- `expires_in`:令牌有效期,单位为秒。
- **失败**
```json
{
"error": "invalid_auth_token",
"message": "认证令牌无效。"
}
```
### 4.2 客户用户 API
#### 4.2.1 发送提示词请求
- **URL**`/api/llm/request`
- **方法**`POST`
- **描述**:使用访问令牌向绑定的 LLM 提供商发送提示词请求。
**请求参数**
- **Header**
- `Content-Type: application/json`
- `Authorization: Bearer {access_token}`
- **Body**
```json
{
"prompt": "string"
}
```
- `prompt`(必填):提示词内容。
**响应示例**
- **成功**
```json
{
"response": "LLM 提供商返回的响应内容"
}
```
- **失败**
```json
{
"error": "invalid_access_token",
"message": "访问令牌无效或已过期。"
}
```
### 4.3 管理员 API
> **注意**:管理员 API 需要使用管理员的身份认证(如 JWT Token 或 Session具体认证方式可根据系统需求设计。
#### 4.3.1 LLM 提供商管理
##### 4.3.1.1 新增 LLM 提供商
- **URL**`/api/admin/llm-providers`
- **方法**`POST`
- **描述**:新增一个 LLM 提供商。
**请求参数**
- **Header**
- `Content-Type: application/json`
- **Body**
```json
{
"name": "string",
"service_name": "string",
"api_url": "string",
"api_token": "string"
}
```
- `name`(必填):提供商名称。
- `service_name`(必填):对应的服务逻辑名称。
- `api_url`(必填):提供商的 API 接口地址。
- `api_token`(必填):调用提供商 API 所需的令牌。
**响应示例**
- **成功**
```json
{
"id": 1,
"name": "OpenAI",
"service_name": "OpenAIService",
"api_url": "https://api.openai.com/v1/engines/davinci/completions",
"api_token": "sk-xxxxx",
"created_at": "2023-10-01T12:00:00Z"
}
```
- **失败**
```json
{
"error": "validation_error",
"message": "提供商名称已存在。"
}
```
##### 4.3.1.2 修改 LLM 提供商
- **URL**`/api/admin/llm-providers/{id}`
- **方法**`PUT`
- **描述**:修改指定的 LLM 提供商信息。
**请求参数**
- **路径参数**
- `id`必填LLM 提供商的 ID。
- **Header**
- `Content-Type: application/json`
- **Body**
```json
{
"name": "string",
"service_name": "string",
"api_url": "string",
"api_token": "string"
}
```
- 参数同新增接口,可选填。
**响应示例**
- **成功**
```json
{
"id": 1,
"name": "OpenAI",
"service_name": "OpenAIService",
"api_url": "https://api.openai.com/v1/engines/davinci/completions",
"api_token": "sk-xxxxx",
"updated_at": "2023-10-02T12:00:00Z"
}
```
- **失败**
```json
{
"error": "not_found",
"message": "LLM 提供商不存在。"
}
```
##### 4.3.1.3 删除 LLM 提供商
- **URL**`/api/admin/llm-providers/{id}`
- **方法**`DELETE`
- **描述**:删除指定的 LLM 提供商。
**请求参数**
- **路径参数**
- `id`必填LLM 提供商的 ID。
**响应示例**
- **成功**
```json
{
"message": "LLM 提供商已删除。"
}
```
- **失败**
```json
{
"error": "not_found",
"message": "LLM 提供商不存在。"
}
```
##### 4.3.1.4 获取 LLM 提供商列表
- **URL**`/api/admin/llm-providers`
- **方法**`GET`
- **描述**:获取所有 LLM 提供商的列表。
**响应示例**
- **成功**
```json
[
{
"id": 1,
"name": "OpenAI",
"service_name": "OpenAIService",
"api_url": "https://api.openai.com/v1/engines/davinci/completions",
"created_at": "2023-10-01T12:00:00Z"
},
{
"id": 2,
"name": "Anthropic",
"service_name": "AnthropicService",
"api_url": "https://api.anthropic.com/v1/complete",
"created_at": "2023-10-01T13:00:00Z"
}
]
```
#### 4.3.2 客户用户管理
##### 4.3.2.1 新增客户用户
- **URL**`/api/admin/clients`
- **方法**`POST`
- **描述**:新增一个客户用户,并绑定 LLM 提供商。
**请求参数**
- **Header**
- `Content-Type: application/json`
- **Body**
```json
{
"name": "string",
"llm_provider_id": 1
}
```
- `name`(必填):客户用户名称。
- `llm_provider_id`(必填):绑定的 LLM 提供商 ID。
**响应示例**
- **成功**
```json
{
"id": 1001,
"name": "Client A",
"llm_provider_id": 1,
"created_at": "2023-10-01T14:00:00Z"
}
```
- **失败**
```json
{
"error": "validation_error",
"message": "客户用户名称已存在。"
}
```
##### 4.3.2.2 修改客户用户
- **URL**`/api/admin/clients/{id}`
- **方法**`PUT`
- **描述**:修改指定的客户用户信息。
**请求参数**
- **路径参数**
- `id`(必填):客户用户的 ID。
- **Header**
- `Content-Type: application/json`
- **Body**
```json
{
"name": "string",
"llm_provider_id": 2
}
```
- 参数可选填。
**响应示例**
- **成功**
```json
{
"id": 1001,
"name": "Client A Updated",
"llm_provider_id": 2,
"updated_at": "2023-10-02T14:00:00Z"
}
```
- **失败**
```json
{
"error": "not_found",
"message": "客户用户不存在。"
}
```
##### 4.3.2.3 删除客户用户
- **URL**`/api/admin/clients/{id}`
- **方法**`DELETE`
- **描述**:删除指定的客户用户。
**请求参数**
- **路径参数**
- `id`(必填):客户用户的 ID。
**响应示例**
- **成功**
```json
{
"message": "客户用户已删除。"
}
```
- **失败**
```json
{
"error": "not_found",
"message": "客户用户不存在。"
}
```
##### 4.3.2.4 获取客户用户列表
- **URL**`/api/admin/clients`
- **方法**`GET`
- **描述**:获取所有客户用户的列表。
**响应示例**
- **成功**
```json
[
{
"id": 1001,
"name": "Client A",
"llm_provider_id": 1,
"created_at": "2023-10-01T14:00:00Z"
},
{
"id": 1002,
"name": "Client B",
"llm_provider_id": 2,
"created_at": "2023-10-01T15:00:00Z"
}
]
```
#### 4.3.3 生成认证令牌
- **URL**`/api/admin/clients/{id}/auth-token`
- **方法**`POST`
- **描述**:为指定的客户用户生成一个新的认证令牌。
**请求参数**
- **路径参数**
- `id`(必填):客户用户的 ID。
**响应示例**
- **成功**
```json
{
"client_id": 1001,
"auth_token": "abcd1234efgh5678ijkl9012mnop3456qrst7890uvwx1234yzab5678cdef9012",
"created_at": "2023-10-01T16:00:00Z"
}
```
- **失败**
```json
{
"error": "not_found",
"message": "客户用户不存在。"
}
```
---
## 5. 请求与响应格式
### 5.1 通用请求头
- `Content-Type: application/json`
- 对于需要认证的接口,使用以下方式传递令牌:
- **客户用户访问令牌**`Authorization: Bearer {access_token}`
- **管理员认证**:根据系统设计,可采用 `Authorization: Bearer {admin_token}`,或使用 Session/Cookie。
### 5.2 响应格式
- 所有响应均为 JSON 格式。
- 成功响应:
- HTTP 状态码为 `200` 或 `201`,响应体为请求的数据。
- 失败响应:
- HTTP 状态码为 `4xx` 或 `5xx`,响应体包含 `error` 和 `message` 字段。
**错误响应示例**
```json
{
"error": "invalid_request",
"message": "请求参数缺失。"
}
```
---
## 6. 错误代码
| 错误代码 | HTTP 状态码 | 描述 |
|------------------------|-------------|------------------------------|
| `invalid_request` | 400 | 请求无效,参数缺失或格式错误。 |
| `unauthorized` | 401 | 未授权,令牌无效或未提供。 |
| `forbidden` | 403 | 禁止访问,没有权限。 |
| `not_found` | 404 | 资源不存在。 |
| `validation_error` | 422 | 请求参数验证失败。 |
| `server_error` | 500 | 服务器内部错误。 |
---
## 7. 安全性考虑
- **HTTPS 加密**:所有 API 请求必须通过 HTTPS 协议,确保数据传输的安全性。
- **令牌安全**
- 认证令牌和访问令牌应保密存储,避免泄露。
- 令牌在传输过程中只能通过 `Authorization` 头部发送,避免在 URL 或请求体中传递。
- **权限控制**
- 后端需要验证令牌的有效性和权限,防止未授权的访问。
- 管理员和客户用户的权限应严格区分,防止越权操作。
- **输入验证**
- 对所有输入参数进行严格的格式和类型验证,防止 SQL 注入和 XSS 攻击。
- **错误信息**
- 返回的错误信息应简洁明了,避免泄露服务器内部信息。
---
## 8. 示例
### 8.1 获取访问令牌示例
**请求**
```http
POST /api/auth/token HTTP/1.1
Host: api.yourdomain.com
Content-Type: application/json
{
"auth_token": "abcd1234efgh5678ijkl9012mnop3456qrst7890uvwx1234yzab5678cdef9012"
}
```
**响应**
```json
{
"access_token": "wxyz1234abcd5678efgh9012ijkl3456mnop7890qrst1234uvwx5678yzab9012",
"expires_in": 3600
}
```
### 8.2 发送提示词请求示例
**请求**
```http
POST /api/llm/request HTTP/1.1
Host: api.yourdomain.com
Content-Type: application/json
Authorization: Bearer wxyz1234abcd5678efgh9012ijkl3456mnop7890qrst1234uvwx5678yzab9012
{
"prompt": "Hello, how are you?"
}
```
**响应**
```json
{
"response": "I'm doing well, thank you for asking!"
}
```
---
## 9. 结论
本 API 开发文档详细描述了 LLM API 转发平台的各项接口、请求与响应格式、错误代码和安全性考虑。开发者应根据本规范进行接口的开发与测试,确保系统的稳定性和安全性。
---
**注意**:在实际开发中,可能需要根据具体的业务需求和技术选型,进一步完善和调整本 API 文档。
---
# 附录
## 技术栈说明
- **Laravel**PHP 的优秀框架,提供了丰富的功能和高效的开发体验。
- **MySQL**:关系型数据库,存储平台的核心数据。
- **Redis**:高性能的内存缓存数据库,用于存储短期令牌和支持动态注销。
## 开发建议
- **代码规范**:遵循 Laravel 和 PHP 的代码规范,使用 PSR 标准。
- **日志记录**:重要的操作和错误需要记录日志,便于追踪和排查问题。
- **单元测试**:编写单元测试和集成测试,确保接口的稳定性和可靠性。
- **性能优化**:关注接口的性能,使用缓存、异步等方式优化响应速度。
---
**感谢阅读本 API 开发文档,如有任何疑问或建议,请与项目组联系。**

View file

@ -0,0 +1,227 @@
# Requirements and Rules Document for LLM API Forwarding Platform
## 1. Introduction
This document outlines the requirements and rules for an LLM (Large Language Model) API forwarding platform. The system enables clients to send prompts to various LLMs and receive responses, managing access through a token-based authentication system. The platform includes separate components for administrators and clients, each with distinct functionalities and access levels.
## 2. System Overview
The platform consists of two main components:
- **Frontend API**: Receives prompts from clients and forwards them to the appropriate LLM based on the client's token.
- **Admin Backend**: Enables administrators to manage client users and other administrators via a separate frontend interface.
The system employs a token-based authentication mechanism, using authentication tokens and access tokens to control access and usage. Client users do not need to log in; they interact with the system using tokens provided by administrators.
## 3. Components
### 3.1 Frontend API
- **Type**: Pure API endpoint (no user interface).
- **Functionality**:
- Receives prompts from clients.
- Determines which LLM to route the prompt to based on the client's token.
- Forwards the prompt to the designated LLM.
- Returns the LLM's response to the client in JSON format.
- **Token Handling**:
- Validates the client's access token before processing the request.
- Access tokens are short-term and obtained using authentication tokens.
### 3.2 Admin Backend
- **Type**: Backend API endpoint with a separate frontend interface for administrators.
- **Functionality**:
- Administrators log in via the frontend interface using a username and password.
- Provides APIs for administrative tasks.
- Administrators can:
- Change their passwords.
- Add new client users.
- Manage authentication tokens for clients.
- Add new administrators (if they have Super Administrator privileges).
- **Client User Management**:
- When adding a new client user, the system:
- Generates one or more authentication tokens for the client.
- Displays the authentication tokens to the administrator.
- Administrators provide these tokens to the client users securely.
- **User Roles**:
- **Super Administrator**: Has full control, including adding other administrators.
- **Administrator**: Can manage client users and their tokens but can only add administrators if they have the necessary privileges.
## 4. User Roles
- **Super Administrator**
- Highest level of access.
- Can add and manage administrators and client users.
- Issues authentication tokens to clients.
- **Administrator**
- Can manage client users.
- Issues authentication tokens.
- Can change their own password.
- **Client User**
- Does not have a username or password.
- Uses tokens provided by administrators to interact with the system.
- Can have multiple authentication tokens.
- Obtains access tokens using their authentication tokens to use the LLM services.
## 5. Authentication and Authorization
### 5.1 Tokens
- **Authentication Tokens**
- Long-term tokens provided by administrators.
- Clients can have multiple authentication tokens.
- Used to obtain short-term access tokens.
- **Access Tokens**
- Short-term tokens (valid for one hour).
- Used to authenticate requests to the Frontend API.
### 5.2 Token Workflow
1. **Issuance**
- Administrators generate authentication tokens for client users.
- Administrators can generate multiple authentication tokens per client for different purposes.
- The system displays the authentication tokens to the administrator upon creation.
- Administrators securely provide these tokens to the client users.
2. **Access Token Retrieval**
- Clients use their authentication tokens to request access tokens.
3. **Service Access**
- Clients use the access tokens to interact with the Frontend API and send prompts to the LLM.
### 5.3 Access Control
- Access to different LLMs is determined by the client's tokens.
- The system ensures that clients can only access LLMs they are authorized to use.
- Authentication tokens can have specific permissions or access levels assigned by administrators.
## 6. Site-Wide Rules
- **Frontend and Backend Separation**
- The system architecture separates frontend interfaces from backend services.
- Communication occurs through APIs.
- **Frontends**
- **Admin Frontend**: For administrators to perform management tasks.
- **No Open Registration**
- New client users are added exclusively by administrators.
- There is no public registration API or interface.
- **User Levels**
- Users are categorized into three levels: Super Administrator, Administrator, and Client User.
- **Token Types**
- Clients use two types of tokens: authentication tokens and access tokens.
- Access tokens are required for using LLM services.
## 7. Additional Requirements and Considerations
### 7.1 Client User Management
- **Multiple Authentication Tokens**
- Clients can have multiple authentication tokens.
- Each authentication token is unique and can be managed independently.
- **Token Management Features**
- **Token List**: Administrators can view and manage all authentication tokens for a client.
- **Token Revocation**: Administrators can deactivate or revoke authentication tokens if necessary.
- **Token Naming**: Administrators can assign names or descriptions to tokens for easier management.
- **Permissions and Access Levels**: Authentication tokens can have different access levels or permissions assigned.
### 7.2 Security
- **Encryption**
- All data transmissions should use HTTPS to secure communications.
- **Token Security**
- Tokens should be securely stored and transmitted.
- Implement measures to prevent token theft and misuse.
- **Administrator Password Policies**
- Enforce strong password requirements for administrators.
- **Vulnerability Protection**
- Protect against common security threats like SQL injection, XSS, CSRF, etc.
- **Token Rotation**
- Encourage regular rotation of authentication tokens for enhanced security.
### 7.3 Error Handling
- Provide clear and descriptive error messages in JSON format.
- Handle token expiration and invalidation gracefully, prompting clients to obtain a new access token if necessary.
### 7.4 Logging and Monitoring
- **Activity Logging**
- Log all authentication attempts, token issuances, user creations, token revocations, and API interactions.
- **Monitoring**
- Implement monitoring tools to track system performance and detect anomalies.
### 7.5 Scalability
- Design the system to handle increasing numbers of clients and requests.
- Consider load balancing and resource optimization strategies.
### 7.6 Rate Limiting
- Implement rate limiting to prevent abuse and ensure fair usage.
- Define rate limits per client or per token as necessary.
### 7.7 Documentation
- Provide comprehensive documentation for administrators and clients.
- Include guidelines on token management, API usage, and best practices.
### 7.8 Internationalization and Localization
- Consider supporting multiple languages for the admin frontend interface.
- Ensure date, time, and numerical formats are adaptable to different locales.
### 7.9 Compliance
- Ensure the system complies with relevant laws and regulations, such as data protection and privacy laws (e.g., GDPR).
- Implement data retention and deletion policies as required.
### 7.10 Backup and Recovery
- Establish regular backup procedures for critical data.
- Develop a disaster recovery plan to restore services in case of system failure.
### 7.11 Future Enhancements
- **Self-Service Features**
- Allow clients to request additional services or features through secure channels.
- **Analytics**
- Provide analytics and reporting tools for administrators to monitor usage patterns.
- **Third-Party Integrations**
- Explore integration with external services or additional LLM providers.
## 8. Assumptions and Constraints
- **No Code or API Specifications Provided**
- This document focuses on functional requirements and rules, not implementation details.
- **Closed System**
- The platform is intended for use by authorized clients and administrators only.
- **Token Validity Periods**
- Authentication tokens have long-term validity, while access tokens expire after one hour.
- **System Availability**
- The platform should aim for high availability, minimizing downtime and maintenance windows.
## 9. Summary of Key Points
- **Clients Use Tokens Exclusively**
- Clients interact with the system using tokens provided by administrators.
- Clients do not have usernames and passwords.
- **Administrator Responsibilities**
- Administrators manage client users and tokens.
- When adding client users, administrators generate and provide authentication tokens.
- **Multiple Authentication Tokens per Client**
- Clients can have multiple authentication tokens for different purposes.
- This allows for greater flexibility and security in managing access.
- **Access Control via Tokens**
- Permissions and access to specific LLMs can be controlled via tokens.
- Tokens can have specific permissions or access levels assigned.
---
This comprehensive requirements document integrates all previous adjustments and considerations, including:
- The removal of client usernames and passwords.
- The use of tokens exclusively for client authentication.
- The ability for clients to have multiple authentication tokens.
- The inclusion of token management features for administrators.
- The display of authentication tokens to administrators when creating client users.
I hope this document meets your needs and accurately reflects all the requirements and adjustments discussed.

239
doc/systemDesign.md Normal file
View file

@ -0,0 +1,239 @@
# LLM API 转发平台系统设计书
---
## 1. 系统概览
### 1.1 系统目标
- **基于令牌的 LLM API 转发平台**:建立一个平台,允许客户用户通过认证和访问令牌,向绑定的 LLM 提供商发送提示词并获取响应。
- **多层级管理员功能**
- **超级管理员**:管理所有管理员、客户用户和 LLM 提供商。
- **管理员**:管理分配给他们的客户用户和对应的 LLM 提供商。
- **LLM 提供商管理功能**:支持管理员通过后台管理不同的 LLM 提供商及其对应的服务处理逻辑。
- **高性能与安全性**:利用 Redis 提升短期令牌的验证性能,支持动态注销,确保系统安全。
### 1.2 技术选型
- **后端框架Laravel**
- 支持服务容器绑定和多种中间件扩展,便于实现动态服务逻辑。
- **数据库MySQL**
- 用于存储管理员、客户用户、令牌、LLM 提供商等数据。
- **缓存系统Redis**
- 存储短期访问令牌,实现高效验证和动态注销。
- **安全措施**
- 强制使用 HTTPS 加密通信。
- 敏感数据如令牌和 LLM 提供商配置加密存储。
---
## 2. 系统架构
### 2.1 核心组件
#### 1. **Frontend API**
- **功能**
- 面向客户用户的 API 服务。
- 根据客户用户的 LLM 配置,路由请求至对应的 LLM 提供商。
- 动态调用不同的响应处理逻辑,适配各 LLM 提供商。
#### 2. **Admin Backend**
- **功能**
- 面向管理员的后台管理模块。
- 支持管理员对客户用户、令牌和 LLM 提供商的管理。
- 提供 LLM 提供商管理功能,允许新增、修改和删除 LLM 提供商。
#### 3. **数据库层MySQL**
- **功能**
- 持久化存储管理员、客户用户、令牌、LLM 提供商等信息。
- 支持复杂的关系管理和查询。
#### 4. **缓存层Redis**
- **功能**
- 存储短期访问令牌,实现高效验证和动态注销。
- 支持令牌的自动过期和主动注销。
---
### 2.2 模块划分
#### 1. **身份验证模块**
- **功能**
- 管理认证令牌和访问令牌的生成、验证与注销。
- 使用 Redis 提升验证性能,支持动态注销。
#### 2. **客户用户管理模块**
- **功能**
- 管理员可以添加、修改、删除客户用户。
- 客户用户绑定特定的 LLM 提供商。
#### 3. **LLM 提供商管理模块**
- **功能**
- 管理员可以管理 LLM 提供商列表。
- 每个提供商需配置名称、服务名称对应的服务逻辑、URL 和 Token。
#### 4. **日志与监控模块**
- **功能**
- 记录系统操作日志,便于审计和故障排查。
- 提供系统性能监控接口,支持集成第三方监控工具。
#### 5. **安全模块**
- **功能**
- 实现 HTTPS 加密通信。
- 防御常见的安全攻击,如 SQL 注入、XSS、CSRF 等。
- 管理令牌的安全性,支持即时注销和过期机制。
---
## 3. 数据流程
### 3.1 客户用户使用流程
1. **认证令牌分发**
- 管理员通过后台为客户用户生成认证令牌,并分发给客户用户。
2. **生成访问令牌**
- 客户用户使用认证令牌,通过 API 获取短期访问令牌。
3. **提示词请求**
- 客户用户使用访问令牌,向 Frontend API 发送提示词请求。
- 系统根据客户用户绑定的 LLM 提供商,调用对应的服务逻辑,发送请求并获取响应。
- 返回处理后的 LLM 响应给客户用户。
---
### 3.2 管理员操作流程
1. **管理员登录**
- 超级管理员和管理员使用用户名和密码登录管理后台。
2. **客户用户管理**
- 超级管理员可以管理所有客户用户。
- 管理员只能管理分配给他们的客户用户。
3. **LLM 提供商管理**
- 管理员可以新增、修改、删除 LLM 提供商。
- 配置提供商的名称、服务名称、URL、Token 等信息。
4. **令牌管理**
- 管理员为客户用户生成和管理认证令牌。
- 可以查看、修改或注销令牌。
---
## 4. 关键技术实现
### 4.1 令牌机制
- **认证令牌**
- 长期有效,由管理员生成,客户用户使用其获取访问令牌。
- **访问令牌**
- 短期有效(如 1 小时),存储在 Redis 中,支持自动过期和动态注销。
### 4.2 权限控制
- **超级管理员**
- 具有全局权限,管理所有资源,包括管理员、客户用户和 LLM 提供商。
- **管理员**
- 管理分配给他们的客户用户和 LLM 提供商。
- 无法访问其他管理员的资源。
### 4.3 LLM 提供商管理
#### 功能描述
- **提供商管理**
- 管理员可通过后台管理 LLM 提供商列表。
- 每个提供商需配置:
- 提供商名称(如 OpenAI、Anthropic 等)。
- 服务名称(对应 Laravel 中的服务类,用于处理逻辑)。
- API URL 和访问 Token。
- **客户用户绑定**
- 客户用户在创建或修改时,需要绑定一个 LLM 提供商。
#### 业务规则
- **权限限制**
- 管理员只能管理自己添加的 LLM 提供商。
- 超级管理员可以管理所有 LLM 提供商。
- **动态调用**
- 系统根据客户用户绑定的 LLM 提供商,动态调用对应的服务逻辑,适配不同的请求和响应格式。
---
## 5. 安全设计
### 5.1 加密通信
- **HTTPS 强制加密**:所有通信均通过 HTTPS确保数据传输安全。
### 5.2 权限隔离
- **数据隔离**
- 管理员和客户用户的资源严格隔离,防止未授权访问。
- **令牌安全**
- 令牌在存储和传输过程中均加密,防止泄露。
### 5.3 令牌注销
- **即时注销**
- 支持管理员主动注销令牌,令牌立即失效。
- **动态验证**
- 使用 Redis 存储令牌状态,支持高效的验证和注销。
---
## 6. 部署架构
### 6.1 服务分层
1. **应用层**
- 部署 Laravel 应用,分别处理 Frontend API 和 Admin Backend。
2. **缓存层**
- 部署 Redis用于存储和管理短期访问令牌。
3. **数据库层**
- 部署 MySQL存储持久化数据。
4. **日志与监控层**
- 部署 ELK 或 Prometheus用于日志收集和系统监控。
### 6.2 部署方式
- **容器化部署**
- 使用 Docker 对各服务进行容器化,便于部署和扩展。
- **负载均衡**
- 使用 Nginx 或其他负载均衡器,实现流量分发和高可用性。
- **高可用性**
- 数据库和 Redis 配置主从或集群模式,支持高并发和容错。
---
## 7. 总结
- **灵活性**
- 系统支持管理员动态管理 LLM 提供商,便于扩展和维护。
- **安全性**
- 采用多重安全措施,确保系统和数据的安全。
- **可扩展性**
- 系统架构设计支持高并发和横向扩展,满足业务增长需求。
如有任何进一步的需求或需要调整的地方,请随时告知!

217
doc/userflow.md Normal file
View file

@ -0,0 +1,217 @@
# LLM API 转发平台使用者操作流程说明书
---
## 目录
1. [简介](#1-简介)
2. [角色与权限](#2-角色与权限)
3. [操作流程概览](#3-操作流程概览)
4. [管理员操作指南](#4-管理员操作指南)
- [4.1 登录后台管理系统](#41-登录后台管理系统)
- [4.2 管理LLM提供商](#42-管理llm提供商)
- [4.2.1 新增LLM提供商](#421-新增llm提供商)
- [4.2.2 修改LLM提供商](#422-修改llm提供商)
- [4.2.3 删除LLM提供商](#423-删除llm提供商)
- [4.3 管理客户用户](#43-管理客户用户)
- [4.3.1 新增客户用户](#431-新增客户用户)
- [4.3.2 修改客户用户](#432-修改客户用户)
- [4.3.3 删除客户用户](#433-删除客户用户)
- [4.4 生成和管理认证令牌](#44-生成和管理认证令牌)
5. [客户用户操作指南](#5-客户用户操作指南)
- [5.1 获取访问令牌](#51-获取访问令牌)
- [5.2 发送提示词请求](#52-发送提示词请求)
6. [常见问题与解答](#6-常见问题与解答)
7. [技术支持](#7-技术支持)
---
## 1. 简介
本说明书旨在指导**管理员**和**客户用户**如何使用LLM API转发平台。平台提供了基于令牌的LLM大型语言模型调用服务支持多层级管理员管理和LLM提供商的动态配置。
---
## 2. 角色与权限
- **超级管理员**
- 拥有系统最高权限。
- 可以管理所有管理员、客户用户和LLM提供商。
- **管理员**
- 可以管理分配给他们的客户用户和LLM提供商。
- 无法访问其他管理员的资源。
- **客户用户**
- 通过认证令牌和访问令牌与系统交互。
- 只能使用绑定的LLM提供商进行提示词请求。
---
## 3. 操作流程概览
1. **管理员登录后台管理系统**
2. **管理员管理LLM提供商**
- 新增、修改或删除LLM提供商。
3. **管理员管理客户用户**
- 新增客户用户并绑定LLM提供商。
- 为客户用户生成认证令牌。
4. **客户用户使用认证令牌获取访问令牌**
5. **客户用户使用访问令牌发送提示词请求**
---
## 4. 管理员操作指南
### 4.1 登录后台管理系统
1. **打开浏览器**访问后台管理系统URL。
2. 在登录页面输入**用户名**和**密码**。
3. 点击“**登录**”按钮进入后台管理界面。
### 4.2 管理LLM提供商
管理员可以通过后台管理界面管理LLM提供商。
#### 4.2.1 新增LLM提供商
1. 在左侧导航栏选择“**LLM提供商管理**”。
2. 点击“**新增提供商**”按钮。
3. 填写提供商信息:
- **提供商名称**如OpenAI、Anthropic等。
- **服务名称**:对应后端服务逻辑的名称。
- **API URL**提供商的API接口地址。
- **访问Token**调用提供商API所需的令牌。
4. 确认信息无误后,点击“**保存**”按钮。
#### 4.2.2 修改LLM提供商
1. 在“**LLM提供商管理**”列表中,找到需要修改的提供商。
2. 点击对应行的“**编辑**”按钮。
3. 修改需要更新的提供商信息。
4. 点击“**保存**”按钮。
#### 4.2.3 删除LLM提供商
1. 在“**LLM提供商管理**”列表中,找到需要删除的提供商。
2. 点击对应行的“**删除**”按钮。
3. 系统会弹出确认提示,点击“**确认**”进行删除。
> **注意**删除LLM提供商会影响绑定了该提供商的客户用户请谨慎操作。
### 4.3 管理客户用户
#### 4.3.1 新增客户用户
1. 在左侧导航栏选择“**客户用户管理**”。
2. 点击“**新增客户用户**”按钮。
3. 填写客户用户信息:
- **用户名称**:客户用户的名称或标识。
- **绑定LLM提供商**从下拉列表中选择一个LLM提供商。
4. 点击“**保存**”按钮。
#### 4.3.2 修改客户用户
1. 在“**客户用户管理**”列表中,找到需要修改的客户用户。
2. 点击对应行的“**编辑**”按钮。
3. 修改客户用户的信息或更换绑定的LLM提供商。
4. 点击“**保存**”按钮。
#### 4.3.3 删除客户用户
1. 在“**客户用户管理**”列表中,找到需要删除的客户用户。
2. 点击对应行的“**删除**”按钮。
3. 系统会弹出确认提示,点击“**确认**”进行删除。
### 4.4 生成和管理认证令牌
1. 在“**客户用户管理**”列表中,找到需要生成令牌的客户用户。
2. 点击对应行的“**生成认证令牌**”按钮。
3. 系统将生成一个新的认证令牌,并显示在页面上。
4. 将认证令牌安全地发送给客户用户。
> **提示**:认证令牌是客户用户获取访问令牌的凭证,请确保安全传输。
---
## 5. 客户用户操作指南
### 5.1 获取访问令牌
客户用户需要使用认证令牌获取短期有效的访问令牌。
1. **发送请求**
- URL`https://api.yourdomain.com/auth/token`
- 方法:`POST`
- 请求头:
- `Content-Type: application/json`
- 请求体:
```json
{
"auth_token": "您的认证令牌"
}
```
2. **接收响应**
- 成功时,返回:
```json
{
"access_token": "您的访问令牌",
"expires_in": 3600
}
```
- `access_token`短期访问令牌有效期一般为1小时。
- `expires_in`:令牌有效期,单位为秒。
### 5.2 发送提示词请求
使用获取的访问令牌,向平台发送提示词请求。
1. **发送请求**
- URL`https://api.yourdomain.com/llm/request`
- 方法:`POST`
- 请求头:
- `Content-Type: application/json`
- `Authorization: Bearer 您的访问令牌`
- 请求体:
```json
{
"prompt": "您的提示词内容"
}
```
2. **接收响应**
- 成功时返回LLM提供商处理后的响应内容。
- 失败时,返回错误信息,如令牌失效、权限不足等。
> **注意**:请确保在访问令牌有效期内发送请求,过期后需要重新获取访问令牌。
---
## 6. 常见问题与解答
**Q1**:访问令牌过期了怎么办?
- **A**访问令牌有效期一般为1小时过期后需要使用认证令牌重新获取新的访问令牌。
**Q2**:提示“认证令牌无效”如何处理?
- **A**:请确认您使用的认证令牌是否正确,若仍有问题,请联系管理员重新生成认证令牌。
**Q3**无法获取LLM响应或响应异常
- **A**可能是绑定的LLM提供商配置有误或LLM服务暂时不可用请联系管理员检查LLM提供商设置。
**Q4**:如何保证令牌的安全性?
- **A**请妥善保管您的认证令牌和访问令牌避免泄露。令牌仅应在HTTPS加密的环境下传输。
---
## 7. 技术支持
如在使用过程中遇到任何问题,请联系技术支持:
- **邮箱**support@yourdomain.com
- **电话**+86-123-4567-890
- **工作时间**:周一至周五 9:00 - 18:00
---
感谢您使用LLM API转发平台您的满意是我们最大的动力

12
routes/api.php Normal file
View file

@ -0,0 +1,12 @@
<?php
use App\Http\Controllers\Api\AuthController;
use Illuminate\Support\Facades\Route;
// Public routes
Route::post('/auth/token', [AuthController::class, 'getAccessToken']);
// Protected routes (require access token)
Route::middleware('auth.access_token')->group(function () {
// Add protected routes here
});