API · api.we2ai.com

API docsAPI 文档

One base URL and one key for Claude, GPT, Gemini and Grok — text, image and video. Use the official SDKs of each vendor; only the base URL and the key change. 一个 Base URL、一把 Key,调用 Claude、GPT、Gemini、Grok 的文本、图片和视频模型。直接用各家官方 SDK,只需要改 Base URL 和 Key。

Quick start快速开始

  1. Sign up and create an API key in the console. Pick the group that matches the models you want (see Groups & endpoints). 注册后在控制台创建 API Key,分组选你要用的模型所在的组(见分组与端点)。
  2. Point your SDK at https://api.we2ai.com (Anthropic / Gemini style) or https://api.we2ai.com/v1 (OpenAI style). 把 SDK 的 Base URL 指向 https://api.we2ai.com(Anthropic、Gemini 风格)或 https://api.we2ai.com/v1(OpenAI 风格)。
  3. Send a request. /v1/chat/completions works for every group, so it is the easiest first call: 发请求。/v1/chat/completions 对所有分组都可用,用它做第一次调用最省事:
curl https://api.we2ai.com/v1/chat/completions \
  -H "Authorization: Bearer sk-your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-6-luna",
    "messages": [{"role": "user", "content": "Say hi in 3 words"}]
  }'
Python · OpenAI SDK
from openai import OpenAI

client = OpenAI(api_key="sk-your-api-key", base_url="https://api.we2ai.com/v1")
resp = client.chat.completions.create(
    model="gpt-6-luna",
    messages=[{"role": "user", "content": "Say hi in 3 words"}],
)
print(resp.choices[0].message.content)
Model Replace model with any model your key's group can call. The list changes as we add models — GET /v1/models always returns the current one for your key (see Models & usage). model 换成你的 Key 所在分组可调用的任意模型。模型会持续更新,GET /v1/models 永远返回你这把 Key 当前可用的列表(见模型与用量)。

Authentication认证

Send your key in any one of these headers. Use whichever your SDK already sends. 在下面任意一个请求头里带上 Key,用你的 SDK 默认发送的那个即可。

HeaderTypical use常见用法
Authorization: Bearer sk-…OpenAI SDKs, curl, CodexOpenAI SDK、curl、Codex
x-api-key: sk-…Anthropic SDKsAnthropic SDK
x-goog-api-key: …Gemini / Google SDKsGemini / Google SDK
Key Keep keys out of public repos and front-end code. Set a quota and an expiry on keys you hand to others. 不要把 Key 放进公开仓库或前端代码。发给别人的 Key 请设置额度和过期时间。

Groups & endpoints分组与端点

Every key belongs to a group, and the group decides which models it can call. Base URL for all endpoints: https://api.we2ai.com. 每把 Key 属于一个分组,分组决定能调用哪些模型。所有端点的 Base URL 都是 https://api.we2ai.com。

Group分组Models模型Endpoints端点
ClaudeClaudePOST /v1/messages
POST /v1/chat/completions
OpenAIGPT, CodexPOST /v1/chat/completions
POST /v1/responses
Image-2GPT ImageGPT 图片模型POST /v1/images/generations
POST /v1/images/edits
GeminiGemini (text & image文本与图片)POST /v1beta/models/{model}:generateContent
POST /v1beta/models/{model}:streamGenerateContent
POST /v1/chat/completions
GrokGrok (text, image, video文本、图片、视频)POST /v1/chat/completions
POST /v1/responses
POST /v1/images/generations
POST /v1/videos

Calling a model your group does not serve returns an error (see Errors). To use several vendors, create one key per group. 调用你所在分组没有的模型会返回错误(见错误处理)。要同时用多家模型,就为每个分组各建一把 Key。

Streaming works on every text endpoint: set "stream": true (Gemini: use :streamGenerateContent). Responses are standard Server-Sent Events. 所有文本端点都支持流式:设置 "stream": true(Gemini 用 :streamGenerateContent),返回标准 Server-Sent Events。

Claude

The native Anthropic Messages API. Use the official Anthropic SDK with base_url="https://api.we2ai.com". 原生 Anthropic Messages API。使用官方 Anthropic SDK,base_url="https://api.we2ai.com"。

curl https://api.we2ai.com/v1/messages \
  -H "x-api-key: sk-your-api-key" \
  -H "anthropic-version: 2023-06-01" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "claude-sonnet-5-5",
    "max_tokens": 1024,
    "messages": [{"role": "user", "content": "Say hi in 3 words"}]
  }'
Python · Anthropic SDK
import anthropic

client = anthropic.Anthropic(api_key="sk-your-api-key", base_url="https://api.we2ai.com")
msg = client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Say hi in 3 words"}],
)
print(msg.content[0].text)
Node.js
import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic({ apiKey: "sk-your-api-key", baseURL: "https://api.we2ai.com" });
const msg = await client.messages.create({
  model: "claude-sonnet-5-5",
  max_tokens: 1024,
  messages: [{ role: "user", content: "Say hi in 3 words" }],
});
console.log(msg.content[0].text);

Images go in as image content blocks (base64), exactly as in Anthropic's API. 图片以 image 内容块(base64)传入,和 Anthropic 官方 API 一致。

OpenAI / GPT

OpenAI-compatible Chat Completions and Responses. Use the official OpenAI SDK with base_url="https://api.we2ai.com/v1". 兼容 OpenAI 的 Chat Completions 与 Responses。使用官方 OpenAI SDK,base_url="https://api.we2ai.com/v1"。

Chat Completions
curl https://api.we2ai.com/v1/chat/completions \
  -H "Authorization: Bearer sk-your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-6-luna",
    "stream": true,
    "messages": [
      {"role": "system", "content": "You are a helpful assistant."},
      {"role": "user", "content": "Write quicksort in Python."}
    ]
  }'
Responses API
curl https://api.we2ai.com/v1/responses \
  -H "Authorization: Bearer sk-your-api-key" \
  -H "Content-Type: application/json" \
  -d '{"model": "gpt-6-luna", "input": "Say hi in 3 words"}'

The Responses API is what Codex uses — see Claude Code & Codex. Codex 使用的就是 Responses API,配置见 Claude Code 与 Codex。

Gemini

The native Gemini API, compatible with Google's SDKs (x-goog-api-key). Prefer OpenAI style? /v1/chat/completions with a Gemini-group key works too. 原生 Gemini API,兼容 Google SDK(x-goog-api-key)。想用 OpenAI 风格?用 Gemini 分组的 Key 调 /v1/chat/completions 也可以。

curl "https://api.we2ai.com/v1beta/models/gemini-3.1-pro-preview:generateContent" \
  -H "x-goog-api-key: your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "system_instruction": {"parts": [{"text": "Answer briefly."}]},
    "contents": [{"role": "user", "parts": [{"text": "What is machine learning?"}]}],
    "generationConfig": {"maxOutputTokens": 1024}
  }'
Python
import requests

r = requests.post(
    "https://api.we2ai.com/v1beta/models/gemini-3.1-pro-preview:generateContent",
    headers={"x-goog-api-key": "your-api-key"},
    json={"contents": [{"parts": [{"text": "Say hi in 3 words"}]}]},
)
print(r.json()["candidates"][0]["content"]["parts"][0]["text"])

Image input uses inline_data parts (mime_type + base64 data). GET /v1beta/models lists the models your key can call. 图片输入使用 inline_data(mime_type + base64 的 data)。GET /v1beta/models 列出你这把 Key 可调用的模型。

Grok

Grok text models use the same OpenAI-style endpoints. Image and video are in the sections below. Grok 文本模型使用同样的 OpenAI 风格端点,图片和视频见下面两节。

curl https://api.we2ai.com/v1/chat/completions \
  -H "Authorization: Bearer sk-your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "grok-4.7",
    "messages": [{"role": "user", "content": "Say hi in 3 words"}]
  }'

Reasoning models also return their reasoning in reasoning_content. /v1/responses is supported as well. 推理模型会在 reasoning_content 里附带推理过程。同样支持 /v1/responses。

Image generation图片生成

OpenAI · GPT Image

Needs a key from an image-enabled group (e.g. Image-2). The response contains b64_json by default. 需要支持图片的分组的 Key(例如 Image-2)。默认返回 b64_json。

curl https://api.we2ai.com/v1/images/generations \
  -H "Authorization: Bearer sk-your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-image-2",
    "prompt": "A red apple on a white table, studio light",
    "n": 1,
    "size": "1024x1024"
  }'

Editing uses POST /v1/images/edits with multipart/form-data (image, optional mask, prompt), as in OpenAI's API. 图片编辑用 POST /v1/images/edits,multipart/form-data(image、可选 mask、prompt),与 OpenAI 官方一致。

import base64
from openai import OpenAI

client = OpenAI(api_key="sk-your-api-key", base_url="https://api.we2ai.com/v1")
r = client.images.generate(model="gpt-image-2", prompt="A red apple on a white table", size="1024x1024")
open("out.png", "wb").write(base64.b64decode(r.data[0].b64_json))

Gemini

Use the native generateContent with responseModalities. imageSize (1K / 2K / 4K) sets the resolution — higher resolutions cost more, so set it explicitly. The image comes back as an inlineData part. 使用原生 generateContent 并设置 responseModalities。imageSize(1K / 2K / 4K)决定分辨率,分辨率越高越贵,建议显式指定。图片以 inlineData 返回。

curl "https://api.we2ai.com/v1beta/models/gemini-3.1-flash-image:generateContent" \
  -H "x-goog-api-key: your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [{"parts": [{"text": "A red apple on a white table"}]}],
    "generationConfig": {
      "responseModalities": ["TEXT", "IMAGE"],
      "imageConfig": {"aspectRatio": "1:1", "imageSize": "1K"}
    }
  }'
import base64, requests

r = requests.post(
    "https://api.we2ai.com/v1beta/models/gemini-3.1-flash-image:generateContent",
    headers={"x-goog-api-key": "your-api-key"},
    json={
        "contents": [{"parts": [{"text": "A red apple on a white table"}]}],
        "generationConfig": {"responseModalities": ["TEXT", "IMAGE"],
                             "imageConfig": {"aspectRatio": "1:1", "imageSize": "1K"}},
    },
)
for part in r.json()["candidates"][0]["content"]["parts"]:
    if "inlineData" in part:
        open("out.png", "wb").write(base64.b64decode(part["inlineData"]["data"]))

Grok Imagine

Same OpenAI-style endpoint. Without response_format the response has a temporary url; set "response_format": "b64_json" to get the image bytes directly. 同样的 OpenAI 风格端点。不传 response_format 时返回临时 url;设置 "response_format": "b64_json" 则直接返回图片数据。

curl https://api.we2ai.com/v1/images/generations \
  -H "Authorization: Bearer sk-your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "grok-imagine-image-2.0",
    "prompt": "A red apple on a white table",
    "n": 1,
    "response_format": "b64_json"
  }'

Video generation视频生成

Grok Imagine video is asynchronous: create a task, poll its status, then download the result. A task is billed when it succeeds. Grok Imagine 视频是异步的:创建任务、轮询状态、下载结果。任务成功时才计费。

# 1. create — returns {"request_id": "..."}
curl https://api.we2ai.com/v1/videos \
  -H "Authorization: Bearer sk-your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "grok-imagine-video-1.5",
    "prompt": "A red apple rotating slowly on a white table",
    "duration": 5,
    "aspect_ratio": "16:9",
    "resolution": "480p"
  }'

# 2. poll until status is "succeeded" (pending → ... → succeeded)
curl https://api.we2ai.com/v1/videos/{request_id} \
  -H "Authorization: Bearer sk-your-api-key"

# 3. download the file (the Authorization header is required)
curl https://api.we2ai.com/v1/videos/{request_id}/content \
  -H "Authorization: Bearer sk-your-api-key" -o out.mp4

To animate an image, add "image": {"url": "https://…", "type": "image_url"} (a data URL also works) to the create request. 要让图片动起来,在创建请求里加 "image": {"url": "https://…", "type": "image_url"}(也可以用 data URL)。

Models & usage模型与用量

List the models your key can call查询 Key 可调用的模型

curl https://api.we2ai.com/v1/models -H "Authorization: Bearer sk-your-api-key"

# Gemini-group keys
curl https://api.we2ai.com/v1beta/models -H "x-goog-api-key: your-api-key"

Check usage and quota查询用量与额度

curl https://api.we2ai.com/v1/usage -H "Authorization: Bearer sk-your-api-key"

Returns the key's status and expiry, quota (limit, used, remaining, in USD) when a quota is set, and usage totals for today and overall: requests, tokens and cost. Optional query parameters: days (1–90) for the daily breakdown, start_date / end_date (YYYY-MM-DD) for per-model stats. 返回 Key 的状态和到期时间;设置了额度时返回额度(limit、used、remaining,单位美元);以及今日和累计的请求数、token 数和费用。可选参数:days(1–90)控制按日明细,start_date / end_date(YYYY-MM-DD)控制按模型统计的区间。

Claude Code & CodexClaude Code 与 Codex

Fastest: the WE2AI desktop client switches Claude Code, Codex and WorkBuddy to WE2AI models in one click. To configure them by hand: 最快的方式:WE2AI 桌面客户端一键把 Claude Code、Codex、WorkBuddy 切到 WE2AI 的模型。手动配置如下:

Claude Code
export ANTHROPIC_BASE_URL="https://api.we2ai.com"
export ANTHROPIC_AUTH_TOKEN="sk-your-api-key"
claude
Codex · ~/.codex/config.toml
model_provider = "we2ai"
model = "gpt-6-luna"

[model_providers.we2ai]
name = "WE2AI"
base_url = "https://api.we2ai.com/v1"
env_key = "WE2AI_API_KEY"
wire_api = "responses"
requires_openai_auth = false
supports_websockets = false
export WE2AI_API_KEY="sk-your-api-key"
codex

Codex needs a key from a group that serves its model; with a WE2AI key you do not need a ChatGPT subscription — usage is billed per token. Codex 需要所在分组提供对应模型的 Key;使用 WE2AI 的 Key 不需要 ChatGPT 订阅,按 token 计费。

Errors错误处理

HTTPMeaning含义What to do怎么处理
400Invalid request parameters请求参数有误Fix the request; the message says which field.按错误信息修正请求。
401Key missing, invalid or disabledKey 缺失、无效或已停用Check the key and the header you send it in; many failed attempts in a row are rate limited.检查 Key 和所用请求头;连续多次认证失败会被限流。
403Key expired, IP not allowed, group unavailable, or insufficient account balanceKey 已过期、IP 不在允许范围、分组不可用,或账户余额不足The error code says which (e.g. API_KEY_EXPIRED, INSUFFICIENT_BALANCE); fix it in the console.错误里的 code 会写明原因(如 API_KEY_EXPIRED、INSUFFICIENT_BALANCE),到控制台处理。
404 / 503The model is not available to your key's group你的分组没有这个模型/v1/chat/completions answers 404 model_not_found; /v1/messages answers 503 "No available accounts". Check GET /v1/models./v1/chat/completions 返回 404 model_not_found,/v1/messages 返回 503 "No available accounts"。用 GET /v1/models 核对。
429Rate limit, or the key's quota / usage limit is reached触发限流,或 Key 的额度 / 用量上限已达到Rate limits: retry with exponential backoff. API_KEY_QUOTA_EXHAUSTED: raise the key's quota in the console — retrying will not help.限流:指数退避后重试。API_KEY_QUOTA_EXHAUSTED:到控制台提高这把 Key 的额度,重试没有用。
5xxTemporary upstream error上游临时故障Retry after a short wait; keep requests idempotent.稍等后重试,请求保持幂等。

Error bodies follow the protocol of the endpoint you called (Anthropic, OpenAI or Google style). Authentication failures return {"code":"INVALID_API_KEY","message":"Invalid API key"}. 错误体的格式跟随你调用的端点的协议(Anthropic、OpenAI 或 Google 风格)。认证失败返回 {"code":"INVALID_API_KEY","message":"Invalid API key"}。

import time, requests

def call(payload, retries=3):
    for i in range(retries):
        r = requests.post("https://api.we2ai.com/v1/chat/completions",
                          headers={"Authorization": "Bearer sk-your-api-key"}, json=payload)
        if r.status_code == 429 or r.status_code >= 500:   # a 429 with API_KEY_QUOTA_EXHAUSTED will not recover by retrying
            time.sleep(2 ** i)
            continue
        r.raise_for_status()
        return r.json()
    raise RuntimeError("retries exhausted")