first commit

This commit is contained in:
2026-02-08 14:42:58 +08:00
commit 20e1deae21
8197 changed files with 2264639 additions and 0 deletions

View File

@@ -0,0 +1,225 @@
#!/usr/bin/env python3
"""
智能算法展示平台命令行工具
"""
import argparse
import json
import sys
from typing import Optional
from algorithm_showcase import AlgorithmShowcaseClient
def parse_args():
"""解析命令行参数"""
parser = argparse.ArgumentParser(description='智能算法展示平台命令行工具')
parser.add_argument('--base-url', default='http://localhost:8000/api/v1', help='API基础URL')
parser.add_argument('--api-key', default=None, help='API密钥')
subparsers = parser.add_subparsers(dest='command', help='子命令')
# 算法相关命令
algo_parser = subparsers.add_parser('algorithm', help='算法相关命令')
algo_subparsers = algo_parser.add_subparsers(dest='algo_command', help='算法子命令')
# 获取算法列表
algo_subparsers.add_parser('list', help='获取算法列表')
# 获取算法详情
algo_detail_parser = algo_subparsers.add_parser('detail', help='获取算法详情')
algo_detail_parser.add_argument('algorithm_id', help='算法ID')
# 获取算法版本列表
algo_versions_parser = algo_subparsers.add_parser('versions', help='获取算法版本列表')
algo_versions_parser.add_argument('algorithm_id', help='算法ID')
# 调用算法
algo_call_parser = algo_subparsers.add_parser('call', help='调用算法')
algo_call_parser.add_argument('algorithm_id', help='算法ID')
algo_call_parser.add_argument('version_id', help='版本ID')
algo_call_parser.add_argument('--input', required=True, help='输入数据JSON文件路径')
algo_call_parser.add_argument('--params', default=None, help='算法参数JSON文件路径')
# 获取调用结果
algo_result_parser = algo_subparsers.add_parser('result', help='获取调用结果')
algo_result_parser.add_argument('call_id', help='调用ID')
# OpenAI相关命令
openai_parser = subparsers.add_parser('openai', help='OpenAI相关命令')
openai_subparsers = openai_parser.add_subparsers(dest='openai_command', help='OpenAI子命令')
# 生成仿真数据
openai_generate_parser = openai_subparsers.add_parser('generate', help='生成仿真输入数据')
openai_generate_parser.add_argument('prompt', help='描述')
openai_generate_parser.add_argument('--type', default='text', choices=['text', 'image', 'structured'], help='数据类型')
# 历史记录相关命令
history_parser = subparsers.add_parser('history', help='历史记录相关命令')
history_subparsers = history_parser.add_subparsers(dest='history_command', help='历史记录子命令')
# 获取调用历史
history_list_parser = history_subparsers.add_parser('list', help='获取调用历史')
history_list_parser.add_argument('--algorithm-id', help='算法ID')
history_list_parser.add_argument('--status', help='调用状态')
history_list_parser.add_argument('--start-date', help='开始日期')
history_list_parser.add_argument('--end-date', help='结束日期')
# 获取调用统计
history_stats_parser = history_subparsers.add_parser('stats', help='获取调用统计')
history_stats_parser.add_argument('--algorithm-id', help='算法ID')
# 导出历史记录
history_export_parser = history_subparsers.add_parser('export', help='导出历史记录')
history_export_parser.add_argument('--algorithm-id', help='算法ID')
history_export_parser.add_argument('--start-date', help='开始日期')
history_export_parser.add_argument('--end-date', help='结束日期')
history_export_parser.add_argument('--format', default='json', help='导出格式')
# 监控相关命令
monitor_parser = subparsers.add_parser('monitor', help='监控相关命令')
monitor_subparsers = monitor_parser.add_subparsers(dest='monitor_command', help='监控子命令')
# 获取系统健康状况
monitor_subparsers.add_parser('health', help='获取系统健康状况')
# 获取算法性能指标
perf_parser = monitor_subparsers.add_parser('performance', help='获取算法性能指标')
perf_parser.add_argument('algorithm_id', help='算法ID')
perf_parser.add_argument('--days', type=int, default=7, help='统计天数')
# 权限相关命令
perm_parser = subparsers.add_parser('permission', help='权限相关命令')
perm_parser.add_argument('algorithm_id', help='算法ID')
perm_parser.add_argument('--type', default='execute', choices=['read', 'execute', 'write', 'admin'], help='权限类型')
return parser.parse_args()
def load_json_file(file_path: str) -> dict:
"""加载JSON文件"""
try:
with open(file_path, 'r', encoding='utf-8') as f:
return json.load(f)
except Exception as e:
print(f"加载文件失败: {e}")
sys.exit(1)
def main():
"""主函数"""
args = parse_args()
# 初始化客户端
client = AlgorithmShowcaseClient(
base_url=args.base_url,
api_key=args.api_key
)
# 处理命令
if args.command == 'algorithm':
if args.algo_command == 'list':
# 获取算法列表
algorithms = client.get_algorithms()
print(json.dumps(algorithms, ensure_ascii=False, indent=2))
elif args.algo_command == 'detail':
# 获取算法详情
algorithm = client.get_algorithm(args.algorithm_id)
print(json.dumps(algorithm.__dict__, ensure_ascii=False, indent=2))
elif args.algo_command == 'versions':
# 获取算法版本列表
versions = client.get_algorithm_versions(args.algorithm_id)
versions_dict = [v.__dict__ for v in versions]
print(json.dumps(versions_dict, ensure_ascii=False, indent=2))
elif args.algo_command == 'call':
# 加载输入数据
input_data = load_json_file(args.input)
# 加载算法参数
params = {}
if args.params:
params = load_json_file(args.params)
# 调用算法
result = client.call_algorithm(
algorithm_id=args.algorithm_id,
version_id=args.version_id,
input_data=input_data,
params=params
)
print(json.dumps(result.__dict__, ensure_ascii=False, indent=2))
elif args.algo_command == 'result':
# 获取调用结果
result = client.get_call_result(args.call_id)
print(json.dumps(result.__dict__, ensure_ascii=False, indent=2))
elif args.command == 'openai':
if args.openai_command == 'generate':
# 生成仿真数据
result = client.generate_simulation_data(
prompt=args.prompt,
data_type=args.type
)
print(json.dumps(result, ensure_ascii=False, indent=2))
elif args.command == 'history':
if args.history_command == 'list':
# 获取调用历史
history = client.get_call_history(
algorithm_id=args.algorithm_id,
status=args.status,
start_date=args.start_date,
end_date=args.end_date
)
print(json.dumps(history, ensure_ascii=False, indent=2))
elif args.history_command == 'stats':
# 获取调用统计
stats = client.get_call_statistics(
algorithm_id=args.algorithm_id
)
print(json.dumps(stats, ensure_ascii=False, indent=2))
elif args.history_command == 'export':
# 导出历史记录
result = client.export_history(
algorithm_id=args.algorithm_id,
start_date=args.start_date,
end_date=args.end_date,
format_type=args.format
)
print(json.dumps(result, ensure_ascii=False, indent=2))
elif args.command == 'monitor':
if args.monitor_command == 'health':
# 获取系统健康状况
health = client.get_system_health()
print(json.dumps(health, ensure_ascii=False, indent=2))
elif args.monitor_command == 'performance':
# 获取算法性能指标
performance = client.get_algorithm_performance(
algorithm_id=args.algorithm_id,
days=args.days
)
print(json.dumps(performance, ensure_ascii=False, indent=2))
elif args.command == 'permission':
# 检查权限
has_permission = client.check_permission(
algorithm_id=args.algorithm_id,
permission_type=args.type
)
print(json.dumps({'has_permission': has_permission}, ensure_ascii=False, indent=2))
else:
print('请指定命令')
sys.exit(1)
if __name__ == '__main__':
main()

797
sdk/docs/openapi.yaml Normal file
View File

@@ -0,0 +1,797 @@
openapi: 3.0.0
info:
title: 智能算法展示平台API
description: 智能算法展示平台的RESTful API接口文档
version: 1.0.0
servers:
- url: http://localhost:8000/api/v1
description: 本地开发环境
components:
schemas:
Algorithm:
type: object
properties:
id:
type: string
description: 算法ID
name:
type: string
description: 算法名称
description:
type: string
description: 算法描述
type:
type: string
description: 算法类型
status:
type: string
description: 算法状态
created_at:
type: string
format: date-time
description: 创建时间
updated_at:
type: string
format: date-time
description: 更新时间
versions:
type: array
items:
$ref: '#/components/schemas/AlgorithmVersion'
required:
- id
- name
- description
- type
AlgorithmVersion:
type: object
properties:
id:
type: string
description: 版本ID
algorithm_id:
type: string
description: 算法ID
version:
type: string
description: 版本号
url:
type: string
description: 算法API地址
params:
type: object
description: 算法参数配置
input_schema:
type: object
description: 输入数据格式
output_schema:
type: object
description: 输出数据格式
is_default:
type: boolean
description: 是否为默认版本
created_at:
type: string
format: date-time
description: 创建时间
updated_at:
type: string
format: date-time
description: 更新时间
required:
- id
- algorithm_id
- version
- url
AlgorithmCallRequest:
type: object
properties:
algorithm_id:
type: string
description: 算法ID
version_id:
type: string
description: 版本ID
input_data:
type: object
description: 输入数据
params:
type: object
description: 算法参数
required:
- algorithm_id
- version_id
- input_data
AlgorithmCallResult:
type: object
properties:
id:
type: string
description: 调用ID
user_id:
type: string
description: 用户ID
algorithm_id:
type: string
description: 算法ID
version_id:
type: string
description: 版本ID
input_data:
type: object
description: 输入数据
params:
type: object
description: 算法参数
output_data:
type: object
description: 输出数据
status:
type: string
description: 调用状态
response_time:
type: number
description: 响应时间(秒)
error_message:
type: string
description: 错误信息
created_at:
type: string
format: date-time
description: 创建时间
updated_at:
type: string
format: date-time
description: 更新时间
required:
- id
- status
OpenAIGenerateRequest:
type: object
properties:
prompt:
type: string
description: 描述
data_type:
type: string
description: 数据类型
required:
- prompt
OpenAIGenerateResponse:
type: object
properties:
data:
type: object
description: 生成的数据
type:
type: string
description: 数据类型
User:
type: object
properties:
id:
type: string
description: 用户ID
username:
type: string
description: 用户名
email:
type: string
description: 邮箱
role:
type: string
description: 角色
status:
type: string
description: 状态
created_at:
type: string
format: date-time
description: 创建时间
updated_at:
type: string
format: date-time
description: 更新时间
UserLoginRequest:
type: object
properties:
username:
type: string
description: 用户名
password:
type: string
description: 密码
required:
- username
- password
UserRegisterRequest:
type: object
properties:
username:
type: string
description: 用户名
email:
type: string
description: 邮箱
password:
type: string
description: 密码
required:
- username
- email
- password
TokenResponse:
type: object
properties:
access_token:
type: string
description: 访问令牌
token_type:
type: string
description: 令牌类型
expires_at:
type: string
format: date-time
description: 过期时间
APIKey:
type: object
properties:
id:
type: string
description: API密钥ID
user_id:
type: string
description: 用户ID
key:
type: string
description: API密钥
name:
type: string
description: 密钥名称
expires_at:
type: string
format: date-time
description: 过期时间
status:
type: string
description: 状态
created_at:
type: string
format: date-time
description: 创建时间
updated_at:
type: string
format: date-time
description: 更新时间
APIKeyCreateRequest:
type: object
properties:
name:
type: string
description: 密钥名称
expires_at:
type: string
format: date-time
description: 过期时间
required:
- name
- expires_at
securitySchemes:
bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
paths:
/algorithms:
get:
summary: 获取算法列表
description: 获取所有算法的列表,可选择按类型过滤
parameters:
- in: query
name: type
schema:
type: string
description: 算法类型
responses:
'200':
description: 成功
content:
application/json:
schema:
type: object
properties:
algorithms:
type: array
items:
$ref: '#/components/schemas/Algorithm'
total:
type: integer
post:
summary: 创建算法
description: 创建新的算法
security:
- bearerAuth: []
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
name:
type: string
description:
type: string
type:
type: string
required:
- name
- description
- type
responses:
'200':
description: 成功
content:
application/json:
schema:
$ref: '#/components/schemas/Algorithm'
/algorithms/{algorithm_id}:
get:
summary: 获取算法详情
description: 获取指定算法的详细信息
parameters:
- in: path
name: algorithm_id
schema:
type: string
required: true
description: 算法ID
responses:
'200':
description: 成功
content:
application/json:
schema:
$ref: '#/components/schemas/Algorithm'
put:
summary: 更新算法
description: 更新指定算法的信息
security:
- bearerAuth: []
parameters:
- in: path
name: algorithm_id
schema:
type: string
required: true
description: 算法ID
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
name:
type: string
description:
type: string
type:
type: string
status:
type: string
responses:
'200':
description: 成功
content:
application/json:
schema:
$ref: '#/components/schemas/Algorithm'
delete:
summary: 删除算法
description: 删除指定的算法
security:
- bearerAuth: []
parameters:
- in: path
name: algorithm_id
schema:
type: string
required: true
description: 算法ID
responses:
'200':
description: 成功
content:
application/json:
schema:
type: object
properties:
message:
type: string
/algorithms/{algorithm_id}/versions:
get:
summary: 获取算法版本列表
description: 获取指定算法的所有版本
parameters:
- in: path
name: algorithm_id
schema:
type: string
required: true
description: 算法ID
responses:
'200':
description: 成功
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/AlgorithmVersion'
post:
summary: 创建算法版本
description: 为指定算法创建新的版本
security:
- bearerAuth: []
parameters:
- in: path
name: algorithm_id
schema:
type: string
required: true
description: 算法ID
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
version:
type: string
url:
type: string
params:
type: object
input_schema:
type: object
output_schema:
type: object
is_default:
type: boolean
required:
- version
- url
responses:
'200':
description: 成功
content:
application/json:
schema:
$ref: '#/components/schemas/AlgorithmVersion'
/algorithms/{algorithm_id}/versions/{version_id}:
get:
summary: 获取算法版本详情
description: 获取指定算法版本的详细信息
parameters:
- in: path
name: algorithm_id
schema:
type: string
required: true
description: 算法ID
- in: path
name: version_id
schema:
type: string
required: true
description: 版本ID
responses:
'200':
description: 成功
content:
application/json:
schema:
$ref: '#/components/schemas/AlgorithmVersion'
put:
summary: 更新算法版本
description: 更新指定算法版本的信息
security:
- bearerAuth: []
parameters:
- in: path
name: algorithm_id
schema:
type: string
required: true
description: 算法ID
- in: path
name: version_id
schema:
type: string
required: true
description: 版本ID
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
version:
type: string
url:
type: string
params:
type: object
input_schema:
type: object
output_schema:
type: object
is_default:
type: boolean
responses:
'200':
description: 成功
content:
application/json:
schema:
$ref: '#/components/schemas/AlgorithmVersion'
delete:
summary: 删除算法版本
description: 删除指定的算法版本
security:
- bearerAuth: []
parameters:
- in: path
name: algorithm_id
schema:
type: string
required: true
description: 算法ID
- in: path
name: version_id
schema:
type: string
required: true
description: 版本ID
responses:
'200':
description: 成功
content:
application/json:
schema:
type: object
properties:
message:
type: string
/algorithms/call:
post:
summary: 调用算法
description: 调用指定的算法并获取结果
security:
- bearerAuth: []
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/AlgorithmCallRequest'
responses:
'200':
description: 成功
content:
application/json:
schema:
$ref: '#/components/schemas/AlgorithmCallResult'
/algorithms/calls/{call_id}:
get:
summary: 获取算法调用结果
description: 获取指定算法调用的结果
security:
- bearerAuth: []
parameters:
- in: path
name: call_id
schema:
type: string
required: true
description: 调用ID
responses:
'200':
description: 成功
content:
application/json:
schema:
$ref: '#/components/schemas/AlgorithmCallResult'
/openai/generate-data:
post:
summary: 生成仿真输入数据
description: 使用OpenAI生成仿真输入数据
security:
- bearerAuth: []
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/OpenAIGenerateRequest'
responses:
'200':
description: 成功
content:
application/json:
schema:
$ref: '#/components/schemas/OpenAIGenerateResponse'
/openai/describe-image:
post:
summary: 生成图片描述
description: 使用OpenAI生成图片描述
security:
- bearerAuth: []
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
image_url:
type: string
required:
- image_url
responses:
'200':
description: 成功
content:
application/json:
schema:
type: object
properties:
description:
type: string
/users/register:
post:
summary: 用户注册
description: 注册新用户
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/UserRegisterRequest'
responses:
'200':
description: 成功
content:
application/json:
schema:
$ref: '#/components/schemas/User'
/users/login:
post:
summary: 用户登录
description: 用户登录获取令牌
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/UserLoginRequest'
responses:
'200':
description: 成功
content:
application/json:
schema:
$ref: '#/components/schemas/TokenResponse'
/users/me:
get:
summary: 获取当前用户信息
description: 获取当前登录用户的信息
security:
- bearerAuth: []
responses:
'200':
description: 成功
content:
application/json:
schema:
$ref: '#/components/schemas/User'
/api-keys:
get:
summary: 获取API密钥列表
description: 获取当前用户的API密钥列表
security:
- bearerAuth: []
responses:
'200':
description: 成功
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/APIKey'
post:
summary: 创建API密钥
description: 为当前用户创建新的API密钥
security:
- bearerAuth: []
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/APIKeyCreateRequest'
responses:
'200':
description: 成功
content:
application/json:
schema:
$ref: '#/components/schemas/APIKey'
/api-keys/{key_id}:
delete:
summary: 删除API密钥
description: 删除指定的API密钥
security:
- bearerAuth: []
parameters:
- in: path
name: key_id
schema:
type: string
required: true
description: 密钥ID
responses:
'200':
description: 成功
content:
application/json:
schema:
type: object
properties:
message:
type: string
/health:
get:
summary: 健康检查
description: 检查系统健康状态
responses:
'200':
description: 成功
content:
application/json:
schema:
type: object
properties:
status:
type: string

214
sdk/javascript/README.md Normal file
View File

@@ -0,0 +1,214 @@
# 智能算法展示平台JavaScript SDK
本SDK提供了与智能算法展示平台API交互的JavaScript客户端支持算法调用、仿真数据生成等功能。
## 安装
### 从源码安装
```bash
cd sdk/javascript
npm install
npm link
```
### 从npm安装
```bash
npm install algorithm-showcase-sdk
```
## 使用示例
### 1. 初始化客户端
```javascript
const AlgorithmShowcaseClient = require('algorithm-showcase-sdk');
// 初始化客户端
const client = new AlgorithmShowcaseClient(
'http://localhost:8000/api/v1', // API基础URL
'your-api-key' // 可选API密钥
);
```
### 2. 获取算法列表
```javascript
// 获取所有算法
async function getAlgorithms() {
try {
const algorithms = await client.getAlgorithms();
// 打印算法信息
algorithms.forEach(algo => {
console.log(`算法ID: ${algo.id}`);
console.log(`算法名称: ${algo.name}`);
console.log(`算法描述: ${algo.description}`);
console.log(`算法类型: ${algo.type}`);
console.log('---');
});
} catch (error) {
console.error('获取算法列表失败:', error.message);
}
}
// 获取特定类型的算法
async function getAlgorithmsByType() {
try {
const algorithms = await client.getAlgorithms('computer_vision');
console.log('计算机视觉算法:', algorithms);
} catch (error) {
console.error('获取算法列表失败:', error.message);
}
}
getAlgorithms();
```
### 3. 获取算法详情
```javascript
// 获取算法详情
async function getAlgorithmDetail() {
try {
const algorithm = await client.getAlgorithm('algorithm-123456');
console.log(`算法ID: ${algorithm.id}`);
console.log(`算法名称: ${algorithm.name}`);
console.log(`算法描述: ${algorithm.description}`);
console.log(`算法类型: ${algorithm.type}`);
console.log('版本信息:');
algorithm.versions.forEach(version => {
console.log(` - 版本: ${version.version} (默认: ${version.is_default})`);
console.log(` URL: ${version.url}`);
console.log(` 参数: ${JSON.stringify(version.params)}`);
});
} catch (error) {
console.error('获取算法详情失败:', error.message);
}
}
getAlgorithmDetail();
```
### 4. 调用算法
```javascript
// 调用算法
async function callAlgorithm() {
try {
// 准备输入数据
const inputData = {
text: '这是一段测试文本'
};
// 准备算法参数
const params = {
confidence_threshold: 0.5,
model_name: 'resnet50'
};
// 调用算法
const result = await client.callAlgorithm(
'algorithm-123456',
'version-123456',
inputData,
params
);
console.log(`调用ID: ${result.id}`);
console.log(`状态: ${result.status}`);
console.log(`响应时间: ${result.response_time} 秒`);
console.log(`输出数据: ${JSON.stringify(result.output_data)}`);
} catch (error) {
console.error('调用算法失败:', error.message);
}
}
callAlgorithm();
```
### 5. 获取调用结果
```javascript
// 获取调用结果
async function getCallResult() {
try {
const result = await client.getCallResult('call-123456');
console.log(`调用ID: ${result.id}`);
console.log(`状态: ${result.status}`);
console.log(`响应时间: ${result.response_time} 秒`);
console.log(`输出数据: ${JSON.stringify(result.output_data)}`);
} catch (error) {
console.error('获取调用结果失败:', error.message);
}
}
getCallResult();
```
### 6. 生成仿真输入数据
```javascript
// 生成仿真输入数据
async function generateSimulationData() {
try {
// 生成文本数据
const textData = await client.generateSimulationData(
'生成一段关于人工智能的新闻文本',
'text'
);
console.log('生成的文本:', textData.data);
// 生成结构化数据
const structuredData = await client.generateSimulationData(
'生成一个包含姓名、年龄、职业的用户信息',
'structured'
);
console.log('生成的结构化数据:', structuredData.data);
} catch (error) {
console.error('生成仿真数据失败:', error.message);
}
}
generateSimulationData();
```
## API文档
### 核心方法
- `getAlgorithms(type)`: 获取算法列表
- `getAlgorithm(algorithmId)`: 获取算法详情
- `getAlgorithmVersions(algorithmId)`: 获取算法版本列表
- `callAlgorithm(algorithmId, versionId, inputData, params)`: 调用算法
- `getCallResult(callId)`: 获取调用结果
- `generateSimulationData(prompt, dataType)`: 生成仿真输入数据
## 错误处理
SDK会捕获API请求中的错误并抛出异常。建议在使用时添加异常处理
```javascript
try {
const result = await client.callAlgorithm(...);
console.log('调用成功:', result);
} catch (error) {
console.error('调用失败:', error.message);
}
```
## 版本兼容性
- Node.js 12+
- axios 1.6.0+
## 浏览器兼容性
本SDK基于axios支持现代浏览器。在浏览器环境中使用时需要注意跨域问题。
## 许可证
MIT License

View File

@@ -0,0 +1,28 @@
{
"name": "algorithm-showcase-sdk",
"version": "1.0.0",
"description": "智能算法展示平台JavaScript SDK",
"main": "src/index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"algorithm",
"showcase",
"SDK",
"API"
],
"author": "Algorithm Showcase Team",
"license": "MIT",
"dependencies": {
"axios": "^1.6.0"
},
"repository": {
"type": "git",
"url": "https://github.com/algorithm-showcase/sdk"
},
"bugs": {
"url": "https://github.com/algorithm-showcase/sdk/issues"
},
"homepage": "https://github.com/algorithm-showcase/sdk#readme"
}

247
sdk/javascript/src/index.js Normal file
View File

@@ -0,0 +1,247 @@
/**
* 智能算法展示平台JavaScript SDK
*/
const axios = require('axios');
/**
* 智能算法展示平台客户端类
*/
class AlgorithmShowcaseClient {
/**
* 初始化客户端
* @param {string} baseUrl - API基础URL
* @param {string} apiKey - API密钥
*/
constructor(baseUrl = 'http://localhost:8000/api/v1', apiKey = null) {
this.baseUrl = baseUrl.replace(/\/$/, '');
this.apiKey = apiKey;
// 创建axios实例
this.client = axios.create({
baseURL: this.baseUrl,
headers: {
'Content-Type': 'application/json'
}
});
// 如果提供了API密钥设置认证头
if (this.apiKey) {
this.client.defaults.headers.common['Authorization'] = `Bearer ${this.apiKey}`;
}
}
/**
* 获取算法列表
* @param {string} type - 算法类型
* @returns {Promise<Array>} 算法列表
*/
async getAlgorithms(type = null) {
try {
const params = {};
if (type) {
params.type = type;
}
const response = await this.client.get('/algorithms', { params });
return response.data.algorithms;
} catch (error) {
throw new Error(`获取算法列表失败: ${error.message}`);
}
}
/**
* 获取算法详情
* @param {string} algorithmId - 算法ID
* @returns {Promise<Object>} 算法详情
*/
async getAlgorithm(algorithmId) {
try {
const response = await this.client.get(`/algorithms/${algorithmId}`);
return response.data;
} catch (error) {
throw new Error(`获取算法详情失败: ${error.message}`);
}
}
/**
* 获取算法版本列表
* @param {string} algorithmId - 算法ID
* @returns {Promise<Array>} 版本列表
*/
async getAlgorithmVersions(algorithmId) {
try {
const response = await this.client.get(`/algorithms/${algorithmId}/versions`);
return response.data;
} catch (error) {
throw new Error(`获取算法版本列表失败: ${error.message}`);
}
}
/**
* 调用算法
* @param {string} algorithmId - 算法ID
* @param {string} versionId - 版本ID
* @param {Object} inputData - 输入数据
* @param {Object} params - 算法参数
* @returns {Promise<Object>} 调用结果
*/
async callAlgorithm(algorithmId, versionId, inputData, params = {}) {
try {
const response = await this.client.post('/algorithms/call', {
algorithm_id: algorithmId,
version_id: versionId,
input_data: inputData,
params: params
});
return response.data;
} catch (error) {
throw new Error(`调用算法失败: ${error.message}`);
}
}
/**
* 获取调用结果
* @param {string} callId - 调用ID
* @returns {Promise<Object>} 调用结果
*/
async getCallResult(callId) {
try {
const response = await this.client.get(`/algorithms/calls/${callId}`);
return response.data;
} catch (error) {
throw new Error(`获取调用结果失败: ${error.message}`);
}
}
/**
* 生成仿真输入数据
* @param {string} prompt - 描述
* @param {string} dataType - 数据类型
* @returns {Promise<Object>} 生成的数据
*/
async generateSimulationData(prompt, dataType = 'text') {
try {
const response = await this.client.post('/openai/generate-data', {
prompt: prompt,
data_type: dataType
});
return response.data;
} catch (error) {
throw new Error(`生成仿真数据失败: ${error.message}`);
}
}
/**
* 获取调用历史
* @param {string} algorithmId - 算法ID
* @param {string} status - 状态
* @param {string} startDate - 开始日期
* @param {string} endDate - 结束日期
* @returns {Promise<Array>} 调用历史
*/
async getCallHistory(algorithmId = null, status = null, startDate = null, endDate = null) {
try {
const params = {};
if (algorithmId) params.algorithm_id = algorithmId;
if (status) params.status = status;
if (startDate) params.start_date = startDate;
if (endDate) params.end_date = endDate;
const response = await this.client.get('/history/user-calls', { params });
return response.data.history;
} catch (error) {
throw new Error(`获取调用历史失败: ${error.message}`);
}
}
/**
* 获取调用统计
* @param {string} algorithmId - 算法ID
* @returns {Promise<Object>} 统计信息
*/
async getCallStatistics(algorithmId = null) {
try {
const params = {};
if (algorithmId) params.algorithm_id = algorithmId;
const response = await this.client.get('/history/statistics', { params });
return response.data;
} catch (error) {
throw new Error(`获取调用统计失败: ${error.message}`);
}
}
/**
* 导出历史记录
* @param {string} algorithmId - 算法ID
* @param {string} startDate - 开始日期
* @param {string} endDate - 结束日期
* @param {string} formatType - 导出格式
* @returns {Promise<Object>} 导出结果
*/
async exportHistory(algorithmId = null, startDate = null, endDate = null, formatType = 'json') {
try {
const params = {
format_type: formatType
};
if (algorithmId) params.algorithm_id = algorithmId;
if (startDate) params.start_date = startDate;
if (endDate) params.end_date = endDate;
const response = await this.client.get('/history/export', { params });
return response.data;
} catch (error) {
throw new Error(`导出历史记录失败: ${error.message}`);
}
}
/**
* 获取算法性能指标
* @param {string} algorithmId - 算法ID
* @param {number} days - 统计天数
* @returns {Promise<Object>} 性能指标
*/
async getAlgorithmPerformance(algorithmId, days = 7) {
try {
const params = { days };
const response = await this.client.get(`/monitoring/performance/algorithm/${algorithmId}`, { params });
return response.data;
} catch (error) {
throw new Error(`获取算法性能指标失败: ${error.message}`);
}
}
/**
* 获取系统健康状况
* @returns {Promise<Object>} 系统健康状况
*/
async getSystemHealth() {
try {
const response = await this.client.get('/monitoring/health');
return response.data;
} catch (error) {
throw new Error(`获取系统健康状况失败: ${error.message}`);
}
}
/**
* 检查权限
* @param {string} algorithmId - 算法ID
* @param {string} permissionType - 权限类型
* @returns {Promise<boolean>} 是否有权限
*/
async checkPermission(algorithmId, permissionType = 'execute') {
try {
const response = await this.client.post('/permissions/check', {
algorithm_id: algorithmId,
permission_type: permissionType
});
return response.data.has_permission;
} catch (error) {
throw new Error(`检查权限失败: ${error.message}`);
}
}
}
module.exports = AlgorithmShowcaseClient;

163
sdk/python/README.md Normal file
View File

@@ -0,0 +1,163 @@
# 智能算法展示平台Python SDK
本SDK提供了与智能算法展示平台API交互的Python客户端支持算法调用、仿真数据生成等功能。
## 安装
### 从源码安装
```bash
cd sdk/python
pip install -e .
```
### 从PyPI安装
```bash
pip install algorithm-showcase-sdk
```
## 使用示例
### 1. 初始化客户端
```python
from algorithm_showcase import AlgorithmShowcaseClient
# 初始化客户端
client = AlgorithmShowcaseClient(
base_url="http://localhost:8000/api/v1", # API基础URL
api_key="your-api-key" # 可选API密钥
)
```
### 2. 获取算法列表
```python
# 获取所有算法
algorithms = client.get_algorithms()
# 获取特定类型的算法
algorithms = client.get_algorithms(algorithm_type="computer_vision")
# 打印算法信息
for algo in algorithms:
print(f"算法ID: {algo.id}")
print(f"算法名称: {algo.name}")
print(f"算法描述: {algo.description}")
print(f"算法类型: {algo.type}")
print("---")
```
### 3. 获取算法详情
```python
# 获取算法详情
algorithm = client.get_algorithm(algorithm_id="algorithm-123456")
print(f"算法ID: {algorithm.id}")
print(f"算法名称: {algorithm.name}")
print(f"算法描述: {algorithm.description}")
print(f"算法类型: {algorithm.type}")
print("版本信息:")
for version in algorithm.versions:
print(f" - 版本: {version.version} (默认: {version.is_default})")
print(f" URL: {version.url}")
print(f" 参数: {version.params}")
```
### 4. 调用算法
```python
# 准备输入数据
input_data = {
"text": "这是一段测试文本"
}
# 准备算法参数
params = {
"confidence_threshold": 0.5,
"model_name": "resnet50"
}
# 调用算法
result = client.call_algorithm(
algorithm_id="algorithm-123456",
version_id="version-123456",
input_data=input_data,
params=params
)
print(f"调用ID: {result.id}")
print(f"状态: {result.status}")
print(f"响应时间: {result.response_time} 秒")
print(f"输出数据: {result.output_data}")
```
### 5. 获取调用结果
```python
# 获取调用结果
result = client.get_call_result(call_id="call-123456")
print(f"调用ID: {result.id}")
print(f"状态: {result.status}")
print(f"响应时间: {result.response_time} 秒")
print(f"输出数据: {result.output_data}")
```
### 6. 生成仿真输入数据
```python
# 生成文本数据
text_data = client.generate_simulation_data(
prompt="生成一段关于人工智能的新闻文本",
data_type="text"
)
print(f"生成的文本: {text_data['data']}")
# 生成结构化数据
structured_data = client.generate_simulation_data(
prompt="生成一个包含姓名、年龄、职业的用户信息",
data_type="structured"
)
print(f"生成的结构化数据: {structured_data['data']}")
```
## API文档
### 核心方法
- `get_algorithms(algorithm_type=None)`: 获取算法列表
- `get_algorithm(algorithm_id)`: 获取算法详情
- `get_algorithm_versions(algorithm_id)`: 获取算法版本列表
- `call_algorithm(algorithm_id, version_id, input_data, params=None)`: 调用算法
- `get_call_result(call_id)`: 获取调用结果
- `generate_simulation_data(prompt, data_type="text")`: 生成仿真输入数据
### 数据模型
- `Algorithm`: 算法信息
- `AlgorithmVersion`: 算法版本信息
- `AlgorithmCallRequest`: 算法调用请求
- `AlgorithmCallResult`: 算法调用结果
## 错误处理
SDK会捕获API请求中的错误并抛出异常。建议在使用时添加异常处理
```python
try:
result = client.call_algorithm(...)
except Exception as e:
print(f"调用失败: {e}")
```
## 版本兼容性
- Python 3.7+
- requests 2.31.0+
## 许可证
MIT License

View File

@@ -0,0 +1,14 @@
"""智能算法展示平台Python SDK"""
__version__ = "1.0.0"
from .client import AlgorithmShowcaseClient
from .models import Algorithm, AlgorithmVersion, AlgorithmCallRequest, AlgorithmCallResult
__all__ = [
"AlgorithmShowcaseClient",
"Algorithm",
"AlgorithmVersion",
"AlgorithmCallRequest",
"AlgorithmCallResult"
]

View File

@@ -0,0 +1,276 @@
"""智能算法展示平台客户端"""
import requests
import json
from typing import List, Optional, Dict, Any
from .models import Algorithm, AlgorithmVersion, AlgorithmCallRequest, AlgorithmCallResult
class AlgorithmShowcaseClient:
"""智能算法展示平台客户端类"""
def __init__(self, base_url: str = "http://localhost:8000/api/v1", api_key: Optional[str] = None):
"""初始化客户端
Args:
base_url: API基础URL
api_key: API密钥
"""
self.base_url = base_url.rstrip("/")
self.api_key = api_key
self.session = requests.Session()
# 设置默认请求头
self.session.headers.update({
"Content-Type": "application/json"
})
# 如果提供了API密钥设置认证头
if self.api_key:
self.session.headers.update({
"Authorization": f"Bearer {self.api_key}"
})
def _request(self, method: str, endpoint: str, data: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
"""发送请求
Args:
method: 请求方法
endpoint: 端点
data: 请求数据
Returns:
响应数据
"""
url = f"{self.base_url}/{endpoint}"
try:
if method == "GET":
response = self.session.get(url, params=data)
elif method == "POST":
response = self.session.post(url, json=data)
elif method == "PUT":
response = self.session.put(url, json=data)
elif method == "DELETE":
response = self.session.delete(url, json=data)
else:
raise ValueError(f"Unsupported method: {method}")
# 检查响应状态
response.raise_for_status()
# 返回响应数据
return response.json()
except requests.RequestException as e:
raise Exception(f"API request failed: {e}")
def get_algorithms(self, algorithm_type: Optional[str] = None) -> List[Algorithm]:
"""获取算法列表
Args:
algorithm_type: 算法类型
Returns:
算法列表
"""
params = {}
if algorithm_type:
params["type"] = algorithm_type
response = self._request("GET", "algorithms", params)
algorithms = []
for algo_data in response.get("algorithms", []):
algorithm = Algorithm(**algo_data)
algorithms.append(algorithm)
return algorithms
def get_algorithm(self, algorithm_id: str) -> Algorithm:
"""获取算法详情
Args:
algorithm_id: 算法ID
Returns:
算法详情
"""
response = self._request("GET", f"algorithms/{algorithm_id}")
return Algorithm(**response)
def get_algorithm_versions(self, algorithm_id: str) -> List[AlgorithmVersion]:
"""获取算法版本列表
Args:
algorithm_id: 算法ID
Returns:
版本列表
"""
response = self._request("GET", f"algorithms/{algorithm_id}/versions")
versions = []
for version_data in response:
version = AlgorithmVersion(**version_data)
versions.append(version)
return versions
def call_algorithm(self, algorithm_id: str, version_id: str, input_data: Dict[str, Any], params: Optional[Dict[str, Any]] = None) -> AlgorithmCallResult:
"""调用算法
Args:
algorithm_id: 算法ID
version_id: 版本ID
input_data: 输入数据
params: 算法参数
Returns:
调用结果
"""
request_data = AlgorithmCallRequest(
algorithm_id=algorithm_id,
version_id=version_id,
input_data=input_data,
params=params or {}
)
response = self._request("POST", "algorithms/call", request_data.dict())
return AlgorithmCallResult(**response)
def get_call_result(self, call_id: str) -> AlgorithmCallResult:
"""获取调用结果
Args:
call_id: 调用ID
Returns:
调用结果
"""
response = self._request("GET", f"algorithms/calls/{call_id}")
return AlgorithmCallResult(**response)
def generate_simulation_data(self, prompt: str, data_type: str = "text") -> Dict[str, Any]:
"""生成仿真输入数据
Args:
prompt: 描述
data_type: 数据类型
Returns:
生成的数据
"""
response = self._request("POST", "openai/generate-data", {
"prompt": prompt,
"data_type": data_type
})
return response
def get_call_history(self, algorithm_id: Optional[str] = None, status: Optional[str] = None,
start_date: Optional[str] = None, end_date: Optional[str] = None) -> List[AlgorithmCallResult]:
"""获取调用历史
Args:
algorithm_id: 算法ID
status: 调用状态
start_date: 开始日期
end_date: 结束日期
Returns:
调用历史列表
"""
params = {}
if algorithm_id:
params["algorithm_id"] = algorithm_id
if status:
params["status"] = status
if start_date:
params["start_date"] = start_date
if end_date:
params["end_date"] = end_date
response = self._request("GET", "history/user-calls", params)
history = []
for call_data in response.get("history", []):
call_result = AlgorithmCallResult(**call_data)
history.append(call_result)
return history
def get_call_statistics(self, algorithm_id: Optional[str] = None) -> Dict[str, Any]:
"""获取调用统计
Args:
algorithm_id: 算法ID
Returns:
统计信息
"""
params = {}
if algorithm_id:
params["algorithm_id"] = algorithm_id
response = self._request("GET", "history/statistics", params)
return response
def export_history(self, algorithm_id: Optional[str] = None, start_date: Optional[str] = None,
end_date: Optional[str] = None, format_type: str = "json") -> Dict[str, Any]:
"""导出历史记录
Args:
algorithm_id: 算法ID
start_date: 开始日期
end_date: 结束日期
format_type: 导出格式
Returns:
导出结果
"""
params = {
"format_type": format_type
}
if algorithm_id:
params["algorithm_id"] = algorithm_id
if start_date:
params["start_date"] = start_date
if end_date:
params["end_date"] = end_date
response = self._request("GET", "history/export", params)
return response
def get_algorithm_performance(self, algorithm_id: str, days: int = 7) -> Dict[str, Any]:
"""获取算法性能指标
Args:
algorithm_id: 算法ID
days: 统计天数
Returns:
性能指标
"""
response = self._request("GET", f"monitoring/performance/algorithm/{algorithm_id}", {"days": days})
return response
def get_system_health(self) -> Dict[str, Any]:
"""获取系统健康状况
Returns:
系统健康状况
"""
response = self._request("GET", "monitoring/health")
return response
def check_permission(self, algorithm_id: str, permission_type: str = "execute") -> bool:
"""检查权限
Args:
algorithm_id: 算法ID
permission_type: 权限类型
Returns:
是否有权限
"""
response = self._request("POST", "permissions/check", {
"algorithm_id": algorithm_id,
"permission_type": permission_type
})
return response.get("has_permission", False)

View File

@@ -0,0 +1,58 @@
"""智能算法展示平台数据模型"""
from typing import List, Optional, Dict, Any
from dataclasses import dataclass
@dataclass
class AlgorithmVersion:
"""算法版本"""
id: str
algorithm_id: str
version: str
url: str
params: Dict[str, Any]
input_schema: Dict[str, Any]
output_schema: Dict[str, Any]
is_default: bool
created_at: str
updated_at: str
@dataclass
class Algorithm:
"""算法"""
id: str
name: str
description: str
type: str
status: str
versions: List[AlgorithmVersion]
created_at: str
updated_at: str
@dataclass
class AlgorithmCallRequest:
"""算法调用请求"""
algorithm_id: str
version_id: str
input_data: Dict[str, Any]
params: Dict[str, Any]
@dataclass
class AlgorithmCallResult:
"""算法调用结果"""
id: str
user_id: str
algorithm_id: str
version_id: str
input_data: Dict[str, Any]
params: Dict[str, Any]
output_data: Dict[str, Any]
status: str
response_time: float
error_message: Optional[str]
created_at: str
updated_at: str

27
sdk/python/setup.py Normal file
View File

@@ -0,0 +1,27 @@
"""智能算法展示平台Python SDK安装配置"""
from setuptools import setup, find_packages
with open("README.md", "r", encoding="utf-8") as f:
long_description = f.read()
setup(
name="algorithm-showcase-sdk",
version="1.0.0",
description="智能算法展示平台Python SDK",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/algorithm-showcase/sdk",
author="Algorithm Showcase Team",
author_email="team@algorithm-showcase.com",
packages=find_packages(),
install_requires=[
"requests>=2.31.0"
],
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
python_requires=">=3.7",
)