跳转到主要内容

快速接入

一键连接30+主流AI服务商
零代码迁移 · 智能路由 · 成本优化

核心理念

EvoLink采用异步任务架构,所有AI服务以任务形式处理:

提交任务

发送请求,立即返回任务ID

实时监控

查询进度,获取状态更新

获取结果

任务完成后获取最终结果

准备工作

获取API密钥

1

注册账户

访问 EvoLink控制台 完成注册
2

创建密钥

进入API管理页面,点击”新建密钥”
3

保存密钥

复制生成的API密钥(格式:sk-evo-xxxxxxxxxx
API密钥具有完整账户权限,请妥善保管。如发现泄露,立即重置。

30秒快速体验

图像生成示例

# 提交图像生成任务
curl -X POST https://api.evolink.ai/v1/images/generations \\
  -H "Authorization: Bearer YOUR_API_KEY" \\
  -H "Content-Type: application/json" \\
  -d '{
    "model": "gpt-4o-image",
    "prompt": "一只在草地上奔跑的可爱猫咪,夕阳西下,温暖光线"
  }'
立即响应 - 任务已创建
{
  "created": 1757156493,
  "id": "task-unified-1757156493-imcg5zqt",
  "model": "gpt-4o-image",
  "object": "image.generation.task",
  "progress": 0,
  "status": "pending",
  "task_info": {
    "can_cancel": true,
    "estimated_time": 100
  },
  "type": "image",
  "usage": {
    "billing_rule": "per_call",
    "credits_reserved": 252,
    "estimated_cost": 0.252,
    "user_group": "default"
  }
}

查询任务状态

# 使用返回的任务ID查询状态
curl https://api.evolink.ai/v1/tasks/task-unified-1757156493-imcg5zqt \\
  -H "Authorization: Bearer YOUR_API_KEY"
任务完成后的响应
{
  "created": 1757156493,
  "id": "task-unified-1757156493-imcg5zqt",
  "model": "gpt-4o-image",
  "object": "image.generation.task",
  "progress": 100,
  "results": [
    "https://tempfile.aiquickdraw.com/s/generated_image_url.png"
  ],
  "status": "completed",
  "task_info": {
    "can_cancel": false
  },
  "type": "image"
}

多模态AI能力

🎨 图像生成

  • GPT-4O Image
  • Seedream 4.0
import requests

# GPT-4O 图像生成
response = requests.post(
    "https://api.evolink.ai/v1/images/generations",
    headers={"Authorization": "Bearer YOUR_API_KEY"},
    json={
        "model": "gpt-4o-image",
        "prompt": "海面上绚丽多彩的美丽日落",
        "size": "1024x1024",
        "n": 1
    }
)

task = response.json()
print(f"任务ID: {task['id']}")
print(f"预估时间: {task['task_info']['estimated_time']}秒")

🎬 视频生成

import requests
import time

# Veo3-Fast 视频生成
def generate_video():
    # 提交视频生成任务
    response = requests.post(
        "https://api.evolink.ai/v1/videos/generations",
        headers={"Authorization": "Bearer YOUR_API_KEY"},
        json={
            "model": "veo3-fast",
            "prompt": "一只猫在花园里追蝴蝶,慢镜头",
            "aspect_ratio": "16:9"
        }
    )
    
    task = response.json()
    task_id = task['id']
    
    print(f"视频任务已创建: {task_id}")
    print(f"预估完成时间: {task['task_info']['estimated_time']}秒")
    print(f"预估成本: ${task['usage']['estimated_cost']}")
    
    return task_id

# 监控任务进度
def monitor_task(task_id):
    while True:
        response = requests.get(
            f"https://api.evolink.ai/v1/tasks/{task_id}",
            headers={"Authorization": "Bearer YOUR_API_KEY"}
        )
        
        task = response.json()
        status = task['status']
        progress = task['progress']
        
        print(f"状态: {status}, 进度: {progress}%")
        
        if status == "completed":
            return task['results'][0]  # 视频URL在results数组中
        elif status == "failed":
            raise Exception(f"任务失败: {task.get('error')}")
        
        time.sleep(10)  # 每10秒查询一次

# 使用示例
task_id = generate_video()
video_url = monitor_task(task_id)
print(f"视频生成完成: {video_url}")

SDK 快速集成

Python SDK

import openai
import requests

class EvoLinkClient:
    def __init__(self, api_key):
        self.api_key = api_key
        self.base_url = "https://api.evolink.ai"
        self.headers = {"Authorization": f"Bearer {api_key}"}
    
    def create_image(self, model, prompt, **kwargs):
        """创建图像生成任务"""
        response = requests.post(
            f"{self.base_url}/v1/images/generations",
            headers=self.headers,
            json={"model": model, "prompt": prompt, **kwargs}
        )
        return response.json()
    
    def create_video(self, model, prompt, **kwargs):
        """创建视频生成任务"""
        response = requests.post(
            f"{self.base_url}/v1/videos/generations",
            headers=self.headers,
            json={"model": model, "prompt": prompt, **kwargs}
        )
        return response.json()
    
    def get_task(self, task_id):
        """获取任务状态"""
        response = requests.get(
            f"{self.base_url}/v1/tasks/{task_id}",
            headers=self.headers
        )
        return response.json()
    
    def wait_for_completion(self, task_id, timeout=300):
        """等待任务完成"""
        import time
        start_time = time.time()
        
        while time.time() - start_time < timeout:
            task = self.get_task(task_id)
            
            if task['status'] == 'completed':
                return task['result']
            elif task['status'] == 'failed':
                raise Exception(f"任务失败: {task.get('error')}")
            
            time.sleep(5)
        
        raise TimeoutError("任务执行超时")

# 使用示例
client = EvoLinkClient("YOUR_API_KEY")

# 生成图像
task = client.create_image(
    model="gpt-4o-image",
    prompt="一座现代化的智能办公大楼"
)

result = client.wait_for_completion(task['id'])
print(f"图像URL: {result['results'][0]}")

JavaScript/Node.js

class EvoLinkClient {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.baseURL = 'https://api.evolink.ai';
  }
  
  async createImage(model, prompt, options = {}) {
    const response = await fetch(`${this.baseURL}/v1/images/generations`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${this.apiKey}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ model, prompt, ...options })
    });
    
    return response.json();
  }
  
  async getTask(taskId) {
    const response = await fetch(`${this.baseURL}/v1/tasks/${taskId}`, {
      headers: { 'Authorization': `Bearer ${this.apiKey}` }
    });
    
    return response.json();
  }
  
  async waitForCompletion(taskId, timeout = 300000) {
    const startTime = Date.now();
    
    while (Date.now() - startTime < timeout) {
      const task = await this.getTask(taskId);
      
      if (task.status === 'completed') {
        return task.result;
      } else if (task.status === 'failed') {
        throw new Error(`任务失败: ${task.error}`);
      }
      
      await new Promise(resolve => setTimeout(resolve, 5000));
    }
    
    throw new Error('任务执行超时');
  }
}

// 使用示例
async function generateImage() {
  const client = new EvoLinkClient('YOUR_API_KEY');
  
  try {
    // 创建任务
    const task = await client.createImage(
      'doubao-seedream-4.0',
      '一幅抽象艺术画,色彩丰富'
    );
    
    console.log('任务已创建:', task.id);
    
    // 等待完成
    const result = await client.waitForCompletion(task.id);
    console.log('图像生成完成:', result.results[0]);
    
  } catch (error) {
    console.error('生成失败:', error.message);
  }
}

generateImage();

生产环境实践

错误处理策略

import requests
from typing import Optional
import time

class EvoLinkError(Exception):
    """EvoLink API异常基类"""
    pass

class RateLimitError(EvoLinkError):
    """频率限制异常"""
    pass

class QuotaExhaustedError(EvoLinkError):
    """配额耗尽异常"""
    pass

def handle_api_call(func, *args, **kwargs):
    """统一API调用错误处理"""
    max_retries = 3
    retry_delay = 1
    
    for attempt in range(max_retries):
        try:
            response = func(*args, **kwargs)
            
            if response.status_code == 200:
                return response.json()
            elif response.status_code == 429:
                # 频率限制,等待后重试
                wait_time = int(response.headers.get('Retry-After', retry_delay))
                print(f"触发频率限制,等待{wait_time}秒后重试...")
                time.sleep(wait_time)
                retry_delay *= 2
                continue
            elif response.status_code == 402:
                raise QuotaExhaustedError("账户余额不足,请充值")
            else:
                error_data = response.json()
                raise EvoLinkError(f"API调用失败: {error_data.get('error', {}).get('message')}")
                
        except requests.exceptions.RequestException as e:
            if attempt == max_retries - 1:
                raise EvoLinkError(f"网络请求失败: {str(e)}")
            time.sleep(retry_delay)
            retry_delay *= 2
    
    raise EvoLinkError("达到最大重试次数")

# 使用示例
try:
    result = handle_api_call(
        requests.post,
        "https://api.evolink.ai/v1/images/generations",
        headers={"Authorization": "Bearer YOUR_API_KEY"},
        json={"model": "gpt-4o-image", "prompt": "测试图像"}
    )
    print("任务创建成功:", result['id'])
except QuotaExhaustedError:
    print("请前往控制台充值: https://evolink.ai/dashboard/billing")
except EvoLinkError as e:
    print(f"API调用异常: {e}")

性能优化技巧

  • 批量处理
  • 任务池管理
import asyncio
import aiohttp

async def create_task_async(session, model, prompt):
    """异步创建任务"""
    async with session.post(
        "https://api.evolink.ai/v1/images/generations",
        json={"model": model, "prompt": prompt}
    ) as response:
        return await response.json()

async def batch_generate_images(prompts, model="gpt-4o-image"):
    """批量生成图像"""
    headers = {"Authorization": "Bearer YOUR_API_KEY"}
    
    async with aiohttp.ClientSession(headers=headers) as session:
        # 并发创建所有任务
        tasks = [
            create_task_async(session, model, prompt) 
            for prompt in prompts
        ]
        results = await asyncio.gather(*tasks)
        
        # 返回任务ID列表
        return [result['id'] for result in results]

# 使用示例
prompts = [
    "现代办公室设计",
    "自然风景画",
    "抽象艺术作品",
    "科技感UI界面"
]

task_ids = asyncio.run(batch_generate_images(prompts))
print(f"已创建{len(task_ids)}个任务")

监控与分析

使用情况监控

访问 EvoLink控制台 实时查看:

实时监控

  • API调用次数统计
  • 成功率和错误率
  • 响应时间分析
  • 并发请求监控

成本分析

  • 按模型的费用分布
  • 日/月使用趋势
  • 成本预测和预警
  • 配额使用情况

自定义监控

import logging
from datetime import datetime

class EvoLinkMonitor:
    def __init__(self):
        # 配置日志
        logging.basicConfig(
            level=logging.INFO,
            format='%(asctime)s - %(levelname)s - %(message)s',
            handlers=[
                logging.FileHandler('evolink_api.log'),
                logging.StreamHandler()
            ]
        )
        self.logger = logging.getLogger(__name__)
        
    def log_task_creation(self, task_id, model, cost):
        """记录任务创建"""
        self.logger.info(f"任务创建 | ID:{task_id} | 模型:{model} | 成本:${cost}")
        
    def log_task_completion(self, task_id, duration, status):
        """记录任务完成"""
        self.logger.info(f"任务完成 | ID:{task_id} | 耗时:{duration}s | 状态:{status}")
        
    def log_error(self, error, context=""):
        """记录错误"""
        self.logger.error(f"API错误 | {context} | {str(error)}")

# 使用示例
monitor = EvoLinkMonitor()

# 在API调用中使用
start_time = time.time()
try:
    task = client.create_image("gpt-4o-image", "测试提示")
    monitor.log_task_creation(
        task['id'], 
        task['model'], 
        task['usage']['estimated_cost']
    )
    
    result = client.wait_for_completion(task['id'])
    duration = time.time() - start_time
    monitor.log_task_completion(task['id'], int(duration), "completed")
    
except Exception as e:
    monitor.log_error(e, f"任务ID: {task.get('id', 'unknown')}")

最佳实践总结

开发建议

  • 始终进行错误处理
  • 使用异步编程提高效率
  • 合理设置超时时间
  • 记录详细的调用日志

性能优化

  • 批量处理减少网络开销
  • 使用任务池管理并发
  • 监控API配额使用情况
  • 缓存常用的生成结果

安全考虑

  • API密钥安全存储
  • 使用环境变量配置
  • 定期轮换访问密钥
  • 监控异常调用行为

成本控制

  • 设置合理的预算限制
  • 选择适合的模型
  • 优化提示词长度
  • 监控使用量趋势

准备就绪?

立即开始您的AI创造之旅需要帮助? 我们的技术团队随时为您提供专业支持