OpenAI 兼容 API
用你已经在用的 OpenAI SDK,只改 base URL,即可通过 infrai 运行 AI 推理。chat、embeddings、图像、语音(TTS/ASR)、moderations 与 models 全部使用与 OpenAI 完全一致的协议,并附带智能跨厂商路由、统一钱包与统一账单。
即插即用:把 OpenAI SDK 指向 infrai
infrai 以与 OpenAI 完全一致的请求/响应格式提供 AI 推理。把任意 OpenAI 客户端的 base URL 指向 https://api.infrai.cc/v1,并用你的 infrai 项目 key 作为 Bearer token——无需新 SDK、无需新知识。每个响应都会附带一个顶层 infrai 对象(成本 / 厂商 / 模型),普通客户端会自动忽略它。
Python
from openai import OpenAI
client = OpenAI(
base_url="https://api.infrai.cc/v1", # the ONLY change vs vanilla OpenAI
api_key="ifr_...", # your infrai project key
)
resp = client.chat.completions.create(
model="auto", # balanced routing across healthy vendors ("cheapest" / "smartest" also valid)
messages=[{"role": "user", "content": "Explain quicksort in one sentence."}],
)
print(resp.choices[0].message.content)
# infrai cost/vendor extension — a vanilla OpenAI client just ignores it:
print(resp.infrai["cost_usd"], resp.infrai["vendor"], resp.infrai["model"])JavaScript / TypeScript
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.infrai.cc/v1", // the only change vs vanilla OpenAI
apiKey: process.env.INFRAI_API_KEY,
});
const resp = await client.chat.completions.create({
model: "auto",
messages: [{ role: "user", content: "Explain quicksort in one sentence." }],
});
console.log(resp.choices[0].message.content);
console.log(resp.infrai.cost_usd, resp.infrai.vendor);curl
curl https://api.infrai.cc/v1/chat/completions \
-H "Authorization: Bearer $INFRAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "auto",
"messages": [{"role": "user", "content": "Explain quicksort in one sentence."}]
}'model="auto" 让 infrai 路由到最优/最便宜的健康厂商;通过 extra_body 传入 task / prefer,或固定一个真实模型如 "gpt-4o-mini"。旧的自定义 /v1/ai/chat 形态已退役——请使用 OpenAI 标准面。
端点
标准的 OpenAI 端点,均位于 base URL 的 /v1 路径下。每个端点对应一个 infrai 能力,具备完整的智能路由、故障转移、缓存与计费。
| 端点 | infrai 能力 | 用途 |
|---|---|---|
POST /v1/chat/completions | ai.chat | 对话补全——文本、视觉与工具调用,支持流式。 |
POST /v1/embeddings | ai.embed | 文本向量,用于检索与 RAG。 |
POST /v1/images/generations | ai.image | 根据文本提示生成图像。 |
POST /v1/moderations | ai.moderation | 判定内容是否违反使用政策。 |
POST /v1/audio/speech | ai.tts | 文本转语音——合成语音音频。 |
POST /v1/audio/transcriptions | ai.asr | 语音转文本——转写音频文件。 |
GET /v1/models | ai.models.list | 列出所有已验证、可路由厂商提供的模型。 |
GET /v1/models/{model} | ai.models.get | 获取单个模型的详情(定价、上下文、可用性)。 |
智能路由随 model 字段生效
infrai 的核心价值——跨厂商路由——在 OpenAI 的 model 字段上得以保留。用路由模式让 infrai 自动选择,或固定一个具体模型(也可固定厂商)以完全掌控。
# 1) Routing MODES — the complete set; infrai picks the vendor/model
# (SSOT: infrai-spec/enums/model_routing.yaml; also listed by GET /v1/models):
model="auto" # balanced default, honors task / prefer (== prefer "balanced")
model="cheapest" # cheapest healthy model for the task
model="smartest" # flagship-tier model
# 2) Pin a concrete model (any model a verified vendor serves):
model="gpt-4o-mini"
model="deepseek-chat"
model="dashscope/qwen-plus" # "vendor/model" pins the vendor too
# task / prefer ride OpenAI's extra_body (ignored by vanilla clients):
client.chat.completions.create(
model="auto",
messages=[...],
extra_body={"task": "coding", "prefer": "cheapest"},
)对话请求参数——由契约生成,因此下方 model 的类型即网关实际接受的取值集合:
| 名称 | 类型 | 必填 | 说明 |
|---|---|---|---|
model | string | 可选 | Model to use. 'auto' (default) lets infrai smart-route across healthy vendors; 'vendor/model' pins a specific vendor and model.e.g. auto |
messages | object[] | 必填 | OpenAI chat messages: a list of {role, content}. |
temperature | number | 可选 | |
max_tokens | integer | 可选 | |
top_p | number | 可选 | |
stream | boolean | 可选 | Server-Sent Events streaming when true. |
tools | object[] | 可选 | |
response_format | object | 可选 |
对话:流式、视觉与工具
流式输出、视觉(图像输入)与工具/函数调用,均与 OpenAI SDK 完全一致。
流式(Server-Sent Events)
stream = client.chat.completions.create(
model="auto",
messages=[{"role": "user", "content": "Write a haiku about smart routing."}],
stream=True, # real token-by-token Server-Sent Events
)
for chunk in stream:
print(chunk.choices[0].delta.content or "", end="", flush=True)视觉——图像输入
resp = client.chat.completions.create(
model="auto", # infrai resolves to an available vision model
messages=[{
"role": "user",
"content": [
{"type": "text", "text": "What is in this image?"},
{"type": "image_url",
"image_url": {"url": "https://example.com/cat.jpg"}},
],
}],
)
print(resp.choices[0].message.content)工具 / 函数调用
resp = client.chat.completions.create(
model="auto",
messages=[{"role": "user", "content": "What's the weather in Paris?"}],
tools=[{
"type": "function",
"function": {
"name": "get_weather",
"parameters": {"type": "object",
"properties": {"city": {"type": "string"}}},
},
}],
)
print(resp.choices[0].message.tool_calls)向量(Embeddings)
生成向量并直接写入 infrai 向量库,用于检索增强生成(RAG)。
resp = client.embeddings.create(
model="auto",
input=["first document", "second document"],
)
vector = resp.data[0].embedding
# → feed straight into POST /v1/vector/upsert for retrieval (RAG)图像、语音与转写
图像生成、文本转语音与语音转文本均使用标准 OpenAI 方法。audio/speech 返回二进制音频;transcriptions 接受 multipart 文件上传或 base64 JSON。
图像生成
img = client.images.generate(
model="auto",
prompt="a red panda coding at a laptop, studio lighting",
size="1024x1024",
)
print(img.data[0].url or img.data[0].b64_json[:32])文本转语音(TTS)
curl https://api.infrai.cc/v1/audio/speech \
-H "Authorization: Bearer $INFRAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{"model": "auto", "voice": "alloy", "input": "Hello from infrai."}' \
--output speech.mp3语音转文本(ASR)
with open("meeting.mp3", "rb") as audio:
tr = client.audio.transcriptions.create(model="auto", file=audio)
print(tr.text)infrai 扩展:成本、厂商与缓存
每个响应都携带一个顶层 infrai 对象,让你清楚看到该次调用的成本、由哪个厂商和模型提供服务、所在地域,以及是否命中缓存。普通 OpenAI 客户端会忽略该字段;进阶用户则可读取它。
{
"id": "chatcmpl-...",
"object": "chat.completion",
"model": "deepseek-chat",
"choices": [{ "message": { "role": "assistant", "content": "..." } }],
"usage": { "prompt_tokens": 12, "completion_tokens": 30, "total_tokens": 42 },
"infrai": {
"cost_usd": 0.0000123,
"vendor": "deepseek",
"model": "deepseek-chat",
"region": "china",
"cache": false,
"request_id": "req_..."
}
}同样的信息也通过响应头返回——X-Infrai-Request-Id、X-Infrai-Vendor 和 X-Infrai-Cost-Usd——让你无需解析响应体即可观测成本与路由。
列出模型
枚举实时可路由的模型清单。/v1/models 为 OpenAI 标准;/v1/ai/models 为 infrai 原生的公开清单,包含可用性与每百万 token 定价,并可按能力筛选。
# OpenAI-standard: every model a verified, routable vendor serves:
curl https://api.infrai.cc/v1/models -H "Authorization: Bearer $INFRAI_API_KEY"
# infrai-native (public, richer): availability + per-Mtok price, filterable:
curl "https://api.infrai.cc/v1/ai/models?capability=vision"错误
失败以 OpenAI 的错误格式返回——包含 message、type 与 code 的 error 对象——因此 OpenAI SDK 会抛出你代码已经处理的 APIError。401 为认证错误,402 对应额度不足(请充值钱包),429 为限流,5xx 为故障转移后的上游厂商错误。完整的机器可读错误码见错误目录。