퀵스타트
십여 줄의 코드로 Llama 3.1 8B 배포.
SDK가 작업 생성, EIP-2612 permit, createJob 트랜잭션을 처리한 뒤 공급자가 엔드포인트를 띄울 때까지 기다립니다.
npm install @mzgrid/sdk viem— SDK와 viem 설치Base의 MZG— 가격 × 최대 실행 시간만큼의 MZG 보유Base의 ETH— 예치 트랜잭션 가스비용 소량의 ETH
deploy.ts
import { CURRENT_TERMS_VERSION, MZGridClient } from "@mzgrid/sdk";
import { createWalletClient, custom } from "viem";
import { base } from "viem/chains";
const wallet = createWalletClient({ chain: base, transport: custom(window.ethereum!) });
// Wallet sign-in requires the Terms of Service version the user has explicitly accepted
const mzg = new MZGridClient({ apiUrl: "https://api.mzgrid.io", walletClient: wallet, termsVersion: CURRENT_TERMS_VERSION });
// 1. Let the scheduler pick the best RTX 4090 by price, reliability and proximity
const created = await mzg.jobs.create({
sku: "rtx4090",
autoSelect: true,
template: "llama-3.1-8b",
maxDurationHours: 4,
});
// 2. Deposit into escrow (EIP-2612 permit + createJob) — deposit = price × 4 h
await mzg.jobs.fund(created, wallet);
// 3. Wait for the OpenAI-compatible endpoint
const { endpointUrl } = await mzg.jobs.waitForEndpoint(created.job.id);
console.log("Ready:", endpointUrl);shell
# Sign in once with your wallet, then create an API key in the dashboard
export MZG_API_KEY="mzg_live_..."
# Browse live offers: cheapest H100 SXM with reliability >= 95
curl -s "https://api.mzgrid.io/v1/market/offers?sku=h100-sxm&minReliability=95&sort=price&limit=5"
# Create a job — returns the escrow parameters to fund on Base
curl -s -X POST "https://api.mzgrid.io/v1/jobs" \
-H "Authorization: Bearer $MZG_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"sku": "h100-sxm",
"autoSelect": true,
"template": "llama-3.3-70b",
"maxDurationHours": 6,
"config": {}
}'
# After funding, report the transaction so the job is dispatched
curl -s -X POST "https://api.mzgrid.io/v1/jobs/$JOB_ID/funded" \
-H "Authorization: Bearer $MZG_API_KEY" \
-H "Content-Type: application/json" \
-d '{"txHash": "0x..."}'poll_job.py
import os, time, requests
API = "https://api.mzgrid.io/v1"
H = {"Authorization": f"Bearer {os.environ['MZG_API_KEY']}"}
# Live GPU catalogue with availability and prices in MZG
for g in requests.get(f"{API}/catalog/gpus").json():
print(f"{g['name']:<24} {g['availableGpus']:>5} free from {g['lowestPrice']} MZG/h")
# Poll a job until its endpoint is ready
job_id = os.environ["JOB_ID"]
while True:
job = requests.get(f"{API}/jobs/{job_id}", headers=H).json()
if job["status"] == "running":
print("Endpoint:", job["endpointUrl"])
break
time.sleep(3)OpenAI 호환
기존 클라이언트를 엔드포인트로 연결하세요.
추론 템플릿은 vLLM을 실행하며 /v1/chat/completions, /v1/completions, /v1/embeddings를 제공합니다. base URL만 바꾸면 LangChain, LlamaIndex, OpenAI SDK가 그대로 작동합니다.
chat.py
from openai import OpenAI
# endpointUrl from GET /v1/jobs/:id once status == "running"
client = OpenAI(base_url=f"{endpoint_url}/v1", api_key=os.environ["VLLM_API_KEY"])
resp = client.chat.completions.create(
model="meta-llama/Llama-3.1-8B-Instruct",
messages=[{"role": "user", "content": "Summarise how MZGrid escrow works in two sentences."}],
max_tokens=200,
)
print(resp.choices[0].message.content)stream.ts
import OpenAI from "openai";
const client = new OpenAI({ baseURL: `${endpointUrl}/v1`, apiKey: process.env.VLLM_API_KEY });
const stream = await client.chat.completions.create({
model: "meta-llama/Llama-3.1-8B-Instruct",
messages: [{ role: "user", content: "Write a haiku about idle GPUs." }],
stream: true,
});
for await (const chunk of stream) process.stdout.write(chunk.choices[0]?.delta?.content ?? "");API 레퍼런스
엔드포인트 한눈에 보기.
Base URL https://api.mzgrid.io/v1. Authorization: Bearer <token | key>로 인증합니다.
공개
- GET
/v1/health서비스 상태, 체인 ID, 인덱싱된 블록 - GET
/v1/catalog/gpus실시간 가용성과 가격이 포함된 GPU 카탈로그 - GET
/v1/catalog/templates워크로드 템플릿 및 권장 GPU - GET
/v1/market/offers실시간 오퍼 — sku, 리전, VRAM, 신뢰도로 필터링 - GET
/v1/market/offers/:id가격 이력과 최근 작업이 포함된 오퍼 상세 - GET
/v1/network/stats네트워크 누적 수치 및 24시간 수치 - GET
/v1/network/timeseriesgpuHours, jobs, providers, mzgSettled 등의 일별 시계열 - GET
/v1/network/regions · /sku-mix · /leaderboard · /activity지역 분포, GPU 구성, 상위 공급자, 실시간 피드
인증 및 키
- POST
/v1/auth/nonce지갑 주소용 로그인 메시지 받기 - POST
/v1/auth/verifyEIP-191 서명을 세션 토큰으로 교환 - POST
/v1/keysAPI 키 생성 (mzg_live_…) - GET · DELETE
/v1/keys · /v1/keys/:idAPI 키 조회 또는 폐기
작업 및 계정
- POST
/v1/jobs오퍼 지정 또는 autoSelect로 작업 생성, 에스크로 파라미터 반환 - POST
/v1/jobs/:id/funded예치 트랜잭션 해시 제출, 코디네이터가 JobFunded 확인 - GET
/v1/jobs · /v1/jobs/:id작업 목록 조회 또는 상태, 엔드포인트, 트랜잭션이 포함된 단일 작업 조회 - GET
/v1/jobs/:id/logs특정 타임스탬프 이후의 컨테이너 로그 - POST
/v1/jobs/:id/stop조기 중지 — 사용한 시간(초)을 정산하고 나머지 환불 - GET
/v1/accountMZG 잔액, 에스크로 보관액, 30일 지출액
Base의 스마트 컨트랙트
MZGToken, MZGridEscrow, ProviderRegistry는 Basescan에서 검증되었습니다. 모든 함수, 이벤트, 상수는 컨트랙트 레퍼런스에서 확인하세요.