详细的代码示例、操作步骤和最佳实践,帮助您快速掌握AIP边缘算力生态系统的使用
访问官网并注册账户
1. 访问 http://www.pidbai.com
2. 点击右上角"注册"按钮
3. 填写邮箱和密码
4. 完成注册
根据您的操作系统下载对应客户端
Windows: http://www.pidbai.com/downloads/AIP-Edge-Client-Setup-1.0.0.exe
macOS: http://www.pidbai.com/downloads/AIP-Edge-Client-macOS-v1.0.0.tar.gz
Linux: http://www.pidbai.com/downloads/AIP-Edge-Client-Linux-v1.0.0.tar.gz
安装完成后启动客户端并登录
提示:客户端会自动检测硬件(CPU、内存、GPU),并自动注册节点到系统。
客户端会自动拉取和执行任务
自动功能:
// 登录获取Token
async function login(email, password) {
const response = await fetch('http://www.pidbai.com/api/v1/auth/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ email, password })
});
const data = await response.json();
if (data.success) {
localStorage.setItem('token', data.token);
return data.token;
}
throw new Error(data.error || '登录失败');
}
// 使用示例
try {
const token = await login('your@email.com', 'password123');
console.log('登录成功,Token:', token);
} catch (error) {
console.error('登录失败:', error.message);
}
// 创建任务
async function createTask(token, taskData) {
const response = await fetch('http://www.pidbai.com/api/v1/enterprise/tasks', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: '图像处理任务',
description: '处理100张图片',
task_type: 'process_image',
input_data_url: 'https://example.com/images.zip',
budget: 1000,
reward: 10
})
});
return await response.json();
}
// 使用示例
const task = await createTask(token, {
title: '图像处理任务',
task_type: 'process_image',
input_data_url: 'https://example.com/images.zip',
reward: 10
});
console.log('任务创建成功:', task);
// 查询任务列表
async function getTasks(token, status = 'all', page = 1) {
const response = await fetch(
`http://www.pidbai.com/api/v1/enterprise/tasks?status=${status}&page=${page}`,
{
headers: {
'Authorization': `Bearer ${token}`
}
}
);
return await response.json();
}
// 使用示例
const tasks = await getTasks(token, 'completed', 1);
console.log('已完成的任务:', tasks.data);
import requests
BASE_URL = "http://www.pidbai.com/api/v1"
def login(email, password):
"""登录获取Token"""
response = requests.post(
f"{BASE_URL}/auth/login",
json={"email": email, "password": password}
)
data = response.json()
if data.get("success"):
return data["token"]
raise Exception(data.get("error", "登录失败"))
# 使用示例
try:
token = login("your@email.com", "password123")
print(f"登录成功,Token: {token}")
except Exception as e:
print(f"登录失败: {e}")
def create_task(token, task_data):
"""创建任务"""
response = requests.post(
f"{BASE_URL}/enterprise/tasks",
headers={"Authorization": f"Bearer {token}"},
json=task_data
)
return response.json()
# 使用示例
task_data = {
"title": "图像处理任务",
"description": "处理100张图片",
"task_type": "process_image",
"input_data_url": "https://example.com/images.zip",
"budget": 1000,
"reward": 10
}
task = create_task(token, task_data)
print(f"任务创建成功: {task}")
def get_task_progress(token, task_id):
"""查询任务进度"""
response = requests.get(
f"{BASE_URL}/compute/tasks/{task_id}/progress",
headers={"Authorization": f"Bearer {token}"}
)
return response.json()
# 使用示例
progress = get_task_progress(token, "task-id-123")
print(f"任务进度: {progress.get('progress', 0)}%")
| 任务类型 | 说明 | 示例 |
|---|---|---|
process_image |
图像处理 | 调整大小、滤镜、增强 |
analyze_data |
数据分析 | 统计分析、数据挖掘 |
ai_inference |
AI推理 | 模型推理、预测 |
encode_video |
视频编码 | 视频转码、压缩 |
// 发布图像处理任务
const task = await createTask(token, {
title: '批量图像处理',
description: '处理1000张图片,调整大小并应用滤镜',
task_type: 'process_image',
input_data_url: 'https://example.com/images.zip',
budget: 5000, // 总预算(AIP)
reward: 5, // 单个任务奖励(AIP)
hardware_requirements: 'GPU 8GB+', // 可选:硬件要求
deadline: '2025-12-31T23:59:59Z' // 可选:截止时间
});
console.log('任务ID:', task.data.id);
// 批量创建任务
async function createBatchTasks(token, tasks) {
const response = await fetch('http://www.pidbai.com/api/v1/tasks/batch', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
tasks: tasks,
total_budget: 10000
})
});
return await response.json();
}
// 准备任务列表
const tasks = [
{
title: '任务1',
task_type: 'process_image',
input_data_url: 'https://example.com/image1.jpg',
reward: 10
},
{
title: '任务2',
task_type: 'analyze_data',
input_data_url: 'https://example.com/data2.csv',
reward: 15
}
// ... 更多任务
];
const result = await createBatchTasks(token, tasks);
console.log('批量任务创建成功:', result);
import requests
import platform
import psutil
def register_node(username, token):
"""注册节点到系统"""
# 获取系统信息
cpu_cores = psutil.cpu_count()
memory_total = psutil.virtual_memory().total
platform_name = platform.system().lower()
node_data = {
"id": f"node-{platform.node()}",
"username": username,
"node_name": f"My Node - {platform.node()}",
"platform": platform_name,
"cpuCores": cpu_cores,
"memoryTotal": memory_total,
"computePower": cpu_cores * 1000 + memory_total // 1024 // 1024 // 1024 * 100
}
response = requests.post(
f"{BASE_URL}/compute/clients/register",
headers={"Authorization": f"Bearer {token}"},
json=node_data
)
return response.json()
# 使用示例
node_info = register_node("username", token)
print(f"节点注册成功: {node_info}")
import time
import threading
def send_heartbeat(node_id, token, interval=30):
"""定期发送心跳"""
while True:
try:
memory = psutil.virtual_memory()
cpu_percent = psutil.cpu_percent(interval=1)
heartbeat_data = {
"nodeId": node_id,
"status": "online",
"current_load": cpu_percent,
"memory_free": memory.available,
"compute_power": psutil.cpu_count() * 1000
}
response = requests.post(
f"{BASE_URL}/compute/clients/heartbeat",
headers={"Authorization": f"Bearer {token}"},
json=heartbeat_data
)
print(f"心跳发送成功: {response.json()}")
except Exception as e:
print(f"心跳发送失败: {e}")
time.sleep(interval)
# 在后台线程中运行
heartbeat_thread = threading.Thread(
target=send_heartbeat,
args=("node-id", token),
daemon=True
)
heartbeat_thread.start()
def pull_tasks(node_id, max_tasks=10):
"""拉取任务"""
response = requests.get(
f"{BASE_URL}/compute/tasks/pull",
params={"nodeId": node_id, "maxTasks": max_tasks},
headers={"X-Node-ID": node_id}
)
return response.json()
# 使用示例
tasks = pull_tasks("node-id", max_tasks=5)
print(f"拉取到 {len(tasks.get('data', []))} 个任务")
def submit_task_result(task_id, node_id, result, token):
"""提交任务结果"""
result_data = {
"taskId": task_id,
"nodeId": node_id,
"result": {
"status": "success",
"data": result,
"metrics": {
"execution_time": 120,
"cpu_usage": 50,
"memory_usage": 60
}
}
}
response = requests.post(
f"{BASE_URL}/compute/tasks/result",
headers={"Authorization": f"Bearer {token}"},
json=result_data
)
return response.json()
# 使用示例
result = submit_task_result(
"task-id-123",
"node-id",
{"processed": 100, "success": 95},
token
)
print(f"结果提交成功: {result}")
import json
from typing import List, Dict
def create_batch_tasks_from_file(token, file_path, total_budget):
"""从文件批量创建任务"""
# 读取任务列表
with open(file_path, 'r') as f:
tasks = json.load(f)
# 分批创建(每批最多100个)
batch_size = 100
results = []
for i in range(0, len(tasks), batch_size):
batch = tasks[i:i + batch_size]
response = requests.post(
f"{BASE_URL}/tasks/batch",
headers={"Authorization": f"Bearer {token}"},
json={
"tasks": batch,
"total_budget": total_budget * len(batch) / len(tasks)
}
)
result = response.json()
results.append(result)
print(f"批次 {i//batch_size + 1} 创建完成: {len(batch)} 个任务")
return results
# 任务文件示例 (tasks.json)
# [
# {
# "title": "任务1",
# "task_type": "process_image",
# "input_data_url": "https://example.com/image1.jpg",
# "reward": 10
# },
# ...
# ]
results = create_batch_tasks_from_file(token, "tasks.json", 10000)
import time
from collections import defaultdict
def monitor_batch_tasks(token, task_ids):
"""监控批量任务进度"""
status_count = defaultdict(int)
while True:
for task_id in task_ids:
response = requests.get(
f"{BASE_URL}/enterprise/tasks/{task_id}",
headers={"Authorization": f"Bearer {token}"}
)
task = response.json().get('data', {})
status = task.get('status', 'unknown')
status_count[status] += 1
print(f"任务状态统计: {dict(status_count)}")
# 如果所有任务都完成或失败,退出
if status_count.get('completed', 0) + status_count.get('failed', 0) == len(task_ids):
break
time.sleep(10) # 每10秒检查一次
return status_count
# 使用示例
task_ids = ["task-1", "task-2", "task-3"]
status_count = monitor_batch_tasks(token, task_ids)
// 查询用户收益
async function getEarnings(token) {
const response = await fetch('http://www.pidbai.com/api/v1/users/earnings', {
headers: {
'Authorization': `Bearer ${token}`
}
});
return await response.json();
}
// 使用示例
const earnings = await getEarnings(token);
console.log('总收益:', earnings.data.total);
console.log('今日收益:', earnings.data.today);
console.log('收益历史:', earnings.data.earnings);
// 查询钱包信息
async function getWalletInfo(token) {
const response = await fetch('http://www.pidbai.com/api/v1/blockchain/wallet/info', {
headers: {
'Authorization': `Bearer ${token}`
}
});
return await response.json();
}
// 使用示例
const wallet = await getWalletInfo(token);
console.log('钱包地址:', wallet.data.wallet.address);
console.log('AIP余额:', wallet.data.wallet.aip_balance);
console.log('TRX余额:', wallet.data.wallet.trx_balance);
// 查询交易记录
async function getTransactions(token, page = 1) {
const response = await fetch(
`http://www.pidbai.com/api/v1/blockchain/wallet/transactions?page=${page}`,
{
headers: {
'Authorization': `Bearer ${token}`
}
}
);
return await response.json();
}
// 使用示例
const transactions = await getTransactions(token, 1);
console.log('交易记录:', transactions.data);