first commit
This commit is contained in:
872
docs/api-examples.md
Normal file
872
docs/api-examples.md
Normal file
@@ -0,0 +1,872 @@
|
||||
# 智能算法展示平台 API 使用示例
|
||||
|
||||
本文档提供了使用智能算法展示平台API的各种示例,涵盖从基础到高级的用法。
|
||||
|
||||
## 准备工作
|
||||
|
||||
在开始之前,请确保您已获得API访问令牌。
|
||||
|
||||
### Python 示例
|
||||
|
||||
```python
|
||||
import requests
|
||||
import json
|
||||
|
||||
# 设置基础URL和认证令牌
|
||||
BASE_URL = "http://localhost:8000/api/v1"
|
||||
headers = {
|
||||
"Authorization": "Bearer YOUR_ACCESS_TOKEN",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
```
|
||||
|
||||
### JavaScript 示例
|
||||
|
||||
```javascript
|
||||
const BASE_URL = "http://localhost:8000/api/v1";
|
||||
const headers = {
|
||||
"Authorization": "Bearer YOUR_ACCESS_TOKEN",
|
||||
"Content-Type": "application/json"
|
||||
};
|
||||
```
|
||||
|
||||
## 算法管理示例
|
||||
|
||||
### 获取算法列表
|
||||
|
||||
**Python**
|
||||
```python
|
||||
def get_algorithms():
|
||||
response = requests.get(f"{BASE_URL}/algorithms", headers=headers)
|
||||
if response.status_code == 200:
|
||||
return response.json()
|
||||
else:
|
||||
print(f"Error: {response.status_code} - {response.text}")
|
||||
return None
|
||||
|
||||
# 使用示例
|
||||
algorithms = get_algorithms()
|
||||
if algorithms:
|
||||
print(f"找到 {len(algorithms['algorithms'])} 个算法")
|
||||
for alg in algorithms['algorithms']:
|
||||
print(f"- {alg['name']} ({alg['type']})")
|
||||
```
|
||||
|
||||
**JavaScript**
|
||||
```javascript
|
||||
async function getAlgorithms() {
|
||||
try {
|
||||
const response = await fetch(`${BASE_URL}/algorithms`, {
|
||||
method: 'GET',
|
||||
headers: headers
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
console.log(`找到 ${data.algorithms.length} 个算法`);
|
||||
data.algorithms.forEach(alg => {
|
||||
console.log(`- ${alg.name} (${alg.type})`);
|
||||
});
|
||||
return data;
|
||||
} else {
|
||||
console.error(`Error: ${response.status} - ${await response.text()}`);
|
||||
return null;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('请求失败:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 获取特定算法详情
|
||||
|
||||
**Python**
|
||||
```python
|
||||
def get_algorithm_details(algorithm_id):
|
||||
response = requests.get(f"{BASE_URL}/algorithms/{algorithm_id}", headers=headers)
|
||||
if response.status_code == 200:
|
||||
return response.json()
|
||||
else:
|
||||
print(f"Error: {response.status_code} - {response.text}")
|
||||
return None
|
||||
|
||||
# 使用示例
|
||||
algorithm = get_algorithm_details("alg-001")
|
||||
if algorithm:
|
||||
print(f"算法名称: {algorithm['name']}")
|
||||
print(f"算法类型: {algorithm['type']}")
|
||||
print(f"版本数量: {len(algorithm['versions'])}")
|
||||
```
|
||||
|
||||
**JavaScript**
|
||||
```javascript
|
||||
async function getAlgorithmDetails(algorithmId) {
|
||||
try {
|
||||
const response = await fetch(`${BASE_URL}/algorithms/${algorithmId}`, {
|
||||
method: 'GET',
|
||||
headers: headers
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
return await response.json();
|
||||
} else {
|
||||
console.error(`Error: ${response.status} - ${await response.text()}`);
|
||||
return null;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('请求失败:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// 使用示例
|
||||
getAlgorithmDetails("alg-001").then(algorithm => {
|
||||
if (algorithm) {
|
||||
console.log(`算法名称: ${algorithm.name}`);
|
||||
console.log(`算法类型: ${algorithm.type}`);
|
||||
console.log(`版本数量: ${algorithm.versions.length}`);
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## 算法调用示例
|
||||
|
||||
### 调用算法
|
||||
|
||||
**Python**
|
||||
```python
|
||||
def call_algorithm(algorithm_id, version_id, input_data, params=None):
|
||||
payload = {
|
||||
"algorithm_id": algorithm_id,
|
||||
"version_id": version_id,
|
||||
"input_data": input_data
|
||||
}
|
||||
|
||||
if params:
|
||||
payload["params"] = params
|
||||
|
||||
response = requests.post(f"{BASE_URL}/algorithms/call",
|
||||
headers=headers,
|
||||
json=payload)
|
||||
|
||||
if response.status_code == 200:
|
||||
return response.json()
|
||||
else:
|
||||
print(f"Error: {response.status_code} - {response.text}")
|
||||
return None
|
||||
|
||||
# 使用示例 - 图像分类算法
|
||||
input_data = {
|
||||
"image_url": "https://example.com/sample-image.jpg"
|
||||
}
|
||||
|
||||
params = {
|
||||
"confidence_threshold": 0.7
|
||||
}
|
||||
|
||||
result = call_algorithm("alg-001", "ver-001", input_data, params)
|
||||
if result:
|
||||
print(f"调用ID: {result['id']}")
|
||||
print(f"状态: {result['status']}")
|
||||
print(f"响应时间: {result['response_time']}秒")
|
||||
|
||||
if result['status'] == 'success':
|
||||
predictions = result['output_data']['predictions']
|
||||
for pred in predictions:
|
||||
print(f"类别: {pred['class']}, 置信度: {pred['confidence']}")
|
||||
```
|
||||
|
||||
**JavaScript**
|
||||
```javascript
|
||||
async function callAlgorithm(algorithmId, versionId, inputData, params = null) {
|
||||
const payload = {
|
||||
algorithm_id: algorithmId,
|
||||
version_id: versionId,
|
||||
input_data: inputData
|
||||
};
|
||||
|
||||
if (params) {
|
||||
payload.params = params;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${BASE_URL}/algorithms/call`, {
|
||||
method: 'POST',
|
||||
headers: headers,
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
return await response.json();
|
||||
} else {
|
||||
console.error(`Error: ${response.status} - ${await response.text()}`);
|
||||
return null;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('请求失败:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// 使用示例
|
||||
const inputData = {
|
||||
image_url: "https://example.com/sample-image.jpg"
|
||||
};
|
||||
|
||||
const params = {
|
||||
confidence_threshold: 0.7
|
||||
};
|
||||
|
||||
callAlgorithm("alg-001", "ver-001", inputData, params)
|
||||
.then(result => {
|
||||
if (result) {
|
||||
console.log(`调用ID: ${result.id}`);
|
||||
console.log(`状态: ${result.status}`);
|
||||
console.log(`响应时间: ${result.response_time}秒`);
|
||||
|
||||
if (result.status === 'success') {
|
||||
const predictions = result.output_data.predictions;
|
||||
predictions.forEach(pred => {
|
||||
console.log(`类别: ${pred.class}, 置信度: ${pred.confidence}`);
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
### 获取调用结果
|
||||
|
||||
**Python**
|
||||
```python
|
||||
def get_call_result(call_id):
|
||||
response = requests.get(f"{BASE_URL}/algorithms/calls/{call_id}", headers=headers)
|
||||
if response.status_code == 200:
|
||||
return response.json()
|
||||
else:
|
||||
print(f"Error: {response.status_code} - {response.text}")
|
||||
return None
|
||||
|
||||
# 使用示例
|
||||
result = get_call_result("call-001")
|
||||
if result:
|
||||
print(f"调用状态: {result['status']}")
|
||||
if result['status'] == 'success':
|
||||
print(f"输出数据: {json.dumps(result['output_data'], indent=2)}")
|
||||
```
|
||||
|
||||
**JavaScript**
|
||||
```javascript
|
||||
async function getCallResult(callId) {
|
||||
try {
|
||||
const response = await fetch(`${BASE_URL}/algorithms/calls/${callId}`, {
|
||||
method: 'GET',
|
||||
headers: headers
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
return await response.json();
|
||||
} else {
|
||||
console.error(`Error: ${response.status} - ${await response.text()}`);
|
||||
return null;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('请求失败:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// 使用示例
|
||||
getCallResult("call-001").then(result => {
|
||||
if (result) {
|
||||
console.log(`调用状态: ${result.status}`);
|
||||
if (result.status === 'success') {
|
||||
console.log(`输出数据:`, JSON.stringify(result.output_data, null, 2));
|
||||
}
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## 通过API网关调用算法
|
||||
|
||||
### 网关调用示例
|
||||
|
||||
**Python**
|
||||
```python
|
||||
def call_algorithm_via_gateway(algorithm_id, version_id, input_data, params=None):
|
||||
payload = {
|
||||
"algorithm_id": algorithm_id,
|
||||
"version_id": version_id,
|
||||
"input_data": input_data
|
||||
}
|
||||
|
||||
if params:
|
||||
payload["params"] = params
|
||||
|
||||
response = requests.post(f"{BASE_URL}/gateway/call",
|
||||
headers=headers,
|
||||
json=payload)
|
||||
|
||||
if response.status_code == 200:
|
||||
return response.json()
|
||||
else:
|
||||
print(f"Error: {response.status_code} - {response.text}")
|
||||
return None
|
||||
|
||||
# 使用示例
|
||||
gateway_result = call_algorithm_via_gateway("alg-001", "ver-001", input_data, params)
|
||||
if gateway_result:
|
||||
print(f"网关调用成功,响应时间: {gateway_result['response_time']}秒")
|
||||
```
|
||||
|
||||
**JavaScript**
|
||||
```javascript
|
||||
async function callAlgorithmViaGateway(algorithmId, versionId, inputData, params = null) {
|
||||
const payload = {
|
||||
algorithm_id: algorithmId,
|
||||
version_id: versionId,
|
||||
input_data: inputData
|
||||
};
|
||||
|
||||
if (params) {
|
||||
payload.params = params;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${BASE_URL}/gateway/call`, {
|
||||
method: 'POST',
|
||||
headers: headers,
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
return await response.json();
|
||||
} else {
|
||||
console.error(`Error: ${response.status} - ${await response.text()}`);
|
||||
return null;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('请求失败:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// 使用示例
|
||||
callAlgorithmViaGateway("alg-001", "ver-001", inputData, params)
|
||||
.then(gatewayResult => {
|
||||
if (gatewayResult) {
|
||||
console.log(`网关调用成功,响应时间: ${gatewayResult.response_time}秒`);
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## 历史记录示例
|
||||
|
||||
### 获取调用历史
|
||||
|
||||
**Python**
|
||||
```python
|
||||
def get_call_history(skip=0, limit=100, algorithm_id=None, status=None):
|
||||
params = {"skip": skip, "limit": limit}
|
||||
if algorithm_id:
|
||||
params["algorithm_id"] = algorithm_id
|
||||
if status:
|
||||
params["status"] = status
|
||||
|
||||
response = requests.get(f"{BASE_URL}/history/user-calls",
|
||||
headers=headers,
|
||||
params=params)
|
||||
|
||||
if response.status_code == 200:
|
||||
return response.json()
|
||||
else:
|
||||
print(f"Error: {response.status_code} - {response.text}")
|
||||
return None
|
||||
|
||||
# 使用示例
|
||||
history = get_call_history(limit=10, status="success")
|
||||
if history:
|
||||
print(f"找到 {history['count']} 条历史记录")
|
||||
for record in history['history']:
|
||||
print(f"- {record['algorithm_id']}: {record['status']} ({record['response_time']}s)")
|
||||
```
|
||||
|
||||
**JavaScript**
|
||||
```javascript
|
||||
async function getCallHistory(skip = 0, limit = 100, algorithmId = null, status = null) {
|
||||
let url = `${BASE_URL}/history/user-calls?skip=${skip}&limit=${limit}`;
|
||||
if (algorithmId) url += `&algorithm_id=${algorithmId}`;
|
||||
if (status) url += `&status=${status}`;
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
method: 'GET',
|
||||
headers: headers
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
return await response.json();
|
||||
} else {
|
||||
console.error(`Error: ${response.status} - ${await response.text()}`);
|
||||
return null;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('请求失败:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// 使用示例
|
||||
getCallHistory(0, 10, null, "success").then(history => {
|
||||
if (history) {
|
||||
console.log(`找到 ${history.count} 条历史记录`);
|
||||
history.history.forEach(record => {
|
||||
console.log(`- ${record.algorithm_id}: ${record.status} (${record.response_time}s)`);
|
||||
});
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
### 获取调用统计
|
||||
|
||||
**Python**
|
||||
```python
|
||||
def get_call_statistics(user_id=None, algorithm_id=None):
|
||||
params = {}
|
||||
if user_id:
|
||||
params["user_id"] = user_id
|
||||
if algorithm_id:
|
||||
params["algorithm_id"] = algorithm_id
|
||||
|
||||
response = requests.get(f"{BASE_URL}/history/statistics",
|
||||
headers=headers,
|
||||
params=params)
|
||||
|
||||
if response.status_code == 200:
|
||||
return response.json()
|
||||
else:
|
||||
print(f"Error: {response.status_code} - {response.text}")
|
||||
return None
|
||||
|
||||
# 使用示例
|
||||
stats = get_call_statistics()
|
||||
if stats:
|
||||
print(f"总调用次数: {stats['total_calls']}")
|
||||
print(f"成功率: {stats['success_rate']}%")
|
||||
print(f"平均响应时间: {stats['avg_response_time']}秒")
|
||||
print(f"今日调用: {stats['today_calls']}")
|
||||
```
|
||||
|
||||
**JavaScript**
|
||||
```javascript
|
||||
async function getCallStatistics(userId = null, algorithmId = null) {
|
||||
let url = `${BASE_URL}/history/statistics`;
|
||||
const params = {};
|
||||
if (userId) params.user_id = userId;
|
||||
if (algorithmId) params.algorithm_id = algorithmId;
|
||||
|
||||
if (Object.keys(params).length > 0) {
|
||||
const queryString = new URLSearchParams(params).toString();
|
||||
url += `?${queryString}`;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
method: 'GET',
|
||||
headers: headers
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
return await response.json();
|
||||
} else {
|
||||
console.error(`Error: ${response.status} - ${await response.text()}`);
|
||||
return null;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('请求失败:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// 使用示例
|
||||
getCallStatistics().then(stats => {
|
||||
if (stats) {
|
||||
console.log(`总调用次数: ${stats.total_calls}`);
|
||||
console.log(`成功率: ${stats.success_rate}%`);
|
||||
console.log(`平均响应时间: ${stats.avg_response_time}秒`);
|
||||
console.log(`今日调用: ${stats.today_calls}`);
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## 监控API示例
|
||||
|
||||
### 获取系统健康状况
|
||||
|
||||
**Python**
|
||||
```python
|
||||
def get_health_status():
|
||||
response = requests.get(f"{BASE_URL}/monitoring/health", headers=headers)
|
||||
if response.status_code == 200:
|
||||
return response.json()
|
||||
else:
|
||||
print(f"Error: {response.status_code} - {response.text}")
|
||||
return None
|
||||
|
||||
# 使用示例
|
||||
health = get_health_status()
|
||||
if health:
|
||||
print(f"系统状态: {health['status']}")
|
||||
print(f"CPU使用率: {health['system_metrics']['cpu_percent']}%")
|
||||
print(f"内存使用率: {health['system_metrics']['memory_percent']}%")
|
||||
```
|
||||
|
||||
**JavaScript**
|
||||
```javascript
|
||||
async function getHealthStatus() {
|
||||
try {
|
||||
const response = await fetch(`${BASE_URL}/monitoring/health`, {
|
||||
method: 'GET',
|
||||
headers: headers
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
return await response.json();
|
||||
} else {
|
||||
console.error(`Error: ${response.status} - ${await response.text()}`);
|
||||
return null;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('请求失败:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// 使用示例
|
||||
getHealthStatus().then(health => {
|
||||
if (health) {
|
||||
console.log(`系统状态: ${health.status}`);
|
||||
console.log(`CPU使用率: ${health.system_metrics.cpu_percent}%`);
|
||||
console.log(`内存使用率: ${health.system_metrics.memory_percent}%`);
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
### 获取算法性能指标
|
||||
|
||||
**Python**
|
||||
```python
|
||||
def get_algorithm_performance(algorithm_id, days=7):
|
||||
response = requests.get(
|
||||
f"{BASE_URL}/monitoring/performance/algorithm/{algorithm_id}",
|
||||
headers=headers,
|
||||
params={"days": days}
|
||||
)
|
||||
if response.status_code == 200:
|
||||
return response.json()
|
||||
else:
|
||||
print(f"Error: {response.status_code} - {response.text}")
|
||||
return None
|
||||
|
||||
# 使用示例
|
||||
performance = get_algorithm_performance("alg-001", 30)
|
||||
if performance:
|
||||
print(f"算法 {performance['algorithm_id']} 的30天性能指标:")
|
||||
print(f"总调用次数: {performance['total_calls']}")
|
||||
print(f"成功率: {performance['success_rate']}%")
|
||||
print(f"平均响应时间: {performance['average_response_time']}秒")
|
||||
```
|
||||
|
||||
**JavaScript**
|
||||
```javascript
|
||||
async function getAlgorithmPerformance(algorithmId, days = 7) {
|
||||
try {
|
||||
const response = await fetch(
|
||||
`${BASE_URL}/monitoring/performance/algorithm/${algorithmId}?days=${days}`,
|
||||
{
|
||||
method: 'GET',
|
||||
headers: headers
|
||||
}
|
||||
);
|
||||
|
||||
if (response.ok) {
|
||||
return await response.json();
|
||||
} else {
|
||||
console.error(`Error: ${response.status} - ${await response.text()}`);
|
||||
return null;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('请求失败:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// 使用示例
|
||||
getAlgorithmPerformance("alg-001", 30).then(performance => {
|
||||
if (performance) {
|
||||
console.log(`算法 ${performance.algorithm_id} 的30天性能指标:`);
|
||||
console.log(`总调用次数: ${performance.total_calls}`);
|
||||
console.log(`成功率: ${performance.success_rate}%`);
|
||||
console.log(`平均响应时间: ${performance.average_response_time}秒`);
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## OpenAI集成示例
|
||||
|
||||
### 生成仿真数据
|
||||
|
||||
**Python**
|
||||
```python
|
||||
def generate_simulation_data(prompt, data_type="text"):
|
||||
payload = {
|
||||
"prompt": prompt,
|
||||
"data_type": data_type
|
||||
}
|
||||
|
||||
response = requests.post(f"{BASE_URL}/openai/generate-data",
|
||||
headers=headers,
|
||||
json=payload)
|
||||
|
||||
if response.status_code == 200:
|
||||
return response.json()
|
||||
else:
|
||||
print(f"Error: {response.status_code} - {response.text}")
|
||||
return None
|
||||
|
||||
# 使用示例
|
||||
simulation_data = generate_simulation_data("一张包含猫和狗的照片", "image")
|
||||
if simulation_data:
|
||||
print(f"生成的仿真数据类型: {simulation_data['type']}")
|
||||
print(f"生成的数据: {simulation_data['data'][:100]}...")
|
||||
```
|
||||
|
||||
**JavaScript**
|
||||
```javascript
|
||||
async function generateSimulationData(prompt, dataType = "text") {
|
||||
const payload = {
|
||||
prompt: prompt,
|
||||
data_type: dataType
|
||||
};
|
||||
|
||||
try {
|
||||
const response = await fetch(`${BASE_URL}/openai/generate-data`, {
|
||||
method: 'POST',
|
||||
headers: headers,
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
return await response.json();
|
||||
} else {
|
||||
console.error(`Error: ${response.status} - ${await response.text()}`);
|
||||
return null;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('请求失败:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// 使用示例
|
||||
generateSimulationData("一张包含猫和狗的照片", "image")
|
||||
.then(simulationData => {
|
||||
if (simulationData) {
|
||||
console.log(`生成的仿真数据类型: ${simulationData.type}`);
|
||||
console.log(`生成的数据: ${simulationData.data.substring(0, 100)}...`);
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## 错误处理
|
||||
|
||||
API调用可能会返回各种错误,以下是常见的错误处理方式:
|
||||
|
||||
**Python**
|
||||
```python
|
||||
def safe_api_call(url, method="GET", payload=None):
|
||||
try:
|
||||
if method.upper() == "GET":
|
||||
response = requests.get(url, headers=headers)
|
||||
elif method.upper() == "POST":
|
||||
response = requests.post(url, headers=headers, json=payload)
|
||||
elif method.upper() == "PUT":
|
||||
response = requests.put(url, headers=headers, json=payload)
|
||||
elif method.upper() == "DELETE":
|
||||
response = requests.delete(url, headers=headers)
|
||||
|
||||
# 检查HTTP状态码
|
||||
if response.status_code >= 200 and response.status_code < 300:
|
||||
return {"success": True, "data": response.json()}
|
||||
else:
|
||||
return {
|
||||
"success": False,
|
||||
"error": f"HTTP {response.status_code}",
|
||||
"message": response.text
|
||||
}
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
return {"success": False, "error": "Request Error", "message": str(e)}
|
||||
except Exception as e:
|
||||
return {"success": False, "error": "Unknown Error", "message": str(e)}
|
||||
|
||||
# 使用示例
|
||||
result = safe_api_call(f"{BASE_URL}/algorithms", "GET")
|
||||
if result["success"]:
|
||||
print("API调用成功:", result["data"])
|
||||
else:
|
||||
print("API调用失败:", result["error"], "-", result["message"])
|
||||
```
|
||||
|
||||
**JavaScript**
|
||||
```javascript
|
||||
async function safeApiCall(url, method = "GET", payload = null) {
|
||||
try {
|
||||
const options = {
|
||||
method: method.toUpperCase(),
|
||||
headers: headers
|
||||
};
|
||||
|
||||
if (payload && (method.toUpperCase() === "POST" || method.toUpperCase() === "PUT")) {
|
||||
options.body = JSON.stringify(payload);
|
||||
}
|
||||
|
||||
const response = await fetch(url, options);
|
||||
|
||||
// 检查HTTP状态码
|
||||
if (response.ok) {
|
||||
return {
|
||||
success: true,
|
||||
data: await response.json()
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
success: false,
|
||||
error: `HTTP ${response.status}`,
|
||||
message: await response.text()
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: "Request Error",
|
||||
message: error.message
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// 使用示例
|
||||
safeApiCall(`${BASE_URL}/algorithms`, "GET")
|
||||
.then(result => {
|
||||
if (result.success) {
|
||||
console.log("API调用成功:", result.data);
|
||||
} else {
|
||||
console.log("API调用失败:", result.error, "-", result.message);
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## 高级用法
|
||||
|
||||
### 批量调用算法
|
||||
|
||||
**Python**
|
||||
```python
|
||||
import asyncio
|
||||
import aiohttp
|
||||
|
||||
async def batch_call_algorithms(calls_data):
|
||||
async with aiohttp.ClientSession() as session:
|
||||
tasks = []
|
||||
for call_data in calls_data:
|
||||
task = asyncio.create_task(
|
||||
async_call_algorithm(session, call_data)
|
||||
)
|
||||
tasks.append(task)
|
||||
|
||||
results = await asyncio.gather(*tasks)
|
||||
return results
|
||||
|
||||
async def async_call_algorithm(session, call_data):
|
||||
headers = {
|
||||
"Authorization": "Bearer YOUR_ACCESS_TOKEN",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
async with session.post(
|
||||
f"{BASE_URL}/algorithms/call",
|
||||
headers=headers,
|
||||
json=call_data
|
||||
) as response:
|
||||
return await response.json()
|
||||
|
||||
# 使用示例
|
||||
calls_data = [
|
||||
{
|
||||
"algorithm_id": "alg-001",
|
||||
"version_id": "ver-001",
|
||||
"input_data": {"image_url": "https://example.com/img1.jpg"}
|
||||
},
|
||||
{
|
||||
"algorithm_id": "alg-001",
|
||||
"version_id": "ver-001",
|
||||
"input_data": {"image_url": "https://example.com/img2.jpg"}
|
||||
}
|
||||
]
|
||||
|
||||
# 注意:这需要在异步环境中运行
|
||||
# results = asyncio.run(batch_call_algorithms(calls_data))
|
||||
```
|
||||
|
||||
### 使用SDK进行API调用
|
||||
|
||||
我们还提供了官方SDK来简化API调用:
|
||||
|
||||
**Python SDK示例**
|
||||
```python
|
||||
from algorithm_showcase.client import AlgorithmShowcaseClient
|
||||
|
||||
# 初始化客户端
|
||||
client = AlgorithmShowcaseClient(
|
||||
base_url="http://localhost:8000",
|
||||
api_key="YOUR_API_KEY"
|
||||
)
|
||||
|
||||
# 调用算法
|
||||
try:
|
||||
result = client.call_algorithm(
|
||||
algorithm_id="alg-001",
|
||||
version_id="ver-001",
|
||||
input_data={"image_url": "https://example.com/sample.jpg"},
|
||||
params={"confidence_threshold": 0.7}
|
||||
)
|
||||
print(f"调用成功: {result}")
|
||||
except Exception as e:
|
||||
print(f"调用失败: {e}")
|
||||
```
|
||||
|
||||
**JavaScript SDK示例**
|
||||
```javascript
|
||||
import { AlgorithmShowcaseClient } from '@algorithm-showcase/sdk';
|
||||
|
||||
// 初始化客户端
|
||||
const client = new AlgorithmShowcaseClient({
|
||||
baseUrl: 'http://localhost:8000',
|
||||
apiKey: 'YOUR_API_KEY'
|
||||
});
|
||||
|
||||
// 调用算法
|
||||
try {
|
||||
const result = await client.callAlgorithm({
|
||||
algorithmId: 'alg-001',
|
||||
versionId: 'ver-001',
|
||||
inputData: { imageUrl: 'https://example.com/sample.jpg' },
|
||||
params: { confidenceThreshold: 0.7 }
|
||||
});
|
||||
console.log('调用成功:', result);
|
||||
} catch (error) {
|
||||
console.error('调用失败:', error);
|
||||
}
|
||||
```
|
||||
|
||||
以上是智能算法展示平台API的完整使用示例。这些示例涵盖了从基本操作到高级用法的各个方面,可以帮助开发者快速上手并有效利用平台的功能。
|
||||
717
docs/api-reference.md
Normal file
717
docs/api-reference.md
Normal file
@@ -0,0 +1,717 @@
|
||||
# 智能算法展示平台 API 文档
|
||||
|
||||
## 概述
|
||||
|
||||
智能算法展示平台提供了一套完整的API,用于管理算法、调用算法以及获取结果。API遵循RESTful设计原则,返回JSON格式的数据。
|
||||
|
||||
### 基础URL
|
||||
|
||||
```
|
||||
http://localhost:8000/api/v1
|
||||
```
|
||||
|
||||
### 认证
|
||||
|
||||
大多数API端点需要认证。认证通过在请求头中添加 `Authorization` 字段实现:
|
||||
|
||||
```
|
||||
Authorization: Bearer <your-token>
|
||||
```
|
||||
|
||||
## 算法管理API
|
||||
|
||||
### 获取算法列表
|
||||
|
||||
**GET** `/algorithms`
|
||||
|
||||
获取所有可用算法的列表。
|
||||
|
||||
#### 参数
|
||||
- `type` (可选): 算法类型 (computer_vision, nlp, ml等)
|
||||
- `skip` (可选): 跳过的记录数,默认为0
|
||||
- `limit` (可选): 返回的最大记录数,默认为100
|
||||
|
||||
#### 响应
|
||||
```json
|
||||
{
|
||||
"algorithms": [
|
||||
{
|
||||
"id": "alg-001",
|
||||
"name": "图像分类算法",
|
||||
"description": "基于深度学习的图像分类算法",
|
||||
"type": "computer_vision",
|
||||
"status": "active",
|
||||
"versions": [],
|
||||
"created_at": "2023-01-01T00:00:00Z",
|
||||
"updated_at": "2023-01-01T00:00:00Z"
|
||||
}
|
||||
],
|
||||
"total": 1
|
||||
}
|
||||
```
|
||||
|
||||
### 获取算法详情
|
||||
|
||||
**GET** `/algorithms/{algorithm_id}`
|
||||
|
||||
获取特定算法的详细信息。
|
||||
|
||||
#### 参数
|
||||
- `algorithm_id`: 算法ID
|
||||
|
||||
#### 响应
|
||||
```json
|
||||
{
|
||||
"id": "alg-001",
|
||||
"name": "图像分类算法",
|
||||
"description": "基于深度学习的图像分类算法",
|
||||
"type": "computer_vision",
|
||||
"status": "active",
|
||||
"versions": [
|
||||
{
|
||||
"id": "ver-001",
|
||||
"algorithm_id": "alg-001",
|
||||
"version": "v1.0",
|
||||
"url": "http://algorithm-service:8000/classify",
|
||||
"params": {
|
||||
"confidence_threshold": {
|
||||
"type": "float",
|
||||
"default": 0.5,
|
||||
"min": 0.0,
|
||||
"max": 1.0
|
||||
}
|
||||
},
|
||||
"input_schema": {},
|
||||
"output_schema": {},
|
||||
"is_default": true,
|
||||
"created_at": "2023-01-01T00:00:00Z",
|
||||
"updated_at": "2023-01-01T00:00:00Z"
|
||||
}
|
||||
],
|
||||
"created_at": "2023-01-01T00:00:00Z",
|
||||
"updated_at": "2023-01-01T00:00:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
### 创建算法
|
||||
|
||||
**POST** `/algorithms`
|
||||
|
||||
创建新算法(需要管理员权限)。
|
||||
|
||||
#### 请求体
|
||||
```json
|
||||
{
|
||||
"name": "新算法",
|
||||
"description": "算法描述",
|
||||
"type": "ml",
|
||||
"status": "active"
|
||||
}
|
||||
```
|
||||
|
||||
#### 响应
|
||||
```json
|
||||
{
|
||||
"id": "alg-002",
|
||||
"name": "新算法",
|
||||
"description": "算法描述",
|
||||
"type": "ml",
|
||||
"status": "active",
|
||||
"versions": [],
|
||||
"created_at": "2023-01-01T00:00:00Z",
|
||||
"updated_at": "2023-01-01T00:00:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
## 算法调用API
|
||||
|
||||
### 调用算法
|
||||
|
||||
**POST** `/algorithms/call`
|
||||
|
||||
调用指定算法。
|
||||
|
||||
#### 请求体
|
||||
```json
|
||||
{
|
||||
"algorithm_id": "alg-001",
|
||||
"version_id": "ver-001",
|
||||
"input_data": {
|
||||
"image_url": "https://example.com/image.jpg"
|
||||
},
|
||||
"params": {
|
||||
"confidence_threshold": 0.7
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 响应
|
||||
```json
|
||||
{
|
||||
"id": "call-001",
|
||||
"user_id": "user-001",
|
||||
"algorithm_id": "alg-001",
|
||||
"version_id": "ver-001",
|
||||
"input_data": {
|
||||
"image_url": "https://example.com/image.jpg"
|
||||
},
|
||||
"params": {
|
||||
"confidence_threshold": 0.7
|
||||
},
|
||||
"output_data": {
|
||||
"predictions": [
|
||||
{
|
||||
"class": "cat",
|
||||
"confidence": 0.95
|
||||
}
|
||||
]
|
||||
},
|
||||
"status": "success",
|
||||
"response_time": 1.2,
|
||||
"error_message": null,
|
||||
"created_at": "2023-01-01T00:00:00Z",
|
||||
"updated_at": "2023-01-01T00:00:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
### 获取调用结果
|
||||
|
||||
**GET** `/algorithms/calls/{call_id}`
|
||||
|
||||
获取特定调用的结果。
|
||||
|
||||
#### 参数
|
||||
- `call_id`: 调用ID
|
||||
|
||||
#### 响应
|
||||
```json
|
||||
{
|
||||
"id": "call-001",
|
||||
"user_id": "user-001",
|
||||
"algorithm_id": "alg-001",
|
||||
"version_id": "ver-001",
|
||||
"input_data": {
|
||||
"image_url": "https://example.com/image.jpg"
|
||||
},
|
||||
"params": {
|
||||
"confidence_threshold": 0.7
|
||||
},
|
||||
"output_data": {
|
||||
"predictions": [
|
||||
{
|
||||
"class": "cat",
|
||||
"confidence": 0.95
|
||||
}
|
||||
]
|
||||
},
|
||||
"status": "success",
|
||||
"response_time": 1.2,
|
||||
"error_message": null,
|
||||
"created_at": "2023-01-01T00:00:00Z",
|
||||
"updated_at": "2023-01-01T00:00:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
## 用户管理API
|
||||
|
||||
### 用户登录
|
||||
|
||||
**POST** `/users/login`
|
||||
|
||||
用户登录并获取访问令牌。
|
||||
|
||||
#### 请求体
|
||||
```json
|
||||
{
|
||||
"username": "testuser",
|
||||
"password": "password123"
|
||||
}
|
||||
```
|
||||
|
||||
#### 响应
|
||||
```json
|
||||
{
|
||||
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
|
||||
"token_type": "bearer"
|
||||
}
|
||||
```
|
||||
|
||||
## 历史记录API
|
||||
|
||||
### 获取调用历史
|
||||
|
||||
**GET** `/history/user-calls`
|
||||
|
||||
获取用户的调用历史。
|
||||
|
||||
#### 参数
|
||||
- `algorithm_id` (可选): 算法ID
|
||||
- `status` (可选): 调用状态
|
||||
- `start_date` (可选): 开始日期
|
||||
- `end_date` (可选): 结束日期
|
||||
- `skip` (可选): 跳过的记录数
|
||||
- `limit` (可选): 返回的最大记录数
|
||||
|
||||
#### 响应
|
||||
```json
|
||||
{
|
||||
"history": [
|
||||
{
|
||||
"id": "call-001",
|
||||
"user_id": "user-001",
|
||||
"algorithm_id": "alg-001",
|
||||
"version_id": "ver-001",
|
||||
"input_data": {},
|
||||
"params": {},
|
||||
"output_data": {},
|
||||
"status": "success",
|
||||
"response_time": 1.2,
|
||||
"error_message": null,
|
||||
"created_at": "2023-01-01T00:00:00Z",
|
||||
"updated_at": "2023-01-01T00:00:00Z"
|
||||
}
|
||||
],
|
||||
"count": 1,
|
||||
"skip": 0,
|
||||
"limit": 100
|
||||
}
|
||||
```
|
||||
|
||||
### 获取调用统计
|
||||
|
||||
**GET** `/history/statistics`
|
||||
|
||||
获取调用统计信息。
|
||||
|
||||
#### 参数
|
||||
- `user_id` (可选): 用户ID
|
||||
- `algorithm_id` (可选): 算法ID
|
||||
|
||||
#### 响应
|
||||
```json
|
||||
{
|
||||
"total_calls": 156,
|
||||
"status_counts": {
|
||||
"success": 145,
|
||||
"failed": 11
|
||||
},
|
||||
"success_rate": 92.3,
|
||||
"avg_response_time": 1.45,
|
||||
"today_calls": 12
|
||||
}
|
||||
```
|
||||
|
||||
## 监控API
|
||||
|
||||
### 获取系统健康状况
|
||||
|
||||
**GET** `/monitoring/health`
|
||||
|
||||
获取系统健康状况。
|
||||
|
||||
#### 响应
|
||||
```json
|
||||
{
|
||||
"status": "healthy",
|
||||
"timestamp": "2023-01-01T00:00:00Z",
|
||||
"system_metrics": {
|
||||
"cpu_percent": 25.5,
|
||||
"memory_percent": 45.2,
|
||||
"disk_percent": 60.1
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 获取算法性能指标
|
||||
|
||||
**GET** `/monitoring/performance/algorithm/{algorithm_id}`
|
||||
|
||||
获取特定算法的性能指标。
|
||||
|
||||
#### 参数
|
||||
- `algorithm_id`: 算法ID
|
||||
- `days`: 统计天数(默认为7)
|
||||
|
||||
#### 响应
|
||||
```json
|
||||
{
|
||||
"algorithm_id": "alg-001",
|
||||
"period_days": 7,
|
||||
"total_calls": 50,
|
||||
"success_calls": 48,
|
||||
"failed_calls": 2,
|
||||
"success_rate": 96.0,
|
||||
"average_response_time": 1.234,
|
||||
"status_distribution": {
|
||||
"success": 48,
|
||||
"failed": 2
|
||||
},
|
||||
"timestamp": "2023-01-01T00:00:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
## 权限管理API
|
||||
|
||||
### 检查权限
|
||||
|
||||
**POST** `/permissions/check`
|
||||
|
||||
检查用户对特定算法的权限。
|
||||
|
||||
#### 请求体
|
||||
```json
|
||||
{
|
||||
"algorithm_id": "alg-001",
|
||||
"permission_type": "execute"
|
||||
}
|
||||
```
|
||||
|
||||
#### 响应
|
||||
```json
|
||||
{
|
||||
"has_permission": true,
|
||||
"user_id": "user-001",
|
||||
"algorithm_id": "alg-001",
|
||||
"permission_type": "execute"
|
||||
}
|
||||
```
|
||||
|
||||
## OpenAI集成API
|
||||
|
||||
### 生成仿真数据
|
||||
|
||||
**POST** `/openai/generate-data`
|
||||
|
||||
使用OpenAI生成仿真输入数据。
|
||||
|
||||
#### 请求体
|
||||
```json
|
||||
{
|
||||
"prompt": "一张包含猫和狗的照片",
|
||||
"data_type": "image"
|
||||
}
|
||||
```
|
||||
|
||||
#### 响应
|
||||
```json
|
||||
{
|
||||
"data": "生成的仿真数据",
|
||||
"type": "image"
|
||||
}
|
||||
```
|
||||
|
||||
## API网关API
|
||||
|
||||
### 通过网关调用算法
|
||||
|
||||
**POST** `/gateway/call`
|
||||
|
||||
通过API网关调用算法,提供统一的访问接口和安全控制。
|
||||
|
||||
#### 请求体
|
||||
```json
|
||||
{
|
||||
"algorithm_id": "alg-001",
|
||||
"version_id": "ver-001",
|
||||
"input_data": {
|
||||
"image_url": "https://example.com/image.jpg"
|
||||
},
|
||||
"params": {
|
||||
"confidence_threshold": 0.7
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 响应
|
||||
```json
|
||||
{
|
||||
"id": "call-001",
|
||||
"user_id": "user-001",
|
||||
"algorithm_id": "alg-001",
|
||||
"version_id": "ver-001",
|
||||
"input_data": {
|
||||
"image_url": "https://example.com/image.jpg"
|
||||
},
|
||||
"params": {
|
||||
"confidence_threshold": 0.7
|
||||
},
|
||||
"output_data": {
|
||||
"predictions": [
|
||||
{
|
||||
"class": "cat",
|
||||
"confidence": 0.95
|
||||
}
|
||||
]
|
||||
},
|
||||
"status": "success",
|
||||
"response_time": 1.2,
|
||||
"error_message": null,
|
||||
"created_at": "2023-01-01T00:00:00Z",
|
||||
"updated_at": "2023-01-01T00:00:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
### 获取网关统计信息
|
||||
|
||||
**GET** `/gateway/stats`
|
||||
|
||||
获取API网关的调用统计信息。
|
||||
|
||||
#### 响应
|
||||
```json
|
||||
{
|
||||
"total_requests": 1250,
|
||||
"successful_requests": 1200,
|
||||
"failed_requests": 50,
|
||||
"blocked_requests": 10,
|
||||
"rate_limited_requests": 40,
|
||||
"last_updated": "2023-01-01T00:00:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
## 算法仓库管理API
|
||||
|
||||
### 获取算法仓库列表
|
||||
|
||||
**GET** `/repositories`
|
||||
|
||||
获取所有算法仓库的列表。
|
||||
|
||||
#### 响应
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"repositories": [
|
||||
{
|
||||
"id": "repo-001",
|
||||
"name": "图像分类算法仓库",
|
||||
"description": "图像分类算法的代码仓库",
|
||||
"type": "code",
|
||||
"repo_url": "https://gitea.example.com/owner/repo.git",
|
||||
"branch": "main",
|
||||
"local_path": "",
|
||||
"algorithm_id": null,
|
||||
"status": "active",
|
||||
"created_at": "2023-01-01T00:00:00Z",
|
||||
"updated_at": "2023-01-01T00:00:00Z"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### 获取单个算法仓库详情
|
||||
|
||||
**GET** `/repositories/{repo_id}`
|
||||
|
||||
获取特定算法仓库的详细信息。
|
||||
|
||||
#### 参数
|
||||
- `repo_id`: 仓库ID
|
||||
|
||||
#### 响应
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"repository": {
|
||||
"id": "repo-001",
|
||||
"name": "图像分类算法仓库",
|
||||
"description": "图像分类算法的代码仓库",
|
||||
"type": "code",
|
||||
"repo_url": "https://gitea.example.com/owner/repo.git",
|
||||
"branch": "main",
|
||||
"local_path": "",
|
||||
"algorithm_id": null,
|
||||
"status": "active",
|
||||
"created_at": "2023-01-01T00:00:00Z",
|
||||
"updated_at": "2023-01-01T00:00:00Z"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 添加算法仓库
|
||||
|
||||
**POST** `/repositories`
|
||||
|
||||
添加新的算法仓库。
|
||||
|
||||
#### 请求体
|
||||
```json
|
||||
{
|
||||
"name": "新算法仓库",
|
||||
"description": "新算法的代码仓库",
|
||||
"type": "code",
|
||||
"repo_url": "https://gitea.example.com/owner/repo.git",
|
||||
"branch": "main",
|
||||
"local_path": ""
|
||||
}
|
||||
```
|
||||
|
||||
#### 响应
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "Repository created successfully",
|
||||
"repository": {
|
||||
"id": "repo-002",
|
||||
"name": "新算法仓库",
|
||||
"description": "新算法的代码仓库",
|
||||
"type": "code",
|
||||
"repo_url": "https://gitea.example.com/owner/repo.git",
|
||||
"branch": "main",
|
||||
"local_path": "",
|
||||
"algorithm_id": null,
|
||||
"status": "active",
|
||||
"created_at": "2023-01-01T00:00:00Z",
|
||||
"updated_at": "2023-01-01T00:00:00Z"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 更新算法仓库
|
||||
|
||||
**PUT** `/repositories/{repo_id}`
|
||||
|
||||
更新特定算法仓库的信息。
|
||||
|
||||
#### 参数
|
||||
- `repo_id`: 仓库ID
|
||||
|
||||
#### 请求体
|
||||
```json
|
||||
{
|
||||
"name": "更新后的算法仓库",
|
||||
"description": "更新后的算法仓库描述",
|
||||
"type": "code"
|
||||
}
|
||||
```
|
||||
|
||||
#### 响应
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "Repository updated successfully",
|
||||
"repository": {
|
||||
"id": "repo-001",
|
||||
"name": "更新后的算法仓库",
|
||||
"description": "更新后的算法仓库描述",
|
||||
"type": "code",
|
||||
"repo_url": "https://gitea.example.com/owner/repo.git",
|
||||
"branch": "main",
|
||||
"local_path": "",
|
||||
"algorithm_id": null,
|
||||
"status": "active",
|
||||
"created_at": "2023-01-01T00:00:00Z",
|
||||
"updated_at": "2023-01-01T00:00:00Z"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 删除算法仓库
|
||||
|
||||
**DELETE** `/repositories/{repo_id}`
|
||||
|
||||
删除特定的算法仓库。
|
||||
|
||||
#### 参数
|
||||
- `repo_id`: 仓库ID
|
||||
|
||||
#### 响应
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "Repository deleted successfully",
|
||||
"gitea_deleted": true
|
||||
}
|
||||
```
|
||||
|
||||
## Gitea集成API
|
||||
|
||||
### 获取Gitea配置
|
||||
|
||||
**GET** `/gitea/config`
|
||||
|
||||
获取Gitea配置信息。
|
||||
|
||||
#### 响应
|
||||
```json
|
||||
{
|
||||
"server_url": "https://gitea.example.com",
|
||||
"access_token": "your-access-token",
|
||||
"default_owner": "owner",
|
||||
"repo_prefix": "alg-"
|
||||
}
|
||||
```
|
||||
|
||||
### 设置Gitea配置
|
||||
|
||||
**POST** `/gitea/config`
|
||||
|
||||
设置Gitea配置信息。
|
||||
|
||||
#### 请求体
|
||||
```json
|
||||
{
|
||||
"server_url": "https://gitea.example.com",
|
||||
"access_token": "your-access-token",
|
||||
"default_owner": "owner",
|
||||
"repo_prefix": "alg-"
|
||||
}
|
||||
```
|
||||
|
||||
#### 响应
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "Gitea config saved successfully"
|
||||
}
|
||||
```
|
||||
|
||||
### 创建Gitea仓库
|
||||
|
||||
**POST** `/gitea/repos/create`
|
||||
|
||||
在Gitea上创建仓库。
|
||||
|
||||
#### 请求体
|
||||
```json
|
||||
{
|
||||
"algorithm_id": "alg-001",
|
||||
"algorithm_name": "图像分类算法",
|
||||
"description": "图像分类算法的代码仓库"
|
||||
}
|
||||
```
|
||||
|
||||
#### 响应
|
||||
```json
|
||||
{
|
||||
"id": 1,
|
||||
"name": "alg-001",
|
||||
"full_name": "owner/alg-001",
|
||||
"description": "图像分类算法的代码仓库",
|
||||
"private": false,
|
||||
"html_url": "https://gitea.example.com/owner/alg-001"
|
||||
}
|
||||
```
|
||||
|
||||
### 更新Gitea仓库信息
|
||||
|
||||
**PATCH** `/gitea/repos/update`
|
||||
|
||||
更新Gitea仓库信息。
|
||||
|
||||
#### 请求体
|
||||
```json
|
||||
{
|
||||
"algorithm_id": "alg-001",
|
||||
"description": "更新后的仓库描述",
|
||||
"private": false
|
||||
}
|
||||
```
|
||||
|
||||
#### 响应
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "Repository updated successfully"
|
||||
}
|
||||
```
|
||||
362
docs/cli-examples.md
Normal file
362
docs/cli-examples.md
Normal file
@@ -0,0 +1,362 @@
|
||||
# 智能算法展示平台 CLI 工具使用示例
|
||||
|
||||
本文档提供了使用智能算法展示平台命令行工具的各种示例,涵盖从基础到高级的用法。
|
||||
|
||||
## 安装CLI工具
|
||||
|
||||
首先,安装命令行工具:
|
||||
|
||||
```bash
|
||||
pip install algorithm-showcase-cli
|
||||
```
|
||||
|
||||
或者直接运行Python脚本(如果您有源代码):
|
||||
|
||||
```bash
|
||||
python -m sdk.cli.algorithm-showcase-cli --help
|
||||
```
|
||||
|
||||
## 配置认证
|
||||
|
||||
在使用CLI工具之前,需要配置API密钥:
|
||||
|
||||
```bash
|
||||
# 设置API密钥
|
||||
algorithm-showcase config set-api-key YOUR_API_KEY
|
||||
|
||||
# 或者设置基础URL
|
||||
algorithm-showcase config set-base-url http://localhost:8000
|
||||
```
|
||||
|
||||
您也可以通过环境变量设置:
|
||||
|
||||
```bash
|
||||
export ALGORITHM_SHOWCASE_API_KEY=your_api_key_here
|
||||
export ALGORITHM_SHOWCASE_BASE_URL=http://localhost:8000
|
||||
```
|
||||
|
||||
## 基本操作示例
|
||||
|
||||
### 查看帮助
|
||||
|
||||
```bash
|
||||
# 查看主帮助
|
||||
algorithm-showcase --help
|
||||
|
||||
# 查看特定子命令的帮助
|
||||
algorithm-showcase algorithms --help
|
||||
algorithm-showcase call --help
|
||||
algorithm-showcase history --help
|
||||
```
|
||||
|
||||
### 列出所有算法
|
||||
|
||||
```bash
|
||||
# 列出所有算法
|
||||
algorithm-showcase algorithms list
|
||||
|
||||
# 列出特定类型的算法
|
||||
algorithm-showcase algorithms list --type computer_vision
|
||||
|
||||
# 限制返回数量
|
||||
algorithm-showcase algorithms list --limit 10
|
||||
|
||||
# 以JSON格式输出
|
||||
algorithm-showcase algorithms list --format json
|
||||
```
|
||||
|
||||
### 查看算法详情
|
||||
|
||||
```bash
|
||||
# 查看特定算法的详细信息
|
||||
algorithm-showcase algorithms get --algorithm-id alg-001
|
||||
|
||||
# 以表格形式显示版本信息
|
||||
algorithm-showcase algorithms get --algorithm-id alg-001 --show-versions
|
||||
```
|
||||
|
||||
## 算法调用示例
|
||||
|
||||
### 调用算法
|
||||
|
||||
```bash
|
||||
# 基本调用(交互式输入数据)
|
||||
algorithm-showcase call --algorithm-id alg-001 --version-id ver-001
|
||||
|
||||
# 传入JSON格式的输入数据
|
||||
algorithm-showcase call \
|
||||
--algorithm-id alg-001 \
|
||||
--version-id ver-001 \
|
||||
--input-data '{"image_url": "https://example.com/sample.jpg"}'
|
||||
|
||||
# 传入参数
|
||||
algorithm-showcase call \
|
||||
--algorithm-id alg-001 \
|
||||
--version-id ver-001 \
|
||||
--input-data '{"image_url": "https://example.com/sample.jpg"}' \
|
||||
--params '{"confidence_threshold": 0.7}'
|
||||
|
||||
# 从文件读取输入数据
|
||||
algorithm-showcase call \
|
||||
--algorithm-id alg-001 \
|
||||
--version-id ver-001 \
|
||||
--input-file ./input.json
|
||||
|
||||
# 将结果保存到文件
|
||||
algorithm-showcase call \
|
||||
--algorithm-id alg-001 \
|
||||
--version-id ver-001 \
|
||||
--input-data '{"image_url": "https://example.com/sample.jpg"}' \
|
||||
--output-file ./result.json
|
||||
```
|
||||
|
||||
### 批量调用算法
|
||||
|
||||
```bash
|
||||
# 从CSV文件批量调用算法
|
||||
algorithm-showcase batch-call \
|
||||
--algorithm-id alg-001 \
|
||||
--input-file ./batch-input.csv \
|
||||
--output-file ./batch-results.json
|
||||
|
||||
# 从JSONL文件批量调用算法(每行一个JSON对象)
|
||||
algorithm-showcase batch-call \
|
||||
--algorithm-id alg-001 \
|
||||
--input-file ./batch-input.jsonl \
|
||||
--concurrency 5 # 并发数
|
||||
```
|
||||
|
||||
## 历史记录操作示例
|
||||
|
||||
### 查看调用历史
|
||||
|
||||
```bash
|
||||
# 查看最近的调用历史
|
||||
algorithm-showcase history list
|
||||
|
||||
# 查看特定算法的调用历史
|
||||
algorithm-showcase history list --algorithm-id alg-001
|
||||
|
||||
# 查看特定状态的调用历史
|
||||
algorithm-showcase history list --status success
|
||||
|
||||
# 查看特定日期范围的调用历史
|
||||
algorithm-showcase history list \
|
||||
--start-date 2023-01-01 \
|
||||
--end-date 2023-01-31
|
||||
|
||||
# 限制返回数量
|
||||
algorithm-showcase history list --limit 50
|
||||
|
||||
# 以表格形式显示
|
||||
algorithm-showcase history list --format table
|
||||
```
|
||||
|
||||
### 查看调用统计
|
||||
|
||||
```bash
|
||||
# 查看总体统计
|
||||
algorithm-showcase history stats
|
||||
|
||||
# 查看特定算法的统计
|
||||
algorithm-showcase history stats --algorithm-id alg-001
|
||||
|
||||
# 查看今日统计
|
||||
algorithm-showcase history stats --today
|
||||
```
|
||||
|
||||
## 监控操作示例
|
||||
|
||||
### 查看系统健康状况
|
||||
|
||||
```bash
|
||||
# 查看系统健康状况
|
||||
algorithm-showcase monitor health
|
||||
|
||||
# 持续监控(类似top命令)
|
||||
algorithm-showcase monitor health --watch --interval 5
|
||||
```
|
||||
|
||||
### 查看算法性能
|
||||
|
||||
```bash
|
||||
# 查看特定算法的性能指标
|
||||
algorithm-showcase monitor performance --algorithm-id alg-001
|
||||
|
||||
# 查看最近30天的性能指标
|
||||
algorithm-showcase monitor performance --algorithm-id alg-001 --days 30
|
||||
```
|
||||
|
||||
## OpenAI集成示例
|
||||
|
||||
### 生成仿真数据
|
||||
|
||||
```bash
|
||||
# 生成文本仿真数据
|
||||
algorithm-showcase openai generate-data \
|
||||
--prompt "一段描述人工智能发展的文本" \
|
||||
--type text
|
||||
|
||||
# 生成图像仿真数据
|
||||
algorithm-showcase openai generate-data \
|
||||
--prompt "一张包含猫和狗的照片" \
|
||||
--type image
|
||||
|
||||
# 生成结构化数据
|
||||
algorithm-showcase openai generate-data \
|
||||
--prompt "一个包含姓名、年龄、职业的用户数据样本" \
|
||||
--type structured
|
||||
|
||||
# 将生成的数据保存到文件
|
||||
algorithm-showcase openai generate-data \
|
||||
--prompt "一段示例文本" \
|
||||
--type text \
|
||||
--output-file ./generated-sample.txt
|
||||
```
|
||||
|
||||
## 高级用法示例
|
||||
|
||||
### 使用配置文件
|
||||
|
||||
创建配置文件 `~/.algorithm-showcase/config.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"api_key": "your_api_key_here",
|
||||
"base_url": "http://localhost:8000",
|
||||
"default_headers": {
|
||||
"User-Agent": "algorithm-showcase-cli/1.0"
|
||||
},
|
||||
"timeout": 30,
|
||||
"retry_count": 3
|
||||
}
|
||||
```
|
||||
|
||||
然后使用配置文件:
|
||||
|
||||
```bash
|
||||
algorithm-showcase --config ~/.algorithm-showcase/config.json call --algorithm-id alg-001
|
||||
```
|
||||
|
||||
### 管道操作
|
||||
|
||||
将多个命令连接起来:
|
||||
|
||||
```bash
|
||||
# 获取算法列表,然后调用第一个算法
|
||||
algorithm-showcase algorithms list --format json | \
|
||||
jq '.algorithms[0].id' | \
|
||||
xargs -I {} algorithm-showcase call --algorithm-id {}
|
||||
|
||||
# 生成仿真数据并立即调用算法
|
||||
algorithm-showcase openai generate-data --prompt "示例数据" --type text | \
|
||||
xargs -I {} algorithm-showcase call --algorithm-id alg-001 --input-data '{}'
|
||||
```
|
||||
|
||||
### 自动化脚本示例
|
||||
|
||||
创建一个自动化脚本来测试算法性能:
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
# performance-test.sh
|
||||
|
||||
ALGORITHM_ID=$1
|
||||
TEST_COUNT=${2:-10} # 默认测试10次
|
||||
|
||||
echo "开始测试算法 $ALGORITHM_ID 性能,共 $TEST_COUNT 次"
|
||||
|
||||
for i in $(seq 1 $TEST_COUNT); do
|
||||
echo "测试 $i/$TEST_COUNT"
|
||||
|
||||
# 生成随机输入数据
|
||||
INPUT_DATA=$(algorithm-showcase openai generate-data --prompt "测试数据" --type text --format raw)
|
||||
|
||||
# 调用算法并记录时间
|
||||
START_TIME=$(date +%s.%N)
|
||||
RESULT=$(algorithm-showcase call --algorithm-id $ALGORITHM_ID --input-data "$INPUT_DATA" --format json)
|
||||
END_TIME=$(date +%s.%N)
|
||||
|
||||
DURATION=$(echo "$END_TIME - $START_TIME" | bc)
|
||||
echo " 响应时间: $DURATION 秒"
|
||||
|
||||
# 检查调用是否成功
|
||||
SUCCESS=$(echo $RESULT | jq -r '.status')
|
||||
if [ "$SUCCESS" != "success" ]; then
|
||||
echo " 调用失败: $RESULT"
|
||||
fi
|
||||
done
|
||||
|
||||
echo "测试完成,获取性能统计:"
|
||||
algorithm-showcase monitor performance --algorithm-id $ALGORITHM_ID
|
||||
```
|
||||
|
||||
使用该脚本:
|
||||
|
||||
```bash
|
||||
chmod +x performance-test.sh
|
||||
./performance-test.sh alg-001 20 # 测试20次
|
||||
```
|
||||
|
||||
### 导出和导入数据
|
||||
|
||||
```bash
|
||||
# 导出调用历史到CSV
|
||||
algorithm-showcase history export --format csv --output-file history.csv
|
||||
|
||||
# 导出算法配置
|
||||
algorithm-showcase algorithms export --algorithm-id alg-001 --output-file alg-config.json
|
||||
|
||||
# 从文件导入算法配置(如果支持)
|
||||
algorithm-showcase algorithms import --input-file alg-config.json
|
||||
```
|
||||
|
||||
## 故障排除
|
||||
|
||||
### 查看详细日志
|
||||
|
||||
```bash
|
||||
# 启用调试模式
|
||||
algorithm-showcase --debug call --algorithm-id alg-001
|
||||
|
||||
# 查看请求和响应详情
|
||||
algorithm-showcase --verbose call --algorithm-id alg-001
|
||||
```
|
||||
|
||||
### 检查网络连接
|
||||
|
||||
```bash
|
||||
# 测试API连接
|
||||
algorithm-showcase ping
|
||||
|
||||
# 检查认证状态
|
||||
algorithm-showcase auth status
|
||||
```
|
||||
|
||||
### 处理常见错误
|
||||
|
||||
```bash
|
||||
# 如果收到认证错误
|
||||
algorithm-showcase auth login # 重新登录
|
||||
|
||||
# 如果API超时,增加超时时间
|
||||
algorithm-showcase call --algorithm-id alg-001 --timeout 60
|
||||
|
||||
# 如果请求被限流,等待后重试或降低并发
|
||||
algorithm-showcase batch-call --concurrency 1 --input-file ./input.json
|
||||
```
|
||||
|
||||
## 环境变量
|
||||
|
||||
CLI工具支持以下环境变量:
|
||||
|
||||
```bash
|
||||
export ALGORITHM_SHOWCASE_API_KEY="your_api_key" # API密钥
|
||||
export ALGORITHM_SHOWCASE_BASE_URL="http://localhost:8000" # API基础URL
|
||||
export ALGORITHM_SHOWCASE_TIMEOUT="30" # 请求超时时间(秒)
|
||||
export ALGORITHM_SHOWCASE_RETRY_COUNT="3" # 重试次数
|
||||
export ALGORITHM_SHOWCASE_OUTPUT_FORMAT="table" # 默认输出格式
|
||||
export ALGORITHM_SHOWCASE_DEBUG="true" # 启用调试模式
|
||||
```
|
||||
|
||||
这些示例展示了CLI工具的各种用法,从基本操作到高级自动化脚本。CLI工具旨在为开发者和运维人员提供一种便捷的方式来与智能算法展示平台进行交互。
|
||||
Reference in New Issue
Block a user