빠른 통합
30개 이상의 주요 AI 서비스 제공업체에 원클릭 연결 코드 변경 없는 마이그레이션 · 지능형 라우팅 · 비용 최적화핵심 개념
EvoLink은 비동기 작업 아키텍처를 채택하여 모든 AI 서비스를 작업으로 처리합니다:작업 제출
요청을 보내면 즉시 작업 ID를 받습니다
실시간 모니터링
진행 상황을 조회하고 상태 업데이트를 받습니다
결과 받기
작업 완료 후 최종 결과를 가져옵니다
사전 준비
API 키 발급
계정 등록
EvoLink 콘솔에 방문하여 등록을 완료하세요
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": "A cute cat running on the grass at sunset with warm lighting"
}'
복사
{
"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 Image 이미지 생성
response = requests.post(
"https://api.evolink.ai/v1/images/generations",
headers={"Authorization": "Bearer YOUR_API_KEY"},
json={
"model": "gpt-4o-image",
"prompt": "A beautiful sunset over the ocean with vibrant colors",
"size": "1024x1024",
"n": 1
}
)
task = response.json()
print(f"Task ID: {task['id']}")
print(f"Estimated time: {task['task_info']['estimated_time']} seconds")
복사
# Seedream 4.0 이미지 생성
response = requests.post(
"https://api.evolink.ai/v1/images/generations",
headers={"Authorization": "Bearer YOUR_API_KEY"},
json={
"model": "doubao-seedream-4.0",
"prompt": "Futuristic city with neon lights at night"
}
)
task = response.json()
print(f"Task created: {task['created']}")
print(f"Estimated cost: ${task['usage']['estimated_cost']}")
🎬 동영상 생성
복사
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": "A cat chasing butterflies in the garden, slow motion",
"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] # results 배열의 동영상 URL
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
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="A modern intelligent office building"
)
result = client.wait_for_completion(task['id'])
print(f"Image 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;
} 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',
'An abstract art painting with rich colors'
);
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": "Test image"}
)
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 = [
"Modern office design",
"Natural landscape painting",
"Abstract artwork",
"Tech-style UI interface"
]
task_ids = asyncio.run(batch_generate_images(prompts))
print(f"{len(task_ids)}개 작업 생성됨")
복사
from concurrent.futures import ThreadPoolExecutor
import queue
import threading
class TaskManager:
def __init__(self, api_key, max_workers=5):
self.api_key = api_key
self.headers = {"Authorization": f"Bearer {api_key}"}
self.task_queue = queue.Queue()
self.executor = ThreadPoolExecutor(max_workers=max_workers)
self.running = True
def submit_task(self, model, prompt, **kwargs):
"""작업을 큐에 제출"""
task_data = {"model": model, "prompt": prompt, **kwargs}
future = self.executor.submit(self._process_task, task_data)
return future
def _process_task(self, task_data):
"""단일 작업 처리"""
# 작업 생성
response = requests.post(
"https://api.evolink.ai/v1/images/generations",
headers=self.headers,
json=task_data
)
task = response.json()
# 완료 대기
return self._wait_for_completion(task['id'])
def _wait_for_completion(self, task_id):
"""작업 완료 대기"""
while True:
response = requests.get(
f"https://api.evolink.ai/v1/tasks/{task_id}",
headers=self.headers
)
task = response.json()
if task['status'] == 'completed':
return task
elif task['status'] == 'failed':
raise Exception(f"작업 실패: {task.get('error')}")
time.sleep(5)
# 사용 예시
manager = TaskManager("YOUR_API_KEY")
futures = []
for i in range(10):
future = manager.submit_task(
model="gpt-4o-image",
prompt=f"Design {i+1}"
)
futures.append(future)
# 모든 결과 가져오기
for i, future in enumerate(futures):
try:
result = future.result(timeout=300)
print(f"작업 {i+1} 완료: {result['results'][0]}")
except Exception as e:
print(f"작업 {i+1} 실패: {e}")
모니터링 및 분석
사용량 모니터링
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}초 | 상태:{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", "Test prompt")
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"Task ID: {task.get('id', 'unknown')}")
모범 사례 요약
개발 권장 사항
- 항상 오류 처리를 구현하세요
- 비동기 프로그래밍으로 효율성을 높이세요
- 합리적인 타임아웃 값을 설정하세요
- 상세한 호출 정보를 로깅하세요
성능 최적화
- 일괄 처리로 네트워크 오버헤드를 줄이세요
- 작업 풀로 동시성을 관리하세요
- API 할당량 사용량을 모니터링하세요
- 자주 사용하는 결과를 캐시하세요
보안 고려 사항
- API 키를 안전하게 저장하세요
- 환경 변수를 사용하여 설정하세요
- 정기적으로 액세스 키를 교체하세요
- 비정상적인 호출 동작을 모니터링하세요
비용 관리
- 합리적인 예산 한도를 설정하세요
- 적절한 모델을 선택하세요
- 프롬프트 길이를 최적화하세요
- 사용량 추이를 모니터링하세요