Skip to content

Docs

Get started with Cloudsome's OpenAI-compatible endpoints.

Quick Start

1. Create an account and generate an API key from the dashboard.
2. Make sure the current space has sufficient balance; top up if needed.
3. Install the OpenAI SDK for your language.
4. Get an available model ID from the Models page or GET /v1/models, then point the base URL to Cloudsome and make requests with that model ID.

Python
Python
from openai import OpenAI

client = OpenAI(
    base_url="https://api.cloudsome.ai/v1",
    api_key="sk_live_...",
)

response = client.chat.completions.create(
    model="YOUR_MODEL_ID",
    messages=[{"role": "user", "content": "Hello!"}],
    stream=True,
)

for chunk in response:
    print(chunk.choices[0].delta.content, end="")
Node.js
JavaScript
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.cloudsome.ai/v1",
  apiKey: "sk_live_...",
});

const response = await client.chat.completions.create({
  model: "YOUR_MODEL_ID",
  messages: [{ role: "user", content: "Hello!" }],
});

console.log(response.choices[0].message.content);
cURL
Bash
curl https://api.cloudsome.ai/v1/chat/completions \
  -H "Authorization: Bearer sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "model": "YOUR_MODEL_ID",
    "messages": [{"role": "user", "content": "Hello!"}]
  }'
Image Generation

Use your API key to call POST /v1/images/generations. Replace model with the image model ID shown on the Models page.

Bash
curl https://api.cloudsome.ai/v1/images/generations \
  -H "Authorization: Bearer sk_live_your_key_here" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "YOUR_IMAGE_MODEL_ID",
    "prompt": "A futuristic city floating above a sea of clouds",
    "n": 1,
    "resolution": "1080P",
    "ratio": "1:1",
    "response_format": "url"
  }'

Common parameters: model and prompt are required; n controls the number of images; resolution and ratio control the output dimensions; response_format selects url or b64_json output.

You may also send additional parameters supported by the selected model's upstream API. Parameter names, values, and limits vary by model; refer to the original documentation from that model's upstream provider.


Video quickstart

Create a task → check its status → get the video URL. Replace the API key and confirm access to the example model and videos scope to generate a 5-second, 720p video. No media upload or separate estimate request is needed.

Run pip install requests, then copy and run this Python example to poll automatically and print the video URL.

Python
import time
import requests

BASE = "https://api.cloudsome.ai/v1"
HEADERS = {"Authorization": "Bearer sk_live_your_key_here"}

response = requests.post(f"{BASE}/videos", headers=HEADERS, json={
    "model": "dreamina-seedance-2.5",
    "prompt": "A golden retriever running on the beach at sunset",
    "duration": 5,
    "resolution": "720p",
}, timeout=60)
response.raise_for_status()
task_id = response.json()["tasks"][0]["id"]
print("Task ID:", task_id)

for _ in range(120):
    response = requests.get(f"{BASE}/videos/{task_id}", headers=HEADERS, timeout=30)
    response.raise_for_status()
    task = response.json()
    if task["status"] == "completed":
        url = task.get("download_url") or task.get("url")
        if not url:
            raise RuntimeError(f"Video URL unavailable; query task {task_id} again.")
        print(url)
        break
    if task["status"] in ("failed", "cancelled", "expired"):
        raise RuntimeError(task.get("error") or task["status"])
    time.sleep(5)
else:
    raise TimeoutError(f"Keep querying task {task_id}; do not create it again.")

On success, open download_url or url to download; failures are explained in error. Links expire after 15 minutes; query the task again for a fresh link. Save the task ID. If the script reaches its polling limit or a query is interrupted, keep querying the original task instead of creating another.

Task stage distinguishes waiting_submission, submitting, upstream_queued, generating, saving, completed, failed and verification_pending. status and billing fields remain compatible. request_id identifies the request; created_at and completed_at are platform timestamps, not model computation or browser first-frame times. Poll every 5 seconds while processing or settlement is pending, and stop after completion and settlement.

A saving task may return save_retrying=true; keep querying the same task. Only a failed task with retryable=true can be regenerated with a new idempotency key and n=1, and it will be charged as a new request. error.category distinguishes input_review, output_review and copyright; the original upstream code is available in error.provider_code. Queue capacity and rate limits return 429; retry later. Unknown submissions and incomplete usage require verification, never automatic regeneration.

IDE & Tool Integration

Cloudsome is compatible with popular AI coding tools. Here's how to configure Claude Code, Codex, OpenCode, and CC Switch.

Set environment variables in your terminal to use Cloudsome as the Claude Code backend. You can also persist settings in ~/.claude/settings.json.

macOS / Linux
Windows
Terminal environment variables
Bash
export ANTHROPIC_BASE_URL="https://api.cloudsome.ai"
export ANTHROPIC_AUTH_TOKEN="sk_live_your_key_here"
export CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1
Config file (recommended) — ~/.claude/settings.json
JavaScript
{
  "env": {
    "ANTHROPIC_BASE_URL": "https://api.cloudsome.ai",
    "ANTHROPIC_AUTH_TOKEN": "sk_live_your_key_here",
    "ANTHROPIC_DEFAULT_HAIKU_MODEL": "claude-haiku-4-5-20251001",
    "ANTHROPIC_DEFAULT_OPUS_MODEL": "claude-opus-4-6",
    "ANTHROPIC_DEFAULT_SONNET_MODEL": "claude-sonnet-4-6",
    "ANTHROPIC_MODEL": "claude-opus-4-6",
    "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1",
    "CLAUDE_CODE_ATTRIBUTION_HEADER": "0"
  }
}

After setting CLOUDSOME_API_KEY, configure Cloudsome as a custom provider in ~/.codex/config.toml. The default model is GPT-5.6 Sol with high reasoning effort, and requests use the Responses API.

macOS / Linux
Windows
Terminal environment variable
Bash
export CLOUDSOME_API_KEY="sk_live_your_key_here"
Config file (recommended) — ~/.codex/config.toml
TOML
model = "gpt-5.6-sol"
model_reasoning_effort = "high"
model_provider = "cloudsome"

[model_providers.cloudsome]
name = "Cloudsome Production"
base_url = "https://api.cloudsome.ai/v1"
env_key = "CLOUDSOME_API_KEY"
wire_api = "responses"

Create an opencode.json config file in your project root to use Cloudsome as the provider.

JavaScript
{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "cloudsome": {
      "models": {
        "claude-haiku-4-5-20251001": {
          "name": "Claude Haiku 4.5"
        },
        "claude-opus-4-6": {
          "name": "Claude Opus 4.6"
        },
        "claude-sonnet-4-6": {
          "name": "Claude Sonnet 4.6"
        }
      },
      "npm": "@ai-sdk/openai-compatible",
      "options": {
        "apiKey": "sk_live_your_key_here",
        "baseURL": "https://api.cloudsome.ai/v1",
        "setCacheKey": true
      }
    }
  }
}

CC Switch

CC Switch is a multi-provider switcher for Claude Code. After installation, import Cloudsome config with a single click via deep link.

Install CC Switch

Endpoints
POST

/v1/chat/completions

Chat completions (streaming supported)
POST

/v1/embeddings

Text embeddings
POST

/v1/rerank

Document reranking
POST

/v1/images/generations

Image generation
POST

/v1/responses

Responses API
GET

/v1/models

List available models
GET

/v1/usage

Usage and spend
POST

/v1/video-assets

Upload reference media
POST

/v1/videos/estimate

Estimate cost
POST

/v1/videos

Create videos
GET

/v1/video-batches/:id

Query batch status
GET

/v1/videos/:id

Query an individual video task
GET

/v1/videos/:id/content

Retrieve and download the video
Usage and spend

GET /v1/usage authenticates with Authorization: Bearer <API Key> or x-api-key; no login JWT or user_id parameter is needed. The backend derives user and project identity from the key and aggregates only that key. A shared organization key returns combined usage across callers, not per-member or organization-wide totals. The response user_id identifies the user associated with the key.

Required start and end use YYYY-MM-DD, inclusive in Beijing time (UTC+8), up to 366 calendar days. Missing, invalid or reversed dates return 400; an invalid or expired key returns 401; IP restrictions or incomplete authenticated identity return 403.

Bash
curl --get 'https://api.cloudsome.ai/v1/usage' \
  -H "Authorization: Bearer $CLOUDSOME_API_KEY" \
  --data-urlencode 'start=2026-10-01' \
  --data-urlencode 'end=2026-10-31'
JSON
{
  "user_id": "user-example",
  "api_key_id": "key-example",
  "start": "2026-10-01",
  "end": "2026-10-31",
  "timezone": "Asia/Shanghai",
  "currency": "USD",
  "summary": {
    "requests": 12,
    "prompt_tokens": 8000,
    "completion_tokens": 2000,
    "total_tokens": 10000,
    "cache_creation_input_tokens": 1000,
    "cache_read_input_tokens": 3000,
    "price_micros": 1234567,
    "unsettled_requests": 0
  }
}

requests counts billing-visible usage records, excluding adjustments and empty attempt logs; it is not all HTTP attempts. Records need nonzero tokens, cache counters or spend, or a settled image billing snapshot. prompt_tokens, completion_tokens and total_tokens are recorded input, output and total tokens. cache_creation_input_tokens and cache_read_input_tokens are recorded cache counters; do not add them to total tokens again.

price_micros is net settled USD spend: divide by 1,000,000 for dollars. It includes refunds and adjustments, can be negative, and excludes provider costs. Facts are counted by creation date; adjustments use their own creation date. Tokenless image/video requests may still incur spend. Empty ranges return zeros.

unsettled_requests counts persisted but unconfirmed usage records excluded from other totals. Async writes and later settlement can change results; zero does not guarantee that every call has arrived. Each Relay process allows an average of one query per key every 5 seconds, burst 5. Back off after 429; retry 500/503 later. Queries do not incur charges.

Authentication

All API requests require a Bearer token in the Authorization header. Generate API keys from your dashboard. Keys start with sk_live_.

Bash
curl https://api.cloudsome.ai/v1/chat/completions \
  -H "Authorization: Bearer sk_live_your_key_here"
Security policies

Security policies define reusable usage and access policies for API keys and organization members. Use them to keep spend limits, model access, and provider access consistent without editing every key one by one.

Budget limits

Set a spend limit with a daily, weekly, or monthly reset period.

Model and provider access

Choose which models and providers covered requests can use.

Flexible binding

Bind to API keys in a personal space, or to API keys or members in an organization. You can also save an unbound policy.
Configure a security policy
1

Open Dashboard > Security policies.

2

Create a security policy, name it, and choose whether it is active.

3

Configure the optional budget, allowed models, and allowed providers.

4

Select API keys or organization members to bind, or leave it unbound for later use.

How budgets are counted
API key binding: the budget is tracked separately for each bound key.
Member binding: the budget is shared by all keys owned by that member.
A direct API key budget can still apply. Requests must pass both the key budget and the security policy budget.
Request behavior
Personal workspaces can bind security policies to API keys.
Organization spaces can bind security policies to API keys or members.
IP Allowlist stays on each API key. Platform traffic safeguards are automatic and are not user-configurable.
Model or provider denials return an HTTP 403 policy error. Exhausted budgets and platform protection return HTTP 429.
Streaming

All chat completion endpoints support streaming via stream: true. Tokens are delivered as server-sent events (SSE) in real time.

Python
response = client.chat.completions.create(
    model="YOUR_MODEL_ID",
    messages=[{"role": "user", "content": "Hello!"}],
    stream=True,
)

for chunk in response:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="")
Streaming Billing Rules

If the upstream errors before any data is streamed, you are fully refunded.

If you disconnect after streaming begins, billing uses the actual usage generated when available. If exact usage is unavailable, it is estimated from the generated content.

If the upstream fails mid-stream, billing uses the actual usage generated when available. If exact usage is unavailable, it is estimated from the partial response received.


Usage Protection

Cloudsome applies platform stability safeguards by default. User-configured spend limits are managed through Security policies or direct API key budgets. When a request exceeds a safeguard or budget, the API returns HTTP 429.

Platform stability

Default traffic safeguards

Burst protection

Automatic overload protection

Budget guardrails

Spend caps by day, week, or month

Error Codes

Common platform error codes for OpenAI-compatible endpoints are listed below. Upstream providers may return additional codes, so clients should also handle unknown codes. The Anthropic Messages endpoint returns errors in Anthropic-compatible format.

Bash
{
  "error": {
    "message": "Insufficient balance",
    "type": "invalid_request_error",
    "code": "personal_balance_insufficient"
  }
}
CodeCategoryDescription

invalid_api_key

Request

The API key is missing or invalid

invalid_json

Request

Request body is not valid JSON

invalid_request

Request

Request parameter or field validation failed

personal_balance_insufficient

Billing

Personal account balance is insufficient; top up before retrying

guardrail_model_not_allowed

Security policy

The requested model is not allowed by the current policy

guardrail_budget_exceeded

Security policy

The security policy budget limit has been exceeded

rate_limit_exceeded

Rate limit

Rate or concurrency limit exceeded

route_unavailable

Routing

No routing target is currently available

no_channel

Routing

No available channel matches the current request

upstream_error

Upstream

The upstream request failed; retry later

One API for the world’s leading AI models.

© 2026 Cloudsome. All rights reserved.