LeaoAPI 开发者文档 LeaoAPI Developer Documentation
面向下一代智能化应用的高性能、全托管大模型分布式中转基础设施。
High-performance, fully managed distributed large model routing infrastructure for next-generation AI applications.
LeaoAPI 提供了行业统一的、高可用的算力接入层。我们的网络接口在底层 100% 兼容 OpenAI 官方客户端及 SDK 规范。
LeaoAPI provides an industry-unified, highly available computing access layer. All API endpoints are 100% compatible with OpenAI client specifications.
企业级服务等级协议 (SLA) 企业账户专属 Enterprise Service Level Agreement (SLA) Enterprise Only
系统实时状态页 ↗Live Status Page ↗针对企业级签约账户,系统内置分布式热轮询动态路由算法。一旦第三方供应商发生突发故障,分发层将在毫秒级内自动执行无感切流,承诺提供 99.9% 的生产级可用性。
Exclusive to Enterprise Accounts, the system guarantees a 99.9% uptime SLA via millisecond-level automated dynamic failover and smart hot-polling routing layers.
交互式在线测试沙盒 Interactive API Playground
无需配置开发环境,在下方直接体验 LeaoAPI 极速响应(此处为文档沙盒模拟器):
Test our API endpoints instantly inside this integrated documentation sandbox simulator:
数据隐私与零缓存承诺 Data Privacy & Zero-Retention Policy
作为面向大厂与高规格出海业务的算力网关,LeaoAPI 严格遵循零知识合规审计:
LeaoAPI adheres to a strict Zero-Knowledge security architecture designed for compliance-sensitive enterprises:
- Payload 100% 透传: 所有流经本网关的提示词及生成内容在底层均采用纯透传协议。系统不设任何持久化日志存储,坚决不缓存用户核心数据。 100% Pass-Through: All payloads route strictly in memory. We run a **Zero-Retention Policy** where no prompts or completions are written to persistent disks.
- 数据训练豁免: 平台已与上游供应商锁定了企业级合规协议,确保您的任何线上商业流数据绝不被用于任何模型的二次训练与微调。 Training Exemption: All connections are wrapped under enterprise commercial clauses, legal binding that guarantees your data is never used for upstream fine-tuning.
快速接入三要素 Three Elements for Quick Access
- 账户可用余额: 前往 [充值中心] 充值。系统依据实际 Token 消耗精准扣费。 Available Balance: Set up credits in the Dashboard. Charges are calculated dynamically per token.
-
创建专属令牌 (API Key): 在 [令牌管理] 申请以
sk-....开头的合法身份密钥。 API Key Authentication: Generate yoursk-....token inside the API token panel. -
统一终节点 Base URL:
https://leaoapi.com/v1Unified Endpoint Base URL:https://leaoapi.com/v1
认证与鉴权 Authentication and Authorization
在发送 HTTP 请求时,在 Headers 中附加 Authorization 字段:
Attach the standard bearer key inside your request headers:
代码示例:cURL (REST API) Code Example: cURL (REST API)
curl https://leaoapi.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-YOUR_LEAO_API_KEY" \
-d '{
"model": "deepseek-r1",
"messages": [{"role": "user", "content": "Hello."}],
"stream": true
}'
代码示例:Python SDK Code Example: Python SDK
from openai import OpenAI
client = OpenAI(api_key="sk-YOUR_API_KEY", base_url="https://leaoapi.com/v1")
response = client.chat.completions.create(
model="deepseek-v3",
messages=[{"role": "user", "content": "Hello"}],
stream=True
)
for chunk in response:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="")
代码示例:Node.js Code Example: Node.js
import OpenAI from "openai";
const openai = new OpenAI({ apiKey: "sk-YOUR_API_KEY", baseURL: "https://leaoapi.com/v1" });
const stream = await openai.chat.completions.create({
model: "deepseek-v3",
messages: [{ role: "user", content: "Hello" }],
stream: true,
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content || "");
}
代码示例:Go 语言 Code Example: Go Lang
package main
import (
"context"
"fmt"
"github.com/sashabaranov/go-openai"
)
func main() {
config := openai.DefaultConfig("sk-YOUR_LEAO_API_KEY")
config.BaseURL = "https://leaoapi.com/v1"
client := openai.NewClientWithConfig(config)
resp, _ := client.CreateChatCompletion(
context.Background(),
openai.ChatCompletionRequest{
Model: "deepseek-v3",
Messages: []openai.ChatCompletionMessage{{Role: "user", Content: "Hello"}},
},
)
fmt.Println(resp.Choices[0].Message.Content)
}
代码示例:Java (OpenAI-Java Client) Code Example: Java (OpenAI-Java Client)
import com.theokanning.openai.service.OpenAiService;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
public class LeaoClient {
public static void main(String[] args) {
// 配置超时与 BaseURLConfigure timeout and BaseURL
OpenAiService service = new OpenAiService("sk-YOUR_KEY", java.time.Duration.ofSeconds(60));
// 注:原生框架底层替换 leaoapi.com/v1 即可完美映射Note: Simply replace the base URL with leaoapi.com/v1 in native framework for perfect routing.
System.out.println("Java SDK Connected successfully to LeaoAPI Layer.");
}
}
SSE 流式协议与 DeepSeek-R1 思维链响应规范 SSE Protocol & DeepSeek-R1 Reasoning Schema
针对类似 deepseek-r1 的深度推理模型,系统在 SSE 协议块的 delta 结构中增加了标准的 reasoning_content 扩展字段。真实的 Chunk JSON 交互序列如下:
For reasoning models like deepseek-r1, the gateway outputs an explicit reasoning_content parameter inside the delta frame:
// 阶段 1:输出模型深度思考思维链Chunk Phase 1: Output model's reasoning thought process
data: {"id":"ch-1","object":"chat.chunk","choices":[{"delta":{"reasoning_content":"Thinking: The user wants..."},"finish_reason":null}]}
// 阶段 2:思维链结束,开始输出最终文本答案Chunk Phase 2: Core answer conversion after reasoning completes
data: {"id":"ch-1","object":"chat.chunk","choices":[{"delta":{"content":"Here is the direct answer:"},"finish_reason":null}]}
// 阶段 3:网关透传标准终止状态符Chunk Phase 3: Finalizer standard stop flag
data: [DONE]
高级功能:智能体工具回调 (Function Calling) Advanced Feature: Tool & Function Calling
LeaoAPI 完美支持模型动态解析结构化插件并调用外部函数:
LeaoAPI perfectly handles structural JSON tool-call routing schemas out of the box:
# 完美支持 tools 传递参数定义Perfectly supports tools parameter definitions
tools = [{
"type": "function",
"function": {
"name": "get_stock_price",
"parameters": {
"type": "object",
"properties": {"ticker": {"type": "string"}}
}
}
}]
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "What's the price of AAPL?"}],
tools=tools
)
print(response.choices[0].message.tool_calls)
高级功能:严格结构化输出 (JSON Mode) Advanced Feature: Structured Outputs
通过锁定 response_format 约束,保证模型 100% 返回可被程序直接无缝反序列化的 JSON 干净结构化数据体:
Enforce strict data boundaries by utilizing the response_format parameter:
// 传入请求核心控制字段约束API Request body format constraint
{
"model": "deepseek-v3",
"messages": [{"role": "user", "content": "List 3 items in JSON format."}],
"response_format": { "type": "json_object" }
}
图像生成与处理接口 (Images API) Image Generation API
LeaoAPI 底层 100% 兼容 OpenAI 官方图像生成规范。统一接入点支持国内顶尖模型的文生图(Text-to-Image)请求。网关针对高并发图像生成任务进行了分发层异步交付处理,确保 URL 返回的高可用性与强稳定性。
LeaoAPI is 100% compatible with the OpenAI Images specification. Our unified endpoint seamlessly routes high-concurrency Text-to-Image requests to top tier domestic models with advanced asynchronous delivery optimization.
-
统一图像终节点 Base URL:
https://leaoapi.com/v1/images/generationsUnified Images Endpoint:https://leaoapi.com/v1/images/generations
代码示例:cURL (REST API)Code Example: cURL
curl https://leaoapi.com/v1/images/generations \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-YOUR_LEAO_API_KEY" \
-d '{
"model": "wanx-v2",
"prompt": "A modern cyberpunk style tech office in Shanghai, realistic cinematic lighting, 4k",
"n": 1,
"size": "1024x1024",
"response_format": "url"
}'
代码示例:Python SDKCode Example: Python SDK
from openai import OpenAI
client = OpenAI(api_key="sk-YOUR_API_KEY", base_url="https://leaoapi.com/v1")
response = client.images.generate(
model="hunyuan-dit",
prompt="A beautiful landscape oil painting of West Lake in Hangzhou, sunset, impressionism style",
n=1,
size="1024x1024",
response_format="url"
)
print(response.data[0].url)
视频生成 / Seedance(火山引擎官方协议) Video Generation / Seedance (Volcengine Native Protocol)
Seedance 视频生成是异步任务:提交请求只返回任务 id,随后查询同一任务直至 succeeded 或 failed。本页保留火山方舟的请求体与路径,仅将官方主机 https://ark.cn-beijing.volces.com 替换为 https://leaoapi.com;请勿把它替换成 /v1/images/generations 或 Chat Completions 端点。
Seedance video generation is an asynchronous task: submission returns an id, then the task is retrieved until it is succeeded or failed. This page preserves Volcengine Ark's request body and path, replacing only https://ark.cn-beijing.volces.com with https://leaoapi.com. Do not use an Images or Chat Completions endpoint.
Base URL 替换规则:https://ark.cn-beijing.volces.com/api/v3 → https://leaoapi.com/api/v3。创建:POST /contents/generations/tasks;查询:GET /contents/generations/tasks/{id}。认证沿用 LeaoAPI:Authorization: Bearer sk-YOUR_LEAO_API_KEY。
Base URL mapping: https://ark.cn-beijing.volces.com/api/v3 → https://leaoapi.com/api/v3. Create with POST /contents/generations/tasks; retrieve with GET /contents/generations/tasks/{id}. Keep LeaoAPI Bearer authentication.
模型与必要字段Models and required fields
| 字段Field | 要求Requirement | 说明Notes |
|---|---|---|
model | 必填Required | 火山方舟 Seedance 模型 ID,例如 doubao-seedance-2-0-260128(标准)或 doubao-seedance-2-0-fast-260128(Fast)。具体可用模型以 LeaoAPI 账户开通状态为准。An enabled Volcengine Ark Seedance model ID, e.g. doubao-seedance-2-0-260128 (standard) or doubao-seedance-2-0-fast-260128 (Fast). Availability is account-dependent. |
content | 必填Required | 输入数组;文生视频至少含一个 {"type":"text","text":"..."}。图生视频使用 image_url 项并提供可访问的 URL。Input array. Text-to-video needs at least {"type":"text","text":"..."}. Image-to-video uses an image_url item with an accessible URL. |
ratio、duration | 按模型能力选填Optional by model | 画幅比例与秒数;不要同时传 duration 与 frames。Aspect ratio and seconds; do not send both duration and frames. |
创建任务:cURLCreate task: cURL
curl -X POST "https://leaoapi.com/api/v3/contents/generations/tasks" \
-H "Authorization: Bearer sk-YOUR_LEAO_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "doubao-seedance-2-0-260128",
"content": [{
"type": "text",
"text": "A golden retriever runs along a sunlit beach, cinematic tracking shot, natural motion"
}],
"ratio": "16:9",
"duration": 5
}'
# Successful submission: {"id":"cgt-..."}
查询任务与取得视频 URL:cURLRetrieve task and video URL: cURL
curl "https://leaoapi.com/api/v3/contents/generations/tasks/cgt-YOUR_TASK_ID" \
-H "Authorization: Bearer sk-YOUR_LEAO_API_KEY"
# When status is "succeeded", read content.video_url:
# {"id":"cgt-...","status":"succeeded",
# "content":{"video_url":"https://.../generated.mp4"}}
Python:使用 requests 创建并轮询Python: create and poll with requests
该原生任务协议不是 OpenAI Python SDK 的 Images API;使用 requests 可避免把任务接口误当成同步生成接口。
This native task protocol is not the OpenAI Python SDK Images API. Use requests to avoid treating it as a synchronous generation endpoint.
import os
import time
import requests
BASE_URL = "https://leaoapi.com/api/v3"
headers = {
"Authorization": f"Bearer {os.environ['LEAO_API_KEY']}",
"Content-Type": "application/json",
}
payload = {
"model": "doubao-seedance-2-0-260128",
"content": [{"type": "text", "text": "A paper boat floats down a quiet stream at dawn"}],
"ratio": "16:9",
"duration": 5,
}
create = requests.post(f"{BASE_URL}/contents/generations/tasks", headers=headers, json=payload, timeout=30)
create.raise_for_status()
task_id = create.json()["id"]
deadline = time.monotonic() + 900
while time.monotonic() < deadline:
task = requests.get(f"{BASE_URL}/contents/generations/tasks/{task_id}", headers=headers, timeout=30)
task.raise_for_status()
result = task.json()
if result["status"] == "succeeded":
print(result["content"]["video_url"])
break
if result["status"] == "failed":
raise RuntimeError(result.get("error", result))
time.sleep(5)
else:
raise TimeoutError(f"Seedance task {task_id} did not finish in time")
结果处理:仅在 status = succeeded 后读取 content.video_url。该 URL 是上游任务结果,建议在业务侧及时保存或转存;失败时读取 error,不要继续轮询。
Result handling: Read content.video_url only after status = succeeded. It is an upstream task-result URL, so save or mirror it promptly if durable storage is required. On failed, inspect error and stop polling.
规范来源:火山方舟 Seedance 视频生成 API(原生 contents/generations/tasks 协议)。Protocol reference: Volcengine Ark Seedance Video Generation API (native contents/generations/tasks protocol). Volcengine Docs ↗
核心国内图像模型清单标识与单独计费边界 Domestic Image Model Identifiers & Pricing Boundaries
请注意:图像类模型不遵循 Token 计费公式。系统采用行业标准,依据请求生成的张数(N)以及分辨率大小进行独立单张额度扣减,不占用文本类 TPM 限制。
Note: Image models do not follow token billing. Charges are calculated strictly per generated image slice based on resolution, completely separated from text TPM constraints.
| Model ID | 推荐分辨率Resolution Limits | 计费口径Billing Method | 国内模型特性与适用场景Model Features & Use Cases |
|---|---|---|---|
wanx-v2 |
1024×1024 / 任意比例Any Ratio | 按张精准扣费Per Image | 阿里通义万相。对中国传统文化、电商古风及中文语义理解极其精准。Tongyi Wanx. Outstanding alignment for Chinese culture and e-commerce designs. |
hunyuan-dit |
1024×1024 / 768×1024 | 按张标准扣费Per Image (Standard) | 腾讯混元文生图。原生 DiT 架构,拥有强大的中文字符画面渲染与海报设计能力。Tencent Hunyuan. Native DiT architecture with superb Chinese text rendering in images. |
cogview-4 |
1024×1024 / 2048×2048 | 按张高规格扣费Per Image (Premium) | 智谱 AI 图像模型。细粒度控制力强,画面真实感与材质纹理细节表现拔尖。Zhipu AI. Advanced prompt matching with incredible material textures and photorealism. |
doubao-image |
任意分辨率自适应Any Resolution Adaptive | 按张低损耗扣费Per Image (Budget) | 字节跳动豆包图像。生图响应速度极快,极其适合大批量、高并发的商业内容生成。ByteDance Doubao. Ultra-fast rendering speed, perfect for massive high-concurrency tasks. |
企业账户混合计费与财务对账公式 Billing Architecture Formula
为了方便企业内部财务系统以及网关层对账,系统扣费严格遵循公开公式(无额外隐性通道服务费):
Charges are calculated purely via a transparent formula mapping exact usage dimensions with no hidden cost:
* 提示:对于自带思维链输出的模型,其生成的推理 Token(Reasoning Tokens)全部归入“输出 Tokens 费率”合并计费,不设双重扣费陷阱。Note: Reasoning tokens generated by models like R1 are aggregated cleanly under Output Token rates without surcharges.
核心可用模型清单标识与硬性上游边界 Core Model Identifiers & Context Hard Limits
| Model ID | 最大上下文Context Window | 单次硬性 Max TokensMax Output Limit |
|---|---|---|
deepseek-v3 |
64K | 8,192 Tokens |
deepseek-r1 |
64K | 8,192 Tokens |
gpt-4o |
128K | 4,096 Tokens |
claude-3-5-sonnet |
200K | 8,192 Tokens |
频率与并发控制分级限制阶梯 Rate Limits Grading Matrix
| 账户等级Tier Level | 每分钟请求数 (RPM)Requests Per Minute (RPM) | 每分钟 Token数 (TPM)Tokens Per Minute (TPM) | 生产级专线通道Channel Isolation |
|---|---|---|---|
| 免费版Free Tier | 3 RPM | 10,000 TPM | 共享网络层(有突发排队抖动)Shared Pool |
| 标准商用版Standard Tier | 60 RPM | 150,000 TPM | 高可用多路由热备轮询通道Multi-route High-Availability |
| 企业尊享版Enterprise Tier | 1,200+ RPM | 3,000,000+ TPM | 专属弹性算力隔离专线,支持无限弹性扩容Premium Dedicated Isolation Line |
全局错误码参考 Global Error Codes Reference
| HTTP Code | 错误类型Error Type | 诱因与官方排查建议Causes & Suggestions |
|---|---|---|
| 401 | 未授权 (Unauthorized)Unauthorized | 令牌挂起/格式错(如 Bearer 后缺失空格)。Invalid API key or missing space. |
| 403 | 余额不足 (Insufficient Balance)Insufficient Balance | 账户额度扣减尽,或者触发了当前令牌的自定义限额。Account out of budget or token hit specific limits. |
| 429 | 触发频率限制 (Rate Limit Exceeded)Rate Limit Exceeded | 触发单机并发阈值。请稍后重试或联系升级企业账户。Rate limits triggered. Switch to higher tier. |
| 500 | 服务器内部错误 (Internal Server Error)Internal Server Error | 上游官方集群崩溃,本层将在毫秒内动态完成剔除与切流。Upstream provider outage; gateway failover active. |