跳到内容

AI 模型网关

受众:开发者 摘要:/api/v1/ai/gateway/** 是 AI 独立模块的模型调用入口,支持 OpenAI Compatible、Claude / Anthropic Messages、Codex / Responses API 和 Gemini Native 兼容协议。

AI 模型网关属于 spring-open-module-ai 的调用面。它面向开发者、AI Agent、第三方服务端和平台内部模块,提供统一模型 API,不直接暴露上游供应商差异。AI 模块内部负责模型别名解析、Provider 路由、限流、计量、quota、成本快照和健康信号;spring-open-starter-ai-model 负责 Provider SPI 和上游模型调用。

当前 AI 模块已承接 GET /api/v1/ai/gateway/status 状态接口、OpenAI Compatible models 模型列表 / 详情 / 删除、Organization costs / usage 只读查询、Organization Invite / Admin API Key / Organization Certificate / Project Certificate / Organization Spend Alert / Project Spend Alert / Organization Group / Group User / Organization Role / Project Role / Organization Project / Project API Key / Project Rate Limit / Project Group / Project Data Retention / Organization User / Audit Log / Project User / Project Service Account 管理 relay、普通 / 流式 chat/completions 对话、存储型 chat/completions 列表 / 详情 / 更新 / 删除 / 消息列表、legacy completions 文本补全、原生 responses 创建 / 详情 / 删除 / 取消 / 输入项查询 / 输入 token 统计 / 上下文压缩、conversations 会话和 item 生命周期、evals 评测任务 / runs / output items 生命周期、realtime client secret / session / transcription session / WebRTC call 创建和 WebSocket 双向 relay、embeddings 向量生成、moderations 内容审核、图片生成 / 编辑 / 变体、音频语音 / 转写 / 翻译、rerank 重排、files 文件生命周期、uploads 分片上传生命周期、batches 批处理任务、fine_tuning/jobs 微调任务、fine_tuning/checkpoints 检查点权限、fine_tuning/alpha/graders 评分器校验 / 运行、vector_stores / files / file_batches 文件检索管理、containers / files 运行容器文件管理、assistantsthreadsmessagesrunsrun steps 管理类 relay,Claude / Anthropic Messages 风格的 /claude/v1/models / /claude/v1/messages,Codex / Responses API 风格的 /codex/v1/models / /codex/v1/responses(兼容 /codex/models / /codex/responses),以及 Gemini Native 风格的 /gemini/v1beta/models:generateContent:streamGenerateContent:countTokens:embedContent:batchEmbedContents

AI 网关路径里可能出现两层版本号,这是有意设计。例如 /api/v1/ai/gateway/claude/v1/messages 中,/api/v1 是平台 API 主版本,决定平台接口演进;claude/v1 是 Claude / Anthropic Messages 协议版本,用来兼容 Claude Code、CC Switch 等外部工具。两层版本不要合并,否则会把平台接口演进和外部协议演进绑死。

路由

API说明
GET /api/v1/ai/gateway/status新 AI 模块网关迁移状态接口,需要后台权限:ai:gateway:view
GET /api/v1/ai/gateway/models目标 OpenAI Compatible 模型列表接口;兼容 GET /api/v1/ai/gateway/v1/models
GET /api/v1/ai/gateway/models/{modelId}目标 OpenAI Compatible 模型详情接口
DELETE /api/v1/ai/gateway/models/{modelId}目标 OpenAI Compatible 模型删除 / 撤销接口
GET /api/v1/ai/gateway/organization/costs目标 OpenAI Compatible Organization Costs 查询接口
GET /api/v1/ai/gateway/organization/usage/{usageType}目标 OpenAI Compatible Organization Usage 查询接口
GET /api/v1/ai/gateway/organization/invites目标 OpenAI Compatible Organization Invite 列表接口
POST /api/v1/ai/gateway/organization/invites目标 OpenAI Compatible Organization Invite 创建接口
GET /api/v1/ai/gateway/organization/invites/{inviteId}目标 OpenAI Compatible Organization Invite 详情接口
DELETE /api/v1/ai/gateway/organization/invites/{inviteId}目标 OpenAI Compatible Organization Invite 删除接口
GET /api/v1/ai/gateway/organization/admin_api_keys目标 OpenAI Compatible Admin API Key 列表接口
POST /api/v1/ai/gateway/organization/admin_api_keys目标 OpenAI Compatible Admin API Key 创建接口
GET /api/v1/ai/gateway/organization/admin_api_keys/{keyId}目标 OpenAI Compatible Admin API Key 详情接口
DELETE /api/v1/ai/gateway/organization/admin_api_keys/{keyId}目标 OpenAI Compatible Admin API Key 删除接口
GET /api/v1/ai/gateway/organization/certificates目标 OpenAI Compatible Organization Certificate 列表接口
POST /api/v1/ai/gateway/organization/certificates目标 OpenAI Compatible Organization Certificate 上传接口
GET /api/v1/ai/gateway/organization/certificates/{certificateId}目标 OpenAI Compatible Organization Certificate 详情接口
POST /api/v1/ai/gateway/organization/certificates/{certificateId}目标 OpenAI Compatible Organization Certificate 修改接口
DELETE /api/v1/ai/gateway/organization/certificates/{certificateId}目标 OpenAI Compatible Organization Certificate 删除接口
POST /api/v1/ai/gateway/organization/certificates/activate目标 OpenAI Compatible Organization Certificate 激活接口
POST /api/v1/ai/gateway/organization/certificates/deactivate目标 OpenAI Compatible Organization Certificate 停用接口
GET /api/v1/ai/gateway/organization/spend_alerts目标 OpenAI Compatible Organization Spend Alert 列表接口
POST /api/v1/ai/gateway/organization/spend_alerts目标 OpenAI Compatible Organization Spend Alert 创建接口
POST /api/v1/ai/gateway/organization/spend_alerts/{alertId}目标 OpenAI Compatible Organization Spend Alert 修改接口
DELETE /api/v1/ai/gateway/organization/spend_alerts/{alertId}目标 OpenAI Compatible Organization Spend Alert 删除接口
GET /api/v1/ai/gateway/organization/groups目标 OpenAI Compatible Organization Group 列表接口
POST /api/v1/ai/gateway/organization/groups目标 OpenAI Compatible Organization Group 创建接口
GET /api/v1/ai/gateway/organization/groups/{groupId}目标 OpenAI Compatible Organization Group 详情接口
POST /api/v1/ai/gateway/organization/groups/{groupId}目标 OpenAI Compatible Organization Group 修改接口
DELETE /api/v1/ai/gateway/organization/groups/{groupId}目标 OpenAI Compatible Organization Group 删除接口
GET /api/v1/ai/gateway/organization/groups/{groupId}/users目标 OpenAI Compatible Organization Group User 列表接口
POST /api/v1/ai/gateway/organization/groups/{groupId}/users目标 OpenAI Compatible Organization Group User 添加接口
DELETE /api/v1/ai/gateway/organization/groups/{groupId}/users/{userId}目标 OpenAI Compatible Organization Group User 移除接口
GET /api/v1/ai/gateway/organization/roles目标 OpenAI Compatible Organization Role 列表接口
POST /api/v1/ai/gateway/organization/roles目标 OpenAI Compatible Organization Role 创建接口
GET /api/v1/ai/gateway/organization/roles/{roleId}目标 OpenAI Compatible Organization Role 详情接口
POST /api/v1/ai/gateway/organization/roles/{roleId}目标 OpenAI Compatible Organization Role 修改接口
DELETE /api/v1/ai/gateway/organization/roles/{roleId}目标 OpenAI Compatible Organization Role 删除接口
POST /api/v1/ai/gateway/organization/projects目标 OpenAI Compatible Organization Project 创建接口
GET /api/v1/ai/gateway/organization/projects目标 OpenAI Compatible Organization Project 列表接口
GET /api/v1/ai/gateway/organization/projects/{projectId}目标 OpenAI Compatible Organization Project 详情接口
POST /api/v1/ai/gateway/organization/projects/{projectId}目标 OpenAI Compatible Organization Project 更新接口
POST /api/v1/ai/gateway/organization/projects/{projectId}/archive目标 OpenAI Compatible Organization Project 归档接口
GET /api/v1/ai/gateway/organization/projects/{projectId}/api_keys目标 OpenAI Compatible Project API Key 列表接口
GET /api/v1/ai/gateway/organization/projects/{projectId}/api_keys/{keyId}目标 OpenAI Compatible Project API Key 详情接口
DELETE /api/v1/ai/gateway/organization/projects/{projectId}/api_keys/{keyId}目标 OpenAI Compatible Project API Key 删除接口
GET /api/v1/ai/gateway/organization/projects/{projectId}/rate_limits目标 OpenAI Compatible Project Rate Limit 列表接口
POST /api/v1/ai/gateway/organization/projects/{projectId}/rate_limits/{rateLimitId}目标 OpenAI Compatible Project Rate Limit 更新接口
GET /api/v1/ai/gateway/organization/projects/{projectId}/groups目标 OpenAI Compatible Project Group 列表接口
POST /api/v1/ai/gateway/organization/projects/{projectId}/groups目标 OpenAI Compatible Project Group 添加接口
GET /api/v1/ai/gateway/organization/projects/{projectId}/groups/{groupId}目标 OpenAI Compatible Project Group 详情接口
DELETE /api/v1/ai/gateway/organization/projects/{projectId}/groups/{groupId}目标 OpenAI Compatible Project Group 移除接口
GET /api/v1/ai/gateway/organization/projects/{projectId}/data_retention目标 OpenAI Compatible Project Data Retention 详情接口
POST /api/v1/ai/gateway/organization/projects/{projectId}/data_retention目标 OpenAI Compatible Project Data Retention 更新接口
GET /api/v1/ai/gateway/organization/projects/{projectId}/certificates目标 OpenAI Compatible Project Certificate 列表接口
POST /api/v1/ai/gateway/organization/projects/{projectId}/certificates/activate目标 OpenAI Compatible Project Certificate 激活接口
POST /api/v1/ai/gateway/organization/projects/{projectId}/certificates/deactivate目标 OpenAI Compatible Project Certificate 停用接口
GET /api/v1/ai/gateway/organization/projects/{projectId}/spend_alerts目标 OpenAI Compatible Project Spend Alert 列表接口
POST /api/v1/ai/gateway/organization/projects/{projectId}/spend_alerts目标 OpenAI Compatible Project Spend Alert 创建接口
POST /api/v1/ai/gateway/organization/projects/{projectId}/spend_alerts/{alertId}目标 OpenAI Compatible Project Spend Alert 修改接口
DELETE /api/v1/ai/gateway/organization/projects/{projectId}/spend_alerts/{alertId}目标 OpenAI Compatible Project Spend Alert 删除接口
GET /api/v1/ai/gateway/projects/{projectId}/roles目标 OpenAI Compatible Project Role 列表接口
POST /api/v1/ai/gateway/projects/{projectId}/roles目标 OpenAI Compatible Project Role 创建接口
GET /api/v1/ai/gateway/projects/{projectId}/roles/{roleId}目标 OpenAI Compatible Project Role 详情接口
POST /api/v1/ai/gateway/projects/{projectId}/roles/{roleId}目标 OpenAI Compatible Project Role 修改接口
DELETE /api/v1/ai/gateway/projects/{projectId}/roles/{roleId}目标 OpenAI Compatible Project Role 删除接口
GET /api/v1/ai/gateway/organization/users目标 OpenAI Compatible Organization User 列表接口
GET /api/v1/ai/gateway/organization/users/{userId}目标 OpenAI Compatible Organization User 详情接口
POST /api/v1/ai/gateway/organization/users/{userId}目标 OpenAI Compatible Organization User 更新接口
DELETE /api/v1/ai/gateway/organization/users/{userId}目标 OpenAI Compatible Organization User 删除接口
GET /api/v1/ai/gateway/organization/audit_logs目标 OpenAI Compatible Organization Audit Log 列表接口
GET /api/v1/ai/gateway/organization/projects/{projectId}/users目标 OpenAI Compatible Project User 列表接口
POST /api/v1/ai/gateway/organization/projects/{projectId}/users目标 OpenAI Compatible Project User 创建接口
GET /api/v1/ai/gateway/organization/projects/{projectId}/users/{userId}目标 OpenAI Compatible Project User 详情接口
POST /api/v1/ai/gateway/organization/projects/{projectId}/users/{userId}目标 OpenAI Compatible Project User 更新接口
DELETE /api/v1/ai/gateway/organization/projects/{projectId}/users/{userId}目标 OpenAI Compatible Project User 删除接口
GET /api/v1/ai/gateway/organization/projects/{projectId}/service_accounts目标 OpenAI Compatible Project Service Account 列表接口
POST /api/v1/ai/gateway/organization/projects/{projectId}/service_accounts目标 OpenAI Compatible Project Service Account 创建接口
GET /api/v1/ai/gateway/organization/projects/{projectId}/service_accounts/{serviceAccountId}目标 OpenAI Compatible Project Service Account 详情接口
DELETE /api/v1/ai/gateway/organization/projects/{projectId}/service_accounts/{serviceAccountId}目标 OpenAI Compatible Project Service Account 删除接口
POST /api/v1/ai/gateway/chat/completions目标 OpenAI Compatible 普通 / 流式对话接口
GET /api/v1/ai/gateway/chat/completions目标 OpenAI Compatible 存储型 Chat Completion 列表接口
GET /api/v1/ai/gateway/chat/completions/{completionId}目标 OpenAI Compatible 存储型 Chat Completion 详情接口
POST /api/v1/ai/gateway/chat/completions/{completionId}目标 OpenAI Compatible 存储型 Chat Completion 更新接口
DELETE /api/v1/ai/gateway/chat/completions/{completionId}目标 OpenAI Compatible 存储型 Chat Completion 删除接口
GET /api/v1/ai/gateway/chat/completions/{completionId}/messages目标 OpenAI Compatible 存储型 Chat Completion 消息列表接口
POST /api/v1/ai/gateway/completions目标 OpenAI Compatible legacy 文本补全接口
POST /api/v1/ai/gateway/responses目标 OpenAI Compatible Responses 创建接口
GET /api/v1/ai/gateway/responses/{responseId}目标 OpenAI Compatible Response 详情接口
DELETE /api/v1/ai/gateway/responses/{responseId}目标 OpenAI Compatible Response 删除接口
POST /api/v1/ai/gateway/responses/{responseId}/cancel目标 OpenAI Compatible Response 取消接口
GET /api/v1/ai/gateway/responses/{responseId}/input_items目标 OpenAI Compatible Response 输入项接口
POST /api/v1/ai/gateway/responses/input_tokens目标 OpenAI Compatible Responses 输入 token 统计接口
POST /api/v1/ai/gateway/responses/compact目标 OpenAI Compatible Responses 上下文压缩接口
POST /api/v1/ai/gateway/conversations目标 OpenAI Compatible Conversation 创建接口
GET /api/v1/ai/gateway/conversations/{conversationId}目标 OpenAI Compatible Conversation 详情接口
POST /api/v1/ai/gateway/conversations/{conversationId}目标 OpenAI Compatible Conversation 更新接口
DELETE /api/v1/ai/gateway/conversations/{conversationId}目标 OpenAI Compatible Conversation 删除接口
POST /api/v1/ai/gateway/conversations/{conversationId}/items目标 OpenAI Compatible Conversation Item 创建接口
GET /api/v1/ai/gateway/conversations/{conversationId}/items目标 OpenAI Compatible Conversation Item 列表接口
GET /api/v1/ai/gateway/conversations/{conversationId}/items/{itemId}目标 OpenAI Compatible Conversation Item 详情接口
DELETE /api/v1/ai/gateway/conversations/{conversationId}/items/{itemId}目标 OpenAI Compatible Conversation Item 删除接口
POST /api/v1/ai/gateway/evals目标 OpenAI Compatible Eval 创建接口
GET /api/v1/ai/gateway/evals目标 OpenAI Compatible Eval 列表接口
GET /api/v1/ai/gateway/evals/{evalId}目标 OpenAI Compatible Eval 详情接口
POST /api/v1/ai/gateway/evals/{evalId}目标 OpenAI Compatible Eval 更新接口
DELETE /api/v1/ai/gateway/evals/{evalId}目标 OpenAI Compatible Eval 删除接口
POST /api/v1/ai/gateway/evals/{evalId}/runs目标 OpenAI Compatible Eval Run 创建接口
GET /api/v1/ai/gateway/evals/{evalId}/runs目标 OpenAI Compatible Eval Run 列表接口
GET /api/v1/ai/gateway/evals/{evalId}/runs/{runId}目标 OpenAI Compatible Eval Run 详情接口
POST /api/v1/ai/gateway/evals/{evalId}/runs/{runId}/cancel目标 OpenAI Compatible Eval Run 取消接口
DELETE /api/v1/ai/gateway/evals/{evalId}/runs/{runId}目标 OpenAI Compatible Eval Run 删除接口
GET /api/v1/ai/gateway/evals/{evalId}/runs/{runId}/output_items目标 OpenAI Compatible Eval Run 输出项接口
GET /api/v1/ai/gateway/evals/{evalId}/runs/{runId}/output_items/{outputItemId}目标 OpenAI Compatible Eval Run 输出项详情接口
POST /api/v1/ai/gateway/realtime/client_secrets目标 OpenAI Compatible Realtime client secret 创建接口
POST /api/v1/ai/gateway/realtime/sessions目标 OpenAI Compatible Realtime beta session 创建接口
POST /api/v1/ai/gateway/realtime/transcription_sessions目标 OpenAI Compatible Realtime transcription session 创建接口
POST /api/v1/ai/gateway/realtime/calls目标 OpenAI Compatible Realtime WebRTC call 创建接口
WS /api/v1/ai/gateway/realtime目标 OpenAI Compatible Realtime WebSocket 双向 JSON 事件 relay
POST /api/v1/ai/gateway/embeddings目标 OpenAI Compatible 向量生成接口
POST /api/v1/ai/gateway/moderations目标 OpenAI Compatible 内容审核接口
POST /api/v1/ai/gateway/images/generations目标 OpenAI Compatible 图片生成接口
POST /api/v1/ai/gateway/images/edits目标 OpenAI Compatible 图片编辑接口,multipart/form-data
POST /api/v1/ai/gateway/images/variations目标 OpenAI Compatible 图片变体接口,multipart/form-data
POST /api/v1/ai/gateway/audio/speech目标 OpenAI Compatible 音频语音接口,支持 JSON 或二进制上游响应
POST /api/v1/ai/gateway/audio/transcriptions目标 OpenAI Compatible 音频转写接口,multipart/form-data
POST /api/v1/ai/gateway/audio/translations目标 OpenAI Compatible 音频翻译接口,multipart/form-data
POST /api/v1/ai/gateway/rerank目标 OpenAI Compatible 重排接口
GET /api/v1/ai/gateway/files目标 OpenAI Compatible 文件列表接口
POST /api/v1/ai/gateway/files目标 OpenAI Compatible 文件上传接口,multipart/form-data
GET /api/v1/ai/gateway/files/{fileId}目标 OpenAI Compatible 文件详情接口
DELETE /api/v1/ai/gateway/files/{fileId}目标 OpenAI Compatible 文件删除接口
GET /api/v1/ai/gateway/files/{fileId}/content目标 OpenAI Compatible 文件内容接口,支持文本、JSON 或二进制透传
POST /api/v1/ai/gateway/uploads目标 OpenAI Compatible Upload 创建接口
POST /api/v1/ai/gateway/uploads/{uploadId}/parts目标 OpenAI Compatible Upload 分片上传接口,multipart/form-data,文件字段名 data
POST /api/v1/ai/gateway/uploads/{uploadId}/complete目标 OpenAI Compatible Upload 完成接口
POST /api/v1/ai/gateway/uploads/{uploadId}/cancel目标 OpenAI Compatible Upload 取消接口
POST /api/v1/ai/gateway/batches目标 OpenAI Compatible 批处理创建接口
GET /api/v1/ai/gateway/batches目标 OpenAI Compatible 批处理列表接口
GET /api/v1/ai/gateway/batches/{batchId}目标 OpenAI Compatible 批处理详情接口
POST /api/v1/ai/gateway/batches/{batchId}/cancel目标 OpenAI Compatible 批处理取消接口
POST /api/v1/ai/gateway/fine_tuning/jobs目标 OpenAI Compatible 微调任务创建接口
GET /api/v1/ai/gateway/fine_tuning/jobs目标 OpenAI Compatible 微调任务列表接口
GET /api/v1/ai/gateway/fine_tuning/jobs/{fineTuningJobId}目标 OpenAI Compatible 微调任务详情接口
POST /api/v1/ai/gateway/fine_tuning/jobs/{fineTuningJobId}/cancel目标 OpenAI Compatible 微调任务取消接口
GET /api/v1/ai/gateway/fine_tuning/jobs/{fineTuningJobId}/events目标 OpenAI Compatible 微调任务事件接口
GET /api/v1/ai/gateway/fine_tuning/jobs/{fineTuningJobId}/checkpoints目标 OpenAI Compatible 微调任务检查点接口
GET /api/v1/ai/gateway/fine_tuning/checkpoints/{fineTunedModelCheckpoint}/permissions目标 OpenAI Compatible 微调检查点权限列表接口
POST /api/v1/ai/gateway/fine_tuning/checkpoints/{fineTunedModelCheckpoint}/permissions目标 OpenAI Compatible 微调检查点权限创建接口
DELETE /api/v1/ai/gateway/fine_tuning/checkpoints/{fineTunedModelCheckpoint}/permissions/{permissionId}目标 OpenAI Compatible 微调检查点权限删除接口
POST /api/v1/ai/gateway/fine_tuning/alpha/graders/validate目标 OpenAI Compatible Grader 校验接口
POST /api/v1/ai/gateway/fine_tuning/alpha/graders/run目标 OpenAI Compatible Grader 运行接口
POST /api/v1/ai/gateway/vector_stores目标 OpenAI Compatible Vector Store 创建接口
GET /api/v1/ai/gateway/vector_stores目标 OpenAI Compatible Vector Store 列表接口
GET /api/v1/ai/gateway/vector_stores/{vectorStoreId}目标 OpenAI Compatible Vector Store 详情接口
POST /api/v1/ai/gateway/vector_stores/{vectorStoreId}目标 OpenAI Compatible Vector Store 更新接口
DELETE /api/v1/ai/gateway/vector_stores/{vectorStoreId}目标 OpenAI Compatible Vector Store 删除接口
POST /api/v1/ai/gateway/vector_stores/{vectorStoreId}/search目标 OpenAI Compatible Vector Store 搜索接口
POST /api/v1/ai/gateway/vector_stores/{vectorStoreId}/files目标 OpenAI Compatible Vector Store File 创建接口
GET /api/v1/ai/gateway/vector_stores/{vectorStoreId}/files目标 OpenAI Compatible Vector Store File 列表接口
GET /api/v1/ai/gateway/vector_stores/{vectorStoreId}/files/{fileId}目标 OpenAI Compatible Vector Store File 详情接口
GET /api/v1/ai/gateway/vector_stores/{vectorStoreId}/files/{fileId}/content目标 OpenAI Compatible Vector Store File 内容接口
DELETE /api/v1/ai/gateway/vector_stores/{vectorStoreId}/files/{fileId}目标 OpenAI Compatible Vector Store File 删除接口
POST /api/v1/ai/gateway/vector_stores/{vectorStoreId}/file_batches目标 OpenAI Compatible Vector Store File Batch 创建接口
GET /api/v1/ai/gateway/vector_stores/{vectorStoreId}/file_batches/{batchId}目标 OpenAI Compatible Vector Store File Batch 详情接口
POST /api/v1/ai/gateway/vector_stores/{vectorStoreId}/file_batches/{batchId}/cancel目标 OpenAI Compatible Vector Store File Batch 取消接口
GET /api/v1/ai/gateway/vector_stores/{vectorStoreId}/file_batches/{batchId}/files目标 OpenAI Compatible Vector Store File Batch 文件列表接口
POST /api/v1/ai/gateway/containers目标 OpenAI Compatible Container 创建接口
GET /api/v1/ai/gateway/containers目标 OpenAI Compatible Container 列表接口
GET /api/v1/ai/gateway/containers/{containerId}目标 OpenAI Compatible Container 详情接口
DELETE /api/v1/ai/gateway/containers/{containerId}目标 OpenAI Compatible Container 删除接口
POST /api/v1/ai/gateway/containers/{containerId}/files目标 OpenAI Compatible Container File 创建接口,multipart/form-data
GET /api/v1/ai/gateway/containers/{containerId}/files目标 OpenAI Compatible Container File 列表接口
GET /api/v1/ai/gateway/containers/{containerId}/files/{fileId}目标 OpenAI Compatible Container File 详情接口
DELETE /api/v1/ai/gateway/containers/{containerId}/files/{fileId}目标 OpenAI Compatible Container File 删除接口
GET /api/v1/ai/gateway/containers/{containerId}/files/{fileId}/content目标 OpenAI Compatible Container File 内容接口,支持文本、JSON 或二进制透传
POST /api/v1/ai/gateway/assistants目标 OpenAI Compatible Assistant 创建接口
GET /api/v1/ai/gateway/assistants目标 OpenAI Compatible Assistant 列表接口
GET /api/v1/ai/gateway/assistants/{assistantId}目标 OpenAI Compatible Assistant 详情接口
POST /api/v1/ai/gateway/assistants/{assistantId}目标 OpenAI Compatible Assistant 更新接口
DELETE /api/v1/ai/gateway/assistants/{assistantId}目标 OpenAI Compatible Assistant 删除接口
POST /api/v1/ai/gateway/threads目标 OpenAI Compatible Thread 创建接口
POST /api/v1/ai/gateway/threads/runs目标 OpenAI Compatible Thread 创建并运行接口
GET /api/v1/ai/gateway/threads/{threadId}目标 OpenAI Compatible Thread 详情接口
POST /api/v1/ai/gateway/threads/{threadId}目标 OpenAI Compatible Thread 更新接口
DELETE /api/v1/ai/gateway/threads/{threadId}目标 OpenAI Compatible Thread 删除接口
POST /api/v1/ai/gateway/threads/{threadId}/messages目标 OpenAI Compatible Thread Message 创建接口
GET /api/v1/ai/gateway/threads/{threadId}/messages目标 OpenAI Compatible Thread Message 列表接口
GET /api/v1/ai/gateway/threads/{threadId}/messages/{messageId}目标 OpenAI Compatible Thread Message 详情接口
POST /api/v1/ai/gateway/threads/{threadId}/messages/{messageId}目标 OpenAI Compatible Thread Message 更新接口
DELETE /api/v1/ai/gateway/threads/{threadId}/messages/{messageId}目标 OpenAI Compatible Thread Message 删除接口
POST /api/v1/ai/gateway/threads/{threadId}/runs目标 OpenAI Compatible Thread Run 创建接口
GET /api/v1/ai/gateway/threads/{threadId}/runs目标 OpenAI Compatible Thread Run 列表接口
GET /api/v1/ai/gateway/threads/{threadId}/runs/{runId}目标 OpenAI Compatible Thread Run 详情接口
POST /api/v1/ai/gateway/threads/{threadId}/runs/{runId}目标 OpenAI Compatible Thread Run 更新接口
POST /api/v1/ai/gateway/threads/{threadId}/runs/{runId}/cancel目标 OpenAI Compatible Thread Run 取消接口
POST /api/v1/ai/gateway/threads/{threadId}/runs/{runId}/submit_tool_outputs目标 OpenAI Compatible Thread Run 工具输出提交接口
GET /api/v1/ai/gateway/threads/{threadId}/runs/{runId}/steps目标 OpenAI Compatible Thread Run Step 列表接口
GET /api/v1/ai/gateway/threads/{threadId}/runs/{runId}/steps/{stepId}目标 OpenAI Compatible Thread Run Step 详情接口
GET /api/v1/ai/gateway/claude/v1/models目标 Claude / Anthropic Models 模型列表接口
POST /api/v1/ai/gateway/claude/v1/messages目标 Claude / Anthropic Messages 普通 / 流式对话接口
GET /api/v1/ai/gateway/gemini/v1beta/models目标 Gemini Native 模型列表接口
GET /api/v1/ai/gateway/gemini/v1beta/models/{modelId}目标 Gemini Native 模型详情接口
POST /api/v1/ai/gateway/gemini/v1beta/models/{modelId}:generateContent目标 Gemini Native 普通内容生成接口
POST /api/v1/ai/gateway/gemini/v1beta/models/{modelId}:streamGenerateContent目标 Gemini Native SSE 流式内容生成接口
POST /api/v1/ai/gateway/gemini/v1beta/models/{modelId}:countTokensGemini Native 本地 token 计数接口,不触发上游调用
POST /api/v1/ai/gateway/gemini/v1beta/models/{modelId}:embedContent目标 Gemini Native 单条 embedding 接口
POST /api/v1/ai/gateway/gemini/v1beta/models/{modelId}:batchEmbedContents目标 Gemini Native 批量 embedding 接口
GET /api/v1/ai/gateway/codex/v1/models目标 Codex / Responses API 模型列表接口;兼容 GET /api/v1/ai/gateway/codex/models
POST /api/v1/ai/gateway/codex/v1/responses目标 Codex / Responses API 普通 / 流式响应接口;兼容 POST /api/v1/ai/gateway/codex/responses

/api/v1/ai/gateway/status 当前返回 status=readyready=true、协议端点、Provider 健康快照和 Provider resilience 快照。它用于运维确认网关状态,也可以给外部控制台展示当前可用协议入口。状态接口读取后台快照,不在每次 HTTP 请求中同步探测上游 /models;后台刷新只访问启用的 Provider,避免慢上游拖住后台页面。

状态接口会额外返回模型发现 contract:

  • modelQueryParameters:模型列表支持的查询参数,包括 keywordprovider / providerNamemodel / modelNamecapabilityoperationoperationSupported
  • modelDiscoveryOperations:网关已知 operation 列表,来自运行时 AiModelOperationCapabilities
  • modelDiscoveryEndpoints:按协议列出可用于模型发现的入口,当前包含 OpenAI Compatible /models(兼容 /v1/models)、Codex /codex/v1/models(兼容 /codex/models)、Claude / Anthropic /claude/v1/models 和 Gemini Native /gemini/v1beta/models,并标记是否支持 operation 过滤。
  • providerDiscoveryQueryParameters:Provider 发现支持的筛选参数,包括 providerNameproviderTypecapabilityoperationchannelTypecapabilityProfilerelayProfileenabled
  • providerDiscoveryFilterOptions:从当前 Provider 配置聚合出来的可选值,用于前端或 SDK 动态渲染筛选器。
  • providerDiscoveryProviders:脱敏 Provider 画像列表,包含配置实例名、实际 Provider 类型、默认模型、能力标签、支持 / 过滤的 operation、channelTypecapabilityProfilerelayProfile、fallback 顺序和公开 priority / weight,不返回 apiKeybaseUrl 或 options 配置值。
  • providerDiscoveryOperationCounts:按 operation 聚合当前 Provider 配置覆盖数量,方便控制台快速观察 chat / stream / embedding / response / realtime 等能力是否有可用承接方。

GET /api/v1/ai/gateway/modelsGET /api/v1/ai/gateway/v1/models 返回 OpenAI Compatible object=list / data[] 结构,同时扩展平台模型运营字段:

  • capabilities:模型能力标签。
  • supported_operations:该模型可承接的网关 operation。
  • filtered_operations:该模型因能力标签不足会被网关过滤的 operation。
  • operation_profiles:逐 operation 展示 operationrequired_capabilitysupported

这些扩展字段只用于模型发现、调试和运营展示,不改变 OpenAI Compatible 基础字段 idobjectowned_bycreated 的语义。

/models/v1/models/codex/v1/models/codex/models/claude/v1/models/gemini/v1beta/models 支持平台扩展查询参数,用于开发者工具或运营台直接筛选可用模型:

  • keyword:按 Provider、模型名、展示名或能力标签模糊过滤。
  • provider / providerName:按 Provider 精确过滤。
  • model / modelName:按模型名精确过滤。
  • capability:按能力标签过滤。
  • operation:按网关 operation 过滤,默认只返回支持该 operation 的模型。
  • operationSupported=false:配合 operation 反查会被该 operation 过滤的模型。

SDK 或 Agent 工具接入时,可以将 OpenAI Compatible baseURL 配置为:

text
https://<host>/api/v1/ai/gateway

Claude Code / CC Switch 接入时,可以将 Anthropic Compatible ANTHROPIC_BASE_URL 或 CC Switch Provider Base URL 配置为:

text
https://<host>/api/v1/ai/gateway/claude

AI Gateway Key 可作为 ANTHROPIC_AUTH_TOKEN 使用。Claude Code 和 CC Switch 通常会在 base URL 后追加 /v1/models/v1/messages 等路径,因此配置值不包含 /v1

AI 网关面向 Claude Code / CC Switch / OpenAI SDK 这类开发者工具,使用 AI 模块原生 Gateway Key 模式。后台创建 Gateway Key 后,可以把本次返回的一次性 sk-ai-... 明文密钥直接作为工具侧 API Key:

http
Authorization: Bearer sk-ai-...

Anthropic / Claude 生态工具如果使用 x-api-key 请求头,也可以直接传同一个 sk-ai-...

http
x-api-key: sk-ai-...

Gemini Native SDK 或兼容客户端如果默认把密钥放到查询参数,也可以传:

text
?key=sk-ai-...

这些 Gateway Key 传递方式只作为 AI 网关工具接入的鉴权方式;Web3 等其他 Open Platform 能力仍按服务端 AppKey + AppSecret + HMAC 签名模式调用。

Gateway Key 只保存 hash 和脱敏前缀,列表不会返回明文。Key 禁用 / 过期、IP 白名单不匹配、scope 不匹配、quota 已达上限、模型或 Provider 白名单不匹配都会返回统一错误,不会绕过访问范围和审计链路。

后台或平台 API 的最小授权流程:

  1. 创建 Gateway Key:POST /api/v1/admin/ai/platform/gateway-keys,响应中的 plainKey 只返回一次。
  2. 授权 scope:模型列表 / 详情至少包含 ai:gateway:model:read,模型删除 / 撤销至少包含 ai:gateway:model:write,Organization costs / usage 查询至少包含 ai:gateway:usage:read,Organization Invite / Admin API Key / Organization Certificate / Project Certificate / Organization Spend Alert / Project Spend Alert / Organization Group / Group User / Organization Role / Project Role / Organization Project / Project API Key / Project Rate Limit / Project Group / Project Data Retention / Organization User / Audit Log / Project User / Project Service Account 查询至少包含 ai:gateway:administration:read,Organization Invite 创建 / 删除、Admin API Key 创建 / 删除、Organization Certificate 上传 / 修改 / 删除 / 激活 / 停用、Project Certificate 激活 / 停用、Organization Spend Alert / Project Spend Alert 创建 / 修改 / 删除、Organization Group 创建 / 修改 / 删除、Group User 添加 / 移除、Organization Role / Project Role 创建 / 修改 / 删除、Organization Project 创建 / 更新 / 归档、Project API Key 删除、Project Rate Limit 更新、Project Group 添加 / 移除、Project Data Retention 更新、Organization User 更新 / 删除、Project User 创建 / 更新 / 删除和 Project Service Account 创建 / 删除至少包含 ai:gateway:administration:write,普通 / 流式对话和存储型 Chat Completion 生命周期至少包含 ai:gateway:chat:write,legacy 文本补全至少包含 ai:gateway:completion:write,Responses 查询至少包含 ai:gateway:response:read,Responses 创建 / 删除 / 取消 / 输入 token 统计 / 压缩至少包含 ai:gateway:response:write,Conversation 查询至少包含 ai:gateway:conversation:read,Conversation 创建 / 更新 / 删除和 item 写入至少包含 ai:gateway:conversation:write,Eval / Run / Output Item 查询至少包含 ai:gateway:eval:read,Eval 创建 / 更新 / 删除和 Run 创建 / 取消 / 删除至少包含 ai:gateway:eval:write,Realtime client secret / session / call 创建至少包含 ai:gateway:realtime:write,向量生成至少包含 ai:gateway:embedding:write,内容审核至少包含 ai:gateway:moderation:write,图片生成 / 编辑 / 变体至少包含 ai:gateway:image:write,音频语音 / 转写 / 翻译至少包含 ai:gateway:audio:write,重排至少包含 ai:gateway:rerank:write,文件列表 / 详情 / 内容至少包含 ai:gateway:file:read,文件上传 / 删除和 Upload 创建 / 分片 / 完成 / 取消至少包含 ai:gateway:file:write,批处理查询 / 内容读取至少包含 ai:gateway:batch:read,批处理创建 / 取消至少包含 ai:gateway:batch:write,微调任务查询 / 事件 / 检查点和微调检查点权限查询至少包含 ai:gateway:fine-tuning:read,微调任务创建 / 取消、微调检查点权限创建 / 删除和 Grader 校验 / 运行至少包含 ai:gateway:fine-tuning:write,Vector Store / File / File 内容 / File Batch 查询至少包含 ai:gateway:vector-store:read,Vector Store / File / File Batch 创建、更新、删除、搜索和取消至少包含 ai:gateway:vector-store:write,Container / Container File 查询和内容读取至少包含 ai:gateway:container:read,Container / Container File 创建和删除至少包含 ai:gateway:container:write,Assistant 查询至少包含 ai:gateway:assistant:read,Assistant 创建 / 更新 / 删除至少包含 ai:gateway:assistant:write,Thread / Message / Run / Run Step 查询至少包含 ai:gateway:thread:read,Thread / Message / Run 创建、更新、删除、取消和工具输出提交至少包含 ai:gateway:thread:write;不传 scope 时默认包含这些 AI Gateway 常用 scope。 Gemini Native /gemini/v1beta/models:countTokens 使用 ai:gateway:model:read:generateContent:streamGenerateContent 使用 ai:gateway:chat:write:embedContent:batchEmbedContents 使用 ai:gateway:embedding:write
  3. 按需配置 groupCodequotaLimitexpiresAtallowedIpsallowedModelsallowedProviders 和归属用户 / 租户 / 组织 / 部门。
  4. 工具侧把上一步返回的 sk-ai-... 填入 Authorization: Bearer ...x-api-key

AI Gateway Key 只对 /api/v1/ai/gateway/** 生效。调用 Web3 或其他开放能力时,仍必须使用原有 X-Open-App-KeyX-Open-TimestampX-Open-NonceX-Open-Signature-MethodX-Open-Signature 完成 HMAC 签名。

Codex / Codex-like 客户端接入时,可以将 OpenAI base URL 配置为:

text
https://<host>/api/v1/ai/gateway/codex

该入口使用 Responses API 风格的 /v1/models/v1/responses 路径;如果客户端要求 base URL 已经包含协议版本,也可以配置为 https://<host>/api/v1/ai/gateway/codex/v1。网关同时支持 /codex/models / /codex/responses/codex/v1/models / /codex/v1/responses,当前模型列表已可返回平台可用模型,Responses 已支持普通文本响应、函数调用输出项和 Responses API 风格 SSE 流式事件;外部工具的真实执行仍由客户端或 Agent 按 function call 循环完成。

开发者快速接入

AI 网关第一版推荐先按下面顺序接入:

  1. 在后台 AI 平台创建 Gateway Key。
  2. 记录本次返回的一次性 sk-ai-... 明文。
  3. 给 Key 授权 ai:gateway:model:readai:gateway:chat:write 和按需使用的 ai:gateway:model:writeai:gateway:usage:readai:gateway:administration:readai:gateway:administration:writeai:gateway:completion:writeai:gateway:response:readai:gateway:response:writeai:gateway:conversation:readai:gateway:conversation:writeai:gateway:eval:readai:gateway:eval:writeai:gateway:realtime:writeai:gateway:embedding:writeai:gateway:moderation:writeai:gateway:image:writeai:gateway:audio:writeai:gateway:rerank:writeai:gateway:file:readai:gateway:file:writeai:gateway:batch:readai:gateway:batch:writeai:gateway:fine-tuning:readai:gateway:fine-tuning:writeai:gateway:vector-store:readai:gateway:vector-store:writeai:gateway:assistant:readai:gateway:assistant:writeai:gateway:thread:readai:gateway:thread:write
  4. 在客户端工具里填入对应协议的 base URL 和同一个 sk-ai-...
  5. 先请求模型列表确认鉴权和路由,再发起普通响应或流式响应。

常用工具配置:

工具 / SDKBase URLAPI Key
OpenAI SDK / OpenAI Compatible 工具https://<host>/api/v1/ai/gateway(兼容 https://<host>/api/v1/ai/gateway/v1Authorization: Bearer sk-ai-...
Claude / Anthropic Messages 兼容工具https://<host>/api/v1/ai/gateway/claudeANTHROPIC_AUTH_TOKEN=sk-ai-... 或工具内 API Key
Codex / Responses API 风格客户端https://<host>/api/v1/ai/gateway/codex(兼容 https://<host>/api/v1/ai/gateway/codex/v1Authorization: Bearer sk-ai-...
Gemini Native SDK / 兼容客户端https://<host>/api/v1/ai/gateway/geminiAuthorization: Bearer sk-ai-...x-api-key: sk-ai-... 或查询参数 key=sk-ai-...

复制给 SDK / 工具的最小配置:

bash
# OpenAI Compatible / Cursor / Continue / OpenAI SDK 类客户端
OPENAI_API_KEY=sk-ai-...
OPENAI_BASE_URL=https://<host>/api/v1/ai/gateway
# 客户端要求 base URL 已包含 OpenAI 协议版本时也可使用:
# OPENAI_BASE_URL=https://<host>/api/v1/ai/gateway/v1

# Claude Code / CC Switch / Anthropic Messages 类客户端
ANTHROPIC_AUTH_TOKEN=sk-ai-...
ANTHROPIC_BASE_URL=https://<host>/api/v1/ai/gateway/claude

# Codex / Responses API 风格客户端
CODEX_OPENAI_API_KEY=sk-ai-...
CODEX_OPENAI_BASE_URL=https://<host>/api/v1/ai/gateway/codex
# 客户端不会自动追加 /v1 时也可使用:
# CODEX_OPENAI_BASE_URL=https://<host>/api/v1/ai/gateway/codex/v1

如果客户端使用的是真正的 OpenAI SDK 或 OpenAI Compatible SDK,通常只需要把 SDK 的 apiKey 设为 sk-ai-...,把 baseURL 设为 https://<host>/api/v1/ai/gateway。框架侧不要求接入方引入专用 SDK;第三方服务端也可以直接按 HTTP contract 调用。

最小 HTTP smoke:

bash
curl -H "Authorization: Bearer sk-ai-..." \
  https://<host>/api/v1/ai/gateway/models

curl -X POST https://<host>/api/v1/ai/gateway/organization/projects \
  -H "Authorization: Bearer sk-ai-..." \
  -H "Content-Type: application/json" \
  -d '{"name":"project-smoke"}'

curl -H "Authorization: Bearer sk-ai-..." \
  "https://<host>/api/v1/ai/gateway/organization/projects?limit=20"

curl -X POST https://<host>/api/v1/ai/gateway/organization/invites \
  -H "Authorization: Bearer sk-ai-..." \
  -H "Content-Type: application/json" \
  -d '{"email":"dev@example.com","role":"reader"}'

curl -H "Authorization: Bearer sk-ai-..." \
  "https://<host>/api/v1/ai/gateway/organization/admin_api_keys?limit=20"

curl -X POST https://<host>/api/v1/ai/gateway/organization/certificates/activate \
  -H "Authorization: Bearer sk-ai-..." \
  -H "Content-Type: application/json" \
  -d '{"certificate_ids":["cert-abc"]}'

curl -X POST https://<host>/api/v1/ai/gateway/organization/projects/proj-abc/rate_limits/rl-abc \
  -H "Authorization: Bearer sk-ai-..." \
  -H "Content-Type: application/json" \
  -d '{"max_requests_per_1_minute":60}'

curl -H "Authorization: Bearer sk-ai-..." \
  "https://<host>/api/v1/ai/gateway/organization/users?limit=20"

curl -H "Authorization: Bearer sk-ai-..." \
  "https://<host>/api/v1/ai/gateway/organization/audit_logs?limit=20"

curl -X POST https://<host>/api/v1/ai/gateway/organization/projects/proj-abc/service_accounts \
  -H "Authorization: Bearer sk-ai-..." \
  -H "Content-Type: application/json" \
  -d '{"name":"gateway-smoke"}'

curl -X POST https://<host>/api/v1/ai/gateway/organization/roles \
  -H "Authorization: Bearer sk-ai-..." \
  -H "Content-Type: application/json" \
  -d '{"name":"gateway-role","permissions":["api.groups.read"]}'

curl -H "Authorization: Bearer sk-ai-..." \
  "https://<host>/api/v1/ai/gateway/projects/proj-abc/roles?limit=20"

curl -X POST https://<host>/api/v1/ai/gateway/chat/completions \
  -H "Authorization: Bearer sk-ai-..." \
  -H "Content-Type: application/json" \
  -d '{"model":"log-chat","messages":[{"role":"user","content":"ping"}],"max_tokens":64,"top_p":0.9}'

curl -X POST https://<host>/api/v1/ai/gateway/completions \
  -H "Authorization: Bearer sk-ai-..." \
  -H "Content-Type: application/json" \
  -d '{"model":"gpt-test","prompt":"Write a release note","max_tokens":64}'

curl -X POST https://<host>/api/v1/ai/gateway/responses \
  -H "Authorization: Bearer sk-ai-..." \
  -H "Content-Type: application/json" \
  -d '{"model":"gpt-test","input":"Write a release note"}'

curl -X POST https://<host>/api/v1/ai/gateway/responses/input_tokens \
  -H "Authorization: Bearer sk-ai-..." \
  -H "Content-Type: application/json" \
  -d '{"model":"gpt-test","input":"Count this text"}'

curl -X POST https://<host>/api/v1/ai/gateway/conversations \
  -H "Authorization: Bearer sk-ai-..." \
  -H "Content-Type: application/json" \
  -d '{"metadata":{"source":"smoke"}}'

curl -X POST https://<host>/api/v1/ai/gateway/evals \
  -H "Authorization: Bearer sk-ai-..." \
  -H "Content-Type: application/json" \
  -d '{"name":"smoke-eval","data_source_config":{"type":"custom"},"testing_criteria":[]}'

curl -H "Authorization: Bearer sk-ai-..." \
  "https://<host>/api/v1/ai/gateway/evals/eval-abc/runs?limit=20"

curl -H "Authorization: Bearer sk-ai-..." \
  "https://<host>/api/v1/ai/gateway/evals/eval-abc/runs/run-abc/output_items/item-abc"

curl -X POST https://<host>/api/v1/ai/gateway/evals/eval-abc/runs/run-abc/cancel \
  -H "Authorization: Bearer sk-ai-..."

curl -X POST https://<host>/api/v1/ai/gateway/realtime/client_secrets \
  -H "Authorization: Bearer sk-ai-..." \
  -H "Content-Type: application/json" \
  -d '{"session":{"type":"realtime","model":"gpt-realtime","modalities":["text","audio"]}}'

websocat -H "Authorization: Bearer sk-ai-..." \
  "wss://<host>/api/v1/ai/gateway/realtime?provider=newapi&model=gpt-realtime"

curl -X POST https://<host>/api/v1/ai/gateway/embeddings \
  -H "Authorization: Bearer sk-ai-..." \
  -H "Content-Type: application/json" \
  -d '{"model":"log-embedding","input":["hello","world"],"encoding_format":"float"}'

curl -X POST https://<host>/api/v1/ai/gateway/moderations \
  -H "Authorization: Bearer sk-ai-..." \
  -H "Content-Type: application/json" \
  -d '{"model":"omni-moderation-latest","input":"safe text"}'

curl -X POST https://<host>/api/v1/ai/gateway/images/generations \
  -H "Authorization: Bearer sk-ai-..." \
  -H "Content-Type: application/json" \
  -d '{"model":"gpt-image-1","prompt":"draw spring open","size":"1024x1024"}'

curl -X POST https://<host>/api/v1/ai/gateway/images/edits \
  -H "Authorization: Bearer sk-ai-..." \
  -F model=gpt-image-1 \
  -F prompt="edit spring open" \
  -F image=@source.png \
  -F mask=@mask.png

curl -X POST https://<host>/api/v1/ai/gateway/audio/transcriptions \
  -H "Authorization: Bearer sk-ai-..." \
  -F model=gpt-4o-transcribe \
  -F file=@speech.mp3 \
  -F response_format=json

curl -X POST https://<host>/api/v1/ai/gateway/rerank \
  -H "Authorization: Bearer sk-ai-..." \
  -H "Content-Type: application/json" \
  -d '{"model":"jina-reranker-v2-base-multilingual","query":"spring open","documents":["spring open ai","other"],"top_n":1}'

curl -H "Authorization: Bearer sk-ai-..." \
  "https://<host>/api/v1/ai/gateway/files?purpose=batch&limit=20"

curl -X POST https://<host>/api/v1/ai/gateway/files \
  -H "Authorization: Bearer sk-ai-..." \
  -F purpose=batch \
  -F file=@batch.jsonl

curl -H "Authorization: Bearer sk-ai-..." \
  https://<host>/api/v1/ai/gateway/files/file-abc/content

curl -X POST https://<host>/api/v1/ai/gateway/batches \
  -H "Authorization: Bearer sk-ai-..." \
  -H "Content-Type: application/json" \
  -d '{"input_file_id":"file-abc","endpoint":"/v1/chat/completions","completion_window":"24h"}'

curl -H "Authorization: Bearer sk-ai-..." \
  "https://<host>/api/v1/ai/gateway/batches?limit=20"

curl -X POST https://<host>/api/v1/ai/gateway/fine_tuning/jobs \
  -H "Authorization: Bearer sk-ai-..." \
  -H "Content-Type: application/json" \
  -d '{"model":"gpt-4o-mini-2024-07-18","training_file":"file-abc"}'

curl -H "Authorization: Bearer sk-ai-..." \
  "https://<host>/api/v1/ai/gateway/fine_tuning/jobs?limit=20"

curl -H "Authorization: Bearer sk-ai-..." \
  "https://<host>/api/v1/ai/gateway/fine_tuning/checkpoints/ckpt-abc/permissions?limit=20"

curl -X POST https://<host>/api/v1/ai/gateway/fine_tuning/checkpoints/ckpt-abc/permissions \
  -H "Authorization: Bearer sk-ai-..." \
  -H "Content-Type: application/json" \
  -d '{"project_ids":["proj-abc"]}'

curl -X POST https://<host>/api/v1/ai/gateway/fine_tuning/alpha/graders/validate \
  -H "Authorization: Bearer sk-ai-..." \
  -H "Content-Type: application/json" \
  -d '{"grader":{"type":"string_check","name":"quality","input":"{{sample.output_text}}","reference":"{{item.label}}","operation":"eq"}}'

curl -X POST https://<host>/api/v1/ai/gateway/fine_tuning/alpha/graders/run \
  -H "Authorization: Bearer sk-ai-..." \
  -H "Content-Type: application/json" \
  -d '{"grader":{"type":"string_check","name":"quality","input":"{{sample.output_text}}","reference":"{{item.label}}","operation":"eq"},"item":{"label":"ok"},"model_sample":"ok"}'

curl -X POST https://<host>/api/v1/ai/gateway/vector_stores \
  -H "Authorization: Bearer sk-ai-..." \
  -H "Content-Type: application/json" \
  -d '{"name":"project-docs","file_ids":["file-abc"]}'

curl -X POST https://<host>/api/v1/ai/gateway/vector_stores/vs-abc/search \
  -H "Authorization: Bearer sk-ai-..." \
  -H "Content-Type: application/json" \
  -d '{"query":"billing policy","max_num_results":5}'

复制配置时只需要四类信息:

信息从哪里获取注意事项
Base URL本页上方表格,或用户控制台接入卡片Claude 入口不要额外加 /v1;Codex 同时兼容 /codex/codex/v1,按客户端是否会自动追加 /v1 选择
API KeyAI Gateway Key 创建或轮换响应中的一次性 sk-ai-... 明文列表页只显示脱敏 Key,丢失明文只能轮换或新建
ScopeAI Gateway Key scope 配置模型列表需要 ai:gateway:model:read;Organization costs / usage 需要 ai:gateway:usage:read;Organization Invite / Admin API Key / Organization Certificate / Project Certificate / Organization Spend Alert / Project Spend Alert / Organization Group / Group User / Organization Role / Project Role / Organization Project / Project API Key / Project Rate Limit / Project Group / Project Data Retention / Organization User / Audit Log / Project User / Project Service Account 查询和写入分别需要 ai:gateway:administration:read / ai:gateway:administration:write;对话 / 存储型 Chat Completion / Claude / Codex 需要 ai:gateway:chat:write;legacy 文本补全、Responses、Conversation、Evals、Realtime、向量生成、内容审核、图片类、音频类、重排、文件类、批处理类、微调任务和检查点权限类、Vector Store 文件检索类、Assistant 类和 Thread / Message / Run 类分别需要 ai:gateway:completion:writeai:gateway:response:read / ai:gateway:response:writeai:gateway:conversation:read / ai:gateway:conversation:writeai:gateway:eval:read / ai:gateway:eval:writeai:gateway:realtime:writeai:gateway:embedding:writeai:gateway:moderation:writeai:gateway:image:writeai:gateway:audio:writeai:gateway:rerank:writeai:gateway:file:read / ai:gateway:file:writeai:gateway:batch:read / ai:gateway:batch:writeai:gateway:fine-tuning:read / ai:gateway:fine-tuning:writeai:gateway:vector-store:read / ai:gateway:vector-store:writeai:gateway:assistant:read / ai:gateway:assistant:writeai:gateway:thread:read / ai:gateway:thread:write
ModelGET /models 返回的模型 id,或后台配置的平台模型别名模型名称默认保持上游官方名称,优先复制 /models 返回值;运营配置了别名时也可填别名

如果客户端配置项写的是 OpenAI Base URL,通常填 https://<host>/api/v1/ai/gateway;如果写的是 Anthropic Base URL,通常填 https://<host>/api/v1/ai/gateway/claude。不要把通用 Open Platform HMAC 的 AppSecret 填到这些工具里,AI 网关工具接入只使用 sk-ai-...

模型名称默认保持上游官方名称。平台模型目录可以补展示名、能力、上下文窗口、价格、状态和可选平台别名,但别名只在网关入口解析;网关命中别名后会转换为官方 provider + model,再交给上游 Provider。不要为了前端展示擅自把官方模型名改成平台自定义 id,否则开发者从供应商官网复制的模型名会失效。

OpenAI Compatible chat/completions 入口会把 modelmessagestemperaturetop_pmax_tokens / max_completion_tokenstoolstool_choice 转换为统一 AiModelRequest。其中 max_completion_tokens 优先于 max_tokens,并会按原字段名进入上游 OpenAI Compatible payload;response_formatseedlogprobstop_logprobsparallel_tool_callsstream_optionsmetadatastorereasoning_effortmodalitiespredictionaudioservice_tierweb_search_optionssafety_identifierprompt_cache_key 等未显式建模字段会保存在请求参数映射中,最终由 starter Provider 透传给上游。复杂 messages[].content 会保留原始数组或对象并提取文本摘要用于内部计量,tool_call_idtool_callsfunction_call 会透传到 starter;messages[] 内部未显式建模的 audiorefusalcache_control 等消息级扩展字段会写入消息 metadata,并由 starter Provider 用原字段名带给上游。普通响应和流式片段的 model 会优先使用上游响应 / SSE event 返回的实际模型名,便于观察平台别名、聚合网关路由或上游自动切换后的真实命中模型。普通响应会优先恢复上游完整 choices[],多候选场景下每个候选的 messagefinish_reasonlogprobscontent_filter_results 都会按原结构输出;普通响应和流式响应还会保真返回上游 choice indexcontent_filter_results、顶层 prompt_filter_resultsmessage.namemessage.tool_callsmessage.function_callmessage.reasoning_contentmessage.reasoning_detailsmessage.refusalmessage.annotationsmessage.audio、显式返回的 delta.roledelta.namedelta.tool_callsdelta.function_calldelta.reasoning_detailsdelta.refusaldelta.annotationsdelta.audio 和 choice 级 logprobs,便于 OpenAI Compatible SDK / Agent 工具继续执行工具调用循环、展示推理内容与结构化推理详情、响应注解或评估 token 概率;上游返回的 prompt_tokens_detailscompletion_tokens_detailsprompt_cache_hit_tokensprompt_cache_miss_tokenscache_creation_input_tokenscache_read_input_tokensinput_tokens_detailsoutput_tokens_details 会进入 usage metadata,并在网关 OpenAI Compatible 响应中按原字段输出。上游顶层 system_fingerprintservice_tier 也会在普通响应和流式片段中保留,方便 SDK、审计和故障排查识别服务侧版本或服务层级。

常见错误

现象常见原因处理方式
401 / 签名无效API Key 不存在、已禁用、已过期或复制了内部 ID重新生成 sk-ai-... 明文;确认只把 sk-ai-... 填给工具
403 / scope 不匹配Gateway Key 没有授权当前入口要求的 ai:gateway:* scope在后台 AI 平台补齐 Gateway Key scope
403 / 模型或 Provider 不允许Gateway Key 配置了 allowedModelsallowedProviders,但当前请求解析后的模型或 Provider 不在白名单中调整 Key 白名单,或使用 /models 和后台路由配置确认实际模型 / Provider
429 / 限流应用、Key、用户或 Provider 触发分钟级、日级或并发限额调整 spring.open.ai.gateway.rate-limit.* 或后台限流配置
429 / 断连风控断连逃费风控开启(abort-guard.enabled=true)且当前用户 / Key 窗口内断连占比超阈值正常用户可放宽 max-abort-ratio / 增大 min-samples;持续高断连的用户 / Key 需排查是否逃费
余额不足应用绑定套餐且套餐单价大于 0,但账务账户可用余额不足充值、补款,或调整套餐 / 价格策略
模型不存在请求模型名不在当前模型目录、别名未配置、模型被停用、未开放,或上游不支持先调用 /models 查看可用模型;如使用别名,确认后台模型目录已启用覆盖并开放该模型
上游认证失败Provider API Key 未配置、失效或没有访问该模型权限检查对应 Provider 的 API Key、base URL 和模型权限
流式响应中断客户端断开、网络代理超时或上游流异常网关会释放预占额度;排查 Nginx / 代理超时和 Provider 日志
工具自动拼出重复路径Base URL 已带 /v1,工具又自动追加 /v1/messages/v1/responsesClaude 入口配置到 /claude;Codex 优先配置到 /codex,已发给用户的 /codex/v1 配置仍兼容
Web3 等接口无法用 sk-ai-... 调用sk-ai-... Gateway Key 只服务 AI 网关Web3、支付等通用开放 API 继续使用 AppKey + AppSecret + HMAC 签名

上游错误会被归一成网关兼容协议错误,并保留平台 requestId。排障时优先用 requestId 到后台调用日志、用量事件和 Provider 健康快照里查询。

价格口径

AI 模型价格默认使用主流供应商更常见的 1M tokens 展示口径。平台响应会同时给出计费单位名称和 billingUnitSize=1000000,方便后台和前端换算:

字段说明
billingUnit展示单位,默认 1M tokens
billingUnitSize计费单位大小,默认 1000000
input-price-per-1m-tokens输入 token 平台售价
output-price-per-1m-tokens输出 token 平台售价
input-cost-per-1m-tokens输入 token 官方成本
output-cost-per-1m-tokens输出 token 官方成本

计费层仍按实际 token 数结算,不把 token 当成余额本身。历史调用会固化当时的平台售价、官方成本、币种、汇率和毛利快照,后续修改价格不会回算历史账单。

配置

yaml
spring:
  open:
    ai:
      gateway:
        enabled: true
        key-auth:
          enabled: true
        realtime:
          enabled: true
          path: /api/v1/ai/gateway/realtime
          connect-timeout: 10s
          pending-message-limit: 32
        health:
          distributed-enabled: true
          snapshot-ttl: 10m
        rate-limit:
          enabled: true
          app-per-minute: 0
          app-per-day: 0
          app-max-concurrent: 0
          key-per-minute: 60
          key-per-day: 0
          key-max-concurrent: 0
          user-per-minute: 120
          user-per-day: 0
          user-max-concurrent: 0
          provider-per-minute: 600
          provider-per-day: 0
          provider-max-concurrent: 0
        abort-guard:
          enabled: false
          window: 10m
          min-samples: 20
          max-abort-ratio: 0.5
          user-dimension-enabled: true
          key-dimension-enabled: true
        abort-settlement:
          enabled: true
配置默认值说明
spring.open.ai.gateway.enabledtrue是否启用 AI 模型网关接口
spring.open.ai.gateway.key-auth.enabledtrue是否启用 AI Gateway Key 鉴权;默认开启,避免模型网关裸露;本地模拟模型或研究学习环境如需裸调,可显式关闭
spring.open.ai.gateway.realtime.enabledtrue是否启用 Realtime WebSocket 双向 relay
spring.open.ai.gateway.realtime.path/api/v1/ai/gateway/realtimeRealtime WebSocket 本地接入路径
spring.open.ai.gateway.realtime.default-modelRealtime WebSocket 请求未传 model 时使用的默认模型
spring.open.ai.gateway.realtime.connect-timeout10s网关连接上游 Realtime WebSocket 的超时时间
spring.open.ai.gateway.realtime.pending-message-limit32上游连接建立前允许暂存的客户端文本消息数;超过后关闭连接
spring.open.ai.gateway.health.distributed-enabledtrue是否在存在 RedisManager 时启用 Provider 健康快照多实例聚合
spring.open.ai.gateway.health.snapshot-ttl10m单实例 Provider 健康快照保留时间,实例异常退出后超过该时间自动不再参与聚合
spring.open.ai.gateway.status-snapshot.refresh-interval30sAI Gateway status 后台快照刷新间隔;接口仅读取最近一次快照
spring.open.ai.gateway.rate-limit.enabledtrue是否启用 AI 网关专属限流
spring.open.ai.gateway.rate-limit.app-per-minute0AI 网关访问上下文分钟限流;小于等于 0 表示不限
spring.open.ai.gateway.rate-limit.app-per-day0AI 网关访问上下文每日限额;小于等于 0 表示不限
spring.open.ai.gateway.rate-limit.app-max-concurrent0AI 网关访问上下文并发限额;小于等于 0 表示不限
spring.open.ai.gateway.rate-limit.key-per-minute60单个 Gateway Key 每分钟允许调用次数;小于等于 0 表示不限
spring.open.ai.gateway.rate-limit.key-per-day0单个 Gateway Key 每日允许调用次数;小于等于 0 表示不限
spring.open.ai.gateway.rate-limit.key-max-concurrent0单个 Gateway Key 最大并发调用数;小于等于 0 表示不限
spring.open.ai.gateway.rate-limit.user-per-minute120单个 Key 归属用户每分钟允许调用次数;小于等于 0 表示不限
spring.open.ai.gateway.rate-limit.user-per-day0单个 Key 归属用户每日允许调用次数;小于等于 0 表示不限
spring.open.ai.gateway.rate-limit.user-max-concurrent0单个 Key 归属用户最大并发调用数;小于等于 0 表示不限
spring.open.ai.gateway.rate-limit.provider-per-minute600单个 Provider 每分钟允许调用次数;请求未显式指定 Provider 时归入 default
spring.open.ai.gateway.rate-limit.provider-per-day0单个 Provider 每日允许调用次数;请求未显式指定 Provider 时归入 default
spring.open.ai.gateway.rate-limit.provider-max-concurrent0单个 Provider 最大并发调用数;请求未显式指定 Provider 时归入 default
spring.open.ai.gateway.abort-guard.enabledfalse客户端流式断连(499)逃费风控;默认关闭,断连仍按“失败即免单”整体释放。仅在真实断连率数据证实逃费滥用后由运营开启
spring.open.ai.gateway.abort-guard.window10m断连统计滚动窗口长度
spring.open.ai.gateway.abort-guard.min-samples20触发判定所需的窗口内最小请求样本数;样本不足不判定,避免低流量误伤
spring.open.ai.gateway.abort-guard.max-abort-ratio0.5断连占比阈值(窗口内断连数 / 请求数);样本足够且达到该占比时在请求准入阶段拒绝(429),不改计费语义、不做部分结算
spring.open.ai.gateway.abort-guard.user-dimension-enabledtrue是否按归属用户维度统计与拦截断连占比
spring.open.ai.gateway.abort-guard.key-dimension-enabledtrue是否按 API Key 维度统计与拦截断连占比
spring.open.ai.gateway.abort-settlement.enabledtrue客户端断连「已传输即按量结算」(ADR-072):默认开启。客户端主动断连时只对已成功传输给客户端的 delta 按 token 估算部分结算(不计 prompt / 未传输 / 最终完整响应);服务端 / 上游异常、无已传输内容或估算失败仍失败即免单。关闭后断连一律失败即免单整体释放

客户端在流式响应写出期间主动断开的请求统一归类 result_code=499默认计费语义为「已传输即按量结算」(ADR-072,默认开启):只对已成功传输给客户端的 delta 按 token 估算做部分结算,input=0,不计 prompt、未传输内容或模型最终完整响应;服务端 / 上游异常、无已传输内容或 token 估算失败仍走「失败即免单」整体释放(不扣费、不落台账)。部分结算的用量事件为 result_code=499billable=true(免单断连为 499 且 billable=false),并把 client-abort-partial-settlement 显式落库到 ai_usage_event.settlement_sourceai_merchant_ledger.settlement_source(正常成功结算为空),商家结算单经其组成台账 + usageEventId 回链,四方对账证据接口在用量事件证据中输出 settlementSource。启用即改变默认计费语义,生产运营须配套公告 / 用户协议条款 / 风控策略;未就绪的部署可显式设 spring.open.ai.gateway.abort-settlement.enabled=false 回到失败即免单。

断连逃费风控守卫(abort-guard,ADR-071)与部分结算相互独立,默认关闭,属监控先行能力:先按 result_code=499 统计断连率分布,确认存在异常高占比的用户 / Key 后再开启,按样本足够且断连占比超阈值在请求准入阶段拒绝疑似逃费流量。

全局 spring.open.ai.enabled=false 时,AI 模块和网关都会关闭。

上线就绪信号由 GET /api/v1/admin/ai/platform/quality 返回;需要保存一次上线检测记录时,由后台 AI 平台质量页或 POST /api/v1/admin/ai/platform/production-checks/run 主动触发。检测会检查专用密钥、Gateway Key 鉴权、真实上游、启用 Key、真实 smoke 和 billing 决策,并执行低成本 Provider smoke。检查结果只用于后台运营判断,不在 /api/v1/ai/gateway/** 请求链路增加额外生产阻断,避免影响模型调用性能。

网关职责

网关是高频调用路径,只负责调用链中必须完成的动作:

  1. 校验 AI Gateway Key 和 scope。
  2. 解析模型别名和 Provider 路由。
  3. 做额度预检和限流判断。
  4. 调用 spring-open-starter-ai-model 的 Provider SPI。
  5. 处理普通响应和流式响应。
  6. 记录 usage、token、耗时、状态、requestId 和错误。
  7. 触发计量扣费或失败释放。

供应商配置、模型价格、后台报表、人工操作和用户控制台不放在网关控制器里,统一走 AI 模型平台 控制面。

普通响应 Pipeline

普通响应入口(OpenAI Compatible chat/completions、Claude Messages 和 Codex Responses)会在协议转换后进入短同步 Pipeline ai.gateway.invoke

  1. ai-gateway-invoke-resolve-model:解析模型别名和 Provider 元数据。
  2. ai-gateway-invoke-acquire-concurrency:执行 AI 网关专属限流和并发占用。
  3. ai-gateway-invoke-reserve-billing:进入 Provider 前预占套餐 / 余额费用。
  4. ai-gateway-invoke-call-model:调用 AiModelManager.chat(...)
  5. ai-gateway-invoke-record-success:按实际用量结算,并记录 Provider / Credential 健康。

Pipeline 禁用或未注入时会回退到原直接调用路径,接口契约不变。Provider 抛出结构化异常时,网关会释放预占、释放并发占用并记录健康失败。流式响应仍由 SSE 生命周期单独控制释放和写出失败处理,避免把长连接生命周期塞进短同步 Pipeline。

用量计量

AI 网关成功通过 Gateway Key 鉴权后,会为普通响应和流式响应记录 ai_usage_event

字段含义
providerName实际命中的 Provider 配置实例名;不受 OpenAI / Anthropic 等传输协议切换影响,并与模型价格的 Provider 维度一致
modelName实际调用的模型
fallbackUsed本次调用是否通过 fallback Provider 成功返回
primaryProviderNamefallback 前的主 Provider
actualProviderNamefallback 后实际成功的 Provider
routeStrategy本次路由命中的策略,例如默认、优先级、权重或模型不可用降级
routeReason路由策略给出的命中原因,方便排查为什么切换 Provider
routeCandidateProviders本次路由评估过的候选 Provider 列表
inputTokens / outputTokens / totalTokens模型返回的 token 用量
stream是否流式响应
latencyMs网关侧调用耗时
traceId本次请求 trace id

AI Gateway Key 调用不使用普通开放接口“一次请求 = 一个单位”的默认计量,避免和 token 计量重复。

后台 AI 用量事件页面可直接按 Provider、模型、fallback 状态、主 Provider、实际 Provider、流式状态和 Trace ID 查询,并在列表 / 详情中查看路由策略、候选 Provider、路由原因、token、延迟和成本快照。排查供应商异常时,优先用 traceId 定位单次调用,再对比 primaryProviderNameactualProviderNamefallbackUsedrouteReason 判断是配置路由、模型不可用降级还是上游异常导致的切换。

套餐配额预检使用同一张 usage event 的可计费用量单元统计:AI 网关按模型返回的 token 用量、模型倍率和分组倍率计算 quota。因此 Key 日 / 月配额会按模型消耗判断是否继续放行,而不是只按请求次数判断。

AI 网关 quota 计费默认关闭,保证本地研究学习、模拟模型和早期接入时不会因为余额或套餐未配置而阻断调用。管理员显式开启 spring.open.ai.gateway.billing.enabled=true 后,请求进入 Provider 前会按预估 input token、max_tokens、模型倍率和分组倍率生成预占快照。

Provider 抛出结构化异常、流式写出异常或客户端断开时会释放本次预占;成功响应按 Provider 返回后的实际 token usage 和 quota 规则写入 ai_usage_event。Gateway Key 的 quotaUsed 会在用量事件落库后按 quotaCount 增量更新,用于 Key 级 quota 上限治理。

AI 网关普通响应和流式响应都已自动接入这三个动作:进入 Provider 前通过 AI Model starter 的 AiModelTokenEstimator 预估输入 token,并结合 max_tokens 生成预计 quota;Provider 成功返回或流式结束片段返回后按实际 usage 结算;失败或中断时释放本次预占,避免长连接异常留下错误占用。

AI 网关 quota 属于平台内部微计量单位,统一保留 6 位小数并使用向下截断,不做四舍五入。真实充值、收款和余额账户仍由 Cashier / Payment / Money 等业务底座按各自规则承接,AI 网关不在 Controller 中直接处理支付渠道。

默认 AiModelTokenEstimator 基于 jtokkit,会优先按模型名匹配 tokenizer,无法匹配时使用 cl100k_base,再失败时按字符数兜底估算。预估只用于预检和预占,最终扣费仍以 Provider 返回的真实 usage 为准。

限流

AI 网关进入 Provider 前会复用 Rate Limit starter 做分钟级限流、可选每日限额和可选并发限额:

  • spring.open.ai.gateway.rate-limit.app-per-minute 默认 0,表示不额外执行应用桶;需要 AI 网关按 Key 映射的访问上下文单独限制时配置为大于 0
  • API Key 桶按当前通过校验的 Gateway Key 隔离,避免多个 Key 相互影响。
  • 用户桶按 Gateway Key 归属用户隔离,限制同一用户名下多个 Key 的整体 AI 网关压力;Key 没有归属用户时会自动跳过用户桶。
  • Provider 桶按请求中的 provider 字段隔离;未显式传 Provider 时进入 default 桶,用于约束默认 Provider 路由压力。
  • *-per-day 默认关闭;需要日限额时按 App / API Key / 用户 / Provider 分别配置为大于 0 的值。
  • *-max-concurrent 默认关闭;配置为大于 0 后按 App / API Key / 用户 / Provider 统计正在执行的 in-flight 调用。普通响应在 Provider 返回或异常后释放;流式响应在流结束、写出异常或客户端断开后释放。

这些限流只在鉴权通过后执行。被限流拒绝时返回统一业务码 429,不会进入 Provider,也不会产生余额预占。

多实例部署时,AI 网关默认可继续使用 Rate Limit starter 的 redis 固定窗口 store;如果要更接近配额桶 / 令牌桶语义,可切换为 redisson store:

yaml
spring:
  open:
    rate-limit:
      default-store: redisson

redisson store 复用 Data Redis starter 的 RedissonManager,不会把 Redisson API 暴露给 AI 网关业务代码。

Provider 健康状态

AI 网关会维护 Provider 健康快照,并通过网关状态接口返回。单实例或 Redis 不可用时使用当前进程内快照;存在 RedisManagerspring.open.ai.gateway.health.distributed-enabled=true 时,会按实例 + Provider 维度写入共享 Redis key,状态接口返回多实例聚合结果。

字段含义
providerProvider 名称;请求未显式指定 Provider 时使用 default
successCount成功调用次数;多实例聚合开启时为共享聚合值
failureCount失败调用次数;多实例聚合开启时为共享聚合值
rateLimitedCount被 AI 网关限流拒绝次数;多实例聚合开启时为共享聚合值
timeoutCountProvider 超时失败次数;多实例聚合开启时为共享聚合值
retryableFailureCount适合 fallback 或稍后重试的失败次数;多实例聚合开启时为共享聚合值
fallbackSuccessCount通过 fallback Provider 成功完成的次数;多实例聚合开启时为共享聚合值
failureRate失败率,按 failure / (success + failure) 计算
lastSuccessAt / lastFailureAt / lastRateLimitedAt最近成功、失败、限流时间
lastTimeoutAt / lastRetryableFailureAt最近 Provider 超时和最近可重试失败时间
lastFallbackSuccessAt最近一次 fallback Provider 成功时间
lastErrorType / lastErrorCode / lastErrorMessage最近一次失败摘要

状态接口还会返回 providerResilience,展示 AI Model starter 当前进程内的 Provider + model 维度韧性快照:

字段含义
provider / modelProvider 和模型
circuitBreakerState熔断器状态,例如 CLOSEDOPENHALF_OPEN
failureRate / slowCallRateResilience4j 当前窗口失败率和慢调用率
bufferedCalls / successfulCalls / failedCalls当前窗口调用统计
slowCalls / notPermittedCalls慢调用数和熔断拒绝调用数

这一步只做轻量运行时观测,方便开发者快速判断 Provider 是否异常;fallback 成功会由 AI Model starter 在响应元数据中标记,AI Gateway 状态接口会按实际成功 Provider 统计。AI 网关用量事件会同步固化 fallbackUsedprimaryProviderNameactualProviderName,后台可按 fallback 状态和 Provider 查询审计。

告警事件源

AI 网关会在关键异常点发布 Spring 应用事件 AiGatewayAlertEvent,用于后续通知、审计或观测模块监听消费。事件发布与主调用链隔离:监听器异常只记录告警,不会影响模型调用、计量、扣费释放或限流返回。

当前已接入的事件源:

事件类型触发时机主要字段
ai.provider-failureProvider 调用失败、超时或可重试失败被健康服务记录时Provider、模型、Key、scope、traceId、错误类型、状态码、失败计数
ai.rate-limitedAI 网关 App / Key / 用户 / Provider 限流或并发限额拒绝时Provider、模型、Key、scope、traceId、限流计数
ai.package-exhaustedAI 网关账务预占前发现套餐不可用时Key、scope、traceId、套餐 ID、原因
ai.balance-lowAI 网关按预计 token 费用预占账务余额失败时Key、scope、traceId、币种、预计金额、预计 token 数、错误摘要
ai.key-exceptionAI 网关 Bearer Key 缺失、禁用、过期、IP 禁止、Scope 禁止或白名单不匹配时Key、scope、path、traceId、请求 IP、异常原因

事件会带 dedupeKey,Notification 规则可按事件类型、Provider、模型、Key 和原因做去重、升级、接收人和渠道选择。当前应用层已监听 AiGatewayAlertEvent 并投递通知发送记录;用户侧 PC / App 消息中心后续按 AI 控制台路由打开开发者控制台。

成本快照

每条 AI 用量事件会固化一份成本快照,避免后续套餐价格、供应商成本或汇率调整后影响历史账务核算:

成本快照严格按本次实际命中的 providerName + modelName 查找价格。providerName 使用 Provider 配置实例名(例如 deepseek),openai-compatibleanthropic-compatible 只表示执行适配器或传输协议,不会覆盖计费、用量汇总和毛利报表的 Provider 归属。

字段含义
platformUnitPrice / platformCostAmount平台对用户计费的单价和本次平台侧金额
officialUnitPrice / officialCostAmount供应商官方成本单价和本次官方成本金额
pricingCurrency / officialCurrency平台计价币种和供应商成本币种
exchangeRate官方成本币种折算到平台计价币种的汇率
grossProfitAmount / grossMarginRate本次调用的毛利金额和毛利率基础字段

当前第一阶段先以应用套餐单价作为平台价格快照,官方成本价默认留空为 0,汇率默认 1。后续 Provider 价格配置、成本 / 毛利报表、限流熔断和审计查询会继续复用这条 usage event。

OpenAI Compatible Contract

第一版优先支持 OpenAI Compatible 格式,降低开发者接入成本。

请求头:

http
Authorization: Bearer sk-ai-...
Content-Type: application/json

Claude Code / CC Switch 可以把平台返回的 sk-ai-... 填到 ANTHROPIC_AUTH_TOKEN、Provider API Key 或工具自己的 API Key 配置项中。网关会用该密钥定位 Gateway Key,再校验 Key 是否拥有 ai:gateway:model:readai:gateway:chat:write scope。

models 已复用 AI Model starter 的模型元数据,返回 OpenAI Compatible 风格响应:

json
{
  "object": "list",
  "data": [
    {
      "id": "log-chat",
      "object": "model",
      "owned_by": "log",
      "display_name": "Log Chat",
      "capabilities": ["chat", "stream"],
      "context_window": 8192,
      "max_output_tokens": 2048
    }
  ]
}

/claude/v1/models 同样复用 AI Model starter 的模型元数据,返回 Claude / Anthropic Models 风格响应:

json
{
  "data": [
    {
      "type": "model",
      "id": "log-chat",
      "display_name": "Log Chat"
    }
  ],
  "first_id": "log-chat",
  "last_id": "log-chat",
  "has_more": false
}

如果模型元数据中包含 created_atcreatedAt 扩展字段,响应会透出 created_at;未配置时省略该字段。

completions 入口用于兼容 legacy OpenAI Compatible 文本补全协议,请求和响应结构原样透传上游,同时仍进入模型别名、Provider 路由、Gateway Key、限流、quota、usage event、Provider 健康和凭证健康链路。

请求示例:

http
POST /api/v1/ai/gateway/completions
Authorization: Bearer sk-ai-...
Content-Type: application/json
json
{
  "model": "gpt-test",
  "prompt": "Write a release note",
  "max_tokens": 64
}

响应示例:

json
{
  "id": "cmpl-...",
  "object": "text_completion",
  "model": "gpt-test",
  "choices": [
    {
      "index": 0,
      "text": "Release note...",
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 6,
    "completion_tokens": 12,
    "total_tokens": 18
  }
}

chat/completions 第一版已支持普通响应和 text/event-stream 流式响应。普通响应如果上游返回顶层 object,网关会优先输出上游对象类型;普通响应如果上游返回多个 choices[],网关会恢复完整候选数组;上游普通响应 message 如果返回 role / name,网关会按原结构输出 message.role / message.name;上游普通响应 message 如果返回 reasoning_contentreasoningthinking,网关会归一输出 message.reasoning_content;上游普通响应 message 如果返回 reasoning_details,网关会按原结构输出 message.reasoning_details;上游 SSE event 如果返回顶层 id / created,网关会优先按上游事件值输出;上游 SSE delta 如果返回 role,网关会按 delta.role 输出,未返回时不伪造角色字段;上游 SSE delta 如果返回 name,网关会按 delta.name 输出;上游 SSE delta 如果返回 reasoning_contentreasoningthinking,网关会在 OpenAI Compatible 响应中输出 delta.reasoning_content,便于支持推理过程展示的客户端消费;上游 SSE delta 如果返回 reasoning_details,网关会按原结构输出 delta.reasoning_details。上游 message / delta 如果返回 refusalannotationsaudio,网关会按普通响应 message.* 或流式响应 delta.* 原字段输出;上游 choice 如果返回 indexlogprobscontent_filter_resultsfinish_detailsnative_finish_reason,普通响应和流式片段会按 choice 级字段原样输出。上游 choice 返回 finish_reason 时,网关会输出独立 finish chunk;最终 usage chunk 只承载 usage,不重复 finish reason。上游顶层 prompt_filter_results 会在普通响应和流式片段中保留。上游 usage 如果返回 token 明细,普通响应和流式最终块会保留 prompt_tokens_details / completion_tokens_details / prompt_cache_hit_tokens / prompt_cache_miss_tokens / cache_creation_input_tokens / cache_read_input_tokens / input_tokens_details / output_tokens_details 等细分字段,用于观察缓存 token、推理 token 或输入 / 输出 token 细节;上游 system_fingerprintservice_tier 会作为 OpenAI Compatible 顶层响应字段输出。请求侧 messages[] 未显式建模字段会作为消息级扩展字段透传,上游需要 audiorefusalcache_control 或其它兼容字段时不需要改 Provider 代码。

字段说明
model平台模型别名或上游模型名
messages对话消息
streamfalse 返回完整 chat.completiontrue 返回 OpenAI Compatible SSE 片段并以 data: [DONE] 结束
temperature采样温度
top_pnucleus sampling 参数,透传到底层 OpenAI Compatible Provider
max_tokens最大输出 token
max_completion_tokens最大输出 token,优先级高于 max_tokens,并按原字段名透传给 OpenAI Compatible Provider
tools工具定义列表,透传给上游 Provider
tool_choice工具选择策略,透传给上游 Provider
其它 OpenAI Compatible 字段例如 response_formatseedlogprobstop_logprobsparallel_tool_callsstream_optionsmetadatastorereasoning_effortmodalitiespredictionaudioservice_tierweb_search_optionssafety_identifierprompt_cache_key 等扩展字段会作为请求参数保留并透传给 Provider
messages[].content支持字符串或复杂 content 数组;内部会提取文本摘要,同时保留原始结构给上游
messages[].tool_call_id工具结果消息对应的调用 ID
messages[].tool_calls助手消息中的工具调用列表
messages[].function_call旧版函数调用结构

请求示例:

http
POST /api/v1/ai/gateway/chat/completions
Authorization: Bearer sk-ai-...
Content-Type: application/json
json
{
  "model": "log-chat",
  "messages": [
    {
      "role": "user",
      "content": "ping"
    }
  ],
  "temperature": 0.2,
  "max_tokens": 128
}

响应示例:

json
{
  "id": "chatcmpl-...",
  "object": "chat.completion",
  "created": 1770000000,
  "model": "log-chat",
  "system_fingerprint": "fp_abc",
  "service_tier": "default",
  "prompt_filter_results": [
    { "prompt_index": 0, "content_filter_results": { "hate": { "filtered": false } } }
  ],
  "choices": [
    {
      "index": 2,
      "message": {
        "role": "assistant",
        "content": "pong",
        "annotations": [
          { "type": "url_citation", "url": "https://example.test" }
        ]
      },
      "finish_reason": "stop",
      "content_filter_results": {
        "hate": { "filtered": false }
      },
      "logprobs": {
        "content": [
          {
            "token": "pong",
            "logprob": -0.1
          }
        ]
      }
    }
  ],
  "usage": {
    "prompt_tokens": 4,
    "completion_tokens": 2,
    "total_tokens": 6,
    "prompt_tokens_details": {
      "cached_tokens": 2
    },
    "completion_tokens_details": {
      "reasoning_tokens": 1
    }
  }
}

流式响应示例:

text
data: {"id":"chatcmpl-...","object":"chat.completion.chunk","created":1770000000,"model":"log-chat","system_fingerprint":"fp_abc","service_tier":"default","prompt_filter_results":[{"prompt_index":0,"content_filter_results":{"hate":{"filtered":false}}}],"choices":[{"index":2,"delta":{"role":"assistant","content":"pong","annotations":[{"type":"url_citation","url":"https://example.test"}]},"content_filter_results":{"hate":{"filtered":false}},"logprobs":{"content":[{"token":"pong","logprob":-0.1}]}}]}

data: {"id":"chatcmpl-...","object":"chat.completion.chunk","created":1770000000,"model":"log-chat","choices":[{"index":0,"delta":{"reasoning_content":"plan first"}}]}

data: {"id":"chatcmpl-...","object":"chat.completion.chunk","created":1770000000,"model":"log-chat","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":4,"completion_tokens":2,"total_tokens":6,"prompt_tokens_details":{"cached_tokens":2},"completion_tokens_details":{"reasoning_tokens":1}}}

data: [DONE]

工具调用普通响应示例:

json
{
  "id": "chatcmpl-...",
  "object": "chat.completion",
  "created": 1770000000,
  "model": "log-chat",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": null,
        "tool_calls": [
          {
            "id": "call_1",
            "type": "function",
            "function": {
              "name": "lookup_order",
              "arguments": "{\"id\":\"A100\"}"
            }
          }
        ]
      },
      "finish_reason": "tool_calls"
    }
  ]
}

工具调用流式片段示例:

text
data: {"id":"chatcmpl-...","object":"chat.completion.chunk","created":1770000000,"model":"log-chat","choices":[{"index":0,"delta":{"role":"assistant","tool_calls":[{"index":0,"id":"call_1","type":"function","function":{"name":"lookup_order","arguments":"{}"}}]}}]}

data: {"id":"chatcmpl-...","object":"chat.completion.chunk","created":1770000000,"model":"log-chat","choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":4,"completion_tokens":6,"total_tokens":10}}

data: [DONE]

/embeddings 使用 OpenAI Compatible 请求和响应格式,进入同一条模型别名、Provider 路由、Gateway Key、限流、quota 和用量事件链路。该入口不做流式响应,适合 Knowledge 检索、项目多语言文本向量化、搜索召回和向量数据库写入前的统一调用。

字段说明:

字段说明
model平台模型别名或上游 embedding 模型名
input字符串、字符串数组、token 数组或 OpenAI Compatible 允许的输入结构
encoding_format可选,常见值为 floatbase64
dimensions可选,指定输出向量维度,只有上游模型支持时才生效
user可选最终用户标识,会透传给上游兼容服务

请求示例:

http
POST /api/v1/ai/gateway/embeddings
Authorization: Bearer sk-ai-...
Content-Type: application/json
json
{
  "model": "text-embedding-3-small",
  "input": [
    "hello",
    "world"
  ],
  "encoding_format": "float"
}

响应示例:

json
{
  "object": "list",
  "data": [
    {
      "object": "embedding",
      "index": 0,
      "embedding": [0.0123, -0.0456]
    },
    {
      "object": "embedding",
      "index": 1,
      "embedding": [0.0789, 0.0123]
    }
  ],
  "model": "text-embedding-3-small",
  "usage": {
    "prompt_tokens": 2,
    "completion_tokens": 0,
    "total_tokens": 2
  }
}

/organization/costs/organization/usage/{usageType}/organization/invites/organization/admin_api_keys/organization/certificates、Project Certificates、/organization/spend_alerts、Project Spend Alerts、/organization/groups、Group Users、/organization/roles、Project Roles、Organization / Project Role Assignments、/organization/projects、Project Groups、Project Data Retention、/organization/users/organization/audit_logs、Project Users、Project Service Accounts、/chat/completions 存储型生命周期、/completions/responses/conversations/evals/realtime/moderations/images/generations/images/edits/images/variations/audio/speech/audio/transcriptions/audio/translations/rerank/files/uploads/batches/fine_tuning/jobs/fine_tuning/checkpoints/fine_tuning/alpha/graders/vector_stores/containers/assistants/threads 使用 AI Model starter 的通用 relay contract。它们仍然进入同一条模型别名、Provider 路由、Gateway Key、限流、quota、usage event、Provider 健康和凭证健康链路;区别是请求 payload、multipart 文件、HTTP method 和路径参数会按 OpenAI Compatible 非对话协议原样转发给上游,响应也会尽量保留上游结构。

通用 relay 会保留调用方显式传入的 model。如果调用方没有在 payload 中显式传 model,Provider 只会在 legacy 文本补全、Responses 创建、旧版 Realtime session 创建、内容审核、图片、音频、重排、微调创建、Assistant 创建 / 更新、Thread 创建并运行和 Run 创建 / 更新这类模型型 endpoint 上补默认模型;Organization costs / usage、Organization Invite / Admin API Key / Organization Certificate / Project Certificate / Organization Spend Alert / Project Spend Alert / Organization Group / Group User / Organization Role / Project Role / Role Assignment / Organization Project / Project API Key / Project Rate Limit / Project Group / Project Data Retention / Organization User / Audit Log / Project User / Project Service Account 管理、新版 Realtime client_secrets / calls、Realtime transcription session、文件、Uploads、批处理列表 / 详情、存储型 Chat Completion 列表 / 详情 / 更新 / 删除 / 消息列表、Responses 详情 / 删除 / 取消 / input items、Conversation 管理、Eval / Run 取消 / Output Item 管理、微调列表 / 详情、微调检查点权限、Grader 校验 / 运行、Vector Store / File / File 内容 / File Batch 查询和管理、Container / Container File 查询和管理、Assistant 查询 / 删除、Thread 查询 / 删除、Message 查询 / 删除和 Run Step 查询不会自动追加 model query。

Realtime WebSocket 使用独立的 /api/v1/ai/gateway/realtime 握手入口。客户端可通过 Authorization: Bearer sk-ai-...X-API-Key / x-api-key 或仅在浏览器受限场景下通过 access_token / api_key query 传入 Gateway Key;providermodel 和其他公开 query 参数会用于本地路由并转发给上游。网关会把上游 HTTP base URL 转换为 ws / wss,默认连接 options.realtime-websocket-path=/realtime,并自动带上 Provider API Key、OpenAI-Beta 和公开附加 Header。该入口会记录连接级耗时、限流、Provider / 凭证健康和异常,并对 Realtime JSON 文本事件做事件级 usage 计量:客户端 conversation.item.createinput_audio_buffer.appendsession.updateresponse.create 会累计输入文本 token 估算和音频字节数;上游 *.delta、音频 delta 和 response.done.usage 会累计输出估算、音频字节数和真实 token 用量。若上游返回 input_tokens / output_tokens / total_tokens,usage event 优先使用真实值;否则使用文本估算值并在 metadata 标记 realtime_usage_source=estimated

入口默认上游路径Scope响应
GET /api/v1/ai/gateway/organization/costs/organization/costsai:gateway:usage:readquery 参数转发,JSON 原样透传
GET /api/v1/ai/gateway/organization/usage/{usageType}/organization/usage/{usage_type}ai:gateway:usage:readquery 参数转发,JSON 原样透传
GET /api/v1/ai/gateway/organization/invites/organization/invitesai:gateway:administration:readquery 参数转发,JSON 原样透传
POST /api/v1/ai/gateway/organization/invites/organization/invitesai:gateway:administration:writeJSON 原样透传
GET /api/v1/ai/gateway/organization/invites/{inviteId}/organization/invites/{invite_id}ai:gateway:administration:readquery 参数转发,JSON 原样透传
DELETE /api/v1/ai/gateway/organization/invites/{inviteId}/organization/invites/{invite_id}ai:gateway:administration:writequery 参数转发,JSON 原样透传
GET /api/v1/ai/gateway/organization/admin_api_keys/organization/admin_api_keysai:gateway:administration:readquery 参数转发,JSON 原样透传
POST /api/v1/ai/gateway/organization/admin_api_keys/organization/admin_api_keysai:gateway:administration:writeJSON 原样透传
GET /api/v1/ai/gateway/organization/admin_api_keys/{keyId}/organization/admin_api_keys/{key_id}ai:gateway:administration:readquery 参数转发,JSON 原样透传
DELETE /api/v1/ai/gateway/organization/admin_api_keys/{keyId}/organization/admin_api_keys/{key_id}ai:gateway:administration:writequery 参数转发,JSON 原样透传
GET /api/v1/ai/gateway/organization/certificates/organization/certificatesai:gateway:administration:readquery 参数转发,JSON 原样透传
POST /api/v1/ai/gateway/organization/certificates/organization/certificatesai:gateway:administration:writeJSON 原样透传
GET /api/v1/ai/gateway/organization/certificates/{certificateId}/organization/certificates/{certificate_id}ai:gateway:administration:readquery 参数转发,JSON 原样透传
POST /api/v1/ai/gateway/organization/certificates/{certificateId}/organization/certificates/{certificate_id}ai:gateway:administration:writeJSON 原样透传
DELETE /api/v1/ai/gateway/organization/certificates/{certificateId}/organization/certificates/{certificate_id}ai:gateway:administration:writequery 参数转发,JSON 原样透传
POST /api/v1/ai/gateway/organization/certificates/activate/organization/certificates/activateai:gateway:administration:writeJSON 原样透传
POST /api/v1/ai/gateway/organization/certificates/deactivate/organization/certificates/deactivateai:gateway:administration:writeJSON 原样透传
GET /api/v1/ai/gateway/organization/spend_alerts/organization/spend_alertsai:gateway:administration:readquery 参数转发,JSON 原样透传
POST /api/v1/ai/gateway/organization/spend_alerts/organization/spend_alertsai:gateway:administration:writeJSON 原样透传
POST /api/v1/ai/gateway/organization/spend_alerts/{alertId}/organization/spend_alerts/{alert_id}ai:gateway:administration:writeJSON 原样透传
DELETE /api/v1/ai/gateway/organization/spend_alerts/{alertId}/organization/spend_alerts/{alert_id}ai:gateway:administration:writequery 参数转发,JSON 原样透传
GET /api/v1/ai/gateway/organization/groups/organization/groupsai:gateway:administration:readquery 参数转发,JSON 原样透传
POST /api/v1/ai/gateway/organization/groups/organization/groupsai:gateway:administration:writeJSON 原样透传
GET /api/v1/ai/gateway/organization/groups/{groupId}/organization/groups/{group_id}ai:gateway:administration:readquery 参数转发,JSON 原样透传
POST /api/v1/ai/gateway/organization/groups/{groupId}/organization/groups/{group_id}ai:gateway:administration:writeJSON 原样透传
DELETE /api/v1/ai/gateway/organization/groups/{groupId}/organization/groups/{group_id}ai:gateway:administration:writequery 参数转发,JSON 原样透传
GET /api/v1/ai/gateway/organization/groups/{groupId}/users/organization/groups/{group_id}/usersai:gateway:administration:readquery 参数转发,JSON 原样透传
POST /api/v1/ai/gateway/organization/groups/{groupId}/users/organization/groups/{group_id}/usersai:gateway:administration:writeJSON 原样透传
DELETE /api/v1/ai/gateway/organization/groups/{groupId}/users/{userId}/organization/groups/{group_id}/users/{user_id}ai:gateway:administration:writequery 参数转发,JSON 原样透传
GET /api/v1/ai/gateway/organization/groups/{groupId}/roles/organization/groups/{group_id}/rolesai:gateway:administration:readquery 参数转发,JSON 原样透传
POST /api/v1/ai/gateway/organization/groups/{groupId}/roles/organization/groups/{group_id}/rolesai:gateway:administration:writeJSON 原样透传
GET /api/v1/ai/gateway/organization/groups/{groupId}/roles/{roleId}/organization/groups/{group_id}/roles/{role_id}ai:gateway:administration:readquery 参数转发,JSON 原样透传
DELETE /api/v1/ai/gateway/organization/groups/{groupId}/roles/{roleId}/organization/groups/{group_id}/roles/{role_id}ai:gateway:administration:writequery 参数转发,JSON 原样透传
GET /api/v1/ai/gateway/organization/roles/organization/rolesai:gateway:administration:readquery 参数转发,JSON 原样透传
POST /api/v1/ai/gateway/organization/roles/organization/rolesai:gateway:administration:writeJSON 原样透传
GET /api/v1/ai/gateway/organization/roles/{roleId}/organization/roles/{role_id}ai:gateway:administration:readquery 参数转发,JSON 原样透传
POST /api/v1/ai/gateway/organization/roles/{roleId}/organization/roles/{role_id}ai:gateway:administration:writeJSON 原样透传
DELETE /api/v1/ai/gateway/organization/roles/{roleId}/organization/roles/{role_id}ai:gateway:administration:writequery 参数转发,JSON 原样透传
POST /api/v1/ai/gateway/organization/projects/organization/projectsai:gateway:administration:writeJSON 原样透传
GET /api/v1/ai/gateway/organization/projects/organization/projectsai:gateway:administration:readquery 参数转发,JSON 原样透传
GET /api/v1/ai/gateway/organization/projects/{projectId}/organization/projects/{project_id}ai:gateway:administration:readquery 参数转发,JSON 原样透传
POST /api/v1/ai/gateway/organization/projects/{projectId}/organization/projects/{project_id}ai:gateway:administration:writeJSON 原样透传
POST /api/v1/ai/gateway/organization/projects/{projectId}/archive/organization/projects/{project_id}/archiveai:gateway:administration:writeJSON 原样透传
GET /api/v1/ai/gateway/organization/projects/{projectId}/api_keys/organization/projects/{project_id}/api_keysai:gateway:administration:readquery 参数转发,JSON 原样透传
GET /api/v1/ai/gateway/organization/projects/{projectId}/api_keys/{keyId}/organization/projects/{project_id}/api_keys/{key_id}ai:gateway:administration:readquery 参数转发,JSON 原样透传
DELETE /api/v1/ai/gateway/organization/projects/{projectId}/api_keys/{keyId}/organization/projects/{project_id}/api_keys/{key_id}ai:gateway:administration:writequery 参数转发,JSON 原样透传
GET /api/v1/ai/gateway/organization/projects/{projectId}/rate_limits/organization/projects/{project_id}/rate_limitsai:gateway:administration:readquery 参数转发,JSON 原样透传
POST /api/v1/ai/gateway/organization/projects/{projectId}/rate_limits/{rateLimitId}/organization/projects/{project_id}/rate_limits/{rate_limit_id}ai:gateway:administration:writeJSON 原样透传
GET /api/v1/ai/gateway/organization/projects/{projectId}/certificates/organization/projects/{project_id}/certificatesai:gateway:administration:readquery 参数转发,JSON 原样透传
POST /api/v1/ai/gateway/organization/projects/{projectId}/certificates/activate/organization/projects/{project_id}/certificates/activateai:gateway:administration:writeJSON 原样透传
POST /api/v1/ai/gateway/organization/projects/{projectId}/certificates/deactivate/organization/projects/{project_id}/certificates/deactivateai:gateway:administration:writeJSON 原样透传
GET /api/v1/ai/gateway/organization/projects/{projectId}/spend_alerts/organization/projects/{project_id}/spend_alertsai:gateway:administration:readquery 参数转发,JSON 原样透传
POST /api/v1/ai/gateway/organization/projects/{projectId}/spend_alerts/organization/projects/{project_id}/spend_alertsai:gateway:administration:writeJSON 原样透传
POST /api/v1/ai/gateway/organization/projects/{projectId}/spend_alerts/{alertId}/organization/projects/{project_id}/spend_alerts/{alert_id}ai:gateway:administration:writeJSON 原样透传
DELETE /api/v1/ai/gateway/organization/projects/{projectId}/spend_alerts/{alertId}/organization/projects/{project_id}/spend_alerts/{alert_id}ai:gateway:administration:writequery 参数转发,JSON 原样透传
GET /api/v1/ai/gateway/projects/{projectId}/roles/projects/{project_id}/rolesai:gateway:administration:readquery 参数转发,JSON 原样透传
POST /api/v1/ai/gateway/projects/{projectId}/roles/projects/{project_id}/rolesai:gateway:administration:writeJSON 原样透传
GET /api/v1/ai/gateway/projects/{projectId}/roles/{roleId}/projects/{project_id}/roles/{role_id}ai:gateway:administration:readquery 参数转发,JSON 原样透传
POST /api/v1/ai/gateway/projects/{projectId}/roles/{roleId}/projects/{project_id}/roles/{role_id}ai:gateway:administration:writeJSON 原样透传
DELETE /api/v1/ai/gateway/projects/{projectId}/roles/{roleId}/projects/{project_id}/roles/{role_id}ai:gateway:administration:writequery 参数转发,JSON 原样透传
GET /api/v1/ai/gateway/projects/{projectId}/users/{userId}/roles/projects/{project_id}/users/{user_id}/rolesai:gateway:administration:readquery 参数转发,JSON 原样透传
POST /api/v1/ai/gateway/projects/{projectId}/users/{userId}/roles/projects/{project_id}/users/{user_id}/rolesai:gateway:administration:writeJSON 原样透传
GET /api/v1/ai/gateway/projects/{projectId}/users/{userId}/roles/{roleId}/projects/{project_id}/users/{user_id}/roles/{role_id}ai:gateway:administration:readquery 参数转发,JSON 原样透传
DELETE /api/v1/ai/gateway/projects/{projectId}/users/{userId}/roles/{roleId}/projects/{project_id}/users/{user_id}/roles/{role_id}ai:gateway:administration:writequery 参数转发,JSON 原样透传
GET /api/v1/ai/gateway/projects/{projectId}/groups/{groupId}/roles/projects/{project_id}/groups/{group_id}/rolesai:gateway:administration:readquery 参数转发,JSON 原样透传
POST /api/v1/ai/gateway/projects/{projectId}/groups/{groupId}/roles/projects/{project_id}/groups/{group_id}/rolesai:gateway:administration:writeJSON 原样透传
GET /api/v1/ai/gateway/projects/{projectId}/groups/{groupId}/roles/{roleId}/projects/{project_id}/groups/{group_id}/roles/{role_id}ai:gateway:administration:readquery 参数转发,JSON 原样透传
DELETE /api/v1/ai/gateway/projects/{projectId}/groups/{groupId}/roles/{roleId}/projects/{project_id}/groups/{group_id}/roles/{role_id}ai:gateway:administration:writequery 参数转发,JSON 原样透传
GET /api/v1/ai/gateway/organization/users/organization/usersai:gateway:administration:readquery 参数转发,JSON 原样透传
GET /api/v1/ai/gateway/organization/users/{userId}/organization/users/{user_id}ai:gateway:administration:readquery 参数转发,JSON 原样透传
POST /api/v1/ai/gateway/organization/users/{userId}/organization/users/{user_id}ai:gateway:administration:writeJSON 原样透传
DELETE /api/v1/ai/gateway/organization/users/{userId}/organization/users/{user_id}ai:gateway:administration:writequery 参数转发,JSON 原样透传
GET /api/v1/ai/gateway/organization/users/{userId}/roles/organization/users/{user_id}/rolesai:gateway:administration:readquery 参数转发,JSON 原样透传
POST /api/v1/ai/gateway/organization/users/{userId}/roles/organization/users/{user_id}/rolesai:gateway:administration:writeJSON 原样透传
GET /api/v1/ai/gateway/organization/users/{userId}/roles/{roleId}/organization/users/{user_id}/roles/{role_id}ai:gateway:administration:readquery 参数转发,JSON 原样透传
DELETE /api/v1/ai/gateway/organization/users/{userId}/roles/{roleId}/organization/users/{user_id}/roles/{role_id}ai:gateway:administration:writequery 参数转发,JSON 原样透传
GET /api/v1/ai/gateway/organization/audit_logs/organization/audit_logsai:gateway:administration:readquery 参数转发,JSON 原样透传
GET /api/v1/ai/gateway/organization/projects/{projectId}/users/organization/projects/{project_id}/usersai:gateway:administration:readquery 参数转发,JSON 原样透传
POST /api/v1/ai/gateway/organization/projects/{projectId}/users/organization/projects/{project_id}/usersai:gateway:administration:writeJSON 原样透传
GET /api/v1/ai/gateway/organization/projects/{projectId}/users/{userId}/organization/projects/{project_id}/users/{user_id}ai:gateway:administration:readquery 参数转发,JSON 原样透传
POST /api/v1/ai/gateway/organization/projects/{projectId}/users/{userId}/organization/projects/{project_id}/users/{user_id}ai:gateway:administration:writeJSON 原样透传
DELETE /api/v1/ai/gateway/organization/projects/{projectId}/users/{userId}/organization/projects/{project_id}/users/{user_id}ai:gateway:administration:writequery 参数转发,JSON 原样透传
GET /api/v1/ai/gateway/organization/projects/{projectId}/service_accounts/organization/projects/{project_id}/service_accountsai:gateway:administration:readquery 参数转发,JSON 原样透传
POST /api/v1/ai/gateway/organization/projects/{projectId}/service_accounts/organization/projects/{project_id}/service_accountsai:gateway:administration:writeJSON 原样透传
GET /api/v1/ai/gateway/organization/projects/{projectId}/service_accounts/{serviceAccountId}/organization/projects/{project_id}/service_accounts/{service_account_id}ai:gateway:administration:readquery 参数转发,JSON 原样透传
DELETE /api/v1/ai/gateway/organization/projects/{projectId}/service_accounts/{serviceAccountId}/organization/projects/{project_id}/service_accounts/{service_account_id}ai:gateway:administration:writequery 参数转发,JSON 原样透传
GET /api/v1/ai/gateway/chat/completions/chat/completionsai:gateway:chat:writequery 参数转发,JSON 原样透传
GET /api/v1/ai/gateway/chat/completions/{completionId}/chat/completions/{completion_id}ai:gateway:chat:writequery 参数转发,JSON 原样透传
POST /api/v1/ai/gateway/chat/completions/{completionId}/chat/completions/{completion_id}ai:gateway:chat:writeJSON 原样透传
DELETE /api/v1/ai/gateway/chat/completions/{completionId}/chat/completions/{completion_id}ai:gateway:chat:writequery 参数转发,JSON 原样透传
GET /api/v1/ai/gateway/chat/completions/{completionId}/messages/chat/completions/{completion_id}/messagesai:gateway:chat:writequery 参数转发,JSON 原样透传
POST /api/v1/ai/gateway/completions/completionsai:gateway:completion:writeJSON 原样透传
POST /api/v1/ai/gateway/responses/responsesai:gateway:response:writeJSON 原样透传,兼容 input_tokens / output_tokens 用量字段
GET /api/v1/ai/gateway/responses/{responseId}/responses/{response_id}ai:gateway:response:readquery 参数转发,JSON 原样透传
DELETE /api/v1/ai/gateway/responses/{responseId}/responses/{response_id}ai:gateway:response:writequery 参数转发,JSON 原样透传
POST /api/v1/ai/gateway/responses/{responseId}/cancel/responses/{response_id}/cancelai:gateway:response:writequery 参数转发,JSON 原样透传
GET /api/v1/ai/gateway/responses/{responseId}/input_items/responses/{response_id}/input_itemsai:gateway:response:readquery 参数转发,JSON 原样透传
POST /api/v1/ai/gateway/evals/evalsai:gateway:eval:writeJSON 原样透传
GET /api/v1/ai/gateway/evals/evalsai:gateway:eval:readquery 参数转发,JSON 原样透传
GET /api/v1/ai/gateway/evals/{evalId}/evals/{eval_id}ai:gateway:eval:readJSON 原样透传
POST /api/v1/ai/gateway/evals/{evalId}/evals/{eval_id}ai:gateway:eval:writeJSON 原样透传
DELETE /api/v1/ai/gateway/evals/{evalId}/evals/{eval_id}ai:gateway:eval:writeJSON 原样透传
POST /api/v1/ai/gateway/evals/{evalId}/runs/evals/{eval_id}/runsai:gateway:eval:writeJSON 原样透传
GET /api/v1/ai/gateway/evals/{evalId}/runs/evals/{eval_id}/runsai:gateway:eval:readquery 参数转发,JSON 原样透传
GET /api/v1/ai/gateway/evals/{evalId}/runs/{runId}/evals/{eval_id}/runs/{run_id}ai:gateway:eval:readJSON 原样透传
POST /api/v1/ai/gateway/evals/{evalId}/runs/{runId}/cancel/evals/{eval_id}/runs/{run_id}/cancelai:gateway:eval:writeJSON 原样透传
DELETE /api/v1/ai/gateway/evals/{evalId}/runs/{runId}/evals/{eval_id}/runs/{run_id}ai:gateway:eval:writeJSON 原样透传
GET /api/v1/ai/gateway/evals/{evalId}/runs/{runId}/output_items/evals/{eval_id}/runs/{run_id}/output_itemsai:gateway:eval:readquery 参数转发,JSON 原样透传
GET /api/v1/ai/gateway/evals/{evalId}/runs/{runId}/output_items/{outputItemId}/evals/{eval_id}/runs/{run_id}/output_items/{output_item_id}ai:gateway:eval:readquery 参数转发,JSON 原样透传
POST /api/v1/ai/gateway/realtime/client_secrets/realtime/client_secretsai:gateway:realtime:writeJSON 原样透传
POST /api/v1/ai/gateway/realtime/sessions/realtime/sessionsai:gateway:realtime:writeJSON 原样透传
POST /api/v1/ai/gateway/realtime/transcription_sessions/realtime/transcription_sessionsai:gateway:realtime:writeJSON 原样透传
POST /api/v1/ai/gateway/realtime/calls/realtime/callsai:gateway:realtime:writeJSON 原样透传
WS /api/v1/ai/gateway/realtime/realtimeai:gateway:realtime:writeJSON 文本事件双向转发
POST /api/v1/ai/gateway/moderations/moderationsai:gateway:moderation:writeJSON 原样透传
POST /api/v1/ai/gateway/images/generations/images/generationsai:gateway:image:writeJSON 原样透传
POST /api/v1/ai/gateway/images/edits/images/editsai:gateway:image:writemultipart/form-data 转发,JSON 原样透传
POST /api/v1/ai/gateway/images/variations/images/variationsai:gateway:image:writemultipart/form-data 转发,JSON 原样透传
POST /api/v1/ai/gateway/audio/speech/audio/speechai:gateway:audio:write上游返回 JSON 时透传 JSON;返回音频二进制时透传 bytes 和 Content-Type
POST /api/v1/ai/gateway/audio/transcriptions/audio/transcriptionsai:gateway:audio:writemultipart/form-data 转发,JSON 原样透传
POST /api/v1/ai/gateway/audio/translations/audio/translationsai:gateway:audio:writemultipart/form-data 转发,JSON 原样透传
POST /api/v1/ai/gateway/rerank/rerankai:gateway:rerank:writeJSON 原样透传
GET /api/v1/ai/gateway/files/filesai:gateway:file:readquery 参数转发,JSON 原样透传
POST /api/v1/ai/gateway/files/filesai:gateway:file:writemultipart/form-data 转发,JSON 原样透传
GET /api/v1/ai/gateway/files/{fileId}/files/{file_id}ai:gateway:file:readJSON 原样透传
DELETE /api/v1/ai/gateway/files/{fileId}/files/{file_id}ai:gateway:file:writeJSON 原样透传
GET /api/v1/ai/gateway/files/{fileId}/content/files/{file_id}/contentai:gateway:file:read上游返回 JSON / 文本 / 二进制时按原 Content-Type 透传
POST /api/v1/ai/gateway/uploads/uploadsai:gateway:file:writeJSON 原样透传
POST /api/v1/ai/gateway/uploads/{uploadId}/parts/uploads/{upload_id}/partsai:gateway:file:writemultipart/form-data 转发,文件字段名 data,JSON 原样透传
POST /api/v1/ai/gateway/uploads/{uploadId}/complete/uploads/{upload_id}/completeai:gateway:file:writeJSON 原样透传
POST /api/v1/ai/gateway/uploads/{uploadId}/cancel/uploads/{upload_id}/cancelai:gateway:file:writeJSON 原样透传
POST /api/v1/ai/gateway/batches/batchesai:gateway:batch:writeJSON 原样透传
GET /api/v1/ai/gateway/batches/batchesai:gateway:batch:readquery 参数转发,JSON 原样透传
GET /api/v1/ai/gateway/batches/{batchId}/batches/{batch_id}ai:gateway:batch:readJSON 原样透传
POST /api/v1/ai/gateway/batches/{batchId}/cancel/batches/{batch_id}/cancelai:gateway:batch:writeJSON 原样透传
POST /api/v1/ai/gateway/fine_tuning/jobs/fine_tuning/jobsai:gateway:fine-tuning:writeJSON 原样透传
GET /api/v1/ai/gateway/fine_tuning/jobs/fine_tuning/jobsai:gateway:fine-tuning:readquery 参数转发,JSON 原样透传
GET /api/v1/ai/gateway/fine_tuning/jobs/{fineTuningJobId}/fine_tuning/jobs/{fine_tuning_job_id}ai:gateway:fine-tuning:readJSON 原样透传
POST /api/v1/ai/gateway/fine_tuning/jobs/{fineTuningJobId}/cancel/fine_tuning/jobs/{fine_tuning_job_id}/cancelai:gateway:fine-tuning:writeJSON 原样透传
GET /api/v1/ai/gateway/fine_tuning/jobs/{fineTuningJobId}/events/fine_tuning/jobs/{fine_tuning_job_id}/eventsai:gateway:fine-tuning:readquery 参数转发,JSON 原样透传
GET /api/v1/ai/gateway/fine_tuning/jobs/{fineTuningJobId}/checkpoints/fine_tuning/jobs/{fine_tuning_job_id}/checkpointsai:gateway:fine-tuning:readquery 参数转发,JSON 原样透传
GET /api/v1/ai/gateway/fine_tuning/checkpoints/{fineTunedModelCheckpoint}/permissions/fine_tuning/checkpoints/{fine_tuned_model_checkpoint}/permissionsai:gateway:fine-tuning:readquery 参数转发,JSON 原样透传
POST /api/v1/ai/gateway/fine_tuning/checkpoints/{fineTunedModelCheckpoint}/permissions/fine_tuning/checkpoints/{fine_tuned_model_checkpoint}/permissionsai:gateway:fine-tuning:writeJSON 原样透传
DELETE /api/v1/ai/gateway/fine_tuning/checkpoints/{fineTunedModelCheckpoint}/permissions/{permissionId}/fine_tuning/checkpoints/{fine_tuned_model_checkpoint}/permissions/{permission_id}ai:gateway:fine-tuning:writequery 参数转发,JSON 原样透传
POST /api/v1/ai/gateway/fine_tuning/alpha/graders/validate/fine_tuning/alpha/graders/validateai:gateway:fine-tuning:writeJSON 原样透传
POST /api/v1/ai/gateway/fine_tuning/alpha/graders/run/fine_tuning/alpha/graders/runai:gateway:fine-tuning:writeJSON 原样透传
POST /api/v1/ai/gateway/vector_stores/vector_storesai:gateway:vector-store:writeJSON 原样透传
GET /api/v1/ai/gateway/vector_stores/vector_storesai:gateway:vector-store:readquery 参数转发,JSON 原样透传
GET /api/v1/ai/gateway/vector_stores/{vectorStoreId}/vector_stores/{vector_store_id}ai:gateway:vector-store:readJSON 原样透传
POST /api/v1/ai/gateway/vector_stores/{vectorStoreId}/vector_stores/{vector_store_id}ai:gateway:vector-store:writeJSON 原样透传
DELETE /api/v1/ai/gateway/vector_stores/{vectorStoreId}/vector_stores/{vector_store_id}ai:gateway:vector-store:writeJSON 原样透传
POST /api/v1/ai/gateway/vector_stores/{vectorStoreId}/search/vector_stores/{vector_store_id}/searchai:gateway:vector-store:writeJSON 原样透传
POST /api/v1/ai/gateway/vector_stores/{vectorStoreId}/files/vector_stores/{vector_store_id}/filesai:gateway:vector-store:writeJSON 原样透传
GET /api/v1/ai/gateway/vector_stores/{vectorStoreId}/files/vector_stores/{vector_store_id}/filesai:gateway:vector-store:readquery 参数转发,JSON 原样透传
GET /api/v1/ai/gateway/vector_stores/{vectorStoreId}/files/{fileId}/vector_stores/{vector_store_id}/files/{file_id}ai:gateway:vector-store:readJSON 原样透传
GET /api/v1/ai/gateway/vector_stores/{vectorStoreId}/files/{fileId}/content/vector_stores/{vector_store_id}/files/{file_id}/contentai:gateway:vector-store:readquery 参数转发,JSON 原样透传
DELETE /api/v1/ai/gateway/vector_stores/{vectorStoreId}/files/{fileId}/vector_stores/{vector_store_id}/files/{file_id}ai:gateway:vector-store:writeJSON 原样透传
POST /api/v1/ai/gateway/vector_stores/{vectorStoreId}/file_batches/vector_stores/{vector_store_id}/file_batchesai:gateway:vector-store:writeJSON 原样透传
GET /api/v1/ai/gateway/vector_stores/{vectorStoreId}/file_batches/{batchId}/vector_stores/{vector_store_id}/file_batches/{batch_id}ai:gateway:vector-store:readJSON 原样透传
POST /api/v1/ai/gateway/vector_stores/{vectorStoreId}/file_batches/{batchId}/cancel/vector_stores/{vector_store_id}/file_batches/{batch_id}/cancelai:gateway:vector-store:writeJSON 原样透传
GET /api/v1/ai/gateway/vector_stores/{vectorStoreId}/file_batches/{batchId}/files/vector_stores/{vector_store_id}/file_batches/{batch_id}/filesai:gateway:vector-store:readquery 参数转发,JSON 原样透传
POST /api/v1/ai/gateway/containers/containersai:gateway:container:writeJSON 原样透传
GET /api/v1/ai/gateway/containers/containersai:gateway:container:readquery 参数转发,JSON 原样透传
GET /api/v1/ai/gateway/containers/{containerId}/containers/{container_id}ai:gateway:container:readJSON 原样透传
DELETE /api/v1/ai/gateway/containers/{containerId}/containers/{container_id}ai:gateway:container:writeJSON 原样透传
POST /api/v1/ai/gateway/containers/{containerId}/files/containers/{container_id}/filesai:gateway:container:writemultipart/form-data 转发,JSON 原样透传
GET /api/v1/ai/gateway/containers/{containerId}/files/containers/{container_id}/filesai:gateway:container:readquery 参数转发,JSON 原样透传
GET /api/v1/ai/gateway/containers/{containerId}/files/{fileId}/containers/{container_id}/files/{file_id}ai:gateway:container:readJSON 原样透传
DELETE /api/v1/ai/gateway/containers/{containerId}/files/{fileId}/containers/{container_id}/files/{file_id}ai:gateway:container:writeJSON 原样透传
GET /api/v1/ai/gateway/containers/{containerId}/files/{fileId}/content/containers/{container_id}/files/{file_id}/contentai:gateway:container:read上游返回 JSON / 文本 / 二进制时按原 Content-Type 透传
POST /api/v1/ai/gateway/assistants/assistantsai:gateway:assistant:writeJSON 原样透传
GET /api/v1/ai/gateway/assistants/assistantsai:gateway:assistant:readquery 参数转发,JSON 原样透传
GET /api/v1/ai/gateway/assistants/{assistantId}/assistants/{assistant_id}ai:gateway:assistant:readJSON 原样透传
POST /api/v1/ai/gateway/assistants/{assistantId}/assistants/{assistant_id}ai:gateway:assistant:writeJSON 原样透传
DELETE /api/v1/ai/gateway/assistants/{assistantId}/assistants/{assistant_id}ai:gateway:assistant:writeJSON 原样透传
POST /api/v1/ai/gateway/threads/threadsai:gateway:thread:writeJSON 原样透传
POST /api/v1/ai/gateway/threads/runs/threads/runsai:gateway:thread:writeJSON 原样透传
GET /api/v1/ai/gateway/threads/{threadId}/threads/{thread_id}ai:gateway:thread:readJSON 原样透传
POST /api/v1/ai/gateway/threads/{threadId}/threads/{thread_id}ai:gateway:thread:writeJSON 原样透传
DELETE /api/v1/ai/gateway/threads/{threadId}/threads/{thread_id}ai:gateway:thread:writeJSON 原样透传
POST /api/v1/ai/gateway/threads/{threadId}/messages/threads/{thread_id}/messagesai:gateway:thread:writeJSON 原样透传
GET /api/v1/ai/gateway/threads/{threadId}/messages/threads/{thread_id}/messagesai:gateway:thread:readquery 参数转发,JSON 原样透传
GET /api/v1/ai/gateway/threads/{threadId}/messages/{messageId}/threads/{thread_id}/messages/{message_id}ai:gateway:thread:readJSON 原样透传
POST /api/v1/ai/gateway/threads/{threadId}/messages/{messageId}/threads/{thread_id}/messages/{message_id}ai:gateway:thread:writeJSON 原样透传
DELETE /api/v1/ai/gateway/threads/{threadId}/messages/{messageId}/threads/{thread_id}/messages/{message_id}ai:gateway:thread:writeJSON 原样透传
POST /api/v1/ai/gateway/threads/{threadId}/runs/threads/{thread_id}/runsai:gateway:thread:writeJSON 原样透传
GET /api/v1/ai/gateway/threads/{threadId}/runs/threads/{thread_id}/runsai:gateway:thread:readquery 参数转发,JSON 原样透传
GET /api/v1/ai/gateway/threads/{threadId}/runs/{runId}/threads/{thread_id}/runs/{run_id}ai:gateway:thread:readJSON 原样透传
POST /api/v1/ai/gateway/threads/{threadId}/runs/{runId}/threads/{thread_id}/runs/{run_id}ai:gateway:thread:writeJSON 原样透传
POST /api/v1/ai/gateway/threads/{threadId}/runs/{runId}/cancel/threads/{thread_id}/runs/{run_id}/cancelai:gateway:thread:writeJSON 原样透传
POST /api/v1/ai/gateway/threads/{threadId}/runs/{runId}/submit_tool_outputs/threads/{thread_id}/runs/{run_id}/submit_tool_outputsai:gateway:thread:writeJSON 原样透传
GET /api/v1/ai/gateway/threads/{threadId}/runs/{runId}/steps/threads/{thread_id}/runs/{run_id}/stepsai:gateway:thread:readquery 参数转发,JSON 原样透传
GET /api/v1/ai/gateway/threads/{threadId}/runs/{runId}/steps/{stepId}/threads/{thread_id}/runs/{run_id}/steps/{step_id}ai:gateway:thread:readJSON 原样透传

内容审核请求示例:

http
POST /api/v1/ai/gateway/moderations
Authorization: Bearer sk-ai-...
Content-Type: application/json
json
{
  "model": "omni-moderation-latest",
  "input": "safe text"
}

图片生成请求示例:

http
POST /api/v1/ai/gateway/images/generations
Authorization: Bearer sk-ai-...
Content-Type: application/json
json
{
  "model": "gpt-image-1",
  "prompt": "draw spring open",
  "size": "1024x1024",
  "response_format": "b64_json"
}

音频语音请求示例:

http
POST /api/v1/ai/gateway/audio/speech
Authorization: Bearer sk-ai-...
Content-Type: application/json
json
{
  "model": "gpt-4o-mini-tts",
  "input": "hello spring open",
  "voice": "alloy",
  "format": "mp3"
}

图片编辑请求示例:

bash
curl -X POST https://<host>/api/v1/ai/gateway/images/edits \
  -H "Authorization: Bearer sk-ai-..." \
  -F model=gpt-image-1 \
  -F prompt="edit spring open" \
  -F size=1024x1024 \
  -F image=@source.png \
  -F mask=@mask.png

图片变体请求示例:

bash
curl -X POST https://<host>/api/v1/ai/gateway/images/variations \
  -H "Authorization: Bearer sk-ai-..." \
  -F model=gpt-image-1 \
  -F size=1024x1024 \
  -F image=@source.png

音频转写请求示例:

bash
curl -X POST https://<host>/api/v1/ai/gateway/audio/transcriptions \
  -H "Authorization: Bearer sk-ai-..." \
  -F model=gpt-4o-transcribe \
  -F file=@speech.mp3 \
  -F language=en \
  -F response_format=json

音频翻译请求示例:

bash
curl -X POST https://<host>/api/v1/ai/gateway/audio/translations \
  -H "Authorization: Bearer sk-ai-..." \
  -F model=whisper-1 \
  -F file=@speech.mp3 \
  -F response_format=json

重排请求示例:

http
POST /api/v1/ai/gateway/rerank
Authorization: Bearer sk-ai-...
Content-Type: application/json
json
{
  "model": "jina-reranker-v2-base-multilingual",
  "query": "spring open",
  "documents": [
    "spring open ai gateway",
    "other document"
  ],
  "top_n": 1
}

文件生命周期请求示例:

bash
curl -H "Authorization: Bearer sk-ai-..." \
  "https://<host>/api/v1/ai/gateway/files?purpose=batch&limit=20"

curl -X POST https://<host>/api/v1/ai/gateway/files \
  -H "Authorization: Bearer sk-ai-..." \
  -F purpose=batch \
  -F file=@batch.jsonl

curl -H "Authorization: Bearer sk-ai-..." \
  https://<host>/api/v1/ai/gateway/files/file-abc

curl -X DELETE https://<host>/api/v1/ai/gateway/files/file-abc \
  -H "Authorization: Bearer sk-ai-..."

curl -H "Authorization: Bearer sk-ai-..." \
  https://<host>/api/v1/ai/gateway/files/file-abc/content

Uploads 分片上传生命周期请求示例:

bash
curl -X POST https://<host>/api/v1/ai/gateway/uploads \
  -H "Authorization: Bearer sk-ai-..." \
  -H "Content-Type: application/json" \
  -d '{"purpose":"assistants","filename":"large.jsonl","bytes":1048576,"mime_type":"application/jsonl"}'

curl -X POST https://<host>/api/v1/ai/gateway/uploads/upload-abc/parts \
  -H "Authorization: Bearer sk-ai-..." \
  -F data=@part-1.bin

curl -X POST https://<host>/api/v1/ai/gateway/uploads/upload-abc/complete \
  -H "Authorization: Bearer sk-ai-..." \
  -H "Content-Type: application/json" \
  -d '{"part_ids":["part-1"]}'

curl -X POST https://<host>/api/v1/ai/gateway/uploads/upload-abc/cancel \
  -H "Authorization: Bearer sk-ai-..."

文件生命周期和 Uploads 接口都是 Provider / 上游网关级能力,通常不要求传 model。如果需要指定某个上游 Provider,可以在 query、JSON payload 或 multipart 表单中传 provider=<providerName>;该字段只用于平台路由选择,不会透传给上游 payload。

批处理请求示例:

http
POST /api/v1/ai/gateway/batches
Authorization: Bearer sk-ai-...
Content-Type: application/json
json
{
  "input_file_id": "file-abc",
  "endpoint": "/v1/chat/completions",
  "completion_window": "24h",
  "metadata": {
    "scene": "nightly-eval"
  }
}

批处理查询 / 取消示例:

bash
curl -H "Authorization: Bearer sk-ai-..." \
  "https://<host>/api/v1/ai/gateway/batches?limit=20"

curl -H "Authorization: Bearer sk-ai-..." \
  https://<host>/api/v1/ai/gateway/batches/batch-abc

curl -X POST https://<host>/api/v1/ai/gateway/batches/batch-abc/cancel \
  -H "Authorization: Bearer sk-ai-..."

微调任务请求示例:

http
POST /api/v1/ai/gateway/fine_tuning/jobs
Authorization: Bearer sk-ai-...
Content-Type: application/json
json
{
  "model": "gpt-4o-mini-2024-07-18",
  "training_file": "file-abc",
  "validation_file": "file-def"
}

微调任务查询 / 事件 / 检查点 / 检查点权限示例:

bash
curl -H "Authorization: Bearer sk-ai-..." \
  "https://<host>/api/v1/ai/gateway/fine_tuning/jobs?limit=20"

curl -H "Authorization: Bearer sk-ai-..." \
  https://<host>/api/v1/ai/gateway/fine_tuning/jobs/ftjob-abc/events

curl -H "Authorization: Bearer sk-ai-..." \
  https://<host>/api/v1/ai/gateway/fine_tuning/jobs/ftjob-abc/checkpoints

curl -H "Authorization: Bearer sk-ai-..." \
  "https://<host>/api/v1/ai/gateway/fine_tuning/checkpoints/ckpt-abc/permissions?limit=20"

curl -X POST https://<host>/api/v1/ai/gateway/fine_tuning/checkpoints/ckpt-abc/permissions \
  -H "Authorization: Bearer sk-ai-..." \
  -H "Content-Type: application/json" \
  -d '{"project_ids":["proj-abc"]}'

curl -X DELETE https://<host>/api/v1/ai/gateway/fine_tuning/checkpoints/ckpt-abc/permissions/cp-abc \
  -H "Authorization: Bearer sk-ai-..."

curl -X POST https://<host>/api/v1/ai/gateway/fine_tuning/alpha/graders/validate \
  -H "Authorization: Bearer sk-ai-..." \
  -H "Content-Type: application/json" \
  -d '{"grader":{"type":"string_check","name":"quality","input":"{{sample.output_text}}","reference":"{{item.label}}","operation":"eq"}}'

curl -X POST https://<host>/api/v1/ai/gateway/fine_tuning/alpha/graders/run \
  -H "Authorization: Bearer sk-ai-..." \
  -H "Content-Type: application/json" \
  -d '{"grader":{"type":"string_check","name":"quality","input":"{{sample.output_text}}","reference":"{{item.label}}","operation":"eq"},"item":{"label":"ok"},"model_sample":"ok"}'

curl -X POST https://<host>/api/v1/ai/gateway/fine_tuning/jobs/ftjob-abc/cancel \
  -H "Authorization: Bearer sk-ai-..."

Vector Store / File Search 请求示例:

bash
curl -X POST https://<host>/api/v1/ai/gateway/vector_stores \
  -H "Authorization: Bearer sk-ai-..." \
  -H "Content-Type: application/json" \
  -d '{"name":"project-docs","file_ids":["file-abc"]}'

curl -H "Authorization: Bearer sk-ai-..." \
  "https://<host>/api/v1/ai/gateway/vector_stores?limit=20"

curl -X POST https://<host>/api/v1/ai/gateway/vector_stores/vs-abc/search \
  -H "Authorization: Bearer sk-ai-..." \
  -H "Content-Type: application/json" \
  -d '{"query":"billing policy","max_num_results":5}'

curl -X POST https://<host>/api/v1/ai/gateway/vector_stores/vs-abc/files \
  -H "Authorization: Bearer sk-ai-..." \
  -H "Content-Type: application/json" \
  -d '{"file_id":"file-abc"}'

curl -H "Authorization: Bearer sk-ai-..." \
  "https://<host>/api/v1/ai/gateway/vector_stores/vs-abc/files/file-abc/content"

curl -X POST https://<host>/api/v1/ai/gateway/vector_stores/vs-abc/file_batches \
  -H "Authorization: Bearer sk-ai-..." \
  -H "Content-Type: application/json" \
  -d '{"file_ids":["file-abc","file-def"]}'

curl -H "Authorization: Bearer sk-ai-..." \
  "https://<host>/api/v1/ai/gateway/vector_stores/vs-abc/file_batches/batch-abc/files?limit=20"

Container / Container File 请求示例:

bash
curl -X POST https://<host>/api/v1/ai/gateway/containers \
  -H "Authorization: Bearer sk-ai-..." \
  -H "Content-Type: application/json" \
  -d '{"name":"runtime-workspace"}'

curl -H "Authorization: Bearer sk-ai-..." \
  "https://<host>/api/v1/ai/gateway/containers?limit=20"

curl -X POST https://<host>/api/v1/ai/gateway/containers/cntr-abc/files \
  -H "Authorization: Bearer sk-ai-..." \
  -F purpose=assistants \
  -F file=@script.py

curl -H "Authorization: Bearer sk-ai-..." \
  "https://<host>/api/v1/ai/gateway/containers/cntr-abc/files?limit=20"

curl -H "Authorization: Bearer sk-ai-..." \
  "https://<host>/api/v1/ai/gateway/containers/cntr-abc/files/cfile-abc/content" \
  --output script.py

Assistant / Thread / Run 请求示例:

bash
curl -X POST https://<host>/api/v1/ai/gateway/assistants \
  -H "Authorization: Bearer sk-ai-..." \
  -H "Content-Type: application/json" \
  -d '{"model":"gpt-4.1","name":"research-helper","instructions":"Answer with project context."}'

curl -H "Authorization: Bearer sk-ai-..." \
  "https://<host>/api/v1/ai/gateway/assistants?limit=20"

curl -X POST https://<host>/api/v1/ai/gateway/threads \
  -H "Authorization: Bearer sk-ai-..." \
  -H "Content-Type: application/json" \
  -d '{"metadata":{"scene":"research"}}'

curl -X POST https://<host>/api/v1/ai/gateway/threads/thread-abc/messages \
  -H "Authorization: Bearer sk-ai-..." \
  -H "Content-Type: application/json" \
  -d '{"role":"user","content":"Summarize this document."}'

curl -X POST https://<host>/api/v1/ai/gateway/threads/thread-abc/runs \
  -H "Authorization: Bearer sk-ai-..." \
  -H "Content-Type: application/json" \
  -d '{"assistant_id":"asst-abc"}'

curl -H "Authorization: Bearer sk-ai-..." \
  "https://<host>/api/v1/ai/gateway/threads/thread-abc/runs/run-abc/steps?limit=20"

curl -X POST https://<host>/api/v1/ai/gateway/threads/thread-abc/runs/run-abc/submit_tool_outputs \
  -H "Authorization: Bearer sk-ai-..." \
  -H "Content-Type: application/json" \
  -d '{"tool_outputs":[{"tool_call_id":"call_abc","output":"{\"ok\":true}"}]}'

批处理、微调任务、微调检查点权限、Grader 校验 / 运行、Vector Store / File Search、Container / Container File、Assistant、Thread、Message、Run 和 Run Step 都是上游网关级管理能力。列表、详情、事件、检查点、检查点权限、Step 查询、内容读取和删除类请求通常不要求传 model;如果需要指定 Provider,可在 query 中传 provider=<providerName>。创建微调任务、Assistant 或 Run 时仍建议按上游协议传 modelassistant_id,这样平台可以继续使用模型别名、Provider 白名单和用量上下文。微调检查点权限创建按上游协议传 project_ids;Grader 校验 / 运行按上游协议传 graderitemmodel_sample;Vector Store 搜索、文件挂载和批量文件处理通常按上游协议传 queryfile_idfile_ids;Container File 上传使用 multipart file 字段和上游要求的表单字段。平台只负责鉴权、路由、治理和响应透传。

Provider path 可通过 spring.open.ai.providers.<name>.options 调整,适配 NewAPI、OpenAI Compatible 聚合网关或自建兼容服务的路径差异:

yaml
spring:
  open:
    ai:
      providers:
        newapi:
          enabled: true
          provider: newapi
          base-url: http://127.0.0.1:3000/v1
          api-key: ${NEWAPI_API_KEY}
          options:
            chat-completions-path: /chat/completions
            chat-completion-path: /chat/completions/{completion_id}
            chat-completion-messages-path: /chat/completions/{completion_id}/messages
            completions-path: /completions
            responses-path: /responses
            response-path: /responses/{response_id}
            response-cancel-path: /responses/{response_id}/cancel
            response-input-items-path: /responses/{response_id}/input_items
            organization-costs-path: /organization/costs
            organization-usage-path: /organization/usage/{usage_type}
            organization-invites-path: /organization/invites
            organization-invite-path: /organization/invites/{invite_id}
            organization-admin-api-keys-path: /organization/admin_api_keys
            organization-admin-api-key-path: /organization/admin_api_keys/{key_id}
            organization-certificates-path: /organization/certificates
            organization-certificate-path: /organization/certificates/{certificate_id}
            organization-certificates-activate-path: /organization/certificates/activate
            organization-certificates-deactivate-path: /organization/certificates/deactivate
            organization-spend-alerts-path: /organization/spend_alerts
            organization-spend-alert-path: /organization/spend_alerts/{alert_id}
            organization-groups-path: /organization/groups
            organization-group-path: /organization/groups/{group_id}
            organization-group-users-path: /organization/groups/{group_id}/users
            organization-group-user-path: /organization/groups/{group_id}/users/{user_id}
            organization-group-roles-path: /organization/groups/{group_id}/roles
            organization-group-role-path: /organization/groups/{group_id}/roles/{role_id}
            organization-roles-path: /organization/roles
            organization-role-path: /organization/roles/{role_id}
            project-roles-path: /projects/{project_id}/roles
            project-role-path: /projects/{project_id}/roles/{role_id}
            project-user-roles-path: /projects/{project_id}/users/{user_id}/roles
            project-user-role-path: /projects/{project_id}/users/{user_id}/roles/{role_id}
            project-group-roles-path: /projects/{project_id}/groups/{group_id}/roles
            project-group-role-path: /projects/{project_id}/groups/{group_id}/roles/{role_id}
            organization-projects-path: /organization/projects
            organization-project-path: /organization/projects/{project_id}
            organization-project-archive-path: /organization/projects/{project_id}/archive
            organization-project-api-keys-path: /organization/projects/{project_id}/api_keys
            organization-project-api-key-path: /organization/projects/{project_id}/api_keys/{key_id}
            organization-project-rate-limits-path: /organization/projects/{project_id}/rate_limits
            organization-project-rate-limit-path: /organization/projects/{project_id}/rate_limits/{rate_limit_id}
            organization-project-groups-path: /organization/projects/{project_id}/groups
            organization-project-group-path: /organization/projects/{project_id}/groups/{group_id}
            organization-project-data-retention-path: /organization/projects/{project_id}/data_retention
            organization-project-certificates-path: /organization/projects/{project_id}/certificates
            organization-project-certificates-activate-path: /organization/projects/{project_id}/certificates/activate
            organization-project-certificates-deactivate-path: /organization/projects/{project_id}/certificates/deactivate
            organization-project-spend-alerts-path: /organization/projects/{project_id}/spend_alerts
            organization-project-spend-alert-path: /organization/projects/{project_id}/spend_alerts/{alert_id}
            organization-users-path: /organization/users
            organization-user-path: /organization/users/{user_id}
            organization-audit-logs-path: /organization/audit_logs
            organization-project-users-path: /organization/projects/{project_id}/users
            organization-project-user-path: /organization/projects/{project_id}/users/{user_id}
            organization-project-service-accounts-path: /organization/projects/{project_id}/service_accounts
            organization-project-service-account-path: /organization/projects/{project_id}/service_accounts/{service_account_id}
            organization-user-roles-path: /organization/users/{user_id}/roles
            organization-user-role-path: /organization/users/{user_id}/roles/{role_id}
            evals-path: /evals
            eval-path: /evals/{eval_id}
            eval-runs-path: /evals/{eval_id}/runs
            eval-run-path: /evals/{eval_id}/runs/{run_id}
            eval-run-cancel-path: /evals/{eval_id}/runs/{run_id}/cancel
            eval-run-output-items-path: /evals/{eval_id}/runs/{run_id}/output_items
            eval-run-output-item-path: /evals/{eval_id}/runs/{run_id}/output_items/{output_item_id}
            realtime-client-secrets-path: /realtime/client_secrets
            realtime-sessions-path: /realtime/sessions
            realtime-transcription-sessions-path: /realtime/transcription_sessions
            realtime-calls-path: /realtime/calls
            realtime-websocket-path: /realtime
            realtime-beta-header: realtime=v1
            moderations-path: /moderations
            images-generations-path: /images/generations
            images-edits-path: /images/edits
            images-variations-path: /images/variations
            audio-speech-path: /audio/speech
            audio-transcriptions-path: /audio/transcriptions
            audio-translations-path: /audio/translations
            audio-speech-accept: audio/mpeg,application/json
            rerank-path: /rerank
            files-path: /files
            file-path: /files/{file_id}
            file-content-path: /files/{file_id}/content
            uploads-path: /uploads
            upload-parts-path: /uploads/{upload_id}/parts
            upload-complete-path: /uploads/{upload_id}/complete
            upload-cancel-path: /uploads/{upload_id}/cancel
            batches-path: /batches
            batch-path: /batches/{batch_id}
            batch-cancel-path: /batches/{batch_id}/cancel
            fine-tuning-jobs-path: /fine_tuning/jobs
            fine-tuning-job-path: /fine_tuning/jobs/{fine_tuning_job_id}
            fine-tuning-job-cancel-path: /fine_tuning/jobs/{fine_tuning_job_id}/cancel
            fine-tuning-job-events-path: /fine_tuning/jobs/{fine_tuning_job_id}/events
            fine-tuning-job-checkpoints-path: /fine_tuning/jobs/{fine_tuning_job_id}/checkpoints
            fine-tuning-checkpoint-permissions-path: /fine_tuning/checkpoints/{fine_tuned_model_checkpoint}/permissions
            fine-tuning-checkpoint-permission-path: /fine_tuning/checkpoints/{fine_tuned_model_checkpoint}/permissions/{permission_id}
            fine-tuning-grader-validate-path: /fine_tuning/alpha/graders/validate
            fine-tuning-grader-run-path: /fine_tuning/alpha/graders/run
            vector-stores-path: /vector_stores
            vector-store-path: /vector_stores/{vector_store_id}
            vector-store-search-path: /vector_stores/{vector_store_id}/search
            vector-store-files-path: /vector_stores/{vector_store_id}/files
            vector-store-file-path: /vector_stores/{vector_store_id}/files/{file_id}
            vector-store-file-content-path: /vector_stores/{vector_store_id}/files/{file_id}/content
            vector-store-file-batches-path: /vector_stores/{vector_store_id}/file_batches
            vector-store-file-batch-path: /vector_stores/{vector_store_id}/file_batches/{batch_id}
            vector-store-file-batch-cancel-path: /vector_stores/{vector_store_id}/file_batches/{batch_id}/cancel
            vector-store-file-batch-files-path: /vector_stores/{vector_store_id}/file_batches/{batch_id}/files
            containers-path: /containers
            container-path: /containers/{container_id}
            container-files-path: /containers/{container_id}/files
            container-file-path: /containers/{container_id}/files/{file_id}
            container-file-content-path: /containers/{container_id}/files/{file_id}/content
            assistants-path: /assistants
            assistant-path: /assistants/{assistant_id}
            threads-path: /threads
            thread-path: /threads/{thread_id}
            threads-runs-path: /threads/runs
            thread-messages-path: /threads/{thread_id}/messages
            thread-message-path: /threads/{thread_id}/messages/{message_id}
            thread-runs-path: /threads/{thread_id}/runs
            thread-run-path: /threads/{thread_id}/runs/{run_id}
            thread-run-cancel-path: /threads/{thread_id}/runs/{run_id}/cancel
            thread-run-submit-tool-outputs-path: /threads/{thread_id}/runs/{run_id}/submit_tool_outputs
            thread-run-steps-path: /threads/{thread_id}/runs/{run_id}/steps
            thread-run-step-path: /threads/{thread_id}/runs/{run_id}/steps/{step_id}
            relay-path.custom.endpoint: /custom/endpoint

relay-path.<endpoint> 用于接入项目内尚未显式建常量的兼容 endpoint。例如请求 DTO 转换出的 endpoint=custom.endpoint 时,Provider 会优先读取 relay-path.custom.endpoint;没有配置时按 /<endpoint> 的点号分段默认拼接。已内置的 Organization costs / usage、Organization Invite / Admin API Key / Organization Certificate / Project Certificate / Organization Spend Alert / Project Spend Alert / Organization Group / Group User / Organization Role / Project Role / Role Assignment / Organization Project / Project API Key / Project Rate Limit / Project Group / Project Data Retention / Organization User / Audit Log / Project User / Project Service Account、存储型 Chat Completions 生命周期、legacy 文本补全、Responses、Conversation、Eval / Run 取消 / Output Item 列表 / 详情、Realtime、内容审核、图片生成 / 编辑 / 变体、音频语音 / 转写 / 翻译、重排、文件生命周期、Uploads、批处理、微调任务、微调检查点权限、Grader 校验 / 运行、Vector Store / File Search(含 File 内容读取)、Container / Container File、Assistant 和 Thread / Message / Run / Run Step 优先使用上表默认路径。

OpenAI Compatible 与 Codex 入口返回 OpenAI 风格错误体。type 表示错误大类,code 表示可供客户端分支处理的具体错误码;例如模型不存在时使用 type=invalid_request_errorcode=model_not_found

json
{
  "error": {
    "message": "The requested model could not be found.",
    "type": "invalid_request_error",
    "param": null,
    "code": "model_not_found"
  }
}

模型目录中不存在、已停用或未开放的模型返回 HTTP 404code=model_not_found;Gateway Key 的模型、Provider、能力或 scope 白名单拒绝请求时返回 HTTP 403type=permission_errorcode=forbidden。这些错误都直接使用协议错误体,不会包装为平台 Result

成本快照、扣费预检、预占、实扣、失败释放和 usage event 已经进入网关基础链路。后续继续按 Provider 能力补齐更多上游协议适配矩阵和复杂工具调用执行链路。

Claude Code / Anthropic Messages Contract

Claude Code / CC Switch 不应强行走 OpenAI Compatible 请求体。第一版提供 Claude Code / Anthropic Messages 兼容入口,让开发者工具可以使用 Anthropic 风格的 base URL、鉴权头和消息格式,同时平台内部继续统一落到模型别名、Provider 路由、Token 计量、余额 / 套餐扣费和审计。

请求头:

http
Authorization: Bearer sk-ai-...
Content-Type: application/json

/claude/v1/messages 第一版已支持普通和流式对话:

字段说明
model平台模型别名或上游模型名
messagesAnthropic Messages 格式消息
system系统提示
streamfalse 返回完整 message;true 返回 Anthropic SSE 事件流
max_tokens最大输出 token
temperature / top_p采样参数
tools / tool_choiceAnthropic 工具定义会映射为内部 OpenAI Compatible tools / tool_choice,由具备工具调用能力的上游 Provider 执行
stop_sequences会映射为 OpenAI Compatible stop 并透传给上游 Provider
metadata / thinking作为请求参数保留,适配支持请求 metadata 或推理预算的兼容上游
output_config.effort会映射为 reasoning_effort,便于 OpenAI Compatible 聚合上游消费
其它 Anthropic 扩展字段containermcp_serversservice_tiertop_k、内容块 cache_control / citations、工具选择里的 disable_parallel_tool_use 等生态字段按兼容网关策略忽略,不透传给 OpenAI Compatible 上游;未知内容块不再盲目塞进 messages[].content

Claude / Anthropic Messages 入口的鉴权拒绝、访问策略拒绝、业务拒绝和模型调用失败统一返回 Anthropic 错误体,不复用 OpenAI error.code,也不会包装为平台 Result。响应头 request-id 与正文 request_id 使用同一个请求标识;模型不存在返回 404 not_found_error,Provider 暂时不可用返回 529 overloaded_error

json
{
  "type": "error",
  "error": {
    "type": "not_found_error",
    "message": "The requested model could not be found."
  },
  "request_id": "req_7f18a02d"
}

流式响应已经建立后发生错误时,网关通过 Anthropic SSE error 事件结束本次输出,并继续执行失败计量和预占释放:

text
event: error
data: {"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}

请求示例:

http
POST /api/v1/ai/gateway/claude/v1/messages
Authorization: Bearer sk-ai-...
Content-Type: application/json
json
{
  "model": "log-chat",
  "system": "be concise",
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "ping"
        }
      ]
    }
  ],
  "max_tokens": 128,
  "temperature": 0.2
}

工具调用请求可以直接使用 Anthropic tool_use / tool_result 内容块。网关会把 tools[].input_schema 映射为 OpenAI Compatible function.parameters,把 tool_choice={"type":"tool","name":"..."} 映射为指定 function choice,把历史 tool_use 映射为助手 tool_calls,把 tool_result 映射为 tool 角色消息。图片块会从 Anthropic source 转为 OpenAI Compatible image_url;base64 图片会转为 data:<media_type>;base64,<data>。请求级 stop_sequencesmetadatathinking 会进入 starter 的通用请求参数链路;output_config.effort 转为 reasoning_effort;Anthropic 生态里常见但 OpenAI Compatible 上游通常不识别的扩展字段会被忽略,避免 Claude Code / CC Switch 默认携带扩展时触发上游 400。

json
{
  "model": "claude-log-chat",
  "tools": [
    {
      "name": "lookup_order",
      "description": "Lookup order status",
      "input_schema": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string"
          }
        }
      }
    }
  ],
  "tool_choice": {
    "type": "tool",
    "name": "lookup_order"
  },
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "inspect image"
        },
        {
          "type": "image",
          "source": {
            "type": "url",
            "url": "https://example.test/order.png"
          }
        }
      ]
    }
  ]
}

响应示例:

json
{
  "id": "msg_...",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "pong"
    }
  ],
  "model": "log-chat",
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "usage": {
    "input_tokens": 4,
    "output_tokens": 2,
    "cache_creation_input_tokens": 3,
    "cache_read_input_tokens": 4
  }
}

如果上游普通响应包含 reasoning_contentreasoningthinking,网关会在 Claude 响应 content 中先输出 thinking block,再输出 text block:

json
{
  "content": [
    {
      "type": "thinking",
      "thinking": "thinking step"
    },
    {
      "type": "text",
      "text": "final answer"
    }
  ],
  "stop_reason": "end_turn",
  "stop_sequence": null
}

当模型返回工具调用时,普通响应会输出 Anthropic tool_use 内容块,并把 OpenAI Compatible tool_calls[].function.arguments 解析回 input 对象:

json
{
  "id": "msg_...",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "need lookup"
    },
    {
      "type": "tool_use",
      "id": "toolu_1",
      "name": "lookup_order",
      "input": {
        "id": "A100"
      }
    }
  ],
  "model": "claude-log-chat",
  "stop_reason": "tool_use"
}

当前网关会把 Claude 文本块数组提取为内部文本消息,系统提示会作为内部 system 消息传给 AiModelManagerstream=true 时返回 text/event-stream,事件序列包含 message_startcontent_block_startcontent_block_deltacontent_block_stopmessage_deltamessage_stop。流式工具调用会使用 content_block_start 输出 tool_use 块,再通过 content_block_delta + input_json_delta.partial_json 输出参数增量,最后在 message_delta.stop_reason=tool_use 收口;如果流中没有前置文本,首个 tool_use block 的 index0。上游 OpenAI Compatible SSE 的 reasoning_contentreasoningthinking 会在 Claude / Anthropic Messages 流式响应中转换为独立 thinking content block 和 thinking_delta,块切换前会先输出上一块的 content_block_stop,不再嵌套在 text block 内。上游 usage metadata 如果包含 cache_creation_input_tokens / cache_read_input_tokens,Claude 普通响应和流式 message_delta.usage 会按 Anthropic 字段名保留。

Claude Code / CC Switch 兼容入口是协议适配面,不等于第一版必须接入 Claude 官方供应商。第一版正式供应商仍优先 DeepSeek 和 GPT;网关负责把 Anthropic Messages 格式转换为内部统一模型调用,再输出 Claude Code / CC Switch 能识别的响应格式。后续如接入 Claude 官方 API,可在同一路由策略中增加 anthropic-compatible Provider。

Codex / Responses API Contract

Codex 兼容入口不应强行走 chat/completions。当前 /codex/v1/models/codex/models 已复用 AI Model starter 的模型元数据,返回 OpenAI Compatible 风格的模型列表,便于 Codex-like coding agents 完成模型发现;/codex/v1/responses/codex/responses 已提供 Responses API 风格的普通文本响应和 SSE 流式事件,同时平台内部继续统一落到模型别名、Provider 路由、Token 计量、余额 / 套餐扣费和审计。

请求头:

http
Authorization: Bearer sk-ai-...
Content-Type: application/json

/codex/v1/responses/codex/responses 第一版支持:

字段说明
model平台模型别名或上游模型名
inputResponses API 风格输入
instructions系统级或任务级指令
streamfalse 返回完整 responsetrue 返回 Responses API 风格 SSE 流式事件
temperature / top_p采样参数,转换为内部统一模型请求
max_output_tokens最大输出 token
tools / tool_choice工具定义和工具选择策略,透传到支持工具调用的上游 Provider

请求示例:

http
POST /api/v1/ai/gateway/codex/v1/responses
Authorization: Bearer sk-ai-...
Content-Type: application/json
json
{
  "model": "log-chat",
  "instructions": "be concise",
  "input": [
    {
      "role": "user",
      "content": [
        {
          "type": "input_text",
          "text": "ping"
        }
      ]
    }
  ],
  "max_output_tokens": 128
}

input 支持字符串、消息数组和 Responses item。网关会把 input_text 转为 OpenAI Compatible 文本块,把 input_image 转为 image_url 块,把历史 function_call 转成助手 tool_calls,把 function_call_output 转成 tool 消息并保留 call_id,便于 Codex-like 客户端继续多轮工具调用循环。文本摘要用于内部计量、审计和降级展示,复杂 content 原始结构会尽量保留给上游 Provider。

响应示例:

json
{
  "id": "resp_...",
  "object": "response",
  "created_at": 1770000000,
  "status": "completed",
  "model": "log-chat",
  "output": [
    {
      "id": "msg_...",
      "type": "message",
      "status": "completed",
      "role": "assistant",
      "content": [
        {
          "type": "output_text",
          "text": "pong"
        }
      ]
    }
  ],
  "output_text": "pong",
  "usage": {
    "input_tokens": 4,
    "output_tokens": 2,
    "total_tokens": 6
  }
}

函数调用响应示例:

json
{
  "id": "resp_...",
  "object": "response",
  "created_at": 1770000000,
  "status": "completed",
  "model": "log-chat",
  "output": [
    {
      "id": "fc_...",
      "type": "function_call",
      "status": "completed",
      "call_id": "call_1",
      "name": "lookup_order",
      "arguments": "{\"id\":\"A100\"}"
    }
  ],
  "output_text": "",
  "usage": {
    "input_tokens": 8,
    "output_tokens": 4,
    "total_tokens": 12
  }
}

Codex 兼容入口是客户端协议适配面,不等于第一版新增一个独立供应商。第一版正式供应商仍优先 DeepSeek 和 GPT;网关负责把 Responses API 风格请求转换为内部统一模型调用,再输出 Codex / Responses API 风格响应。模型返回 function_call 时,网关只负责转换响应结构和计量,具体工具执行、结果回传和多轮循环仍由客户端或 Agent 完成。

stream=true 时返回 text/event-stream,第一版事件序列包含:

  • response.created
  • response.in_progress
  • response.output_item.added
  • response.content_part.added
  • response.output_text.delta
  • response.function_call_arguments.delta
  • response.function_call_arguments.done
  • response.output_text.done
  • response.content_part.done
  • response.output_item.done
  • response.completed

Gemini Native Contract

Gemini Native 兼容入口用于接入使用 Google Gemini v1beta 请求结构的 SDK、工具或自研客户端。调用方可以把 base URL 配置为:

text
https://<host>/api/v1/ai/gateway/gemini

当前支持:

API说明Gateway Key scope
GET /v1beta/models返回 Gemini Native models[] 结构,包含 namedisplayNameinputTokenLimitoutputTokenLimitsupportedGenerationMethodsai:gateway:model:read
GET /v1beta/models/{modelId}返回单个 Gemini Native 模型项ai:gateway:model:read
POST /v1beta/models/{modelId}:generateContent接收 Gemini Native contentssystemInstructiongenerationConfigtoolssafetySettings,输出 candidates / usageMetadataai:gateway:chat:write
POST /v1beta/models/{modelId}:streamGenerateContent输出 Gemini Native SSE,逐块返回 data: { candidates, usageMetadata };不会追加 OpenAI [DONE] 标记ai:gateway:chat:write
POST /v1beta/models/{modelId}:countTokens使用本地 AiModelTokenEstimator 预估 GenerateContent 请求 token,返回 totalTokens,不触发上游模型调用、用量结算或 Provider 健康记录ai:gateway:model:read
POST /v1beta/models/{modelId}:embedContent接收 Gemini contenttaskTypetitleoutputDimensionality,转换到统一 embeddings 管线,返回 embedding.valuesai:gateway:embedding:write
POST /v1beta/models/{modelId}:batchEmbedContents接收 Gemini requests[],转换为一次 embeddings 批量输入,返回 embeddings[].valuesai:gateway:embedding:write

鉴权方式:

  • 推荐使用 Authorization: Bearer sk-ai-...x-api-key: sk-ai-...
  • 兼容 Gemini Native SDK 的查询参数形态:?key=sk-ai-...。该参数只作为 AI Gateway Key 读取入口,不会绕过 scope、模型白名单、Provider 白名单、限流、quota 或审计。

请求转换规则:

  • systemInstruction.parts[].text 会转为内部 system 消息。
  • contents[].role=model 会转为内部 assistant,其它角色按原语义保留;parts[].text 会合并为文本摘要用于计量和审计。
  • inlineDatafileData 会尽量转换为 OpenAI Compatible image_url 内容块,让当前 OpenAI Compatible Provider 能继续消费多模态输入;不可识别片段会保留到消息扩展结构。
  • parts[].functionCall 会保留到内部 functionCallparts[].functionResponse 会保留到消息扩展结构,便于后续工具循环或兼容上游继续消费。
  • generationConfig.temperaturetopPmaxOutputTokens 会映射到统一模型参数;stopSequencesresponseMimeTyperesponseSchemacandidateCountseed 和其它扩展字段会进入请求参数映射。
  • toolstoolConfig 保留到请求 metadata,供后续 Provider 模板、兼容上游或工具循环消费。
  • :countTokens 同时支持直接传入 GenerateContent payload,或按 Gemini SDK 常见形态传入 { "generateContentRequest": { ... } } 包装;包装只用于解析有效请求,不触发上游调用、用量结算或健康记录。

响应转换规则:

  • 普通响应输出 candidates[0].content.role=model,文本放入 parts[].text
  • 内部 finishReason=stop 输出 STOPfinishReason=length 输出 MAX_TOKENS,其它结束原因按大写原样输出。
  • AiModelUsage.inputTokens / outputTokens / totalTokens 分别映射为 usageMetadata.promptTokenCountcandidatesTokenCounttotalTokenCount
  • 流式响应使用 text/event-stream,每个增量片段都输出 Gemini Native JSON;最终 done 片段携带 usage,用于 usage event、扣费和凭证健康收口。
  • Embedding 响应会把内部 AiModelEmbedding.embedding 映射为 Gemini embedding.valuesembeddings[].values;批量请求作为一次网关调用进行 quota、usage event、Provider / Credential 健康记录。

Gemini Native 入口只是协议适配面,不新增独立供应商,也不绕过 AI Model Provider SPI。底层仍会进入模型别名、Provider 路由、Gateway Key、限流、quota、usage event、Provider 健康和凭证健康链路。若使用 Google 官方 OpenAI Compatible 入口,可以继续启用内置 gemini Provider 预设;若使用 Gemini Native 客户端,则访问本节的 /gemini/v1beta/** 网关入口。

Provider 路由

网关不直接写死某个模型厂商。调用链通过 AI 模型底座处理:

text
Gateway
  -> AiModelManager
  -> AiModelConfigResolver
  -> AiModelProvider

Provider 候选集会先按当前操作能力过滤,再进入 priority、weight、health 和 fallback 选择。chat/completions、流式对话、embeddings 和通用 relay 会分别要求对应 capabilities;例如 rerank 只会进入声明 rerank 的 Provider,files / uploads 只会进入声明 file 的 Provider,responses / conversations 会进入声明 response 的 Provider。后台路由视图会返回 supportedOperationsfilteredOperationsoperationRoutes,用于观察每个 Provider 能承接哪些 endpoint、哪些 endpoint 被能力过滤排除。

第一版 Provider 顺序建议:

Provider用途
mock离线测试、合同测试、构建验证
log调试、审计和观察请求结构
deepseek 配置实例第一阶段优先支持的正式供应商,使用 provider: openai-compatible 接入 DeepSeek 官方接口
openai-compatible公共 Provider 实现,用于接入 OpenAI Compatible 服务商和企业自建网关
newapiNewAPI 聚合网关快速接入 Provider,后台列表默认展示但关闭,管理员填入 NewAPI base URL / API Key 后启用;可通过 options.parameter-template / options.parameter-override 做上游默认参数和请求归一化;Provider metadata 暴露 channel-type=aggregatorcapability-profile=aggregated-openai-compatiblerelay-profile=full-relay
gemini / cerebras / fireworks / sambanova默认关闭的 OpenAI Compatible 官方渠道预设,后台启用并填写 API Key 后即可作为上游 Provider;如上游只支持部分 endpoint,可在 Provider options 中关闭业务路由或覆盖对应 relay-path.*;Provider 列表和路由视图会直接透出 channelTypecapabilityProfilerelayProfile
openai-officialOpenAI 官方 SDK 可选桥接 Provider;应用或可选 starter 提供 AiModelOfficialSdkClient 后可作为 fallback
anthropic-officialAnthropic 官方 SDK 可选桥接 Provider;用于后续 Claude 官方 SDK 能力兜底
anthropic-compatible支撑 Claude Code / Anthropic Messages 协议适配,后续可接 Claude 官方 API 或授权代理
codex-compatible支撑 Codex / Responses API 协议适配,面向 agentic coding、流式事件和工具调用
self-hosted远期接入自建算力中心或托管 GPU 网关

官方 SDK Provider 不引入默认 SDK 依赖,只提供统一模型 contract 的桥接点。配置到 fallback 链时,如果当前进程没有匹配的 AiModelOfficialSdkClient,Manager 会跳过该 Provider 并继续尝试后续 Provider;真实 OpenAI SDK、Claude Code / CC Switch、Cursor、Continue 等外部客户端联调仍放 P2 外部验收。

fallback 后必须记录原始模型、最终模型、Provider、切换原因和 requestId。

计量与安全

  • 鉴权失败、限流失败、余额不足:不调用上游,不扣费。
  • 上游失败且无有效输出:不扣费,只记录失败。
  • 流式中断但已产生有效输出:按实际 token 结算。
  • 用户 API Key 只保存 hash,不明文落库。
  • 供应商 Key 加密保存,后台脱敏展示。
  • 默认不保存完整 Prompt / Completion;需要保存时必须可配置、可脱敏、可关闭。
  • 管理员查看调用日志必须有权限和审计。

相关文档

Released under the Apache License 2.0.