8 Commits
Author SHA1 Message Date
wangdefa e1f8a0539c AI网关:Responses直通codex兼容与流式升级回退
CI / test (push) Successful in 31s
Release / release (push) Successful in 39s
2026-07-15 10:39:56 +08:00
wangdefa a8bde89b56 更新 DASH_VERSION 至 v0.6.0
CI / test (push) Successful in 46s
Release / release (push) Successful in 43s
2026-07-14 19:33:33 +08:00
wangdefa 1da2197a6c 渠道模型列表与测试端点,修复探测无配额误判 2026-07-14 19:33:33 +08:00
wangdefa 79c9e4d9b9 更新 DASH_VERSION 至 v0.5.1
CI / test (push) Successful in 24s
Release / release (push) Successful in 55s
2026-07-14 11:04:56 +08:00
wangdefa 2fea315430 OIDC 登录/绑定回调写系统日志
CI / test (push) Successful in 30s
2026-07-14 11:00:55 +08:00
wangdefa b4ef98a25e AI网关新增xAI格式TTS端点与过滤弃用模型开关
CI / test (push) Successful in 32s
Release / release (push) Successful in 54s
- POST /ai/v1/tts:xAI 官方 TTS 格式转换层(text/voice_id→input/voice),复用 Speech 编排,model 缺省 xai.grok-tts;实测 output_format/speed 透传生效
- 「过滤弃用模型」开关(GET/PUT /api/v1/ai-settings,settings 表持久化):开启后已宣布弃用(未退役)模型从列表与路由排除;同步入库与退役提醒不受影响
- AI 网关文档更名 docs/AI网关.md,补 tts 矩阵段与开关说明;README 引用同步
- CHANGELOG 0.5.0(0.4.0 已发版冻结);DASH_VERSION v0.5.0
2026-07-14 09:49:28 +08:00
wangdefa 0a86b5a291 AI网关新增TTS/重排/审核端点,xAI工具扩展,swagger修缺
CI / test (push) Successful in 32s
Release / release (push) Successful in 1m4s
- 新端点 /ai/v1/audio/speech(xai.grok-tts)、/rerank(cohere.rerank-v4)、/moderations(OCI Guardrails)
- Responses 放行 code_interpreter 与远程 mcp 工具,web_search/x_search 解除仅非流式限制
- 模型能力映射扩展:TEXT_RERANK→RERANK、TEXT_TO_AUDIO→TTS
- AI 网关文档独立 docs/ai-gateway.md,字段兼容矩阵只列支持项;README 精简引用
- swagger 修缺:135 处响应注解具体化,RawMessage/联合类型统一渲染 AnyJSON,overrides 迁至 docs/.swaggo
- CHANGELOG 0.4.0,版本段不再记日期;DASH_VERSION v0.4.0
2026-07-13 20:17:06 +08:00
wangdefa 9309ad1ffc 修复 AI 网关流式断流:错误透传、自动降级,max_tokens 可缺省
CI / test (push) Successful in 33s
Release / release (push) Successful in 56s
2026-07-13 15:06:01 +08:00
59 changed files with 13583 additions and 1431 deletions
+2 -2
View File
@@ -1,6 +1,6 @@
# Backend Development Guidelines(oci-portal 后端规范) # Backend Development Guidelines(oci-portal 后端规范)
> Go 后端(`oci-portal/`)编码规范入口。规范提炼自 Google / Uber Go Style Guide、Effective Go 与 Go 官方模块布局指南,按本项目裁剪;条目与项目约定冲突时,以本 spec 为准。迁自 docs/开发指南.md 与根目录 AGENTS.md(2026-07)。 > Go 后端(`oci-portal/`)编码规范入口。规范提炼自 Google / Uber Go Style Guide、Effective Go 与 Go 官方模块布局指南,按本项目裁剪;条目与项目约定冲突时,以本 spec 为准。
--- ---
@@ -51,7 +51,7 @@ go mod tidy # 依赖有变更时
全部 HTTP 接口带 swaggo 注释(@Summary 中文/@Tags 按域/@Param/@Success/@Router;JWT 组接口标 @Security BearerAuth)。**新增或修改接口必须同步注释**,并重新生成 spec: 全部 HTTP 接口带 swaggo 注释(@Summary 中文/@Tags 按域/@Param/@Success/@Router;JWT 组接口标 @Security BearerAuth)。**新增或修改接口必须同步注释**,并重新生成 spec:
```bash ```bash
go tool swag init -g cmd/server/main.go -o docs --parseInternal --parseDependency go tool swag init -g cmd/server/main.go -o docs --parseInternal --parseDependency --overridesFile docs/.swaggo
``` ```
生成的 `docs/` 一并提交;UI 由 `SWAGGER=1` 开启(/swagger/index.html)。同名 handler 方法(list/create/get/update/remove)分布在多个 struct 上,写注释时确认 @Router 路径与该 receiver 的真实注册一致(routes_*.go)。 生成的 `docs/` 一并提交;UI 由 `SWAGGER=1` 开启(/swagger/index.html)。同名 handler 方法(list/create/get/update/remove)分布在多个 struct 上,写注释时确认 @Router 路径与该 receiver 的真实注册一致(routes_*.go)。
+80 -5
View File
@@ -1,8 +1,83 @@
# Changelog # Changelog
格式遵循 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/),版本号遵循语义化版本。 格式参考 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/)(版本段不记日期),版本号遵循语义化版本。
## [0.3.0] - 2026-07-13 ## [0.6.1]
### Added
- Responses 直通 codex 兼容层,codex CLI`wire_api = "responses"`)指向网关即用,实测 codex-cli 0.144.1 主会话与 multi-agent 子代理全链路可用:
- `namespace` 工具组(承载 codex multi-agent 与全部 MCP 工具,仅 OpenAI 原生后端识别,OCI 实测 422)拍平为限定名 `function` 工具上送(`ns__child``mcp__` 开头子工具名不加前缀),响应中命中的 `function_call` 还原为短名并补回 `namespace` 字段(codex 以该双字段路由);多轮历史 `function_call` 与对象形态 `tool_choice` 上的 `namespace` 字段自动重限定
- `custom` 自由格式工具(apply_patch 及 GPT-5.x 档位子代理形态,OCI 不识别)转换为带 `{"input": string}` 包装 schema 的 `function`,响应回转 `custom_tool_call` 并解包 `input`,多轮历史的 `custom_tool_call(_output)` 逆向转换,往返无损;例外:`apply_patch` 整体剥离(grok 系未训练 codex 补丁格式,模型自然回落 shell 编辑)
- `tool_search`(codex 工具目录搜索)剥离:namespace 已全量拍平上送,搜索语义冗余且上游不识别
- `web_search` 的 OpenAI 专有参数 `external_web_access`OCI 实测 400):`true` 仅删键放行(等价上游默认行为),`false` 为"仅缓存检索"降权模式,按不越权原则连工具剥离
- 以上改写动作(拍平 / 转换 / 剥离)与校验拒绝均记服务端日志可观测
- Responses 直通流式升级回退:实测 OCI 上游对超过约 82KB 的流式请求会在推理阶段掐断流(纯请求体积触发,与工具构成无关,非流式不受影响),请求体超 76KB 时自动改调非流式上游并合成最小 SSE 事件序列(`created` → 逐项 `output_item.done``completed`)返回,语义完整仅丢失增量输出——0.3.1 中「Responses 直通无法透明降级」的限制自此按体积预判解除
### Changed
- `/ai/v1/responses` 工具类型白名单扩展:`namespace` / `custom` / `tool_search` 不再 400 拒绝,按上述兼容策略处理后转发;其余未知工具类型维持请求前置拒绝
## [0.6.0]
### Added
- 渠道模型缓存列表端点 `GET /api/v1/ai-channels/{id}/models`:黑名单模型查询层兜底排除,「过滤弃用模型」开关开启时同样剔除已宣布弃用者(数据保留,展示口径过滤)
- 单模型测试端点 `POST /api/v1/ai-channels/{id}/test-model`:对指定模型发 max_tokens=16 试调,通过即写入渠道「探测验证模型」(此后手动探测与每日后台任务将其置于试调候选首位),渠道探测状态不为可用时顺带置可用并复位熔断;未通过如实返回上游错误且不改动渠道状态
- 渠道列表响应回填 `modelCount`(模型缓存计数,与模型列表同口径:排除黑名单、随过滤弃用开关)
### Fixed
- 修复渠道探测「无配额」误判:配额试调遇 401/403/鉴权 404 不再立即定论租户无配额(可能仅个别模型无权限),改为继续尝试其余候选,任一成功即判可用,全部失败且出现过鉴权拒绝才判无配额
- 探测试调 `max_output_tokens` 由 1 提升到 16openai.gpt-oss 系列要求 ≥16,原值被 400 拒导致仅有该系列对话模型的渠道被误判
## [0.5.1]
### Fixed
- 修复外部身份(OAuth2)登录 / 绑定无系统日志的问题:回调成功记 200(用户名为面板账号)、失败记 401(附失败原因);此前回调为 GET 请求不经写操作日志中间件,完全无记录
## [0.5.0]
### Added
- xAI 官方格式文本转语音端点 `POST /ai/v1/tts`:接受 xAI 官方 TTS 请求(`text` / `language` 必填,`voice_id``output_format`{codec, sample_rate, bit_rate}、`speed` 等),网关转换为 OpenAI 兼容形态后与 `/ai/v1/audio/speech` 走同一上游与渠道调度;`model` 为网关扩展字段(缺省 `xai.grok-tts`);实测 `output_format` 对象与 `speed` 透传生效,xAI SDK / 客户端可直接指向网关
- 「过滤弃用模型」开关(`GET` / `PUT /api/v1/ai-settings`,持久化):开启后 OCI 已宣布弃用(即使未到退役日)的模型从模型列表与路由中同时排除,关闭恢复;渠道同步入库与 30 天退役提醒不受影响
### Changed
- AI 网关文档更名为 `docs/AI网关.md`(原 `docs/ai-gateway.md`),README 引用同步
## [0.4.0]
### Added
- 文本转语音端点 `POST /ai/v1/audio/speech`OpenAI Audio Speech 兼容,直通 OCI 兼容面(模型 `xai.grok-tts`voice 取 xAI Grok Voice 列表 `ara`/`eve`/`leo`/`rex`/`sal`);上游必填的 `language` 缺省时自动注入 `"auto"`,xAI 专属参数平铺透传;响应为一次性完整音频(Content-Type 透传上游,缺省 audio/mpeg),不提供流式
- 文档重排端点 `POST /ai/v1/rerank`Jina / Cohere 通行协议,走 OCI typed 面(`cohere.rerank-v4.0-pro` / `-fast`),支持 `top_n``return_documents``results[].index` 指向入参 `documents` 下标
- 内容审核端点 `POST /ai/v1/moderations`OpenAI moderations 外壳映射 OCI Guardrails(内容审核 / PII / 提示注入),`input` 为字符串或字符串数组(单次至多 8 条),categories 用 OCI 原生维度 `overall` / `blocklist` / `prompt_injection`(任一得分 ≥0.5 判 `flagged`),PII 命中放扩展字段 `results[].pii`(不参与 flagged;实测中文人名 / 手机号识别较弱,英文正常)
- Responses 服务端工具扩展:放行 Oracle 文档化的 xAI `code_interpreter` 与远程 `mcp` 工具,并解除 `web_search` / `x_search` 仅非流式的限制——四类服务端工具非流式与流式均实测可用;`code_interpreter` 的命名容器管理与 File Search 不提供
- 模型能力映射扩展:`TEXT_RERANK` → RERANK、`TEXT_TO_AUDIO` → TTS,渠道探测 / 同步自动发现重排与语音模型入池
### Changed
- AI 网关文档独立成篇 `docs/ai-gateway.md`(端点定位、兼容边界、已知上游限制、字段兼容矩阵——矩阵只列支持项,不支持 / 忽略项以文字简述),README 精简为概览并引用;实测披露:Responses `input_file` 内容块被上游以 ZDR 形态拒绝,能力不可用
- swagger 全面修缺:135 处响应注解从泛型 map 改为具体类型(补文档用途响应结构与泛型列表外壳),AI 网关端点请求 / 响应 schema 完整可见;`json.RawMessage` 与联合类型统一渲染为任意 JSON 值(AnyJSON),不再误显示为 byte 数组;swag overrides 配置移至 `docs/.swaggo`,生成命令加 `--overridesFile docs/.swaggo`;顺带修正网页控制台会话创建响应码(200→201)与 SAML 元数据下载(改文件响应)两处注解失真
## [0.3.1]
### Added
- AI 网关流式断流自动降级:Messages 与 Chat Completions 流式请求在客户端尚未收到任何输出时遭遇上游断流,自动降级为非流式重做,结果按标准事件 / chunk 序列一次推送,调用日志记 `retries=1` 与降级标记。实测 OCI 兼容面对 `instructions``tools` 合计超约 64.5KB 的流式请求会静默断连(无错误事件,非流式正常,消息正文不计入),Claude Code 等大体量系统提示客户端极易触发;Responses 直通因初始事件已转发无法透明降级,日志记「上游流提前终止」;README 增补「已知上游限制:大 system 区流式断流」小节
### Changed
- Messages 的 `max_tokens` 改为可缺省:缺省或 ≤0 时按默认值 8192 放行(此前返回 400;部分客户端将该字段视为选填)
### Fixed
- AI 网关流式假成功:上游 error / `response.failed` 事件此前被吞掉,流提前 EOF 也被伪装成正常结束,调用日志呈现 200 · 0/0 且无错误信息;现 Messages 将上游失败转为 Anthropic `error` 事件,三个流式端点日志均记录上游错误消息或「上游流提前终止,未返回终态事件」
## [0.3.0]
### Added ### Added
@@ -19,7 +94,7 @@
- **移除自定义审计告警规则**及其阈值、窗口和冷却匹配能力;`/api/v1/log-events/alert-rules``/api/v1/log-events/alert-rules/{ruleId}` 管理接口、`audit_alert` 通知模板不再提供,已有规则升级后不再执行 - **移除自定义审计告警规则**及其阈值、窗口和冷却匹配能力;`/api/v1/log-events/alert-rules``/api/v1/log-events/alert-rules/{ruleId}` 管理接口、`audit_alert` 通知模板不再提供,已有规则升级后不再执行
## [0.2.0] - 2026-07-12 ## [0.2.0]
### Added ### Added
@@ -46,7 +121,7 @@
- 渠道「同步模型成功但探测报错不可用」:法兰克福等区域的微调基座模型占满探测候选导致的误报(探测状态与真实可用性不符的根因) - 渠道「同步模型成功但探测报错不可用」:法兰克福等区域的微调基座模型占满探测候选导致的误报(探测状态与真实可用性不符的根因)
- 租户删除:告警命中清理改子查询,日志事件数万条时不再超出 SQL 绑定变量上限导致删除失败;无法解析的任务 payload 记警告跳过并保留原任务,不再永久阻断租户删除 - 租户删除:告警命中清理改子查询,日志事件数万条时不再超出 SQL 绑定变量上限导致删除失败;无法解析的任务 payload 记警告跳过并保留原任务,不再永久阻断租户删除
## [0.1.0] - 2026-07-10 ## [0.1.0]
### Added ### Added
@@ -74,7 +149,7 @@
- HTTP 入口加固:显式读写超时与优雅关闭、请求体上限(面板 1MB / AI 网关 10MB)、登录字段长度上限、登录守卫条目数有界 - HTTP 入口加固:显式读写超时与优雅关闭、请求体上限(面板 1MB / AI 网关 10MB)、登录字段长度上限、登录守卫条目数有界
- 出错响应脱敏:内部错误只返回固定文案 + requestId,完整原因写服务端日志;GORM SQL 日志参数化输出,不再记录实参 - 出错响应脱敏:内部错误只返回固定文案 + requestId,完整原因写服务端日志;GORM SQL 日志参数化输出,不再记录实参
## [0.0.1] - 2026-07-09 ## [0.0.1]
首个版本:自托管 OCI 多租户管理面板后端。 首个版本:自托管 OCI 多租户管理面板后端。
+1 -1
View File
@@ -1 +1 @@
v0.3.0 v0.6.0
+9 -184
View File
@@ -197,196 +197,21 @@ server {
## AI 网关 ## AI 网关
AI 网关使用面板创建的独立密钥鉴权,支持 `Authorization: Bearer sk-...` `x-api-key: sk-...`。密钥可绑定渠道分组和模型白名单;全局模型黑名单会从模型列表、路由和探测候选中同时排除目标模型 面板内置 OpenAI / Anthropic 兼容的 GenAI 网关:独立密钥鉴权`Authorization: Bearer sk-...` `x-api-key`),支持渠道分组、加权路由、熔断探测、模型黑白名单、内容日志与调用日志
| 端点 | 定位 | 流式 | | 端点 | 定位 | 流式 |
| --- | --- | --- | | --- | --- | --- |
| `POST /ai/v1/responses` | OpenAI Responses,无状态主接口 | SSE;服务端工具除外 | | `POST /ai/v1/responses` | OpenAI Responses,无状态主接口xAI 服务端工具 / MCP | SSE |
| `POST /ai/v1/chat/completions` | OpenAI Chat Completions,存量客户端兼容层 | SSE | | `POST /ai/v1/chat/completions` | OpenAI Chat Completions 兼容层 | SSE |
| `POST /ai/v1/messages` | Anthropic Messages 转换层 | SSE | | `POST /ai/v1/messages` | Anthropic Messages 转换层 | SSE |
| `POST /ai/v1/embeddings` | OpenAI Embeddings | 否 | | `POST /ai/v1/embeddings` | OpenAI Embeddings | 否 |
| `POST /ai/v1/audio/speech` | 文本转语音(xAI Voice | 否 |
| `POST /ai/v1/tts` | 文本转语音(xAI 官方格式) | 否 |
| `POST /ai/v1/rerank` | 文档重排(Cohere Rerank | 否 |
| `POST /ai/v1/moderations` | 内容审核(OCI Guardrails | 否 |
| `GET /ai/v1/models` | 当前密钥可见的模型列表 | 否 | | `GET /ai/v1/models` | 当前密钥可见的模型列表 | 否 |
兼容边界 协议兼容边界、已知上游限制与逐字段兼容矩阵见 **[AI 网关文档](./docs/AI网关.md)**。
- 对话请求统一转发 OCI OpenAI 兼容面,当前供给以 `xai.`、`meta.`、`openai.` 前缀模型为主;Cohere Embeddings 不受该对话模型范围影响
- 网关不保存会话历史,客户端需要携带完整上下文;Responses 拒绝非空 `previous_response_id`、非 `null` `conversation` 和 `background:true`
- Responses 支持 xAI Grok `web_search` / `x_search` 服务端工具,但仅限非流式请求
- Responses 的 `reasoning.effort`、Messages 的 `output_config.effort` 和 Chat Completions 的 `reasoning_effort` 会传给上游,实际档位和效果由模型决定
- Chat Completions 只承担协议转换与兼容修复;新能力优先在 Responses 和 Messages 提供
- 单次请求最多尝试三个渠道;可重试错误会切换渠道,流式响应建立后不会换渠道重试
这里提供的是兼容接口而非 OpenAI / Anthropic 协议的完整实现。OCI OpenAI 兼容面的部分行为来自实测,未见 Oracle 文档承诺,可能随上游调整。路由与鉴权定义以 [Swagger YAML](docs/swagger.yaml) 或运行时 Swagger UI 为准;无法由 OpenAPI 完整表达的兼容边界列于上方。
### 字段兼容矩阵
以下矩阵以 2026-07-13 的 [OpenAI Responses](https://developers.openai.com/api/reference/resources/responses/methods/create)、[Chat Completions](https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create)、[Embeddings](https://developers.openai.com/api/reference/resources/embeddings/methods/create) 和 [Anthropic Messages](https://platform.claude.com/docs/en/api/messages/create) 为标准基线,并与当前实现逐项核对。
这是一份兼容性快照,不替代 Swagger。标准接口和 OCI 上游都可能变化,最终行为以当前版本代码与实测为准。
| 标记 | 含义 |
| :---: | --- |
| ✅ | 网关直接支持 |
| ➡️ | 网关原样透传;是否生效由 OCI 上游决定 |
| 🔄 | 网关进行字段或协议转换后支持 |
| ◐ | 部分支持、存在前置条件或语义降级 |
| ⚠️ | 请求可被接受,但字段会被忽略 |
| ❌ | 网关在请求到达上游前拒绝 |
<details>
<summary><code>POST /ai/v1/responses</code> 对比 OpenAI Responses</summary>
Responses 是“原始 JSON 直通 + 本地门禁”。除 `store` 外,网关不会重建请求体;未知顶层字段也会保留并送往 OCI。
| 标准字段 | 状态 | 网关行为 |
| --- | :---: | --- |
| `model` | ◐ | 必须非空,还要通过密钥模型白名单并匹配可用渠道;随后原样透传 |
| `input` | ➡️ | 支持标准的字符串或 item 数组,原始内容透传;网关不逐项保证 OCI 能处理所有 item 类型 |
| `instructions`、`max_output_tokens` | ➡️ | 类型可解析后原样透传,不做范围或模型能力校验 |
| `temperature`、`top_p`、`parallel_tool_calls` | ➡️ | 原样透传,不做取值范围校验 |
| `text` / `text.format` / `text.verbosity` | ➡️ | 整个原始对象透传;结构化输出是否可用由 OCI 模型决定 |
| `reasoning` | ➡️ | 整个原始对象透传;`effort` 不校验档位,`summary` 等字段不会被网关删除 |
| `tool_choice` | ➡️ | 任意 JSON 原样透传,本地不校验枚举或结构 |
| `context_management`、`include`、`max_tool_calls`、`metadata`、`moderation`、`prompt` | ➡️ | 网关未建模但会保留在原始请求中,由 OCI 决定是否接受 |
| `prompt_cache_key`、`prompt_cache_retention`、`safety_identifier`、`service_tier` | ➡️ | 原样透传,不代表 OCI 一定实现 OpenAI 的对应语义 |
| `stream_options`、`top_logprobs`、`truncation`、`user` | ➡️ | 原样透传,不做本地语义校验 |
| `store` | 🔄 | 无论客户端传什么,上游请求都强制改写为 `false` |
| `previous_response_id` | ❌ | 非空即返回 400;网关不保存历史响应 |
| `conversation` | ◐ | 省略或 `null` 可通过;任何非 `null` 值返回 400 |
| `background` | ◐ | `true` 返回 400`false`、`null` 或省略时继续透传 |
| `stream` | ◐ | 普通请求和 `function` 工具支持 SSE;含 `web_search` / `x_search` 时拒绝流式 |
| `tools[].type=function` | ➡️ | 非流式和流式均可,工具对象原样透传 |
| `tools[].type=web_search` / `x_search` | ◐ | 使用 xAI 服务端工具语义且仅支持非流式;`x_search` 不是 OpenAI 标准工具 |
| 其他标准工具类型 | ❌ | `web_search_preview`、`file_search`、`computer`、`code_interpreter`、`image_generation`、`mcp`、`shell`、`custom` 等返回 400 |
| 其他未知顶层字段 | ➡️ | 只要整个请求是合法 JSON,字段名、结构和数值都会保留 |
响应边界:
- 非流式成功响应不做转换,OCI JSON 原样返回;usage 解析只用于面板调用日志
- SSE 事件逐行原样转发,不补 `data: [DONE]`,推理增量也不会被网关过滤
- 流建立前最多切换三个渠道;流建立后中断不重试,客户端可能只收到部分事件
- 未知模型返回 404、无渠道返回 503;上游错误会套入 OpenAI 风格错误体,不保证与标准 OpenAI 错误字段完全相同
实现依据:[`airesponses.go`](internal/service/airesponses.go) · [`responses.go`](internal/aiwire/responses.go) · [`aigateway.go`](internal/api/aigateway.go)
</details>
<details>
<summary><code>POST /ai/v1/chat/completions</code> 对比 OpenAI Chat Completions</summary>
Chat Completions 会先转换为 Responses 请求,再把 OCI Responses 响应桥接回 Chat Completions 形态。
| 标准字段 | 状态 | 网关行为 |
| --- | :---: | --- |
| `model` | ◐ | 必填,受密钥白名单和可用渠道限制;模型名保留到上游请求 |
| `messages` | 🔄 | 必填并转换为 Responses `input` / `instructions` |
| `system` / `developer` 消息 | ◐ | 文本按出现顺序合并为 `instructions`;块数组中的非文本内容被忽略 |
| `user` / `assistant` 文本内容 | 🔄 | 字符串及 `text` 块分别转为 `input_text` / `output_text` |
| `image_url` 内容块 | ◐ | URL 或 data URI 转为 `input_image``image_url.detail` 被忽略 |
| `input_audio`、`file`、`refusal` 等内容块 | ❌ | 当前消息转换器不支持,返回 400 |
| assistant `tool_calls` / `role=tool` | 🔄 | 转为 `function_call` / `function_call_output`,保留调用 ID、函数名和参数 |
| 消息 `name`、`refusal`、`audio`、旧式 `function_call` | ⚠️ | 当前消息结构未建模,静默忽略 |
| `max_completion_tokens` | 🔄 | 转为 `max_output_tokens`,优先于 `max_tokens` |
| `max_tokens` | 🔄 | 未提供 `max_completion_tokens` 时转为 `max_output_tokens` |
| `temperature`、`top_p`、`parallel_tool_calls` | ◐ | 原值写入 Responses 请求,但不校验范围或模型能力 |
| `stream` | 🔄 | OCI Responses SSE 桥接为 `chat.completion.chunk`,末尾补 `data: [DONE]` |
| `stream_options.include_usage` | 🔄 | 控制网关在终块后追加 `choices: []` 的 usage 块 |
| `stream_options.include_obfuscation` | ⚠️ | 未建模,静默忽略 |
| `tools[].type=function` | ◐ | `name`、`description`、`parameters` 支持;`function.strict` 被忽略 |
| `tools[].type=custom` 及其他工具 | ❌ | 只接受 `function`,其他类型返回 400 |
| `tool_choice` | ◐ | 支持 `auto` / `none` / `required` 和具名 function;非法或未知值被静默忽略 |
| `response_format` | ◐ | `json_object`、`json_schema` 转为 Responses `text.format`;未知类型交给 OCI 处理 |
| `reasoning_effort` | ◐ | 转小写后映射为 `reasoning.effort`,不校验模型或档位 |
| `store` | ⚠️ / 🔄 | 客户端字段被忽略,转换后的上游请求始终使用 `store:false` |
| `stop`、`seed`、`n`、`frequency_penalty`、`presence_penalty` | ⚠️ | 静默忽略;`n` 因此恒为单个 choice |
| `logprobs`、`top_logprobs`、`logit_bias`、`user` | ⚠️ | 静默忽略 |
| `audio`、`modalities`、`prediction`、`metadata`、`moderation` | ⚠️ | 静默忽略 |
| `prompt_cache_key`、`safety_identifier`、`service_tier`、`verbosity`、`web_search_options` | ⚠️ | 静默忽略 |
| 其他未知字段 | ⚠️ | JSON 解码器不会拒绝未知字段,但转换后的上游请求不包含它们 |
响应边界:
- 非流式固定生成一个 `choices[0]`;文本会合并,函数调用转为 `tool_calls`
- `finish_reason` 只生成 `stop`、`tool_calls`、`length`;其他上游终止原因不保留
- reasoning 输出、logprobs、refusal、annotations、audio、service tier 和 system fingerprint 不返回
- usage 保留 `prompt_tokens`、`completion_tokens`、`total_tokens` 和 `prompt_tokens_details.cached_tokens`
- 已建立的流中断或上游 `response.failed` 不会转换成标准 SSE 错误事件
实现依据:[`chatresponses.go`](internal/service/chatresponses.go) · [`openai.go`](internal/aiwire/openai.go) · [`aigateway.go`](internal/api/aigateway.go)
</details>
<details>
<summary><code>POST /ai/v1/embeddings</code> 对比 OpenAI Embeddings</summary>
| 标准字段 | 状态 | 网关行为 |
| --- | :---: | --- |
| `model` | ◐ | 必填,受密钥白名单限制,并且必须存在具有 `EMBEDDING` 能力的渠道 |
| `input` 为字符串 | ✅ | 包装为单个输入后调用 OCI |
| `input` 为字符串数组 | ✅ | 按原顺序调用 OCI |
| `input` 为 token ID 数组或二维 token ID 数组 | ❌ | 只能解码字符串或字符串数组,绑定阶段返回 400 |
| 空数组 / `null` | ❌ | 本地返回 400;空字符串不在本地拒绝,由 OCI 决定 |
| `dimensions` | ◐ | 映射为 OCI 输出维度,不做范围或模型能力校验 |
| `encoding_format=float` | ✅ | 返回 float 数组;省略时行为相同 |
| `encoding_format=base64` | ❌ | 本地返回 400,不提供 base64 响应 |
| `user` | ⚠️ | 能解析但不会传给 OCI |
| 其他未知字段 | ⚠️ | 静默忽略 |
响应使用标准的 `object:"list"`、`data[].object:"embedding"`、`index`、`model` 和可选 `usage` 外壳;向量为 `float32` 数组,不支持流式。
实现依据:[`embeddings.go`](internal/aiwire/embeddings.go) · [`aigateway_chat.go`](internal/service/aigateway_chat.go) · [`aigateway.go`](internal/api/aigateway.go)
</details>
<details>
<summary><code>POST /ai/v1/messages</code> 对比 Anthropic Messages</summary>
网关接受 `Authorization: Bearer` 或 `x-api-key`,但不会校验或使用标准 Anthropic `anthropic-version`、`anthropic-beta` 请求头。
| 标准字段 | 状态 | 网关行为 |
| --- | :---: | --- |
| `model` | ◐ | 用于模型与渠道选择,但空字符串不会在 handler 中按参数错误拒绝,通常最终返回模型不存在 |
| `max_tokens` | 🔄 | 必填且必须大于 0,转换为 `max_output_tokens` |
| `messages` | ◐ | 必须非空;角色、交替顺序和空内容不做完整校验 |
| `system` | ◐ | 支持字符串或 text 块数组;多个文本块直接拼接,`cache_control` 等附加字段被忽略 |
| `temperature`、`top_p` | ◐ | 写入 Responses 请求,不做取值范围或模型能力校验 |
| `top_k` | ⚠️ | 能解析但不会传给上游 |
| `stop_sequences` | ⚠️ | 能解析但不会传给上游;响应 `stop_sequence` 恒为 `null` |
| `stream` | 🔄 | Responses SSE 桥接为 Anthropic 事件序列 |
| `tools` | ◐ | 每个工具都转换成 Responses `function`;自定义客户端工具可用,Anthropic 服务端工具类型不保留原语义 |
| `tool_choice` | ◐ | 支持 `auto`、`any`、`none`、具名 `tool``disable_parallel_tool_use` 等附加字段被忽略 |
| `metadata` | ⚠️ | 能解析但不会传给上游 |
| `thinking` | ⚠️ | 顶层 thinking 配置不会控制上游思考预算 |
| `output_config.effort` | 🔄 | 转小写后映射为 Responses `reasoning.effort` |
| `output_config` 其他子字段 | ⚠️ | 未建模,静默忽略 |
| `cache_control`、`container`、`inference_geo`、`service_tier` | ⚠️ | 标准 SDK 中存在,但当前请求结构未建模,静默忽略 |
| 其他未知顶层字段 | ⚠️ | JSON 解码器接受,但转换后的上游请求不包含它们 |
`messages[].content`
| 标准内容块 | 状态 | 网关行为 |
| --- | :---: | --- |
| 字符串 / `text` | 🔄 | user 转 `input_text`assistant 历史转 `output_text` |
| `image` | ◐ | 仅支持 `base64` 和 `url` source;缺字段或其他 source 类型返回 400 |
| `tool_use` | 🔄 | 转为 `function_call`,保留 ID、名称和输入 |
| `tool_result` | ◐ | 转为 `function_call_output`;块数组只拼接 text`is_error` 和非文本结果丢失 |
| `thinking` / `redacted_thinking` | ⚠️ | 历史思考块被删除,不进入上游上下文 |
| `document`、服务端工具结果及其他未知块 | ❌ | 返回 400 |
| `null` / 空块数组 | ◐ | 该消息可能从上游 input 中消失,不返回参数错误 |
响应边界:
- 非流式只把 Responses `output_text` 转成 `text`、`function_call` 转成 `tool_use`
- `stop_reason` 只生成 `end_turn`、`tool_use`、`max_tokens``stop_sequence` 恒为 `null`
- reasoning 不会生成 Anthropic `thinking` / `redacted_thinking` 块,也没有 signature
- usage 只保留 `input_tokens`、`output_tokens` 和 `cache_read_input_tokens`,不提供 `cache_creation_input_tokens`
- 流式输出标准事件骨架,但不生成 `thinking_delta`、`signature_delta` 或上游失败对应的 Anthropic `error` 事件
实现依据:[`anthresponses.go`](internal/service/anthresponses.go) · [`anthropic.go`](internal/aiwire/anthropic.go) · [`aigateway.go`](internal/api/aigateway.go)
</details>
`GET /ai/v1/models` 使用 OpenAI Models 列表外壳(`object`、`data[].id/object/created/owned_by`),但只返回当前渠道目录中通过分组、全局黑名单和密钥白名单筛选后的模型;网关不提供标准的单模型检索端点。
## API 与配置 ## API 与配置
@@ -436,7 +261,7 @@ go vet ./...
go test ./... go test ./...
# Handler 注释变更后重新生成唯一的对外 API 文档。 # Handler 注释变更后重新生成唯一的对外 API 文档。
go tool swag init -g cmd/server/main.go -o docs --parseInternal --parseDependency go tool swag init -g cmd/server/main.go -o docs --parseInternal --parseDependency --overridesFile docs/.swaggo
``` ```
- Go 后端规范与目录约定:[`AGENTS.md`](AGENTS.md) · [`.trellis/spec/backend/`](.trellis/spec/backend/) - Go 后端规范与目录约定:[`AGENTS.md`](AGENTS.md) · [`.trellis/spec/backend/`](.trellis/spec/backend/)
+6
View File
@@ -0,0 +1,6 @@
// swag 全局类型替换:原始 JSON 与联合类型统一渲染为 AnyJSON(任意 JSON 值),
// 避免 json.RawMessage 被误渲染成 byte 数组、联合类型暴露内部字段。
replace encoding/json.RawMessage oci-portal/internal/aiwire.AnyJSON
replace oci-portal/internal/aiwire.RespInput oci-portal/internal/aiwire.AnyJSON
replace oci-portal/internal/aiwire.Content oci-portal/internal/aiwire.AnyJSON
replace oci-portal/internal/aiwire.StringList oci-portal/internal/aiwire.AnyJSON
+512
View File
@@ -0,0 +1,512 @@
# AI 网关
> [!NOTE]
> OCI Portal AI 网关将多个 OCI GenAI 渠道统一为 OpenAI、Anthropic 与 xAI
> 兼容接口,并集中处理鉴权、模型访问控制、渠道调度和协议适配。
>
> 路径、参数与响应结构以 [Swagger YAML](swagger.yaml) 或运行时 Swagger UI
> 为准;协议差异、兼容改写和实测边界以本文为准。
**兼容快照:2026-07-15**
## 快速导航
- [快速接入](#quick-start)
- [端点一览](#endpoints)
- [路由与全局行为](#routing)
- [Codex 接入](#codex)
- [已知限制](#limitations)
- [字段兼容矩阵](#compatibility)
- [实现索引](#implementation)
<a id="quick-start"></a>
## 快速接入
### 基础地址与鉴权
```text
Base URL: https://<网关地址>/ai/v1
```
网关密钥在管理面板中创建,支持以下任一请求头:
```http
Authorization: Bearer sk-...
```
```http
x-api-key: sk-...
```
密钥可绑定渠道分组和模型白名单。全局模型黑名单会同时作用于模型列表、
请求路由和探测候选;开启「过滤弃用模型」后,OCI 已宣布弃用的模型也会从
列表与路由中移除。
可先用模型列表验证地址与密钥:
```bash
curl "https://<网关地址>/ai/v1/models" \
-H "Authorization: Bearer $OCI_PORTAL_KEY"
```
<a id="endpoints"></a>
## 端点一览
| 协议域 | 端点 | 角色 | 流式 |
| --- | --- | --- | :---: |
| 对话 | `POST /ai/v1/responses` | OpenAI Responses,无状态主接口 | SSE |
| 对话 | `POST /ai/v1/chat/completions` | OpenAI Chat Completions 兼容层 | SSE |
| 对话 | `POST /ai/v1/messages` | Anthropic Messages 转换层 | SSE |
| 向量 | `POST /ai/v1/embeddings` | OpenAI Embeddings | — |
| 语音 | `POST /ai/v1/audio/speech` | OpenAI Audio Speech 外壳 | — |
| 语音 | `POST /ai/v1/tts` | xAI TTS 格式转换层 | — |
| 检索 | `POST /ai/v1/rerank` | Cohere / Jina 风格文档重排 | — |
| 安全 | `POST /ai/v1/moderations` | OpenAI 外壳映射 OCI Guardrails | — |
| 发现 | `GET /ai/v1/models` | 当前密钥可见模型列表 | — |
选择建议:
- 新客户端优先使用 **Responses**
- Anthropic SDK 或 Claude 生态客户端使用 **Messages**
- 仅支持旧 OpenAI 对话协议的客户端使用 **Chat Completions**
- Embeddings、TTS、Rerank 与 Moderations 使用各自专用端点
<a id="routing"></a>
## 路由与全局行为
### 请求链路
```mermaid
flowchart LR
A[客户端] --> B[网关密钥鉴权]
B --> C[分组、白名单与全局过滤]
C --> D[模型与能力匹配]
D --> E[选择最小 Priority]
E --> F[同优先级按 Weight 加权]
F --> G[OCI GenAI]
G -. 可重试且流未建立 .-> D
```
单次请求最多尝试三个渠道。模型不可用、限流、上游服务错误或网络错误可触发
换渠道;流式连接建立后不会切换渠道重试。
### 全局兼容边界
| 主题 | 当前行为 |
| --- | --- |
| 会话状态 | 网关不保存会话历史,客户端必须在每次请求中携带完整上下文 |
| 上游存储 | Responses 请求始终强制 `store:false` |
| 有状态字段 | Responses 拒绝非空 `previous_response_id`、非 `null``conversation``background:true` |
| 对话上游 | 对话请求统一进入 OCI OpenAI 兼容面,当前供给以 `xai.``meta.``openai.` 前缀模型为主 |
| 推理强度 | Responses `reasoning.effort`、Messages `output_config.effort`、Chat `reasoning_effort` 会传给上游;可用档位由模型决定 |
| 服务端工具 | Responses 支持 `web_search``x_search``code_interpreter` 和远程 `mcp`;命名容器管理与 File Search 不提供 |
| 文件输入 | `input_file` 会被 OCI ZDR 形态拒绝,详见[已知限制](#limitations) |
| Chat 定位 | Chat Completions 只承担协议转换与兼容修复;新能力优先落在 Responses 与 Messages |
<a id="codex"></a>
## Codex 接入
### 主配置
自定义模型提供方必须写在用户级 `~/.codex/config.toml`。Codex 的项目级
`.codex/config.toml` 不允许改写 `model_provider``model_providers`
```toml
model = "xai.grok-4.3"
model_provider = "oci"
[model_providers.oci]
name = "oci-portal"
base_url = "https://<网关地址>/ai/v1"
env_key = "OCI_PORTAL_KEY"
wire_api = "responses"
```
### 自定义子代理
新版 Codex 可在 `~/.codex/agents/` 或项目级 `.codex/agents/` 放置独立 TOML
文件,并为子代理覆盖模型。每个文件都需要 `name``description`
`developer_instructions`
```toml
# .codex/agents/oci-worker.toml
name = "oci-worker"
description = "通过 OCI Portal 网关执行通用开发任务。"
developer_instructions = """
完成被分配的开发任务,保持改动聚焦,并返回验证结果。
"""
model = "xai.grok-4.3"
```
> [!IMPORTANT]
> `codex-cli 0.144.1` 已实测主会话和 multi-agent 子代理全链路可用。
> 内置 worker 可能先尝试 `gpt-5.6-luna` 或 `gpt-5.4`;网关没有对应渠道时
> 会出现少量 404,随后由 Codex 回落到可用模型。自定义 agent 的模型覆盖是否
> 直接生效取决于 Codex 版本;0.144.1 的实测主要依赖自动回落。
Codex 工具兼容现状:
| 工具形态 | 网关处理 | 验证状态 |
| --- | --- | --- |
| `function` | 原样透传 | 可用 |
| `namespace` | 子工具拍平为限定名 `function`,响应时还原 | multi-agent 已端到端实测;MCP 同路径有单测 |
| `custom` | 顶层普通工具转换为 `function`,调用与历史记录双向回转 | 可用,但存在降级边界 |
| `custom:apply_patch` | 直接剥离,让模型回落到其他编辑方式 | 有意限制 |
| `tool_search` | namespace 已完整展开,目录搜索语义冗余,直接剥离 | 有意降级 |
配置语法参考 [Codex Subagents](https://learn.chatgpt.com/docs/agent-configuration/subagents)
与 [Codex Advanced Configuration](https://learn.chatgpt.com/docs/config-file/config-advanced)。
<a id="limitations"></a>
## 已知限制
### 超大流式请求
> [!WARNING]
> 2026-07 实测:OCI xAI 兼容面对**完整请求体超过约 82 KB** 的流式请求,
> 可能在推理阶段提前断流;该现象由请求体积触发,与工具构成或字符集无关,
> 同一请求改为非流式可正常完成。
网关按协议采取不同保护:
- **Responses**:兼容改写后的请求体超过 **76 KB** 时,预防性改为非流式上游
请求,再合成最小 SSE 序列(`response.created`
`response.output_item.done``response.completed`);结果语义保留,但没有增量输出
- **Chat Completions / Messages**:若上游在客户端收到任何内容前断流,自动用
非流式重做,并合成对应 chunk / event 序列
- **已开始输出的流**:不能透明重试;调用日志会记录提前终止,客户端可能只拿到
部分事件
### ZDR 与文件输入
Responses 的 `input_file` 内容块(`file_url` / `file_data`)实测会被上游拒绝:
```text
File content is currently unsupported for ZDR customers
```
网关强制 `store:false`,属于 ZDR 请求形态,因此当前不能通过该端点上传或引用文件。
### 规格与实测边界
本项目提供的是兼容接口,而不是 OpenAI、Anthropic 或 xAI 协议的完整实现。
部分 OCI OpenAI 兼容行为来自实测,未见 Oracle 文档合同,可能随上游调整。
<a id="compatibility"></a>
## 字段兼容矩阵
矩阵基线:
- [OpenAI Responses](https://developers.openai.com/api/reference/resources/responses/methods/create)
- [OpenAI Chat Completions](https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create)
- [OpenAI Embeddings](https://developers.openai.com/api/reference/resources/embeddings/methods/create)
- [OpenAI Audio Speech](https://developers.openai.com/api/reference/resources/audio/methods/speech)
- [OpenAI Moderations](https://developers.openai.com/api/reference/resources/moderations/methods/create)
- [Anthropic Messages](https://platform.claude.com/docs/en/api/messages/create)
- [Cohere Rerank](https://docs.cohere.com/reference/rerank)
| 标记 | 含义 |
| :---: | --- |
| ✅ | 网关直接支持 |
| ➡️ | 原样保留或透传;是否生效由 OCI 上游决定 |
| 🔄 | 网关执行字段或协议转换后支持 |
| ◐ | 部分支持、存在前置条件或语义降级 |
### OpenAI Responses
**`POST /ai/v1/responses` · 无状态主接口**
网关以原始 JSON 为基底保留未知字段,但会强制关闭上游存储,并执行下表列出的
Codex 工具兼容改写。请求会重新编码,不承诺字节级原样转发。
<details open>
<summary><strong>核心字段</strong></summary>
| 标准字段 | 状态 | 网关行为 |
| --- | :---: | --- |
| `model` | ◐ | 必填;通过密钥白名单并匹配可用渠道后送往上游 |
| `input` | ➡️ | 支持字符串或 item 数组;普通内容保留,Codex 工具历史项可能改写 |
| `instructions``max_output_tokens` | ➡️ | 类型可解析后保留,不做范围或模型能力校验 |
| `temperature``top_p` | ➡️ | 保留,不做取值范围校验 |
| `parallel_tool_calls` | ◐ | 通常保留;若全部工具被剥离,则与 `tool_choice` 一并删除 |
| `text` / `text.format` / `text.verbosity` | ➡️ | 整个对象保留;是否生效由 OCI 模型决定 |
| `reasoning` | ➡️ | 整个对象保留;`effort` 不校验档位 |
| `tool_choice` | ◐ | 普通形态保留;namespace 对象会重限定,全部工具被剥离时删除 |
| `store` | 🔄 | 无论客户端传什么,上游请求都强制改写为 `false` |
| `stream` | ◐ | 支持 SSE;请求体超过 76 KB 时改为非流式上游并合成 SSE |
| 其余标准与未知顶层字段 | ➡️ | `context_management``include``metadata``prompt``prompt_cache_key``service_tier``truncation``user` 等均保留,由 OCI 决定是否接受 |
</details>
<details open>
<summary><strong>工具兼容</strong></summary>
| 工具或参数 | 状态 | 网关行为 |
| --- | :---: | --- |
| `tools[].type=function` | ➡️ | 非流式与流式均可,工具对象保留 |
| `web_search` / `x_search` / `code_interpreter` | ◐ | Oracle 文档化的 xAI 服务端工具;参数与限制遵循 [xAI 规格](https://docs.oracle.com/en-us/iaas/Content/generative-ai/get-started-agents.htm#xai-compatible-tools) |
| `tools[].type=mcp` | ➡️ | 远程 MCP 由上游直连,`server_url``require_approval``authorization` 等保留 |
| `tools[].type=namespace` | 🔄 | 子 `function` 上提并限定命名;响应、历史调用和 `tool_choice` 会反向还原;组内非 `function` 子工具被剥离 |
| `tools[].type=custom` | ◐ | 顶层非 `apply_patch` 工具转为带 `input` schema 的 `function`;响应与多轮历史双向回转;`format` 会删除 |
| `custom:apply_patch` | ◐ | 整体剥离;grok 系未针对 Codex 补丁格式训练,模型应回落其他编辑方式 |
| `tools[].type=tool_search` | ◐ | 请求可被接受,但工具本身直接剥离 |
| `web_search.external_web_access=true` | 🔄 | 删除上游不识别的字段,保留 `web_search` |
| `web_search.external_web_access=false` | ◐ | 上游没有“仅缓存检索”对应能力,按不越权原则剥离整个工具 |
</details>
本地拒绝(返回 400):
- 非空 `previous_response_id`
-`null``conversation`
- `background:true`
- 未列入白名单的工具类型,例如 `web_search_preview``file_search`
`computer``image_generation``shell`
响应边界:
- 无工具还原且未触发流式升级时,普通响应保持直通语义
- namespace / custom 调用会在非流式响应与命中的 SSE `data` 事件中定向还原
- 普通 SSE 不补 `data: [DONE]`reasoning 增量不会被过滤
- 未知模型返回 404,无可用渠道返回 503
- 上游错误使用 OpenAI 风格错误外壳,但不保证字段与标准 OpenAI 完全一致
### OpenAI Chat Completions
**`POST /ai/v1/chat/completions` · 存量客户端兼容层**
请求先转换为 Responses,再将 OCI Responses 响应桥接回 Chat Completions。
只有下表字段会进入上游请求。
<details>
<summary><strong>展开字段矩阵</strong></summary>
| 标准字段 | 状态 | 网关行为 |
| --- | :---: | --- |
| `model` | ◐ | 必填,受密钥白名单和可用渠道限制 |
| `messages` | 🔄 | 必填,转换为 Responses `input` / `instructions` |
| `system` / `developer` 消息 | ◐ | 文本按顺序合并为 `instructions`;块数组中的非文本内容忽略 |
| `user` / `assistant` 文本 | 🔄 | 字符串和 `text` 块分别转为 `input_text` / `output_text` |
| `image_url` | ◐ | URL 或 data URI 转为 `input_image``detail` 忽略 |
| assistant `tool_calls` / `role=tool` | 🔄 | 转为 `function_call` / `function_call_output` |
| `max_completion_tokens` | 🔄 | 转为 `max_output_tokens`,优先于 `max_tokens` |
| `max_tokens` | 🔄 | 未提供 `max_completion_tokens` 时转为 `max_output_tokens` |
| `temperature``top_p``parallel_tool_calls` | ◐ | 写入 Responses,不校验范围或模型能力 |
| `stream` | 🔄 | Responses SSE 转为 `chat.completion.chunk`,末尾补 `data: [DONE]` |
| `stream_options.include_usage` | 🔄 | 控制终块后的独立 usage 块 |
| `tools[].type=function` | ◐ | 支持 `name``description``parameters``strict` 忽略 |
| `tool_choice` | ◐ | 支持 `auto` / `none` / `required` 和具名 function |
| `response_format` | ◐ | `json_object``json_schema` 转为 Responses `text.format` |
| `reasoning_effort` | ◐ | 转小写后映射为 `reasoning.effort` |
| `store` | 🔄 | 客户端取值忽略,上游始终使用 `store:false` |
</details>
不支持(返回 400):`input_audio``file``refusal` 等消息内容块,以及
`function` 之外的工具类型。
<details>
<summary><strong>静默忽略字段</strong></summary>
消息级 `name` / `refusal` / `audio` / 旧式 `function_call``stop``seed`
`n``frequency_penalty``presence_penalty``logprobs``top_logprobs`
`logit_bias``user``audio``modalities``prediction``metadata`
`moderation``prompt_cache_key``safety_identifier``service_tier`
`verbosity``web_search_options``stream_options.include_obfuscation`
及其他未知字段。
</details>
响应边界:
- 非流式固定生成一个 `choices[0]`;文本合并,函数调用转为 `tool_calls`
- `finish_reason` 只生成 `stop``tool_calls``length`
- reasoning、logprobs、refusal、annotations、audio、service tier 和 system fingerprint 不返回
- usage 保留 `prompt_tokens``completion_tokens``total_tokens`
`prompt_tokens_details.cached_tokens`
- 已开始输出的流中断不会转换成标准 SSE 错误事件
### Anthropic Messages
**`POST /ai/v1/messages` · Anthropic 协议转换层**
支持 `Authorization: Bearer``x-api-key`,但不校验或使用
`anthropic-version``anthropic-beta` 请求头。
<details>
<summary><strong>展开顶层字段矩阵</strong></summary>
| 标准字段 | 状态 | 网关行为 |
| --- | :---: | --- |
| `model` | ◐ | 用于模型与渠道选择;空字符串通常最终返回模型不存在 |
| `max_tokens` | 🔄 | 缺省或 ≤0 时使用 8192,再转为 `max_output_tokens` |
| `messages` | ◐ | 必须非空;角色、交替顺序和空内容不做完整校验 |
| `system` | ◐ | 支持字符串或 text 块数组;文本块拼接,附加字段忽略 |
| `temperature``top_p` | ◐ | 写入 Responses,不校验范围或模型能力 |
| `stream` | 🔄 | Responses SSE 桥接为 Anthropic 标准事件序列 |
| `tools` | ◐ | 每个工具转为 Responses `function`;服务端工具类型不保留原语义 |
| `tool_choice` | ◐ | 支持 `auto``any``none`、具名 `tool` |
| `output_config.effort` | 🔄 | 转小写后映射为 `reasoning.effort` |
</details>
内容块兼容:
| `messages[].content` | 状态 | 网关行为 |
| --- | :---: | --- |
| 字符串 / `text` | 🔄 | user 转 `input_text`assistant 历史转 `output_text` |
| `image` | ◐ | 仅支持 `base64``url` source |
| `tool_use` | 🔄 | 转为 `function_call`,保留 ID、名称与输入 |
| `tool_result` | ◐ | 转为 `function_call_output`;块数组只拼接 text`is_error` 与非文本结果丢失 |
| `null` / 空块数组 | ◐ | 消息可能从上游 input 中消失,不返回参数错误 |
不支持(返回 400):`document`、服务端工具结果及未知内容块。历史
`thinking` / `redacted_thinking` 会删除。
<details>
<summary><strong>静默忽略字段</strong></summary>
`top_k``stop_sequences``metadata``thinking``output_config` 其余子字段、
`cache_control``container``inference_geo``service_tier` 及其他未知顶层字段。
</details>
响应边界:
- 仅将 Responses `output_text` 转为 `text``function_call` 转为 `tool_use`
- `stop_reason` 只生成 `end_turn``tool_use``max_tokens`
- 不生成 Anthropic thinking / signature 内容块
- usage 只保留 `input_tokens``output_tokens``cache_read_input_tokens`
- 流式上游错误与无终态断流会转成 Anthropic `error` 事件
### OpenAI Embeddings
**`POST /ai/v1/embeddings` · 向量化专用端点**
| 标准字段 | 状态 | 网关行为 |
| --- | :---: | --- |
| `model` | ◐ | 必填,受白名单限制,且需要 `EMBEDDING` 能力渠道 |
| 字符串 `input` | ✅ | 包装为单个输入后调用 OCI |
| 字符串数组 `input` | ✅ | 按原顺序调用 OCI |
| `dimensions` | ◐ | 映射为 OCI 输出维度,不校验范围或模型能力 |
| `encoding_format=float` | ✅ | 返回 float 数组;省略时相同 |
不支持(返回 400):token ID 数组、空数组、`null`
`encoding_format=base64``user` 与其他未知字段静默忽略。
响应使用标准 `object:"list"` 外壳,向量为 `float32` 数组,不支持流式。
### 语音生成
两个端点最终使用同一 OCI xAI TTS 上游与渠道调度:
#### OpenAI Audio Speech
**`POST /ai/v1/audio/speech`**
| 标准字段 | 状态 | 网关行为 |
| --- | :---: | --- |
| `model` | ◐ | 必填,受白名单限制,需要 `TTS` 能力渠道;当前为 `xai.grok-tts` |
| `input` | ◐ | 必填非空,随后保留 |
| `voice` | ➡️ | 使用 xAI 音色 `ara` / `eve` / `leo` / `rex` / `sal` |
| `response_format` | ➡️ | 实测 `mp3` 可用,其余格式由上游决定 |
| `language`(扩展) | 🔄 | 上游必填;缺省时注入 `"auto"` |
| `speed``instructions` 与未知字段 | ➡️ | 保留,是否生效由上游决定 |
#### xAI TTS
**`POST /ai/v1/tts`**
接受 [xAI 官方 TTS 格式](https://docs.x.ai/developers/model-capabilities/audio/text-to-speech)
转换为 OpenAI 兼容形态后进入同一上游。
| 字段 | 状态 | 网关行为 |
| --- | :---: | --- |
| `text` | 🔄 | 必填非空,转换为 `input` |
| `language` | ◐ | 必填,接受 BCP-47 或 `auto` |
| `voice_id` | 🔄 | 转为 `voice`;缺省交给上游默认值 `eve` |
| `output_format` | ➡️ | `{codec, sample_rate, bit_rate}` 对象保留,实测生效 |
| `speed` | ➡️ | 保留,实测可用 |
| `model`(网关扩展) | ◐ | 缺省注入 `xai.grok-tts`,可覆盖,受白名单限制 |
| 其余未知字段 | ➡️ | 保留,是否生效由上游决定 |
共同响应边界:
- 成功响应为一次性完整音频,`Content-Type` 透传上游,缺省 `audio/mpeg`
- 不提供 HTTP 流式音频或 WebSocket 代理
- 无 token 用量口径,调用日志只记时延与渠道
### Rerank
**`POST /ai/v1/rerank` · Cohere / Jina 风格协议**
上游走 OCI typed 面,模型为 `cohere.rerank-v4.0-pro``-fast`
| 字段 | 状态 | 网关行为 |
| --- | :---: | --- |
| `model` | ◐ | 必填,受白名单限制,需要 `RERANK` 能力渠道 |
| `query` | ✅ | 必填非空 |
| `documents` | ◐ | 仅接受字符串数组;旧版 `{"text": ...}` 对象数组返回 400 |
| `top_n` | ✅ | 可选,限制返回条数 |
| `return_documents` | ✅ | 为 `true` 时回带原文 |
`max_tokens_per_doc` 与未知字段静默忽略。响应按相关度降序,
`results[].index` 指向输入下标,`relevance_score` 为 0~1 浮点;无 token 用量口径。
### Moderations
**`POST /ai/v1/moderations` · OpenAI 外壳映射 OCI Guardrails**
| 标准字段 | 状态 | 网关行为 |
| --- | :---: | --- |
| 字符串 `input` | ✅ | 单条审核 |
| 字符串数组 `input` | ✅ | 逐条审核,单次 1~8 条 |
不支持(返回 400):多模态 input、空字符串条目、空数组或超过 8 条。
`model` 接受但忽略,不参与白名单判断。
响应边界:
- categories 使用 OCI 原生维度 `overall` / `blocklist` / `prompt_injection`
- 任一维度得分 ≥ 0.5 时 `flagged=true`
- PII 命中放在扩展字段 `results[].pii`,包含 `text``label``score`
`offset``length`,不参与 `flagged`
- 实测中文人名与手机号识别较弱,英文 PII 识别正常
- 响应 `model` 恒为 `oci-guardrails`
### Models
**`GET /ai/v1/models` · 当前密钥可见模型列表**
响应使用 OpenAI Models 列表外壳,只返回同时通过以下条件的模型:
1. 存在于当前渠道目录
2. 匹配密钥绑定的渠道分组
3. 不在全局模型黑名单
4. 命中密钥模型白名单(配置时)
5. 未被「过滤弃用模型」开关排除
网关不提供标准的单模型检索端点。
<a id="implementation"></a>
## 实现索引
| 端点 / 能力 | 主要实现 |
| --- | --- |
| Responses 直通与 Codex 工具兼容 | [`airesponses.go`](../internal/service/airesponses.go) · [`responses.go`](../internal/aiwire/responses.go) |
| Chat Completions 转换 | [`chatresponses.go`](../internal/service/chatresponses.go) · [`openai.go`](../internal/aiwire/openai.go) |
| Anthropic Messages 转换 | [`anthresponses.go`](../internal/service/anthresponses.go) · [`anthropic.go`](../internal/aiwire/anthropic.go) |
| 渠道路由与 Embeddings | [`aigateway_chat.go`](../internal/service/aigateway_chat.go) |
| TTS 上游 | [`genai_speech.go`](../internal/oci/genai_speech.go) · [`aigateway_extras.go`](../internal/service/aigateway_extras.go) |
| Rerank / Moderations 上游 | [`genai_guard.go`](../internal/oci/genai_guard.go) · [`rerank.go`](../internal/aiwire/rerank.go) · [`moderations.go`](../internal/aiwire/moderations.go) |
| HTTP Handler 与流式桥接 | [`aigateway.go`](../internal/api/aigateway.go) · [`aigateway_extras.go`](../internal/api/aigateway_extras.go) |
本文是兼容性快照,不替代 Swagger。标准接口、Codex 客户端与 OCI 上游均可能
变化,最终行为以当前版本代码、运行时 Swagger 和实测结果为准。
+3661 -331
View File
File diff suppressed because it is too large Load Diff
+3661 -331
View File
File diff suppressed because it is too large Load Diff
+2460 -319
View File
File diff suppressed because it is too large Load Diff
+100
View File
@@ -1,24 +1,40 @@
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo=
filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc= github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc=
github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE= github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE=
github.com/PuerkitoBio/purell v1.1.1 h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tNFfI= github.com/PuerkitoBio/purell v1.1.1 h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tNFfI=
github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0= github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0=
github.com/PuerkitoBio/purell v1.2.2 h1:irlAloIzZaJ5RP/+UcaT1Nw0H9on2HKWdRehCsbJWJw=
github.com/PuerkitoBio/purell v1.2.2/go.mod h1:ZwHcC/82TOaovDi//J/804umJFFmbOHPngi8iYYv/Eo=
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 h1:d+Bc7a5rLufV/sSk/8dngufqelfh6jnri85riMAaF/M= github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 h1:d+Bc7a5rLufV/sSk/8dngufqelfh6jnri85riMAaF/M=
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE= github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE=
github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc h1:biVzkmvwrH8WK8raXaxBx6fRVTlJILwEwQGL1I/ByEI= github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc h1:biVzkmvwrH8WK8raXaxBx6fRVTlJILwEwQGL1I/ByEI=
github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8= github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8=
github.com/boombuler/barcode v1.1.0 h1:ChaYjBR63fr4LFyGn8E8nt7dBSt3MiU3zMOZqFvVkHo=
github.com/boombuler/barcode v1.1.0/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8=
github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M= github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M=
github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM= github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM=
github.com/bytedance/gopkg v0.1.4 h1:oZnQwnX82KAIWb7033bEwtxvTqXcYMxDBaQxo5JJHWM=
github.com/bytedance/gopkg v0.1.4/go.mod h1:v1zWfPm21Fb+OsyXN2VAHdL6TBb2L88anLQgdyje6R4=
github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE= github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE=
github.com/bytedance/sonic v1.15.0/go.mod h1:tFkWrPz0/CUCLEF4ri4UkHekCIcdnkqXw9VduqpJh0k= github.com/bytedance/sonic v1.15.0/go.mod h1:tFkWrPz0/CUCLEF4ri4UkHekCIcdnkqXw9VduqpJh0k=
github.com/bytedance/sonic v1.15.2 h1:90H+rcF/FwLXwfB1cudOLq/je83n683Utf4Cbp0xHCo=
github.com/bytedance/sonic v1.15.2/go.mod h1:mT2NbXunuaEbnZ+mRIX/vYqKISmgEuHFDI4UzmKx2SA=
github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiDd5VjlgE= github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiDd5VjlgE=
github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo= github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo=
github.com/bytedance/sonic/loader v0.5.1 h1:Ygpfa9zwRCCKSlrp5bBP/b/Xzc3VxsAW+5NIYXrOOpI=
github.com/bytedance/sonic/loader v0.5.1/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo=
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M= github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU= github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
github.com/cloudwego/base64x v0.1.7 h1:NppS+Fgzg5ovhn4NkUXaDT3x9jldgH5ToMCqzBSi2zI=
github.com/cloudwego/base64x v0.1.7/go.mod h1:Cu1PV9zfrSf7ET2tIbWbbEy7jO7HHJ13q4X2SQ8aWYg=
github.com/coreos/go-oidc/v3 v3.19.0 h1:F/xyOi3x1UnG1U27YVnM1N6bHiL1K2upi6U/0qr8r+I= github.com/coreos/go-oidc/v3 v3.19.0 h1:F/xyOi3x1UnG1U27YVnM1N6bHiL1K2upi6U/0qr8r+I=
github.com/coreos/go-oidc/v3 v3.19.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4= github.com/coreos/go-oidc/v3 v3.19.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4=
github.com/coreos/go-oidc/v3 v3.20.0 h1:EtE0WIBHk03N+DqGkY4+UONzzZHk7amKt6IyNd7OsZE=
github.com/coreos/go-oidc/v3 v3.20.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4=
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d h1:U+s90UTSYgptZMwQh2aRr3LuazLJIa+Pg3Kc1ylSYVY= github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d h1:U+s90UTSYgptZMwQh2aRr3LuazLJIa+Pg3Kc1ylSYVY=
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
@@ -29,14 +45,20 @@ github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkp
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw= github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw=
github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s= github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
github.com/gabriel-vasile/mimetype v1.4.13 h1:46nXokslUBsAJE/wMsp5gtO500a4F3Nkz9Ufpk2AcUM=
github.com/gabriel-vasile/mimetype v1.4.13/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
github.com/gin-contrib/gzip v0.0.6 h1:NjcunTcGAj5CO1gn4N8jHOSIeRFHIbn51z6K+xaN4d4= github.com/gin-contrib/gzip v0.0.6 h1:NjcunTcGAj5CO1gn4N8jHOSIeRFHIbn51z6K+xaN4d4=
github.com/gin-contrib/gzip v0.0.6/go.mod h1:QOJlmV2xmayAjkNS2Y8NQsMneuRShOU/kjovCXNuzzk= github.com/gin-contrib/gzip v0.0.6/go.mod h1:QOJlmV2xmayAjkNS2Y8NQsMneuRShOU/kjovCXNuzzk=
github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w= github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM= github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
github.com/gin-contrib/sse v1.1.1 h1:uGYpNwTacv5R68bSGMapo62iLTRa9l5zxGCps4hK6ko=
github.com/gin-contrib/sse v1.1.1/go.mod h1:QXzuVkA0YO7o/gun03UI1Q+FTI8ZV/n5t03kIQAI89s=
github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8= github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8=
github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc= github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc=
github.com/glebarez/go-sqlite v1.21.2 h1:3a6LFC4sKahUunAmynQKLZceZCOzUthkRkEAl9gAXWo= github.com/glebarez/go-sqlite v1.21.2 h1:3a6LFC4sKahUunAmynQKLZceZCOzUthkRkEAl9gAXWo=
github.com/glebarez/go-sqlite v1.21.2/go.mod h1:sfxdZyhQjTM2Wry3gVYWaW072Ri1WMdWJi0k6+3382k= github.com/glebarez/go-sqlite v1.21.2/go.mod h1:sfxdZyhQjTM2Wry3gVYWaW072Ri1WMdWJi0k6+3382k=
github.com/glebarez/go-sqlite v1.22.0 h1:uAcMJhaA6r3LHMTFgP0SifzgXg46yJkgxqyuyec+ruQ=
github.com/glebarez/go-sqlite v1.22.0/go.mod h1:PlBIdHe0+aUEFn+r2/uthrWq4FxbzugL0L8Li6yQJbc=
github.com/glebarez/sqlite v1.11.0 h1:wSG0irqzP6VurnMEpFGer5Li19RpIRi2qvQz++w0GMw= github.com/glebarez/sqlite v1.11.0 h1:wSG0irqzP6VurnMEpFGer5Li19RpIRi2qvQz++w0GMw=
github.com/glebarez/sqlite v1.11.0/go.mod h1:h8/o8j5wiAsqSPoWELDUdJXhjAhsVliSn7bWZjOhrgQ= github.com/glebarez/sqlite v1.11.0/go.mod h1:h8/o8j5wiAsqSPoWELDUdJXhjAhsVliSn7bWZjOhrgQ=
github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA= github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA=
@@ -44,13 +66,35 @@ github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9
github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg=
github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY= github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY=
github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg=
github.com/go-openapi/jsonpointer v1.0.0 h1:kR9tHqY0CtZaOPVFm622dPVNhrvYpwr4uCxgL3h1H8s=
github.com/go-openapi/jsonpointer v1.0.0/go.mod h1:Z3rw7dWu1p9IgitXCFamSlA5lmDiklEB6vkaxcNZW5Y=
github.com/go-openapi/jsonreference v0.19.6 h1:UBIxjkht+AWIgYzCDSv2GN+E/togfwXUJFRTWhl2Jjs= github.com/go-openapi/jsonreference v0.19.6 h1:UBIxjkht+AWIgYzCDSv2GN+E/togfwXUJFRTWhl2Jjs=
github.com/go-openapi/jsonreference v0.19.6/go.mod h1:diGHMEHg2IqXZGKxqyvWdfWU/aim5Dprw5bqpKkTvns= github.com/go-openapi/jsonreference v0.19.6/go.mod h1:diGHMEHg2IqXZGKxqyvWdfWU/aim5Dprw5bqpKkTvns=
github.com/go-openapi/jsonreference v1.0.0 h1:jlmTr6torcd1YgDQvSfNmRtKzYDO4FGBkrAdlAVWnpY=
github.com/go-openapi/jsonreference v1.0.0/go.mod h1:jtwdyGbJk0Xhe5Y+rwtglQP6Sb1WZST4rT32LWB+sv0=
github.com/go-openapi/spec v0.20.4 h1:O8hJrt0UMnhHcluhIdUgCLRWyM2x7QkBXRvOs7m+O1M= github.com/go-openapi/spec v0.20.4 h1:O8hJrt0UMnhHcluhIdUgCLRWyM2x7QkBXRvOs7m+O1M=
github.com/go-openapi/spec v0.20.4/go.mod h1:faYFR1CvsJZ0mNsmsphTMSoRrNV3TEDoAM7FOEWeq8I= github.com/go-openapi/spec v0.20.4/go.mod h1:faYFR1CvsJZ0mNsmsphTMSoRrNV3TEDoAM7FOEWeq8I=
github.com/go-openapi/spec v0.22.6 h1:Tyy1pLaNCM8GBCFLoGYLonjJi6zykqyLCjXLc19ZPic=
github.com/go-openapi/spec v0.22.6/go.mod h1:HZvTHat+iH0PALQRWhrqIHtU/PEqxqd89fu0MxGlMeM=
github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk=
github.com/go-openapi/swag v0.19.15 h1:D2NRCBzS9/pEY3gP9Nl8aDqGUcPFrwG2p+CNFrLyrCM= github.com/go-openapi/swag v0.19.15 h1:D2NRCBzS9/pEY3gP9Nl8aDqGUcPFrwG2p+CNFrLyrCM=
github.com/go-openapi/swag v0.19.15/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ= github.com/go-openapi/swag v0.19.15/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ=
github.com/go-openapi/swag v0.27.0 h1:8ecSuZlh4NXc3GsmAOqECIYqDTApCWaMe3gO4gjJNEE=
github.com/go-openapi/swag v0.27.0/go.mod h1:Kkgz9Ht0+ul9/aVdFmc9xSyPzUwf/aFF5KiFPBXfSY0=
github.com/go-openapi/swag/conv v0.27.0 h1:EKOH4feXrvdo8DbSsXSAqRT8fz1epEnS5O2IfXUOzE8=
github.com/go-openapi/swag/conv v0.27.0/go.mod h1:pfiv0uKQTbaGApk8Zs/lZV3uSjmSpa2FO1y183YngN8=
github.com/go-openapi/swag/jsonname v0.27.0 h1:4QVB//CKOdE8IOiBg19JNY2wfDS48MhesIquYBy2rUE=
github.com/go-openapi/swag/jsonname v0.27.0/go.mod h1:I1YsyvvhBuZsFXSW6I7ODfdyq13p7hDil//1T9/pFFk=
github.com/go-openapi/swag/jsonutils v0.27.0 h1:VYtd9jEQYeU4j8q5vdn5KWotF4vKywhGdMBrALtAsfE=
github.com/go-openapi/swag/jsonutils v0.27.0/go.mod h1:U7pb8AGuwhok3RDicHeHwSG4L3PXSq6PAL98Aon632g=
github.com/go-openapi/swag/loading v0.27.0 h1:s8DA9aPEdFH6OluHUYUn3DnIuoTdyWs9RwffXBUfyeI=
github.com/go-openapi/swag/loading v0.27.0/go.mod h1:VOz+Jg6UGGywcmRvYsI4fvtp+bd7NfioseGEPleYdA4=
github.com/go-openapi/swag/stringutils v0.27.0 h1:Of7w/HljWsNZvuxsUAnw3n+hCOyI6HLJOxW2kQRAxio=
github.com/go-openapi/swag/stringutils v0.27.0/go.mod h1:lzRN95CxXmA03XcDWHLOb6nOMcxCqR5rGY0lOgsfRoM=
github.com/go-openapi/swag/typeutils v0.27.0 h1:aCf4MSGo8NLwZP8Q6t32DWLJSvl/WwNqgmEG+xJ6v2o=
github.com/go-openapi/swag/typeutils v0.27.0/go.mod h1:Srm0xFNRZ1Y+vCxJclo5qzx8aj+1pAKda/YfFPrG0dQ=
github.com/go-openapi/swag/yamlutils v0.27.0 h1:bQ6eAMil5X9tdcf7dMn4t15alzG6jddnrKPuKa/zxKM=
github.com/go-openapi/swag/yamlutils v0.27.0/go.mod h1:yRfIo7qqVkmJRQjX8exjA3AfcI8rH1KDNPsTparoCv4=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
@@ -59,14 +103,22 @@ github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJn
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w= github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w=
github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM= github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM=
github.com/go-playground/validator/v10 v10.30.3 h1:4MU6YkEwx7GbcPJOZxrtbu+QfF3pJLJuaYTeAH0DYy8=
github.com/go-playground/validator/v10 v10.30.3/go.mod h1:4Axh7oCNGcoGkqLoE4YWt6n20mcEIsPRlB7vPk3lpyc=
github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y= github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y=
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg= github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
github.com/go-sql-driver/mysql v1.10.0 h1:Q+1LV8DkHJvSYAdR83XzuhDaTykuDx0l6fkXxoWCWfw=
github.com/go-sql-driver/mysql v1.10.0/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk=
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4= github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
github.com/goccy/go-json v0.10.6 h1:p8HrPJzOakx/mn/bQtjgNjdTcN+/S6FcG2CTtQOrHVU=
github.com/goccy/go-json v0.10.6/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM= github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=
github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
github.com/gofrs/flock v0.10.0 h1:SHMXenfaB03KbroETaCMtbBg3Yn29v4w1r+tgy4ff4k= github.com/gofrs/flock v0.10.0 h1:SHMXenfaB03KbroETaCMtbBg3Yn29v4w1r+tgy4ff4k=
github.com/gofrs/flock v0.10.0/go.mod h1:FirDy1Ing0mI2+kB6wk+vyyAH+e6xiE+EYA0jnzV9jc= github.com/gofrs/flock v0.10.0/go.mod h1:FirDy1Ing0mI2+kB6wk+vyyAH+e6xiE+EYA0jnzV9jc=
github.com/gofrs/flock v0.13.0 h1:95JolYOvGMqeH31+FC7D2+uULf6mG61mEZ/A8dRYMzw=
github.com/gofrs/flock v0.13.0/go.mod h1:jxeyy9R1auM5S6JYDBhDt+E2TCo7DkratH4Pgi8P+Z0=
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
@@ -74,8 +126,11 @@ github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ= github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ=
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26/go.mod h1:dDKJzRmX4S37WGHujM7tX//fmj1uioxKzKxz3lo4HJo= github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26/go.mod h1:dDKJzRmX4S37WGHujM7tX//fmj1uioxKzKxz3lo4HJo=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
@@ -84,6 +139,8 @@ github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7Ulw
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.9.2 h1:3ZhOzMWnR4yJ+RW1XImIPsD1aNSz4T4fyP7zlQb56hw= github.com/jackc/pgx/v5 v5.9.2 h1:3ZhOzMWnR4yJ+RW1XImIPsD1aNSz4T4fyP7zlQb56hw=
github.com/jackc/pgx/v5 v5.9.2/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= github.com/jackc/pgx/v5 v5.9.2/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0=
github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
@@ -96,6 +153,8 @@ github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnr
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw=
github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
@@ -109,8 +168,12 @@ github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN
github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
github.com/mailru/easyjson v0.7.6 h1:8yTIVnZgCoiM1TgqoeTl+LfU5Jg6/xL3QhGQnimLYnA= github.com/mailru/easyjson v0.7.6 h1:8yTIVnZgCoiM1TgqoeTl+LfU5Jg6/xL3QhGQnimLYnA=
github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
github.com/mailru/easyjson v0.9.2 h1:dX8U45hQsZpxd80nLvDGihsQ/OxlvTkVUXH2r/8cb2M=
github.com/mailru/easyjson v0.9.2/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-isatty v0.0.22 h1:j8l17JJ9i6VGPUFUYoTUKPSgKe/83EYU2zBC7YNKMw4=
github.com/mattn/go-isatty v0.0.22/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
@@ -118,11 +181,15 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/oracle/oci-go-sdk/v65 v65.120.0 h1:qpGdts2Yleg6TdmtxXkL8MAnsASO+SOG+iG/Nd8wUGk= github.com/oracle/oci-go-sdk/v65 v65.120.0 h1:qpGdts2Yleg6TdmtxXkL8MAnsASO+SOG+iG/Nd8wUGk=
github.com/oracle/oci-go-sdk/v65 v65.120.0/go.mod h1:Pzy+BpgkDesvGZXEHgslwhIYobHCPHg6wRta1mWnlqQ= github.com/oracle/oci-go-sdk/v65 v65.120.0/go.mod h1:Pzy+BpgkDesvGZXEHgslwhIYobHCPHg6wRta1mWnlqQ=
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/pelletier/go-toml/v2 v2.4.3 h1:GTRvJQutkOSftxIFD5xw9aepkYNuPWmVJpffdDPYVpY=
github.com/pelletier/go-toml/v2 v2.4.3/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pquerna/otp v1.5.0 h1:NMMR+WrmaqXU4EzdGJEE1aUUI0AMRzsp96fFFWNPwxs= github.com/pquerna/otp v1.5.0 h1:NMMR+WrmaqXU4EzdGJEE1aUUI0AMRzsp96fFFWNPwxs=
@@ -131,6 +198,8 @@ github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII= github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
github.com/quic-go/quic-go v0.59.1 h1:0Gmua0HW1Tv7ANR7hUYwRyD0MG5OJfgvYSZasGZzBic= github.com/quic-go/quic-go v0.59.1 h1:0Gmua0HW1Tv7ANR7hUYwRyD0MG5OJfgvYSZasGZzBic=
github.com/quic-go/quic-go v0.59.1/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU= github.com/quic-go/quic-go v0.59.1/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU=
github.com/quic-go/quic-go v0.60.0 h1:xcQioE8OM66UQLeUMHltK1CCcOu3JbVB4JAQdDQSB+0=
github.com/quic-go/quic-go v0.60.0/go.mod h1:wpKpjmPpftl30sL6pFh7REVpjbcCVy4zt2vDyK1TuJk=
github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
@@ -175,17 +244,27 @@ github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78/go.mod h1:aL8wCCfTfS
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE= go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE=
go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0= go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0=
go.mongodb.org/mongo-driver/v2 v2.8.0 h1:CxWDGQYY8QQwNjAl/aq2sfWakdnWZynnqJ9F4DhHbP8=
go.mongodb.org/mongo-driver/v2 v2.8.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0=
go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y= go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=
go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU= go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI= golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI=
golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A= golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=
golang.org/x/arch v0.29.0 h1:8sSET5wB0+exBm0FGmOtdHMqjlRdV2DRD3/IV6OZgho=
golang.org/x/arch v0.29.0/go.mod h1:0X+GdSIP+kL5wPmpK7sdkEVTt2XoYP0cSjQSbZBwOi8=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto= golang.org/x/crypto v0.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto=
golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio= golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio=
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.36.0 h1:JJjpVx6myfUsUdAzZuOSTTmRE0PfZeNWzzvKrP7amb4= golang.org/x/mod v0.36.0 h1:JJjpVx6myfUsUdAzZuOSTTmRE0PfZeNWzzvKrP7amb4=
golang.org/x/mod v0.36.0/go.mod h1:moc6ELqsWcOw5Ef3xVprK5ul/MvtVvkIXLziUOICjUQ= golang.org/x/mod v0.36.0/go.mod h1:moc6ELqsWcOw5Ef3xVprK5ul/MvtVvkIXLziUOICjUQ=
golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk=
golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210421230115-4e50805a0758/go.mod h1:72T/g9IO56b78aLF+1Kcs5dz7/ng1VjMUvfKvpfy+jM= golang.org/x/net v0.0.0-20210421230115-4e50805a0758/go.mod h1:72T/g9IO56b78aLF+1Kcs5dz7/ng1VjMUvfKvpfy+jM=
@@ -193,12 +272,16 @@ golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug
golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o= golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o=
golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec= golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec=
golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=
golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs= golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q= golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM= golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210420072515-93ed5bcd2bfe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210420072515-93ed5bcd2bfe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
@@ -209,11 +292,14 @@ golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw= golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/term v0.44.0 h1:0rLvDRCtNj0gZkyIXhCyOb2OAzEhLVqc4B+hrsBhrmc= golang.org/x/term v0.44.0 h1:0rLvDRCtNj0gZkyIXhCyOb2OAzEhLVqc4B+hrsBhrmc=
golang.org/x/term v0.44.0/go.mod h1:7ze4MdzUzLXpSAoFP1H0bOI9aXDqveSvatT5vKcFh2Y= golang.org/x/term v0.44.0/go.mod h1:7ze4MdzUzLXpSAoFP1H0bOI9aXDqveSvatT5vKcFh2Y=
golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
@@ -221,6 +307,8 @@ golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.38.0 h1:sXmwo9DwP3OK9EZ7PqAdaooSGozfl/3a6/xJcbzPRhE= golang.org/x/text v0.38.0 h1:sXmwo9DwP3OK9EZ7PqAdaooSGozfl/3a6/xJcbzPRhE=
golang.org/x/text v0.38.0/go.mod h1:YXZt3QhHUKYT53r2lLKFIVi6Ao1jdzrTR/KQ09qyxF4= golang.org/x/text v0.38.0/go.mod h1:YXZt3QhHUKYT53r2lLKFIVi6Ao1jdzrTR/KQ09qyxF4=
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
@@ -228,9 +316,13 @@ golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtn
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.45.0 h1:18qN3FAooORvApf5XjCXgsuayZOEtXf6JK18I3+ONa8= golang.org/x/tools v0.45.0 h1:18qN3FAooORvApf5XjCXgsuayZOEtXf6JK18I3+ONa8=
golang.org/x/tools v0.45.0/go.mod h1:LuUGqqaXcXMEFEruIVJVm5mgDD8vww/z/SR1gQ4uE/0= golang.org/x/tools v0.45.0/go.mod h1:LuUGqqaXcXMEFEruIVJVm5mgDD8vww/z/SR1gQ4uE/0=
golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE=
golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE=
google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
@@ -254,11 +346,19 @@ gorm.io/gorm v1.31.2 h1:3o8FXNo9v9S858gil+3LlZA1LkCOzgb4g5BL64FgaCo=
gorm.io/gorm v1.31.2/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs= gorm.io/gorm v1.31.2/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
modernc.org/libc v1.22.5 h1:91BNch/e5B0uPbJFgqbxXuOnxBQjlS//icfQEGmvyjE= modernc.org/libc v1.22.5 h1:91BNch/e5B0uPbJFgqbxXuOnxBQjlS//icfQEGmvyjE=
modernc.org/libc v1.22.5/go.mod h1:jj+Z7dTNX8fBScMVNRAYZ/jF91K8fdT2hYMThc3YjBY= modernc.org/libc v1.22.5/go.mod h1:jj+Z7dTNX8fBScMVNRAYZ/jF91K8fdT2hYMThc3YjBY=
modernc.org/libc v1.74.1 h1:bdR4VTKFMC4966QSNZ05XLGI/VwzVa2kTUX51Dm0riQ=
modernc.org/libc v1.74.1/go.mod h1:uH4t5bOx3G3g9Xcmj10YKlTcVISlRDwv8VoQJG9n8Os=
modernc.org/mathutil v1.5.0 h1:rV0Ko/6SfM+8G+yKiyI830l3Wuz1zRutdslNoQ0kfiQ= modernc.org/mathutil v1.5.0 h1:rV0Ko/6SfM+8G+yKiyI830l3Wuz1zRutdslNoQ0kfiQ=
modernc.org/mathutil v1.5.0/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E= modernc.org/mathutil v1.5.0/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.5.0 h1:N+/8c5rE6EqugZwHii4IFsaJ7MUhoWX07J5tC/iI5Ds= modernc.org/memory v1.5.0 h1:N+/8c5rE6EqugZwHii4IFsaJ7MUhoWX07J5tC/iI5Ds=
modernc.org/memory v1.5.0/go.mod h1:PkUhL0Mugw21sHPeskwZW4D6VscE/GQJOnIpCnW6pSU= modernc.org/memory v1.5.0/go.mod h1:PkUhL0Mugw21sHPeskwZW4D6VscE/GQJOnIpCnW6pSU=
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/sqlite v1.23.1 h1:nrSBg4aRQQwq59JpvGEQ15tNxoO5pX/kUjcRNwSAGQM= modernc.org/sqlite v1.23.1 h1:nrSBg4aRQQwq59JpvGEQ15tNxoO5pX/kUjcRNwSAGQM=
modernc.org/sqlite v1.23.1/go.mod h1:OrDj17Mggn6MhE+iPbBNf7RGKODDE9NFT0f3EwDzJqk= modernc.org/sqlite v1.23.1/go.mod h1:OrDj17Mggn6MhE+iPbBNf7RGKODDE9NFT0f3EwDzJqk=
modernc.org/sqlite v1.53.0 h1:20WG8N9q4ji/dEqGk4uiI0c6OPjSeLTNYGFCc3+7c1M=
modernc.org/sqlite v1.53.0/go.mod h1:xoEpOIpGrgT48H5iiyt/YXPCZPEzlfmfFwtk8Lklw8s=
sigs.k8s.io/yaml v1.3.0 h1:a2VclLzOGrwOHDiV8EfBGhvjHvP46CtW5j6POvhYGGo= sigs.k8s.io/yaml v1.3.0 h1:a2VclLzOGrwOHDiV8EfBGhvjHvP46CtW5j6POvhYGGo=
sigs.k8s.io/yaml v1.3.0/go.mod h1:GeOyir5tyXNByN85N/dRIT9es5UQNerPYEKK56eTBm8= sigs.k8s.io/yaml v1.3.0/go.mod h1:GeOyir5tyXNByN85N/dRIT9es5UQNerPYEKK56eTBm8=
+5
View File
@@ -0,0 +1,5 @@
package aiwire
// AnyJSON 仅供 swagger 文档渲染:经 .swaggo 全局替换,代表任意 JSON 值
// (json.RawMessage 与 string/数组联合类型),运行时代码不使用。
type AnyJSON struct{}
+63
View File
@@ -0,0 +1,63 @@
package aiwire
import "encoding/json"
// ModerationsRequest 是 /ai/v1/moderations 请求体;input 兼容 OpenAI 的
// string 与 []string 两种形态,model 字段接受但忽略(上游为服务级 API)。
type ModerationsRequest struct {
Model string `json:"model,omitempty"`
Input json.RawMessage `json:"input"`
}
// ModerationPii 是一处 PII 命中(OCI 扩展,OpenAI 协议无对应物)。
type ModerationPii struct {
Text string `json:"text"`
Label string `json:"label"`
Score float64 `json:"score"`
Offset int `json:"offset"`
Length int `json:"length"`
}
// ModerationResult 是一条输入的审核结果:categories / category_scores 用
// OCI 原生维度(overall / blocklist / prompt_injection),pii 为扩展字段。
type ModerationResult struct {
Flagged bool `json:"flagged"`
Categories map[string]bool `json:"categories"`
CategoryScores map[string]float64 `json:"category_scores"`
Pii []ModerationPii `json:"pii,omitempty"`
}
// ModerationsResponse 是 /ai/v1/moderations 响应体(OpenAI moderations 外壳)。
type ModerationsResponse struct {
ID string `json:"id"`
Model string `json:"model"`
Results []ModerationResult `json:"results"`
}
// SpeechRequest 描述 /ai/v1/audio/speech 请求体的已知字段(文档用途)。
// 直通端点实际按原样透传,未列字段与 xAI 专属参数(如 output_format)同样保留。
type SpeechRequest struct {
Model string `json:"model"`
Input string `json:"input"`
Voice string `json:"voice,omitempty"`
ResponseFormat string `json:"response_format,omitempty"`
Language string `json:"language,omitempty"`
}
// TtsRequest 描述 /ai/v1/tts 请求体的已知字段(xAI 官方 TTS 格式,文档用途)。
// model 为网关扩展字段(缺省 xai.grok-tts);未列字段原样透传上游。
type TtsRequest struct {
Model string `json:"model,omitempty"`
Text string `json:"text"`
Language string `json:"language"`
VoiceID string `json:"voice_id,omitempty"`
OutputFormat *TtsOutputFormat `json:"output_format,omitempty"`
Speed float64 `json:"speed,omitempty"`
}
// TtsOutputFormat 是 xAI TTS 输出格式配置(缺省 MP3 24kHz/128kbps)。
type TtsOutputFormat struct {
Codec string `json:"codec,omitempty"`
SampleRate int `json:"sample_rate,omitempty"`
BitRate int `json:"bit_rate,omitempty"`
}
+28
View File
@@ -0,0 +1,28 @@
package aiwire
// RerankRequest 是 /ai/v1/rerank 请求体(Jina / Cohere 通行风格)。
type RerankRequest struct {
Model string `json:"model"`
Query string `json:"query"`
Documents []string `json:"documents"`
TopN *int `json:"top_n,omitempty"`
ReturnDocuments *bool `json:"return_documents,omitempty"`
}
// RerankDocument 包装原文,仅在 return_documents 时返回。
type RerankDocument struct {
Text string `json:"text"`
}
// RerankResult 是一条重排结果:index 指向请求 documents 下标。
type RerankResult struct {
Index int `json:"index"`
RelevanceScore float64 `json:"relevance_score"`
Document *RerankDocument `json:"document,omitempty"`
}
// RerankResponse 是 /ai/v1/rerank 响应体。
type RerankResponse struct {
Model string `json:"model"`
Results []RerankResult `json:"results"`
}
+13
View File
@@ -184,3 +184,16 @@ type RespError struct {
type RespIncomplete struct { type RespIncomplete struct {
Reason string `json:"reason"` Reason string `json:"reason"`
} }
// RespResponse 描述 /ai/v1/responses 非流式响应的常用顶层字段(文档用途)。
// 直通端点原样返回上游 JSON,未列字段(reasoning、incomplete_details 等)同样保留。
type RespResponse struct {
ID string `json:"id"`
Object string `json:"object"`
CreatedAt int64 `json:"created_at"`
Status string `json:"status"`
Model string `json:"model"`
Output json.RawMessage `json:"output"`
Usage *RespUsage `json:"usage,omitempty"`
Error *RespError `json:"error,omitempty"`
}
+1 -1
View File
@@ -30,7 +30,7 @@ func SetAboutRuntime(dbDriver, dbPath string) {
// //
// @Summary 返回构建、运行时长与资源占用信息,「设置 · 关于」页展示 // @Summary 返回构建、运行时长与资源占用信息,「设置 · 关于」页展示
// @Tags 设置 // @Tags 设置
// @Success 200 {object} map[string]any // @Success 200 {object} aboutResponse
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/about [get] // @Router /api/v1/about [get]
func about(c *gin.Context) { func about(c *gin.Context) {
+101 -12
View File
@@ -6,6 +6,9 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
_ "oci-portal/internal/aiwire" // swagger 注解引用
_ "oci-portal/internal/model" // swagger 注解引用
"oci-portal/internal/service" "oci-portal/internal/service"
) )
@@ -18,7 +21,7 @@ type aiAdminHandler struct {
// @Summary ---- 密钥 ---- // @Summary ---- 密钥 ----
// @Tags AI 管理 // @Tags AI 管理
// @Success 200 {object} map[string]any // @Success 200 {object} itemsResponse[model.AiKey]
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/ai-keys [get] // @Router /api/v1/ai-keys [get]
func (h *aiAdminHandler) listKeys(c *gin.Context) { func (h *aiAdminHandler) listKeys(c *gin.Context) {
@@ -35,7 +38,7 @@ func (h *aiAdminHandler) listKeys(c *gin.Context) {
// @Summary 生成密钥 // @Summary 生成密钥
// @Tags AI 管理 // @Tags AI 管理
// @Param body body object true "请求体(见接口说明)" // @Param body body object true "请求体(见接口说明)"
// @Success 201 {object} map[string]any // @Success 201 {object} aiKeyCreateResponse "key 为明文密钥,仅本次返回"
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/ai-keys [post] // @Router /api/v1/ai-keys [post]
func (h *aiAdminHandler) createKey(c *gin.Context) { func (h *aiAdminHandler) createKey(c *gin.Context) {
@@ -110,7 +113,7 @@ func (h *aiAdminHandler) deleteKey(c *gin.Context) {
// @Tags AI 管理 // @Tags AI 管理
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param body body object true "请求体(见接口说明)" // @Param body body object true "请求体(见接口说明)"
// @Success 200 {object} map[string]any // @Success 200 {object} model.AiKey
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/ai-keys/{id}/content-log [put] // @Router /api/v1/ai-keys/{id}/content-log [put]
func (h *aiAdminHandler) updateKeyContentLog(c *gin.Context) { func (h *aiAdminHandler) updateKeyContentLog(c *gin.Context) {
@@ -137,7 +140,7 @@ func (h *aiAdminHandler) updateKeyContentLog(c *gin.Context) {
// //
// @Summary 分页查询内容日志 // @Summary 分页查询内容日志
// @Tags AI 管理 // @Tags AI 管理
// @Success 200 {object} map[string]any // @Success 200 {object} pagedResponse[model.AiCallLog]
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/ai-content-logs [get] // @Router /api/v1/ai-content-logs [get]
func (h *aiAdminHandler) listContentLogs(c *gin.Context) { func (h *aiAdminHandler) listContentLogs(c *gin.Context) {
@@ -157,7 +160,7 @@ func (h *aiAdminHandler) listContentLogs(c *gin.Context) {
// @Summary ---- 渠道 ---- // @Summary ---- 渠道 ----
// @Tags AI 管理 // @Tags AI 管理
// @Success 200 {object} map[string]any // @Success 200 {object} itemsResponse[model.AiChannel]
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/ai-channels [get] // @Router /api/v1/ai-channels [get]
func (h *aiAdminHandler) listChannels(c *gin.Context) { func (h *aiAdminHandler) listChannels(c *gin.Context) {
@@ -172,7 +175,7 @@ func (h *aiAdminHandler) listChannels(c *gin.Context) {
// @Summary 创建 AI 渠道 // @Summary 创建 AI 渠道
// @Tags AI 管理 // @Tags AI 管理
// @Param body body service.ChannelInput true "请求体" // @Param body body service.ChannelInput true "请求体"
// @Success 201 {object} map[string]any // @Success 201 {object} model.AiChannel
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/ai-channels [post] // @Router /api/v1/ai-channels [post]
func (h *aiAdminHandler) createChannel(c *gin.Context) { func (h *aiAdminHandler) createChannel(c *gin.Context) {
@@ -236,7 +239,7 @@ func (h *aiAdminHandler) deleteChannel(c *gin.Context) {
// @Summary 触发探测:服务可见性 + 模型同步 + 配额试调,返回更新后的渠道 // @Summary 触发探测:服务可见性 + 模型同步 + 配额试调,返回更新后的渠道
// @Tags AI 管理 // @Tags AI 管理
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Success 200 {object} map[string]any // @Success 200 {object} model.AiChannel
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/ai-channels/{id}/probe [post] // @Router /api/v1/ai-channels/{id}/probe [post]
func (h *aiAdminHandler) probeChannel(c *gin.Context) { func (h *aiAdminHandler) probeChannel(c *gin.Context) {
@@ -255,7 +258,7 @@ func (h *aiAdminHandler) probeChannel(c *gin.Context) {
// @Summary 同步渠道模型缓存 // @Summary 同步渠道模型缓存
// @Tags AI 管理 // @Tags AI 管理
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Success 200 {object} map[string]any // @Success 200 {object} itemsResponse[model.AiModelCache]
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/ai-channels/{id}/sync-models [post] // @Router /api/v1/ai-channels/{id}/sync-models [post]
func (h *aiAdminHandler) syncChannelModels(c *gin.Context) { func (h *aiAdminHandler) syncChannelModels(c *gin.Context) {
@@ -271,11 +274,60 @@ func (h *aiAdminHandler) syncChannelModels(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"items": models}) c.JSON(http.StatusOK, gin.H{"items": models})
} }
// @Summary 渠道模型缓存列表
// @Tags AI 管理
// @Param id path int true "渠道 ID"
// @Success 200 {object} itemsResponse[model.AiModelCache]
// @Security BearerAuth
// @Router /api/v1/ai-channels/{id}/models [get]
func (h *aiAdminHandler) listChannelModels(c *gin.Context) {
id, ok := aiPathID(c)
if !ok {
return
}
models, err := h.gw.ChannelModels(c.Request.Context(), id)
if err != nil {
respondError(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"items": models})
}
type testChannelModelRequest struct {
Model string `json:"model" binding:"required"`
}
// @Summary 测试渠道模型(max_tokens=16 试调;通过即设为探测验证模型并按需置渠道可用)
// @Tags AI 管理
// @Param id path int true "渠道 ID"
// @Param body body testChannelModelRequest true "模型名"
// @Success 200 {object} model.AiChannel
// @Failure 502 {object} errorResponse "试调未通过"
// @Security BearerAuth
// @Router /api/v1/ai-channels/{id}/test-model [post]
func (h *aiAdminHandler) testChannelModel(c *gin.Context) {
id, ok := aiPathID(c)
if !ok {
return
}
var req testChannelModelRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
ch, err := h.gw.TestChannelModel(c.Request.Context(), id, req.Model)
if err != nil {
c.JSON(http.StatusBadGateway, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, ch)
}
// ---- 聚合模型与调用日志 ---- // ---- 聚合模型与调用日志 ----
// @Summary ---- 聚合模型与调用日志 ---- // @Summary ---- 聚合模型与调用日志 ----
// @Tags AI 管理 // @Tags AI 管理
// @Success 200 {object} map[string]any // @Success 200 {object} itemsResponse[aiwire.Model]
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/ai-models [get] // @Router /api/v1/ai-models [get]
func (h *aiAdminHandler) gatewayModels(c *gin.Context) { func (h *aiAdminHandler) gatewayModels(c *gin.Context) {
@@ -291,7 +343,7 @@ func (h *aiAdminHandler) gatewayModels(c *gin.Context) {
// @Summary 模型黑名单列表 // @Summary 模型黑名单列表
// @Tags AI 管理 // @Tags AI 管理
// @Success 200 {object} map[string]any // @Success 200 {object} itemsResponse[model.AiModelBlacklist]
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/ai-blacklist [get] // @Router /api/v1/ai-blacklist [get]
func (h *aiAdminHandler) listBlacklist(c *gin.Context) { func (h *aiAdminHandler) listBlacklist(c *gin.Context) {
@@ -308,7 +360,7 @@ func (h *aiAdminHandler) listBlacklist(c *gin.Context) {
// @Summary 添加模型黑名单 // @Summary 添加模型黑名单
// @Tags AI 管理 // @Tags AI 管理
// @Param body body object true "请求体:{name: 模型名}" // @Param body body object true "请求体:{name: 模型名}"
// @Success 201 {object} map[string]any // @Success 201 {object} itemResponse[model.AiModelBlacklist]
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/ai-blacklist [post] // @Router /api/v1/ai-blacklist [post]
func (h *aiAdminHandler) addBlacklist(c *gin.Context) { func (h *aiAdminHandler) addBlacklist(c *gin.Context) {
@@ -347,7 +399,7 @@ func (h *aiAdminHandler) removeBlacklist(c *gin.Context) {
// @Summary AI 调用日志列表 // @Summary AI 调用日志列表
// @Tags AI 管理 // @Tags AI 管理
// @Success 200 {object} map[string]any // @Success 200 {object} pagedResponse[model.AiContentLog]
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/ai-logs [get] // @Router /api/v1/ai-logs [get]
func (h *aiAdminHandler) listLogs(c *gin.Context) { func (h *aiAdminHandler) listLogs(c *gin.Context) {
@@ -369,3 +421,40 @@ func aiPathID(c *gin.Context) (uint, bool) {
} }
return uint(id), true return uint(id), true
} }
// aiSettingsResponse 是 AI 网关全局设置(文档与响应共用)。
type aiSettingsResponse struct {
FilterDeprecated bool `json:"filterDeprecated"`
}
// aiSettings 返回 AI 网关全局设置。
//
// @Summary AI 网关全局设置
// @Tags AI 管理
// @Success 200 {object} aiSettingsResponse
// @Security BearerAuth
// @Router /api/v1/ai-settings [get]
func (h *aiAdminHandler) aiSettings(c *gin.Context) {
c.JSON(http.StatusOK, aiSettingsResponse{FilterDeprecated: h.gw.FilterDeprecated()})
}
// updateAiSettings 更新 AI 网关全局设置(当前仅「过滤弃用模型」开关)。
//
// @Summary 更新 AI 网关全局设置
// @Tags AI 管理
// @Param body body aiSettingsResponse true "开启后已宣布弃用(即使未退役)的模型从列表与路由中排除"
// @Success 200 {object} aiSettingsResponse
// @Security BearerAuth
// @Router /api/v1/ai-settings [put]
func (h *aiAdminHandler) updateAiSettings(c *gin.Context) {
var req aiSettingsResponse
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if err := h.gw.SetFilterDeprecated(c.Request.Context(), req.FilterDeprecated); err != nil {
respondError(c, err)
return
}
c.JSON(http.StatusOK, aiSettingsResponse{FilterDeprecated: h.gw.FilterDeprecated()})
}
+221 -26
View File
@@ -8,6 +8,7 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"io" "io"
"log"
"net/http" "net/http"
"slices" "slices"
"strings" "strings"
@@ -165,8 +166,8 @@ func fillUsage(entry *model.AiCallLog, u *aiwire.Usage) {
// //
// @Summary OpenAI 兼容向量嵌入 // @Summary OpenAI 兼容向量嵌入
// @Tags AI 网关 // @Tags AI 网关
// @Param body body object true "OpenAI embeddings 请求体" // @Param body body aiwire.EmbeddingsRequest true "OpenAI embeddings 请求体"
// @Success 200 {object} map[string]any "OpenAI 兼容响应" // @Success 200 {object} aiwire.EmbeddingsResponse "OpenAI 兼容响应"
// @Router /ai/v1/embeddings [post] // @Router /ai/v1/embeddings [post]
func (h *aiGatewayHandler) embeddings(c *gin.Context) { func (h *aiGatewayHandler) embeddings(c *gin.Context) {
var req aiwire.EmbeddingsRequest var req aiwire.EmbeddingsRequest
@@ -210,12 +211,16 @@ func sseHeaders(c *gin.Context) {
c.Writer.Flush() c.Writer.Flush()
} }
// anthDefaultMaxTokens 是 max_tokens 缺省时的默认输出上限:Anthropic 协议
// 该字段必填,但部分客户端当选填不传,按默认值放行而非 400 拒绝。
const anthDefaultMaxTokens = 8192
// messages 是 Anthropic /ai/v1/messages 端点。 // messages 是 Anthropic /ai/v1/messages 端点。
// //
// @Summary Anthropic Messages 兼容端点 // @Summary Anthropic Messages 兼容端点
// @Tags AI 网关 // @Tags AI 网关
// @Param body body object true "Anthropic messages 请求体(支持 stream;经 OCI OpenAI 兼容面直通)" // @Param body body aiwire.MessagesRequest true "Anthropic messages 请求体(支持 stream;经 OCI OpenAI 兼容面直通;max_tokens 可缺省,默认 8192)"
// @Success 200 {object} map[string]any "Anthropic 兼容响应(流式为 SSE)" // @Success 200 {object} aiwire.MessagesResponse "Anthropic 兼容响应(非流式;流式为 SSE 事件序列)"
// @Router /ai/v1/messages [post] // @Router /ai/v1/messages [post]
func (h *aiGatewayHandler) messages(c *gin.Context) { func (h *aiGatewayHandler) messages(c *gin.Context) {
var req aiwire.MessagesRequest var req aiwire.MessagesRequest
@@ -224,8 +229,7 @@ func (h *aiGatewayHandler) messages(c *gin.Context) {
return return
} }
if req.MaxTokens <= 0 { if req.MaxTokens <= 0 {
aiError(c, http.StatusBadRequest, "invalid_request_error", "max_tokens 必填且需大于 0") req.MaxTokens = anthDefaultMaxTokens
return
} }
if len(req.Messages) == 0 { if len(req.Messages) == 0 {
aiError(c, http.StatusBadRequest, "invalid_request_error", "messages 不能为空") aiError(c, http.StatusBadRequest, "invalid_request_error", "messages 不能为空")
@@ -281,10 +285,30 @@ func (h *aiGatewayHandler) streamAnthropic(c *gin.Context, body []byte, req aiwi
defer upstream.Close() defer upstream.Close()
sseHeaders(c) sseHeaders(c)
bridge := service.NewAnthRespBridge(aiRandID("msg_"), req.Model) bridge := service.NewAnthRespBridge(aiRandID("msg_"), req.Model)
if err := forwardSSEData(upstream, func(data []byte) { writeAnthEvents(c, bridge.Feed(data)) }); err != nil { emitted := 0
if err := forwardSSEData(upstream, func(data []byte) {
evs := bridge.Feed(data)
emitted += len(evs)
writeAnthEvents(c, evs)
}); err != nil {
entry.ErrMsg = err.Error() entry.ErrMsg = err.Error()
} }
// 上游断流且客户端尚未收到任何事件(OCI 兼容面对大请求 + 推理模型的
// 流式通道会在 reasoning 阶段掐断):降级非流式重做,结果按事件序列推送
if emitted == 0 && !bridge.SawTerminal() && c.Request.Context().Err() == nil {
if h.anthFallback(c, &entry, req) {
entry.Status = http.StatusOK
entry.LatencyMs = time.Since(start).Milliseconds()
callID := h.gw.LogCall(entry)
h.maybeLogContent(c, callID, "anthropic", req.Model, true, req, nil)
return
}
}
writeAnthEvents(c, bridge.Finish()) writeAnthEvents(c, bridge.Finish())
// 上游错误事件 / 提前终止:SSE 头已发出维持 200,错误落日志可查
if msg := bridge.Err(); msg != "" && entry.ErrMsg == "" {
entry.ErrMsg = msg
}
entry.Status = http.StatusOK entry.Status = http.StatusOK
entry.LatencyMs = time.Since(start).Milliseconds() entry.LatencyMs = time.Since(start).Milliseconds()
usage := bridge.Usage() usage := bridge.Usage()
@@ -295,6 +319,30 @@ func (h *aiGatewayHandler) streamAnthropic(c *gin.Context, body []byte, req aiwi
h.maybeLogContent(c, callID, "anthropic", req.Model, true, req, nil) h.maybeLogContent(c, callID, "anthropic", req.Model, true, req, nil)
} }
// anthFallback 用非流式重做同一请求并把完整结果按事件序列推送;
// 成功返回 true 并把渠道 / 用量 / 降级标注写入日志条目。
func (h *aiGatewayHandler) anthFallback(c *gin.Context, entry *model.AiCallLog, req aiwire.MessagesRequest) bool {
req.Stream = false
body, err := service.AnthropicToResponsesBody(req)
if err != nil {
return false
}
payload, meta, err := h.gw.RespPassthrough(c.Request.Context(), body, req.Model, keyGroup(c))
if err != nil {
return false
}
out, err := service.ResponsesToAnthropic(payload, aiRandID("msg_"))
if err != nil {
return false
}
writeAnthEvents(c, service.AnthMessageEvents(out))
entry.ChannelID, entry.ChannelName = meta.ChannelID, meta.ChannelName
entry.Retries++
entry.ErrMsg = "流式上游断流,已降级非流式完成"
fillUsage(entry, service.RespPassthroughUsage(payload))
return true
}
// forwardSSEData 逐行读上游 SSE,把 data 行交给 emit 即时转换写出; // forwardSSEData 逐行读上游 SSE,把 data 行交给 emit 即时转换写出;
// Anthropic 与 Chat Completions 两条流式桥共用。 // Anthropic 与 Chat Completions 两条流式桥共用。
func forwardSSEData(upstream io.Reader, emit func([]byte)) error { func forwardSSEData(upstream io.Reader, emit func([]byte)) error {
@@ -334,8 +382,8 @@ func writeAnthEvents(c *gin.Context, events []service.AnthEvent) {
// //
// @Summary OpenAI Chat Completions 兼容端点 // @Summary OpenAI Chat Completions 兼容端点
// @Tags AI 网关 // @Tags AI 网关
// @Param body body object true "OpenAI chat/completions 请求体(支持 stream;经 Responses 转换直通)" // @Param body body aiwire.ChatRequest true "OpenAI chat/completions 请求体(支持 stream;经 Responses 转换直通)"
// @Success 200 {object} map[string]any "OpenAI 兼容响应(流式为 SSE,末尾 data: [DONE])" // @Success 200 {object} aiwire.ChatResponse "OpenAI 兼容响应(非流式;流式为 SSE,末尾 data: [DONE])"
// @Router /ai/v1/chat/completions [post] // @Router /ai/v1/chat/completions [post]
func (h *aiGatewayHandler) chatCompletions(c *gin.Context) { func (h *aiGatewayHandler) chatCompletions(c *gin.Context) {
var req aiwire.ChatRequest var req aiwire.ChatRequest
@@ -403,12 +451,31 @@ func (h *aiGatewayHandler) streamChat(c *gin.Context, body []byte, req aiwire.Ch
sseHeaders(c) sseHeaders(c)
includeUsage := req.StreamOptions != nil && req.StreamOptions.IncludeUsage includeUsage := req.StreamOptions != nil && req.StreamOptions.IncludeUsage
bridge := service.NewChatRespBridge(aiRandID("chatcmpl-"), req.Model, time.Now().Unix(), includeUsage) bridge := service.NewChatRespBridge(aiRandID("chatcmpl-"), req.Model, time.Now().Unix(), includeUsage)
if err := forwardSSEData(upstream, func(data []byte) { writeChatChunks(c, bridge.Feed(data)) }); err != nil { emitted := 0
if err := forwardSSEData(upstream, func(data []byte) {
chunks := bridge.Feed(data)
emitted += len(chunks)
writeChatChunks(c, chunks)
}); err != nil {
entry.ErrMsg = err.Error() entry.ErrMsg = err.Error()
} }
// 上游断流且客户端尚未收到任何块:降级非流式重做(成因同 messages 端点)
if emitted == 0 && bridge.Usage() == nil && c.Request.Context().Err() == nil {
if h.chatFallback(c, &entry, req, includeUsage) {
entry.Status = http.StatusOK
entry.LatencyMs = time.Since(start).Milliseconds()
callID := h.gw.LogCall(entry)
h.maybeLogContent(c, callID, "openai", req.Model, true, req, nil)
return
}
}
writeChatChunks(c, bridge.Finish()) writeChatChunks(c, bridge.Finish())
c.Writer.WriteString("data: [DONE]\n\n") c.Writer.WriteString("data: [DONE]\n\n")
c.Writer.Flush() c.Writer.Flush()
// 未见 completed 即结束:usage 缺失说明上游流异常提前终止,落日志可查
if bridge.Usage() == nil && entry.ErrMsg == "" {
entry.ErrMsg = "上游流提前终止,未返回终态事件"
}
entry.Status = http.StatusOK entry.Status = http.StatusOK
entry.LatencyMs = time.Since(start).Milliseconds() entry.LatencyMs = time.Since(start).Milliseconds()
fillUsage(&entry, bridge.Usage()) fillUsage(&entry, bridge.Usage())
@@ -416,6 +483,32 @@ func (h *aiGatewayHandler) streamChat(c *gin.Context, body []byte, req aiwire.Ch
h.maybeLogContent(c, callID, "openai", req.Model, true, req, nil) h.maybeLogContent(c, callID, "openai", req.Model, true, req, nil)
} }
// chatFallback 用非流式重做同一请求并把完整结果按 chunk 序列推送;
// 成功返回 true 并把渠道 / 用量 / 降级标注写入日志条目。
func (h *aiGatewayHandler) chatFallback(c *gin.Context, entry *model.AiCallLog, req aiwire.ChatRequest, includeUsage bool) bool {
req.Stream = false
body, err := service.ChatToResponsesBody(req)
if err != nil {
return false
}
payload, meta, err := h.gw.RespPassthrough(c.Request.Context(), body, req.Model, keyGroup(c))
if err != nil {
return false
}
out, err := service.ResponsesToChat(payload, aiRandID("chatcmpl-"), time.Now().Unix())
if err != nil {
return false
}
writeChatChunks(c, service.ChatResponseChunks(out, includeUsage))
c.Writer.WriteString("data: [DONE]\n\n")
c.Writer.Flush()
entry.ChannelID, entry.ChannelName = meta.ChannelID, meta.ChannelName
entry.Retries++
entry.ErrMsg = "流式上游断流,已降级非流式完成"
fillUsage(entry, service.RespPassthroughUsage(payload))
return true
}
// writeChatChunks 逐块写出 chunk 的 SSE data 行并 flush。 // writeChatChunks 逐块写出 chunk 的 SSE data 行并 flush。
func writeChatChunks(c *gin.Context, chunks []aiwire.ChatChunk) { func writeChatChunks(c *gin.Context, chunks []aiwire.ChatChunk) {
for _, ch := range chunks { for _, ch := range chunks {
@@ -436,7 +529,7 @@ func writeChatChunks(c *gin.Context, chunks []aiwire.ChatChunk) {
// //
// @Summary 可用模型列表 // @Summary 可用模型列表
// @Tags AI 网关 // @Tags AI 网关
// @Success 200 {object} map[string]any "OpenAI 兼容 models 列表" // @Success 200 {object} aiwire.ModelList "OpenAI 兼容 models 列表"
// @Router /ai/v1/models [get] // @Router /ai/v1/models [get]
func (h *aiGatewayHandler) listModels(c *gin.Context) { func (h *aiGatewayHandler) listModels(c *gin.Context) {
list, err := h.gw.GatewayModels(c.Request.Context(), keyGroup(c)) list, err := h.gw.GatewayModels(c.Request.Context(), keyGroup(c))
@@ -460,8 +553,8 @@ func (h *aiGatewayHandler) listModels(c *gin.Context) {
// //
// @Summary OpenAI Responses 兼容端点 // @Summary OpenAI Responses 兼容端点
// @Tags AI 网关 // @Tags AI 网关
// @Param body body object true "OpenAI responses 请求体(支持 stream;web_search/x_search 服务端工具仅非流式)" // @Param body body aiwire.RespRequest true "OpenAI responses 请求体(支持 stream;服务端工具 web_search/x_search/code_interpreter/mcp 含流式;codex 兼容:namespace 工具组拍平为限定名 function 并在响应还原,custom 工具转 function 包装并回转 custom_tool_call(apply_patch 丢弃),tool_search 剥离,web_search.external_web_access 上游不支持自动处理,超 76KB 流式请求自动改非流式合成 SSE;未列字段原样透传上游)"
// @Success 200 {object} map[string]any "OpenAI 兼容响应(流式为 SSE)" // @Success 200 {object} aiwire.RespResponse "OpenAI 兼容响应(非流式;流式为 SSE);直通仅建模常用字段,未列字段原样返回"
// @Router /ai/v1/responses [post] // @Router /ai/v1/responses [post]
func (h *aiGatewayHandler) responses(c *gin.Context) { func (h *aiGatewayHandler) responses(c *gin.Context) {
raw, err := c.GetRawData() raw, err := c.GetRawData()
@@ -484,16 +577,22 @@ func (h *aiGatewayHandler) responses(c *gin.Context) {
// OCI /actions/v1/responses,响应原样透传。 // OCI /actions/v1/responses,响应原样透传。
func (h *aiGatewayHandler) responsesPassthrough(c *gin.Context, raw []byte, req aiwire.RespRequest) { func (h *aiGatewayHandler) responsesPassthrough(c *gin.Context, raw []byte, req aiwire.RespRequest) {
if err := service.RespPassthroughValidate(req); err != nil { if err := service.RespPassthroughValidate(req); err != nil {
log.Printf("responses 直通(model=%s): 校验拒绝: %v", req.Model, err)
aiError(c, http.StatusBadRequest, "invalid_request_error", err.Error()) aiError(c, http.StatusBadRequest, "invalid_request_error", err.Error())
return return
} }
body, err := service.RespPassthroughBody(raw) body, compat, err := service.RespPassthroughBody(raw)
if err != nil { if err != nil {
aiError(c, http.StatusBadRequest, "invalid_request_error", err.Error()) aiError(c, http.StatusBadRequest, "invalid_request_error", err.Error())
return return
} }
logRespCompat(req.Model, compat)
if req.Stream { if req.Stream {
h.responsesPassthroughStream(c, body, req) if len(body) > service.RespStreamUpgradeLimit {
h.responsesStreamUpgrade(c, body, req, compat)
return
}
h.responsesPassthroughStream(c, body, req, compat)
return return
} }
start := time.Now() start := time.Now()
@@ -505,6 +604,7 @@ func (h *aiGatewayHandler) responsesPassthrough(c *gin.Context, raw []byte, req
h.logFailure(c, entry, req) h.logFailure(c, entry, req)
return return
} }
payload = service.RespRestoreToolCalls(payload, compat)
entry.Status = http.StatusOK entry.Status = http.StatusOK
fillUsage(&entry, service.RespPassthroughUsage(payload)) fillUsage(&entry, service.RespPassthroughUsage(payload))
callID := h.gw.LogCall(entry) callID := h.gw.LogCall(entry)
@@ -512,9 +612,74 @@ func (h *aiGatewayHandler) responsesPassthrough(c *gin.Context, raw []byte, req
c.Data(http.StatusOK, "application/json; charset=utf-8", payload) c.Data(http.StatusOK, "application/json; charset=utf-8", payload)
} }
// logRespCompat 记录直通请求的 codex 兼容改写动作(观测)。
func logRespCompat(model string, compat service.RespCompat) {
if len(compat.Flattened) == 0 && len(compat.Dropped) == 0 && len(compat.Converted) == 0 {
return
}
var parts []string
if len(compat.Flattened) > 0 {
parts = append(parts, "拍平: "+strings.Join(compat.Flattened, ", "))
}
if len(compat.Converted) > 0 {
parts = append(parts, "转换: "+strings.Join(compat.Converted, ", "))
}
if len(compat.Dropped) > 0 {
parts = append(parts, "剥离: "+strings.Join(compat.Dropped, ", "))
}
log.Printf("responses 直通(model=%s): %s", model, strings.Join(parts, "; "))
}
// responsesStreamUpgrade 流式升级回退:上游对超大流式请求会在推理途中掐断
// (实测 >~82KB,见 RespStreamUpgradeLimit),超限时改调非流式上游拿完整响应,
// 本地合成最小 SSE 事件序列回给客户端;丢失增量输出,换会话不中断。
func (h *aiGatewayHandler) responsesStreamUpgrade(c *gin.Context, body []byte, req aiwire.RespRequest, compat service.RespCompat) {
start := time.Now()
nsBody, err := service.RespDisableStream(body)
if err != nil {
aiError(c, http.StatusBadRequest, "invalid_request_error", err.Error())
return
}
log.Printf("responses 直通(model=%s): 请求体 %dKB 超流式安全上限,改走非流式合成 SSE", req.Model, len(body)/1024)
payload, meta, err := h.gw.RespPassthrough(c.Request.Context(), nsBody, req.Model, keyGroup(c))
entry := h.logEntry(c, "responses", req.Model, true, meta, start)
if err != nil {
upstreamError(c, err)
entry.ErrMsg = err.Error()
h.logFailure(c, entry, req)
return
}
payload = service.RespRestoreToolCalls(payload, compat)
writeSynthSSE(c, payload)
entry.Status = http.StatusOK
entry.LatencyMs = time.Since(start).Milliseconds()
fillUsage(&entry, service.RespPassthroughUsage(payload))
callID := h.gw.LogCall(entry)
h.maybeLogContent(c, callID, "responses", req.Model, true, req, json.RawMessage(payload))
}
// writeSynthSSE 把完整响应按合成事件序列写出;合成失败时降级为一次性 JSON,
// 客户端至少拿到完整结果。
func writeSynthSSE(c *gin.Context, payload []byte) {
events, err := service.RespSynthSSEEvents(payload)
if err != nil {
log.Printf("responses 直通: 合成 SSE 失败,降级 JSON 返回: %v", err)
c.Data(http.StatusOK, "application/json; charset=utf-8", payload)
return
}
sseHeaders(c)
for _, ev := range events {
c.Writer.Write([]byte("data: "))
c.Writer.Write(ev)
c.Writer.Write([]byte("\n\n"))
}
c.Writer.Flush()
}
// responsesPassthroughStream 流式直通:SSE 事件原样转发(推理增量等直达客户端), // responsesPassthroughStream 流式直通:SSE 事件原样转发(推理增量等直达客户端),
// 逐行扫描 completed 事件提取 usage 记账 // 逐行扫描 completed 事件提取 usage 记账;refs 非空时对 function_call 事件做
func (h *aiGatewayHandler) responsesPassthroughStream(c *gin.Context, body []byte, req aiwire.RespRequest) { // namespace 还原后再转发。
func (h *aiGatewayHandler) responsesPassthroughStream(c *gin.Context, body []byte, req aiwire.RespRequest, compat service.RespCompat) {
start := time.Now() start := time.Now()
upstream, meta, err := h.gw.RespPassthroughStream(c.Request.Context(), body, req.Model, keyGroup(c)) upstream, meta, err := h.gw.RespPassthroughStream(c.Request.Context(), body, req.Model, keyGroup(c))
entry := h.logEntry(c, "responses", req.Model, true, meta, start) entry := h.logEntry(c, "responses", req.Model, true, meta, start)
@@ -526,9 +691,14 @@ func (h *aiGatewayHandler) responsesPassthroughStream(c *gin.Context, body []byt
} }
defer upstream.Close() defer upstream.Close()
sseHeaders(c) sseHeaders(c)
usage, err := forwardSSE(c, upstream) usage, upErr, err := forwardSSE(c, upstream, compat)
if err != nil { if err != nil {
entry.ErrMsg = err.Error() entry.ErrMsg = err.Error()
} else if upErr != "" {
// 上游错误事件已原样转发给客户端,这里落日志可查
entry.ErrMsg = upErr
} else if usage == nil {
entry.ErrMsg = "上游流提前终止,未返回终态事件"
} }
entry.Status = http.StatusOK entry.Status = http.StatusOK
entry.LatencyMs = time.Since(start).Milliseconds() entry.LatencyMs = time.Since(start).Milliseconds()
@@ -538,29 +708,54 @@ func (h *aiGatewayHandler) responsesPassthroughStream(c *gin.Context, body []byt
} }
// forwardSSE 把上游 SSE 逐行转发给客户端,空行(事件边界)即 flush; // forwardSSE 把上游 SSE 逐行转发给客户端,空行(事件边界)即 flush;
// 顺带从 data 行提取 response.completed 的 usage // 顺带从 data 行提取 response.completed 的 usage 与错误事件消息;
func forwardSSE(c *gin.Context, upstream io.Reader) (*aiwire.Usage, error) { // refs 非空时 data 行先做 namespace 还原(未改动的行原样转发)。
func forwardSSE(c *gin.Context, upstream io.Reader, compat service.RespCompat) (*aiwire.Usage, string, error) {
reader := bufio.NewReader(upstream) reader := bufio.NewReader(upstream)
var usage *aiwire.Usage var usage *aiwire.Usage
var upErr string
for { for {
line, err := reader.ReadBytes('\n') line, err := reader.ReadBytes('\n')
if len(line) > 0 { if len(line) > 0 {
c.Writer.Write(line)
trimmed := bytes.TrimSpace(line) trimmed := bytes.TrimSpace(line)
if len(trimmed) == 0 { if data, ok := bytes.CutPrefix(trimmed, []byte("data: ")); ok {
c.Writer.Flush() c.Writer.Write(restoreSSELine(line, data, compat))
} else if data, ok := bytes.CutPrefix(trimmed, []byte("data: ")); ok {
if u := service.RespStreamCompletedUsage(data); u != nil { if u := service.RespStreamCompletedUsage(data); u != nil {
usage = u usage = u
} }
if m := service.RespStreamErrorMsg(data); m != "" && upErr == "" {
upErr = m
}
} else {
c.Writer.Write(line)
if len(trimmed) == 0 {
c.Writer.Flush()
}
} }
} }
if err != nil { if err != nil {
c.Writer.Flush() c.Writer.Flush()
if errors.Is(err, io.EOF) { if errors.Is(err, io.EOF) {
return usage, nil return usage, upErr, nil
} }
return usage, err return usage, upErr, err
} }
} }
} }
// restoreSSELine 对一行 data 事件做工具调用项还原(namespace/custom),
// 未改动时原行透传(字节级直通)。
func restoreSSELine(line, data []byte, compat service.RespCompat) []byte {
if !compat.NeedRestore() {
return line
}
restored, changed := service.RespRestoreToolCallsEvent(data, compat)
if !changed {
return line
}
out := make([]byte, 0, len(restored)+8)
out = append(out, "data: "...)
out = append(out, restored...)
out = append(out, '\n')
return out
}
+145
View File
@@ -0,0 +1,145 @@
package api
import (
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"oci-portal/internal/aiwire"
"oci-portal/internal/service"
)
// audioSpeech 是 OpenAI /ai/v1/audio/speech 端点(TTS,直通兼容面)。
//
// @Summary OpenAI Audio Speech 兼容端点(文本转语音)
// @Tags AI 网关
// @Param body body aiwire.SpeechRequest true "OpenAI audio speech 请求体(model/input 必填,voice 见 xAI Grok Voice 列表,language 缺省 auto;未列字段原样透传)"
// @Success 200 {file} binary "音频字节(Content-Type 透传上游,默认 audio/mpeg)"
// @Router /ai/v1/audio/speech [post]
func (h *aiGatewayHandler) audioSpeech(c *gin.Context) {
raw, err := c.GetRawData()
if err != nil {
aiError(c, http.StatusBadRequest, "invalid_request_error", err.Error())
return
}
modelName, body, err := service.SpeechBodyNormalize(raw)
if err != nil {
aiError(c, http.StatusBadRequest, "invalid_request_error", err.Error())
return
}
h.speechRespond(c, "speech", modelName, raw, body)
}
// tts 是 xAI 官方格式 TTS 端点(/ai/v1/tts),转换为上游 OpenAI 兼容形态后复用 Speech 编排。
//
// @Summary xAI 官方格式文本转语音端点
// @Tags AI 网关
// @Param body body aiwire.TtsRequest true "xAI TTS 请求体(text/language 必填,voice_id 缺省 eve;model 为网关扩展,缺省 xai.grok-tts;未列字段原样透传)"
// @Success 200 {file} binary "音频字节(Content-Type 透传上游,默认 audio/mpeg)"
// @Router /ai/v1/tts [post]
func (h *aiGatewayHandler) tts(c *gin.Context) {
raw, err := c.GetRawData()
if err != nil {
aiError(c, http.StatusBadRequest, "invalid_request_error", err.Error())
return
}
modelName, body, err := service.TtsBodyConvert(raw)
if err != nil {
aiError(c, http.StatusBadRequest, "invalid_request_error", err.Error())
return
}
h.speechRespond(c, "tts", modelName, raw, body)
}
// speechRespond 是 audioSpeech / tts 的公共主体:白名单校验、上游调用、日志与音频响应。
func (h *aiGatewayHandler) speechRespond(c *gin.Context, endpoint, modelName string, raw, body []byte) {
if !checkKeyModel(c, modelName) {
return
}
start := time.Now()
audio, contentType, meta, err := h.gw.Speech(c.Request.Context(), modelName, body, keyGroup(c))
entry := h.logEntry(c, endpoint, modelName, false, meta, start)
if err != nil {
upstreamError(c, err)
entry.ErrMsg = err.Error()
h.logFailure(c, entry, string(raw))
return
}
entry.Status = http.StatusOK
callID := h.gw.LogCall(entry)
h.maybeLogContent(c, callID, endpoint, modelName, false, string(raw), nil)
if contentType == "" {
contentType = "audio/mpeg"
}
c.Data(http.StatusOK, contentType, audio)
}
// rerank 是 /ai/v1/rerank 端点(Jina / Cohere 风格文档重排)。
//
// @Summary 文档重排端点(Cohere Rerank)
// @Tags AI 网关
// @Param body body aiwire.RerankRequest true "重排请求体(model/query/documents 必填,可选 top_n/return_documents)"
// @Success 200 {object} aiwire.RerankResponse "重排结果(results[].index 指向入参下标)"
// @Router /ai/v1/rerank [post]
func (h *aiGatewayHandler) rerank(c *gin.Context) {
var req aiwire.RerankRequest
if err := c.ShouldBindJSON(&req); err != nil {
aiError(c, http.StatusBadRequest, "invalid_request_error", err.Error())
return
}
if strings.TrimSpace(req.Model) == "" || strings.TrimSpace(req.Query) == "" || len(req.Documents) == 0 {
aiError(c, http.StatusBadRequest, "invalid_request_error", "model、query 与 documents 不能为空")
return
}
if !checkKeyModel(c, req.Model) {
return
}
start := time.Now()
resp, meta, err := h.gw.Rerank(c.Request.Context(), req, keyGroup(c))
entry := h.logEntry(c, "rerank", req.Model, false, meta, start)
if err != nil {
upstreamError(c, err)
entry.ErrMsg = err.Error()
h.logFailure(c, entry, req)
return
}
entry.Status = http.StatusOK
callID := h.gw.LogCall(entry)
h.maybeLogContent(c, callID, "rerank", req.Model, false, req, resp)
c.JSON(http.StatusOK, resp)
}
// moderations 是 /ai/v1/moderations 端点(OpenAI 外壳映射 OCI Guardrails)。
//
// @Summary 内容审核端点(OCI Guardrails)
// @Tags AI 网关
// @Param body body aiwire.ModerationsRequest true "审核请求体(input 为字符串或字符串数组,单次至多 8 条;model 接受但忽略)"
// @Success 200 {object} aiwire.ModerationsResponse "审核结果(categories/category_scores 为 overall/blocklist/prompt_injection,pii 为扩展字段)"
// @Router /ai/v1/moderations [post]
func (h *aiGatewayHandler) moderations(c *gin.Context) {
var req aiwire.ModerationsRequest
if err := c.ShouldBindJSON(&req); err != nil {
aiError(c, http.StatusBadRequest, "invalid_request_error", err.Error())
return
}
inputs, err := service.ModerationInputs(req.Input)
if err != nil {
aiError(c, http.StatusBadRequest, "invalid_request_error", err.Error())
return
}
start := time.Now()
resp, meta, err := h.gw.Moderations(c.Request.Context(), aiRandID("modr_"), inputs, keyGroup(c))
entry := h.logEntry(c, "moderations", "oci-guardrails", false, meta, start)
if err != nil {
upstreamError(c, err)
entry.ErrMsg = err.Error()
h.logFailure(c, entry, req)
return
}
entry.Status = http.StatusOK
callID := h.gw.LogCall(entry)
h.maybeLogContent(c, callID, "moderations", "oci-guardrails", false, req, resp)
c.JSON(http.StatusOK, resp)
}
+14
View File
@@ -85,6 +85,8 @@ func TestAiGatewayKeyModelRestrict(t *testing.T) {
`{"model":"meta.llama-3.3-70b-instruct","messages":[{"role":"user","content":"hi"}]}`, 404, deny}, `{"model":"meta.llama-3.3-70b-instruct","messages":[{"role":"user","content":"hi"}]}`, 404, deny},
{"chat completions 白名单内穿透", "limited-key-1234", "/ai/v1/chat/completions", {"chat completions 白名单内穿透", "limited-key-1234", "/ai/v1/chat/completions",
`{"model":"ghost-model","messages":[{"role":"user","content":"hi"}]}`, 404, pass}, `{"model":"ghost-model","messages":[{"role":"user","content":"hi"}]}`, 404, pass},
{"messages 缺 max_tokens 按默认值放行", "open-key-12345", "/ai/v1/messages",
`{"model":"ghost-model","messages":[{"role":"user","content":"hi"}]}`, 404, pass},
{"chat completions 缺 messages 拒绝", "open-key-12345", "/ai/v1/chat/completions", {"chat completions 缺 messages 拒绝", "open-key-12345", "/ai/v1/chat/completions",
`{"model":"ghost-model"}`, 400, []string{"invalid_request_error"}}, `{"model":"ghost-model"}`, 400, []string{"invalid_request_error"}},
{"chat completions 非 function 工具拒绝", "open-key-12345", "/ai/v1/chat/completions", {"chat completions 非 function 工具拒绝", "open-key-12345", "/ai/v1/chat/completions",
@@ -93,6 +95,18 @@ func TestAiGatewayKeyModelRestrict(t *testing.T) {
{"chat completions 不支持内容块拒绝", "open-key-12345", "/ai/v1/chat/completions", {"chat completions 不支持内容块拒绝", "open-key-12345", "/ai/v1/chat/completions",
`{"model":"ghost-model","messages":[{"role":"user","content":[{"type":"input_audio"}]}]}`, `{"model":"ghost-model","messages":[{"role":"user","content":[{"type":"input_audio"}]}]}`,
400, []string{"invalid_request_error"}}, 400, []string{"invalid_request_error"}},
{"audio speech 白名单外拦截", "limited-key-1234", "/ai/v1/audio/speech",
`{"model":"meta.llama-3.3-70b-instruct","input":"你好"}`, 404, deny},
{"rerank 白名单外拦截", "limited-key-1234", "/ai/v1/rerank",
`{"model":"meta.llama-3.3-70b-instruct","query":"q","documents":["d"]}`, 404, deny},
{"rerank 缺 documents 拒绝", "open-key-12345", "/ai/v1/rerank",
`{"model":"ghost-model","query":"q"}`, 400, []string{"invalid_request_error"}},
{"moderations 空 input 拒绝", "open-key-12345", "/ai/v1/moderations",
`{"input":[]}`, 400, []string{"invalid_request_error"}},
{"tts 缺 language 拒绝", "open-key-12345", "/ai/v1/tts",
`{"text":"你好"}`, 400, []string{"invalid_request_error"}},
{"tts 白名单外拦截", "limited-key-1234", "/ai/v1/tts",
`{"model":"meta.llama-3.3-70b-instruct","text":"你好","language":"zh"}`, 404, deny},
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
+11 -11
View File
@@ -15,7 +15,7 @@ import (
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param instanceId path string true "instanceId" // @Param instanceId path string true "instanceId"
// @Param body body object true "请求体(见接口说明)" // @Param body body object true "请求体(见接口说明)"
// @Success 200 {object} map[string]any // @Success 200 {object} publicIpResponse
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/instances/{instanceId}/change-public-ip [post] // @Router /api/v1/oci-configs/{id}/instances/{instanceId}/change-public-ip [post]
func (h *ociConfigHandler) changePublicIP(c *gin.Context) { func (h *ociConfigHandler) changePublicIP(c *gin.Context) {
@@ -40,7 +40,7 @@ func (h *ociConfigHandler) changePublicIP(c *gin.Context) {
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param instanceId path string true "instanceId" // @Param instanceId path string true "instanceId"
// @Param body body object true "请求体(见接口说明)" // @Param body body object true "请求体(见接口说明)"
// @Success 201 {object} map[string]any // @Success 201 {object} ipv6AddressResponse
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/instances/{instanceId}/ipv6-addresses [post] // @Router /api/v1/oci-configs/{id}/instances/{instanceId}/ipv6-addresses [post]
func (h *ociConfigHandler) addInstanceIpv6(c *gin.Context) { func (h *ociConfigHandler) addInstanceIpv6(c *gin.Context) {
@@ -92,7 +92,7 @@ type attachVnicRequest struct {
// @Tags 计算 // @Tags 计算
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param instanceId path string true "instanceId" // @Param instanceId path string true "instanceId"
// @Success 200 {object} map[string]any // @Success 200 {array} oci.Vnic
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/instances/{instanceId}/vnics [get] // @Router /api/v1/oci-configs/{id}/instances/{instanceId}/vnics [get]
func (h *ociConfigHandler) listInstanceVnics(c *gin.Context) { func (h *ociConfigHandler) listInstanceVnics(c *gin.Context) {
@@ -113,7 +113,7 @@ func (h *ociConfigHandler) listInstanceVnics(c *gin.Context) {
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param instanceId path string true "instanceId" // @Param instanceId path string true "instanceId"
// @Param body body attachVnicRequest true "请求体" // @Param body body attachVnicRequest true "请求体"
// @Success 201 {object} map[string]any // @Success 201 {object} oci.Vnic
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/instances/{instanceId}/vnics [post] // @Router /api/v1/oci-configs/{id}/instances/{instanceId}/vnics [post]
func (h *ociConfigHandler) attachVnic(c *gin.Context) { func (h *ociConfigHandler) attachVnic(c *gin.Context) {
@@ -160,7 +160,7 @@ func (h *ociConfigHandler) detachVnic(c *gin.Context) {
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param vnicId path string true "vnicId" // @Param vnicId path string true "vnicId"
// @Param body body object true "请求体(见接口说明)" // @Param body body object true "请求体(见接口说明)"
// @Success 201 {object} map[string]any // @Success 201 {object} addressResponse
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/vnics/{vnicId}/ipv6-addresses [post] // @Router /api/v1/oci-configs/{id}/vnics/{vnicId}/ipv6-addresses [post]
func (h *ociConfigHandler) addVnicIpv6(c *gin.Context) { func (h *ociConfigHandler) addVnicIpv6(c *gin.Context) {
@@ -195,7 +195,7 @@ type attachBootVolumeRequest struct {
// @Tags 存储 // @Tags 存储
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param instanceId path string true "instanceId" // @Param instanceId path string true "instanceId"
// @Success 200 {object} map[string]any // @Success 200 {array} oci.BootVolumeAttachment
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/instances/{instanceId}/boot-volume-attachments [get] // @Router /api/v1/oci-configs/{id}/instances/{instanceId}/boot-volume-attachments [get]
func (h *ociConfigHandler) listBootVolumeAttachments(c *gin.Context) { func (h *ociConfigHandler) listBootVolumeAttachments(c *gin.Context) {
@@ -216,7 +216,7 @@ func (h *ociConfigHandler) listBootVolumeAttachments(c *gin.Context) {
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param instanceId path string true "instanceId" // @Param instanceId path string true "instanceId"
// @Param body body attachBootVolumeRequest true "请求体" // @Param body body attachBootVolumeRequest true "请求体"
// @Success 201 {object} map[string]any // @Success 201 {object} oci.BootVolumeAttachment
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/instances/{instanceId}/boot-volume-attachments [post] // @Router /api/v1/oci-configs/{id}/instances/{instanceId}/boot-volume-attachments [post]
func (h *ociConfigHandler) attachBootVolume(c *gin.Context) { func (h *ociConfigHandler) attachBootVolume(c *gin.Context) {
@@ -242,7 +242,7 @@ func (h *ociConfigHandler) attachBootVolume(c *gin.Context) {
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param instanceId path string true "instanceId" // @Param instanceId path string true "instanceId"
// @Param body body attachBootVolumeRequest true "请求体" // @Param body body attachBootVolumeRequest true "请求体"
// @Success 200 {object} map[string]any // @Success 200 {object} oci.BootVolumeAttachment
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/instances/{instanceId}/replace-boot-volume [post] // @Router /api/v1/oci-configs/{id}/instances/{instanceId}/replace-boot-volume [post]
func (h *ociConfigHandler) replaceBootVolume(c *gin.Context) { func (h *ociConfigHandler) replaceBootVolume(c *gin.Context) {
@@ -293,7 +293,7 @@ type attachVolumeRequest struct {
// @Summary 块存储卷列表 // @Summary 块存储卷列表
// @Tags 存储 // @Tags 存储
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Success 200 {object} map[string]any // @Success 200 {array} oci.BlockVolume
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/volumes [get] // @Router /api/v1/oci-configs/{id}/volumes [get]
func (h *ociConfigHandler) listBlockVolumes(c *gin.Context) { func (h *ociConfigHandler) listBlockVolumes(c *gin.Context) {
@@ -313,7 +313,7 @@ func (h *ociConfigHandler) listBlockVolumes(c *gin.Context) {
// @Tags 存储 // @Tags 存储
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param instanceId path string true "instanceId" // @Param instanceId path string true "instanceId"
// @Success 200 {object} map[string]any // @Success 200 {array} oci.VolumeAttachment
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/instances/{instanceId}/volume-attachments [get] // @Router /api/v1/oci-configs/{id}/instances/{instanceId}/volume-attachments [get]
func (h *ociConfigHandler) listVolumeAttachments(c *gin.Context) { func (h *ociConfigHandler) listVolumeAttachments(c *gin.Context) {
@@ -334,7 +334,7 @@ func (h *ociConfigHandler) listVolumeAttachments(c *gin.Context) {
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param instanceId path string true "instanceId" // @Param instanceId path string true "instanceId"
// @Param body body attachVolumeRequest true "请求体" // @Param body body attachVolumeRequest true "请求体"
// @Success 201 {object} map[string]any // @Success 201 {object} oci.VolumeAttachment
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/instances/{instanceId}/volume-attachments [post] // @Router /api/v1/oci-configs/{id}/instances/{instanceId}/volume-attachments [post]
func (h *ociConfigHandler) attachVolume(c *gin.Context) { func (h *ociConfigHandler) attachVolume(c *gin.Context) {
+3 -3
View File
@@ -32,9 +32,9 @@ type loginRequest struct {
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param body body loginRequest true "登录凭据" // @Param body body loginRequest true "登录凭据"
// @Success 200 {object} map[string]any "token 与 expiresAt" // @Success 200 {object} tokenResponse "token 与 expiresAt"
// @Failure 401 {object} map[string]string "凭据错误" // @Failure 401 {object} errorResponse "凭据错误"
// @Failure 428 {object} map[string]any "需要两步验证码(totpRequired=true)" // @Failure 428 {object} totpRequiredResponse "需要两步验证码(totpRequired=true)"
// @Router /api/v1/auth/login [post] // @Router /api/v1/auth/login [post]
func (h *authHandler) login(c *gin.Context) { func (h *authHandler) login(c *gin.Context) {
var req loginRequest var req loginRequest
+37 -12
View File
@@ -5,9 +5,12 @@ import (
"net/http" "net/http"
"net/url" "net/url"
"strconv" "strconv"
"time"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"oci-portal/internal/model"
"oci-portal/internal/service" "oci-portal/internal/service"
) )
@@ -15,6 +18,7 @@ import (
type authxHandler struct { type authxHandler struct {
auth *service.AuthService auth *service.AuthService
oauth *service.OAuthService oauth *service.OAuthService
logs *service.SystemLogService
} }
// ---- TOTP(JWT 组内) ---- // ---- TOTP(JWT 组内) ----
@@ -23,7 +27,7 @@ type authxHandler struct {
// //
// @Summary 两步验证状态 // @Summary 两步验证状态
// @Tags 认证 // @Tags 认证
// @Success 200 {object} map[string]bool "enabled" // @Success 200 {object} enabledResponse "enabled"
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/auth/totp [get] // @Router /api/v1/auth/totp [get]
func (h *authxHandler) totpStatus(c *gin.Context) { func (h *authxHandler) totpStatus(c *gin.Context) {
@@ -39,8 +43,8 @@ func (h *authxHandler) totpStatus(c *gin.Context) {
// //
// @Summary 发起两步验证设置 // @Summary 发起两步验证设置
// @Tags 认证 // @Tags 认证
// @Success 200 {object} map[string]string "secret 与 otpauthUri" // @Success 200 {object} totpSetupResponse "secret 与 otpauthUri"
// @Failure 409 {object} map[string]string "已启用" // @Failure 409 {object} errorResponse "已启用"
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/auth/totp/setup [post] // @Router /api/v1/auth/totp/setup [post]
func (h *authxHandler) totpSetup(c *gin.Context) { func (h *authxHandler) totpSetup(c *gin.Context) {
@@ -128,7 +132,7 @@ func (h *authxHandler) respondFreshToken(c *gin.Context) {
// //
// @Summary 撤销全部会话 // @Summary 撤销全部会话
// @Tags 认证 // @Tags 认证
// @Success 200 {object} map[string]string "新 token 与 expiresAt" // @Success 200 {object} tokenResponse "新 token 与 expiresAt"
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/auth/revoke-sessions [post] // @Router /api/v1/auth/revoke-sessions [post]
func (h *authxHandler) revokeSessions(c *gin.Context) { func (h *authxHandler) revokeSessions(c *gin.Context) {
@@ -146,7 +150,7 @@ func (h *authxHandler) revokeSessions(c *gin.Context) {
// //
// @Summary 登录凭据摘要 // @Summary 登录凭据摘要
// @Tags 认证 // @Tags 认证
// @Success 200 {object} map[string]any "username 与 passwordLoginDisabled" // @Success 200 {object} credentialsResponse "username 与 passwordLoginDisabled"
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/auth/credentials [get] // @Router /api/v1/auth/credentials [get]
func (h *authxHandler) getCredentials(c *gin.Context) { func (h *authxHandler) getCredentials(c *gin.Context) {
@@ -167,7 +171,7 @@ func (h *authxHandler) getCredentials(c *gin.Context) {
// @Tags 认证 // @Tags 认证
// @Param body body service.UpdateCredentialsInput true "新凭据(当前密码必验)" // @Param body body service.UpdateCredentialsInput true "新凭据(当前密码必验)"
// @Success 204 "已更新,请重新登录" // @Success 204 "已更新,请重新登录"
// @Failure 401 {object} map[string]string "当前密码错误" // @Failure 401 {object} errorResponse "当前密码错误"
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/auth/credentials [put] // @Router /api/v1/auth/credentials [put]
func (h *authxHandler) updateCredentials(c *gin.Context) { func (h *authxHandler) updateCredentials(c *gin.Context) {
@@ -199,7 +203,7 @@ func (h *authxHandler) updateCredentials(c *gin.Context) {
// @Tags 认证 // @Tags 认证
// @Param body body object true "{disabled: bool}" // @Param body body object true "{disabled: bool}"
// @Success 204 "已保存" // @Success 204 "已保存"
// @Failure 409 {object} map[string]string "未绑定外部身份" // @Failure 409 {object} errorResponse "未绑定外部身份"
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/auth/password-login [put] // @Router /api/v1/auth/password-login [put]
func (h *authxHandler) updatePasswordLogin(c *gin.Context) { func (h *authxHandler) updatePasswordLogin(c *gin.Context) {
@@ -230,7 +234,7 @@ func (h *authxHandler) updatePasswordLogin(c *gin.Context) {
// //
// @Summary 外部登录 provider 列表 // @Summary 外部登录 provider 列表
// @Tags 认证 // @Tags 认证
// @Success 200 {object} map[string]any "providers 与 passwordLoginDisabled" // @Success 200 {object} oauthProvidersResponse "providers 与 passwordLoginDisabled"
// @Router /api/v1/auth/oauth/providers [get] // @Router /api/v1/auth/oauth/providers [get]
func (h *authxHandler) oauthProviders(c *gin.Context) { func (h *authxHandler) oauthProviders(c *gin.Context) {
providers := h.oauth.Providers(c.Request.Context()) providers := h.oauth.Providers(c.Request.Context())
@@ -247,7 +251,7 @@ func (h *authxHandler) oauthProviders(c *gin.Context) {
// @Tags 认证 // @Tags 认证
// @Param provider path string true "oidc / github" // @Param provider path string true "oidc / github"
// @Param mode query string false "bind=绑定当前账号(需 Bearer),缺省登录" // @Param mode query string false "bind=绑定当前账号(需 Bearer),缺省登录"
// @Success 200 {object} map[string]string "url" // @Success 200 {object} urlResponse "url"
// @Router /api/v1/auth/oauth/{provider}/authorize [get] // @Router /api/v1/auth/oauth/{provider}/authorize [get]
func (h *authxHandler) oauthAuthorize(c *gin.Context) { func (h *authxHandler) oauthAuthorize(c *gin.Context) {
provider := c.Param("provider") provider := c.Param("provider")
@@ -299,10 +303,12 @@ func (h *authxHandler) bearerUser(c *gin.Context) (string, bool) {
// @Success 302 "登录 token 经 fragment 回前端,绑定回设置页" // @Success 302 "登录 token 经 fragment 回前端,绑定回设置页"
// @Router /api/v1/auth/oauth/{provider}/callback [get] // @Router /api/v1/auth/oauth/{provider}/callback [get]
func (h *authxHandler) oauthCallback(c *gin.Context) { func (h *authxHandler) oauthCallback(c *gin.Context) {
start := time.Now()
provider := c.Param("provider") provider := c.Param("provider")
token, _, mode, err := h.oauth.HandleCallback( token, username, mode, err := h.oauth.HandleCallback(
c.Request.Context(), provider, c.Query("state"), c.Query("code")) c.Request.Context(), provider, c.Query("state"), c.Query("code"))
if err != nil { if err != nil {
h.recordOauth(c, username, http.StatusUnauthorized, oauthErrText(err), start)
target := "/login" target := "/login"
if mode == "bind" { if mode == "bind" {
target = "/settings" target = "/settings"
@@ -310,6 +316,7 @@ func (h *authxHandler) oauthCallback(c *gin.Context) {
c.Redirect(http.StatusFound, target+"?oauthError="+url.QueryEscape(oauthErrText(err))) c.Redirect(http.StatusFound, target+"?oauthError="+url.QueryEscape(oauthErrText(err)))
return return
} }
h.recordOauth(c, username, http.StatusOK, "", start)
if mode == "bind" { if mode == "bind" {
// 绑定模式:版本已递增,新 token 经 fragment 带回设置页无感换发 // 绑定模式:版本已递增,新 token 经 fragment 带回设置页无感换发
c.Redirect(http.StatusFound, "/settings?oauth=bound#oauthToken="+url.QueryEscape(token)) c.Redirect(http.StatusFound, "/settings?oauth=bound#oauthToken="+url.QueryEscape(token))
@@ -319,6 +326,24 @@ func (h *authxHandler) oauthCallback(c *gin.Context) {
c.Redirect(http.StatusFound, "/login#oauthToken="+url.QueryEscape(token)) c.Redirect(http.StatusFound, "/login#oauthToken="+url.QueryEscape(token))
} }
// recordOauth 把外部登录 / 绑定结果记入系统日志——回调是 GET,
// 不经写方法中间件;实际响应恒为 302,日志按语义记 200 / 401。
func (h *authxHandler) recordOauth(c *gin.Context, username string, status int, errMsg string, start time.Time) {
if h.logs == nil {
return
}
h.logs.Record(model.SystemLog{
Username: username,
Method: c.Request.Method,
Path: requestPath(c),
Status: status,
DurationMs: time.Since(start).Milliseconds(),
ClientIP: requestIP(c),
UserAgent: truncateLogField(c.Request.UserAgent(), 256),
ErrMsg: errMsg,
})
}
// oauthErrText 把流程错误转为用户可读文案;内部错误不透出细节。 // oauthErrText 把流程错误转为用户可读文案;内部错误不透出细节。
func oauthErrText(err error) string { func oauthErrText(err error) string {
for _, known := range []error{service.ErrOAuthNotConfigured, service.ErrOAuthNoAppURL, service.ErrOAuthDisabled, service.ErrOAuthState, service.ErrOAuthNotBound, service.ErrOAuthBound} { for _, known := range []error{service.ErrOAuthNotConfigured, service.ErrOAuthNoAppURL, service.ErrOAuthDisabled, service.ErrOAuthState, service.ErrOAuthNotBound, service.ErrOAuthBound} {
@@ -333,7 +358,7 @@ func oauthErrText(err error) string {
// //
// @Summary 已绑定外部身份 // @Summary 已绑定外部身份
// @Tags 认证 // @Tags 认证
// @Success 200 {object} map[string]any "items" // @Success 200 {object} itemsResponse[model.UserIdentity] "items"
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/auth/identities [get] // @Router /api/v1/auth/identities [get]
func (h *authxHandler) identities(c *gin.Context) { func (h *authxHandler) identities(c *gin.Context) {
@@ -351,7 +376,7 @@ func (h *authxHandler) identities(c *gin.Context) {
// @Tags 认证 // @Tags 认证
// @Param id path int true "身份 ID" // @Param id path int true "身份 ID"
// @Success 204 "已解绑" // @Success 204 "已解绑"
// @Failure 409 {object} map[string]string "最后一个身份不可解绑" // @Failure 409 {object} errorResponse "最后一个身份不可解绑"
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/auth/identities/{id} [delete] // @Router /api/v1/auth/identities/{id} [delete]
func (h *authxHandler) unbindIdentity(c *gin.Context) { func (h *authxHandler) unbindIdentity(c *gin.Context) {
+4 -2
View File
@@ -4,6 +4,8 @@ import (
"net/http" "net/http"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
_ "oci-portal/internal/oci" // swagger 注解引用
) )
// ---- 控制台连接(VNC / 串口) ---- // ---- 控制台连接(VNC / 串口) ----
@@ -18,7 +20,7 @@ type createConsoleConnectionRequest struct {
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param instanceId path string true "instanceId" // @Param instanceId path string true "instanceId"
// @Param body body createConsoleConnectionRequest true "请求体" // @Param body body createConsoleConnectionRequest true "请求体"
// @Success 201 {object} map[string]any // @Success 201 {object} oci.ConsoleConnection
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/instances/{instanceId}/console-connections [post] // @Router /api/v1/oci-configs/{id}/instances/{instanceId}/console-connections [post]
func (h *ociConfigHandler) createConsoleConnection(c *gin.Context) { func (h *ociConfigHandler) createConsoleConnection(c *gin.Context) {
@@ -43,7 +45,7 @@ func (h *ociConfigHandler) createConsoleConnection(c *gin.Context) {
// @Tags 计算 // @Tags 计算
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param instanceId path string true "instanceId" // @Param instanceId path string true "instanceId"
// @Success 200 {object} map[string]any // @Success 200 {array} oci.ConsoleConnection
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/instances/{instanceId}/console-connections [get] // @Router /api/v1/oci-configs/{id}/instances/{instanceId}/console-connections [get]
func (h *ociConfigHandler) listConsoleConnections(c *gin.Context) { func (h *ociConfigHandler) listConsoleConnections(c *gin.Context) {
+6 -6
View File
@@ -41,7 +41,7 @@ func boolOr(v *bool, def bool) bool {
// @Tags 租户 IAM // @Tags 租户 IAM
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param domainId query string false "身份域 OCID(缺省 Default 域)" // @Param domainId query string false "身份域 OCID(缺省 Default 域)"
// @Success 200 {object} map[string]any // @Success 200 {array} oci.IdentityProviderInfo
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/identity-providers [get] // @Router /api/v1/oci-configs/{id}/identity-providers [get]
func (h *ociConfigHandler) listIdentityProviders(c *gin.Context) { func (h *ociConfigHandler) listIdentityProviders(c *gin.Context) {
@@ -62,7 +62,7 @@ func (h *ociConfigHandler) listIdentityProviders(c *gin.Context) {
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param domainId query string false "身份域 OCID(缺省 Default 域)" // @Param domainId query string false "身份域 OCID(缺省 Default 域)"
// @Param body body createIdpRequest true "请求体" // @Param body body createIdpRequest true "请求体"
// @Success 201 {object} map[string]any // @Success 201 {object} oci.IdentityProviderInfo
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/identity-providers [post] // @Router /api/v1/oci-configs/{id}/identity-providers [post]
func (h *ociConfigHandler) createIdentityProvider(c *gin.Context) { func (h *ociConfigHandler) createIdentityProvider(c *gin.Context) {
@@ -102,7 +102,7 @@ func (h *ociConfigHandler) createIdentityProvider(c *gin.Context) {
// @Param domainId query string false "身份域 OCID(缺省 Default 域)" // @Param domainId query string false "身份域 OCID(缺省 Default 域)"
// @Param idpId path string true "idpId" // @Param idpId path string true "idpId"
// @Param body body object true "请求体(见接口说明)" // @Param body body object true "请求体(见接口说明)"
// @Success 200 {object} map[string]any // @Success 200 {object} oci.IdentityProviderInfo
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/identity-providers/{idpId}/activate [post] // @Router /api/v1/oci-configs/{id}/identity-providers/{idpId}/activate [post]
func (h *ociConfigHandler) activateIdentityProvider(c *gin.Context) { func (h *ociConfigHandler) activateIdentityProvider(c *gin.Context) {
@@ -149,7 +149,7 @@ func (h *ociConfigHandler) deleteIdentityProvider(c *gin.Context) {
// @Tags 租户 IAM // @Tags 租户 IAM
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param domainId query string false "身份域 OCID(缺省 Default 域)" // @Param domainId query string false "身份域 OCID(缺省 Default 域)"
// @Success 200 {object} map[string]any // @Success 200 {file} file "SAML 元数据 XML(附件下载)"
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/saml-metadata [get] // @Router /api/v1/oci-configs/{id}/saml-metadata [get]
func (h *ociConfigHandler) downloadSamlMetadata(c *gin.Context) { func (h *ociConfigHandler) downloadSamlMetadata(c *gin.Context) {
@@ -170,7 +170,7 @@ func (h *ociConfigHandler) downloadSamlMetadata(c *gin.Context) {
// @Tags 租户 IAM // @Tags 租户 IAM
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param domainId query string false "身份域 OCID(缺省 Default 域)" // @Param domainId query string false "身份域 OCID(缺省 Default 域)"
// @Success 200 {object} map[string]any // @Success 200 {array} oci.SignOnRuleInfo
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/sign-on-rules [get] // @Router /api/v1/oci-configs/{id}/sign-on-rules [get]
func (h *ociConfigHandler) listSignOnRules(c *gin.Context) { func (h *ociConfigHandler) listSignOnRules(c *gin.Context) {
@@ -191,7 +191,7 @@ func (h *ociConfigHandler) listSignOnRules(c *gin.Context) {
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param domainId query string false "身份域 OCID(缺省 Default 域)" // @Param domainId query string false "身份域 OCID(缺省 Default 域)"
// @Param body body object true "请求体(见接口说明)" // @Param body body object true "请求体(见接口说明)"
// @Success 201 {object} map[string]any // @Success 201 {object} oci.SignOnRuleInfo
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/sign-on-exemptions [post] // @Router /api/v1/oci-configs/{id}/sign-on-exemptions [post]
func (h *ociConfigHandler) createMfaExemption(c *gin.Context) { func (h *ociConfigHandler) createMfaExemption(c *gin.Context) {
+9 -9
View File
@@ -11,7 +11,7 @@ import (
// @Summary 可用域列表 // @Summary 可用域列表
// @Tags 租户配置 // @Tags 租户配置
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Success 200 {object} map[string]any // @Success 200 {array} string
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/availability-domains [get] // @Router /api/v1/oci-configs/{id}/availability-domains [get]
func (h *ociConfigHandler) availabilityDomains(c *gin.Context) { func (h *ociConfigHandler) availabilityDomains(c *gin.Context) {
@@ -67,7 +67,7 @@ type instanceActionRequest struct {
// @Summary 实例列表 // @Summary 实例列表
// @Tags 计算 // @Tags 计算
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Success 200 {object} map[string]any // @Success 200 {array} oci.Instance
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/instances [get] // @Router /api/v1/oci-configs/{id}/instances [get]
func (h *ociConfigHandler) listInstances(c *gin.Context) { func (h *ociConfigHandler) listInstances(c *gin.Context) {
@@ -87,7 +87,7 @@ func (h *ociConfigHandler) listInstances(c *gin.Context) {
// @Tags 计算 // @Tags 计算
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param body body createInstanceRequest true "请求体" // @Param body body createInstanceRequest true "请求体"
// @Success 201 {object} map[string]any // @Success 201 {object} createInstancesResponse "部分成功仍 201,errors 为逐台失败信息"
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/instances [post] // @Router /api/v1/oci-configs/{id}/instances [post]
func (h *ociConfigHandler) createInstance(c *gin.Context) { func (h *ociConfigHandler) createInstance(c *gin.Context) {
@@ -147,7 +147,7 @@ func (h *ociConfigHandler) createInstance(c *gin.Context) {
// @Tags 计算 // @Tags 计算
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param instanceId path string true "instanceId" // @Param instanceId path string true "instanceId"
// @Success 200 {object} map[string]any // @Success 200 {object} oci.Instance
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/instances/{instanceId} [get] // @Router /api/v1/oci-configs/{id}/instances/{instanceId} [get]
func (h *ociConfigHandler) getInstance(c *gin.Context) { func (h *ociConfigHandler) getInstance(c *gin.Context) {
@@ -168,7 +168,7 @@ func (h *ociConfigHandler) getInstance(c *gin.Context) {
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param instanceId path string true "instanceId" // @Param instanceId path string true "instanceId"
// @Param body body updateInstanceRequest true "请求体" // @Param body body updateInstanceRequest true "请求体"
// @Success 200 {object} map[string]any // @Success 200 {object} oci.Instance
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/instances/{instanceId} [put] // @Router /api/v1/oci-configs/{id}/instances/{instanceId} [put]
func (h *ociConfigHandler) updateInstance(c *gin.Context) { func (h *ociConfigHandler) updateInstance(c *gin.Context) {
@@ -220,7 +220,7 @@ func (h *ociConfigHandler) terminateInstance(c *gin.Context) {
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param instanceId path string true "instanceId" // @Param instanceId path string true "instanceId"
// @Param body body instanceActionRequest true "请求体" // @Param body body instanceActionRequest true "请求体"
// @Success 200 {object} map[string]any // @Success 200 {object} oci.Instance
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/instances/{instanceId}/action [post] // @Router /api/v1/oci-configs/{id}/instances/{instanceId}/action [post]
func (h *ociConfigHandler) instanceAction(c *gin.Context) { func (h *ociConfigHandler) instanceAction(c *gin.Context) {
@@ -253,7 +253,7 @@ type updateBootVolumeRequest struct {
// @Summary 引导卷列表 // @Summary 引导卷列表
// @Tags 存储 // @Tags 存储
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Success 200 {object} map[string]any // @Success 200 {array} oci.BootVolume
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/boot-volumes [get] // @Router /api/v1/oci-configs/{id}/boot-volumes [get]
func (h *ociConfigHandler) listBootVolumes(c *gin.Context) { func (h *ociConfigHandler) listBootVolumes(c *gin.Context) {
@@ -273,7 +273,7 @@ func (h *ociConfigHandler) listBootVolumes(c *gin.Context) {
// @Tags 存储 // @Tags 存储
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param bootVolumeId path string true "bootVolumeId" // @Param bootVolumeId path string true "bootVolumeId"
// @Success 200 {object} map[string]any // @Success 200 {object} oci.BootVolume
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/boot-volumes/{bootVolumeId} [get] // @Router /api/v1/oci-configs/{id}/boot-volumes/{bootVolumeId} [get]
func (h *ociConfigHandler) getBootVolume(c *gin.Context) { func (h *ociConfigHandler) getBootVolume(c *gin.Context) {
@@ -294,7 +294,7 @@ func (h *ociConfigHandler) getBootVolume(c *gin.Context) {
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param bootVolumeId path string true "bootVolumeId" // @Param bootVolumeId path string true "bootVolumeId"
// @Param body body updateBootVolumeRequest true "请求体" // @Param body body updateBootVolumeRequest true "请求体"
// @Success 200 {object} map[string]any // @Success 200 {object} oci.BootVolume
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/boot-volumes/{bootVolumeId} [put] // @Router /api/v1/oci-configs/{id}/boot-volumes/{bootVolumeId} [put]
func (h *ociConfigHandler) updateBootVolume(c *gin.Context) { func (h *ociConfigHandler) updateBootVolume(c *gin.Context) {
+7 -5
View File
@@ -7,6 +7,8 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
_ "oci-portal/internal/model" // swagger 注解引用
"oci-portal/internal/service" "oci-portal/internal/service"
) )
@@ -20,7 +22,7 @@ type logEventHandler struct {
// @Summary 查询配置的回调地址 // @Summary 查询配置的回调地址
// @Tags 任务与日志回传 // @Tags 任务与日志回传
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Success 200 {object} map[string]any // @Success 200 {object} logWebhookStatusResponse
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/log-webhook [get] // @Router /api/v1/oci-configs/{id}/log-webhook [get]
func (h *logEventHandler) getWebhook(c *gin.Context) { func (h *logEventHandler) getWebhook(c *gin.Context) {
@@ -45,7 +47,7 @@ func (h *logEventHandler) getWebhook(c *gin.Context) {
// @Summary 生成 // @Summary 生成
// @Tags 任务与日志回传 // @Tags 任务与日志回传
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Success 200 {object} map[string]any // @Success 200 {object} service.LogWebhookInfo
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/log-webhook [post] // @Router /api/v1/oci-configs/{id}/log-webhook [post]
func (h *logEventHandler) ensureWebhook(c *gin.Context) { func (h *logEventHandler) ensureWebhook(c *gin.Context) {
@@ -87,7 +89,7 @@ func (h *logEventHandler) revokeWebhook(c *gin.Context) {
// @Tags 任务与日志回传 // @Tags 任务与日志回传
// @Param configId query int false "按配置过滤" // @Param configId query int false "按配置过滤"
// @Param q query string false "关键字" // @Param q query string false "关键字"
// @Success 200 {object} map[string]any "items 与 total" // @Success 200 {object} pagedResponse[model.LogEvent] "items 与 total"
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/log-events [get] // @Router /api/v1/log-events [get]
func (h *logEventHandler) list(c *gin.Context) { func (h *logEventHandler) list(c *gin.Context) {
@@ -111,7 +113,7 @@ func (h *logEventHandler) list(c *gin.Context) {
// @Summary 查询 OCI 侧链路状态与关键事件清单 // @Summary 查询 OCI 侧链路状态与关键事件清单
// @Tags 任务与日志回传 // @Tags 任务与日志回传
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Success 200 {object} map[string]any // @Success 200 {object} service.RelayView
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/log-relay [get] // @Router /api/v1/oci-configs/{id}/log-relay [get]
func (h *logEventHandler) getRelay(c *gin.Context) { func (h *logEventHandler) getRelay(c *gin.Context) {
@@ -132,7 +134,7 @@ func (h *logEventHandler) getRelay(c *gin.Context) {
// @Summary 一键建立回传链路 // @Summary 一键建立回传链路
// @Tags 任务与日志回传 // @Tags 任务与日志回传
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Success 200 {object} map[string]any // @Success 200 {object} service.RelayView
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/log-relay [post] // @Router /api/v1/oci-configs/{id}/log-relay [post]
func (h *logEventHandler) setupRelay(c *gin.Context) { func (h *logEventHandler) setupRelay(c *gin.Context) {
+16 -16
View File
@@ -11,7 +11,7 @@ import (
// @Summary 实例形状列表 // @Summary 实例形状列表
// @Tags 租户配置 // @Tags 租户配置
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Success 200 {object} map[string]any // @Success 200 {array} oci.ComputeShape
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/shapes [get] // @Router /api/v1/oci-configs/{id}/shapes [get]
func (h *ociConfigHandler) shapes(c *gin.Context) { func (h *ociConfigHandler) shapes(c *gin.Context) {
@@ -30,7 +30,7 @@ func (h *ociConfigHandler) shapes(c *gin.Context) {
// @Summary 镜像列表 // @Summary 镜像列表
// @Tags 租户配置 // @Tags 租户配置
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Success 200 {object} map[string]any // @Success 200 {array} oci.Image
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/images [get] // @Router /api/v1/oci-configs/{id}/images [get]
func (h *ociConfigHandler) images(c *gin.Context) { func (h *ociConfigHandler) images(c *gin.Context) {
@@ -54,7 +54,7 @@ func (h *ociConfigHandler) images(c *gin.Context) {
// @Tags 租户配置 // @Tags 租户配置
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param imageId path string true "imageId" // @Param imageId path string true "imageId"
// @Success 200 {object} map[string]any // @Success 200 {object} oci.Image
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/images/{imageId} [get] // @Router /api/v1/oci-configs/{id}/images/{imageId} [get]
func (h *ociConfigHandler) getImage(c *gin.Context) { func (h *ociConfigHandler) getImage(c *gin.Context) {
@@ -89,7 +89,7 @@ type renameRequest struct {
// @Summary VCN 列表 // @Summary VCN 列表
// @Tags 网络 // @Tags 网络
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Success 200 {object} map[string]any // @Success 200 {array} oci.VCN
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/vcns [get] // @Router /api/v1/oci-configs/{id}/vcns [get]
func (h *ociConfigHandler) listVCNs(c *gin.Context) { func (h *ociConfigHandler) listVCNs(c *gin.Context) {
@@ -109,7 +109,7 @@ func (h *ociConfigHandler) listVCNs(c *gin.Context) {
// @Tags 网络 // @Tags 网络
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param body body createVCNRequest true "请求体" // @Param body body createVCNRequest true "请求体"
// @Success 201 {object} map[string]any // @Success 201 {object} oci.VCN
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/vcns [post] // @Router /api/v1/oci-configs/{id}/vcns [post]
func (h *ociConfigHandler) createVCN(c *gin.Context) { func (h *ociConfigHandler) createVCN(c *gin.Context) {
@@ -141,7 +141,7 @@ func (h *ociConfigHandler) createVCN(c *gin.Context) {
// @Tags 网络 // @Tags 网络
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param vcnId path string true "vcnId" // @Param vcnId path string true "vcnId"
// @Success 200 {object} map[string]any // @Success 200 {object} oci.VCN
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/vcns/{vcnId} [get] // @Router /api/v1/oci-configs/{id}/vcns/{vcnId} [get]
func (h *ociConfigHandler) getVCN(c *gin.Context) { func (h *ociConfigHandler) getVCN(c *gin.Context) {
@@ -162,7 +162,7 @@ func (h *ociConfigHandler) getVCN(c *gin.Context) {
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param vcnId path string true "vcnId" // @Param vcnId path string true "vcnId"
// @Param body body renameRequest true "请求体" // @Param body body renameRequest true "请求体"
// @Success 200 {object} map[string]any // @Success 200 {object} oci.VCN
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/vcns/{vcnId} [put] // @Router /api/v1/oci-configs/{id}/vcns/{vcnId} [put]
func (h *ociConfigHandler) updateVCN(c *gin.Context) { func (h *ociConfigHandler) updateVCN(c *gin.Context) {
@@ -211,7 +211,7 @@ type enableIPv6Request struct {
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param vcnId path string true "vcnId" // @Param vcnId path string true "vcnId"
// @Param body body enableIPv6Request true "请求体" // @Param body body enableIPv6Request true "请求体"
// @Success 200 {object} map[string]any // @Success 200 {object} ipv6StepsResponse
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/vcns/{vcnId}/enable-ipv6 [post] // @Router /api/v1/oci-configs/{id}/vcns/{vcnId}/enable-ipv6 [post]
func (h *ociConfigHandler) enableVCNIPv6(c *gin.Context) { func (h *ociConfigHandler) enableVCNIPv6(c *gin.Context) {
@@ -247,7 +247,7 @@ type createSubnetRequest struct {
// @Summary 子网列表 // @Summary 子网列表
// @Tags 网络 // @Tags 网络
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Success 200 {object} map[string]any // @Success 200 {array} oci.Subnet
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/subnets [get] // @Router /api/v1/oci-configs/{id}/subnets [get]
func (h *ociConfigHandler) listSubnets(c *gin.Context) { func (h *ociConfigHandler) listSubnets(c *gin.Context) {
@@ -267,7 +267,7 @@ func (h *ociConfigHandler) listSubnets(c *gin.Context) {
// @Tags 网络 // @Tags 网络
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param body body createSubnetRequest true "请求体" // @Param body body createSubnetRequest true "请求体"
// @Success 201 {object} map[string]any // @Success 201 {object} oci.Subnet
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/subnets [post] // @Router /api/v1/oci-configs/{id}/subnets [post]
func (h *ociConfigHandler) createSubnet(c *gin.Context) { func (h *ociConfigHandler) createSubnet(c *gin.Context) {
@@ -300,7 +300,7 @@ func (h *ociConfigHandler) createSubnet(c *gin.Context) {
// @Tags 网络 // @Tags 网络
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param subnetId path string true "subnetId" // @Param subnetId path string true "subnetId"
// @Success 200 {object} map[string]any // @Success 200 {object} oci.Subnet
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/subnets/{subnetId} [get] // @Router /api/v1/oci-configs/{id}/subnets/{subnetId} [get]
func (h *ociConfigHandler) getSubnet(c *gin.Context) { func (h *ociConfigHandler) getSubnet(c *gin.Context) {
@@ -321,7 +321,7 @@ func (h *ociConfigHandler) getSubnet(c *gin.Context) {
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param subnetId path string true "subnetId" // @Param subnetId path string true "subnetId"
// @Param body body renameRequest true "请求体" // @Param body body renameRequest true "请求体"
// @Success 200 {object} map[string]any // @Success 200 {object} oci.Subnet
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/subnets/{subnetId} [put] // @Router /api/v1/oci-configs/{id}/subnets/{subnetId} [put]
func (h *ociConfigHandler) updateSubnet(c *gin.Context) { func (h *ociConfigHandler) updateSubnet(c *gin.Context) {
@@ -381,7 +381,7 @@ type updateSecurityListRequest struct {
// @Summary 安全列表清单 // @Summary 安全列表清单
// @Tags 网络 // @Tags 网络
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Success 200 {object} map[string]any // @Success 200 {array} oci.SecurityList
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/security-lists [get] // @Router /api/v1/oci-configs/{id}/security-lists [get]
func (h *ociConfigHandler) listSecurityLists(c *gin.Context) { func (h *ociConfigHandler) listSecurityLists(c *gin.Context) {
@@ -401,7 +401,7 @@ func (h *ociConfigHandler) listSecurityLists(c *gin.Context) {
// @Tags 网络 // @Tags 网络
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param body body createSecurityListRequest true "请求体" // @Param body body createSecurityListRequest true "请求体"
// @Success 201 {object} map[string]any // @Success 201 {object} oci.SecurityList
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/security-lists [post] // @Router /api/v1/oci-configs/{id}/security-lists [post]
func (h *ociConfigHandler) createSecurityList(c *gin.Context) { func (h *ociConfigHandler) createSecurityList(c *gin.Context) {
@@ -432,7 +432,7 @@ func (h *ociConfigHandler) createSecurityList(c *gin.Context) {
// @Tags 网络 // @Tags 网络
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param securityListId path string true "securityListId" // @Param securityListId path string true "securityListId"
// @Success 200 {object} map[string]any // @Success 200 {object} oci.SecurityList
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/security-lists/{securityListId} [get] // @Router /api/v1/oci-configs/{id}/security-lists/{securityListId} [get]
func (h *ociConfigHandler) getSecurityList(c *gin.Context) { func (h *ociConfigHandler) getSecurityList(c *gin.Context) {
@@ -453,7 +453,7 @@ func (h *ociConfigHandler) getSecurityList(c *gin.Context) {
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param securityListId path string true "securityListId" // @Param securityListId path string true "securityListId"
// @Param body body updateSecurityListRequest true "请求体" // @Param body body updateSecurityListRequest true "请求体"
// @Success 200 {object} map[string]any // @Success 200 {object} oci.SecurityList
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/security-lists/{securityListId} [put] // @Router /api/v1/oci-configs/{id}/security-lists/{securityListId} [put]
func (h *ociConfigHandler) updateSecurityList(c *gin.Context) { func (h *ociConfigHandler) updateSecurityList(c *gin.Context) {
+10 -8
View File
@@ -9,8 +9,10 @@ import (
"strconv" "strconv"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/oracle/oci-go-sdk/v65/common" "github.com/oracle/oci-go-sdk/v65/common"
"gorm.io/gorm" "gorm.io/gorm"
_ "oci-portal/internal/model" // swagger 注解引用
"oci-portal/internal/oci" "oci-portal/internal/oci"
"oci-portal/internal/service" "oci-portal/internal/service"
@@ -39,7 +41,7 @@ type importRequest struct {
// @Summary 导入租户配置 // @Summary 导入租户配置
// @Tags 租户配置 // @Tags 租户配置
// @Param body body importRequest true "API Key 配置(私钥密文落库)" // @Param body body importRequest true "API Key 配置(私钥密文落库)"
// @Success 201 {object} map[string]any // @Success 201 {object} model.OciConfig
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs [post] // @Router /api/v1/oci-configs [post]
func (h *ociConfigHandler) create(c *gin.Context) { func (h *ociConfigHandler) create(c *gin.Context) {
@@ -71,7 +73,7 @@ func (h *ociConfigHandler) create(c *gin.Context) {
// @Summary 租户配置列表 // @Summary 租户配置列表
// @Tags 租户配置 // @Tags 租户配置
// @Success 200 {object} map[string]any "items" // @Success 200 {array} service.ConfigSummary
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs [get] // @Router /api/v1/oci-configs [get]
func (h *ociConfigHandler) list(c *gin.Context) { func (h *ociConfigHandler) list(c *gin.Context) {
@@ -86,7 +88,7 @@ func (h *ociConfigHandler) list(c *gin.Context) {
// @Summary 租户配置详情 // @Summary 租户配置详情
// @Tags 租户配置 // @Tags 租户配置
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Success 200 {object} map[string]any // @Success 200 {object} model.OciConfig
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id} [get] // @Router /api/v1/oci-configs/{id} [get]
func (h *ociConfigHandler) get(c *gin.Context) { func (h *ociConfigHandler) get(c *gin.Context) {
@@ -105,7 +107,7 @@ func (h *ociConfigHandler) get(c *gin.Context) {
// @Summary 验证配置连通性并刷新画像 // @Summary 验证配置连通性并刷新画像
// @Tags 租户配置 // @Tags 租户配置
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Success 200 {object} map[string]any // @Success 200 {object} configChangesResponse "config 与 changes 字段变更对照"
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/verify [post] // @Router /api/v1/oci-configs/{id}/verify [post]
func (h *ociConfigHandler) verify(c *gin.Context) { func (h *ociConfigHandler) verify(c *gin.Context) {
@@ -139,7 +141,7 @@ type updateConfigRequest struct {
// @Tags 租户配置 // @Tags 租户配置
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param body body object true "可更新字段(别名/分组/代理/多区域开关等)" // @Param body body object true "可更新字段(别名/分组/代理/多区域开关等)"
// @Success 200 {object} map[string]any // @Success 200 {object} configChangesResponse "config 与 changes 字段变更对照"
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id} [put] // @Router /api/v1/oci-configs/{id} [put]
func (h *ociConfigHandler) update(c *gin.Context) { func (h *ociConfigHandler) update(c *gin.Context) {
@@ -194,7 +196,7 @@ func (h *ociConfigHandler) remove(c *gin.Context) {
// @Summary 列出租户下全部 ACTIVE compartment // @Summary 列出租户下全部 ACTIVE compartment
// @Tags 租户配置 // @Tags 租户配置
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Success 200 {object} map[string]any // @Success 200 {array} oci.Compartment
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/compartments [get] // @Router /api/v1/oci-configs/{id}/compartments [get]
func (h *ociConfigHandler) compartments(c *gin.Context) { func (h *ociConfigHandler) compartments(c *gin.Context) {
@@ -216,7 +218,7 @@ func (h *ociConfigHandler) compartments(c *gin.Context) {
// @Summary 返回筛选器用区域列表:未开多区域支持只含默认区域 // @Summary 返回筛选器用区域列表:未开多区域支持只含默认区域
// @Tags 租户配置 // @Tags 租户配置
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Success 200 {object} map[string]any // @Success 200 {array} service.RegionSubscriptionView
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/cached-regions [get] // @Router /api/v1/oci-configs/{id}/cached-regions [get]
func (h *ociConfigHandler) cachedRegions(c *gin.Context) { func (h *ociConfigHandler) cachedRegions(c *gin.Context) {
@@ -237,7 +239,7 @@ func (h *ociConfigHandler) cachedRegions(c *gin.Context) {
// @Summary 返回筛选器用区间列表:未开多区间支持返回空数组 // @Summary 返回筛选器用区间列表:未开多区间支持返回空数组
// @Tags 租户配置 // @Tags 租户配置
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Success 200 {object} map[string]any // @Success 200 {array} oci.Compartment
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/cached-compartments [get] // @Router /api/v1/oci-configs/{id}/cached-compartments [get]
func (h *ociConfigHandler) cachedCompartments(c *gin.Context) { func (h *ociConfigHandler) cachedCompartments(c *gin.Context) {
+3 -1
View File
@@ -4,13 +4,15 @@ import (
"net/http" "net/http"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
_ "oci-portal/internal/service" // swagger 注解引用
) )
// overview 返回总览页聚合数据(本地快照,不发云端请求)。 // overview 返回总览页聚合数据(本地快照,不发云端请求)。
// //
// @Summary 返回总览页聚合数据 // @Summary 返回总览页聚合数据
// @Tags 租户配置 // @Tags 租户配置
// @Success 200 {object} map[string]any // @Success 200 {object} service.Overview
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/overview [get] // @Router /api/v1/overview [get]
func (h *ociConfigHandler) overview(c *gin.Context) { func (h *ociConfigHandler) overview(c *gin.Context) {
+6 -6
View File
@@ -18,7 +18,7 @@ type proxyHandler struct {
// //
// @Summary 代理列表 // @Summary 代理列表
// @Tags 设置 // @Tags 设置
// @Success 200 {object} map[string]any "items" // @Success 200 {object} itemsResponse[service.ProxyView] "items"
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/proxies [get] // @Router /api/v1/proxies [get]
func (h *proxyHandler) list(c *gin.Context) { func (h *proxyHandler) list(c *gin.Context) {
@@ -35,7 +35,7 @@ func (h *proxyHandler) list(c *gin.Context) {
// @Summary 创建代理 // @Summary 创建代理
// @Tags 设置 // @Tags 设置
// @Param body body service.ProxyInput true "代理配置(密码只写不回)" // @Param body body service.ProxyInput true "代理配置(密码只写不回)"
// @Success 201 {object} map[string]any // @Success 201 {object} service.ProxyView
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/proxies [post] // @Router /api/v1/proxies [post]
func (h *proxyHandler) create(c *gin.Context) { func (h *proxyHandler) create(c *gin.Context) {
@@ -58,7 +58,7 @@ func (h *proxyHandler) create(c *gin.Context) {
// @Tags 设置 // @Tags 设置
// @Param id path int true "代理 ID" // @Param id path int true "代理 ID"
// @Param body body service.ProxyInput true "代理配置(密码缺省沿用)" // @Param body body service.ProxyInput true "代理配置(密码缺省沿用)"
// @Success 200 {object} map[string]any // @Success 200 {object} service.ProxyView
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/proxies/{id} [put] // @Router /api/v1/proxies/{id} [put]
func (h *proxyHandler) update(c *gin.Context) { func (h *proxyHandler) update(c *gin.Context) {
@@ -104,7 +104,7 @@ func (h *proxyHandler) remove(c *gin.Context) {
// @Summary 批量导入代理 // @Summary 批量导入代理
// @Tags 设置 // @Tags 设置
// @Param body body object true "请求体(见接口说明)" // @Param body body object true "请求体(见接口说明)"
// @Success 200 {object} map[string]any // @Success 200 {object} service.ImportResult
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/proxies/import [post] // @Router /api/v1/proxies/import [post]
func (h *proxyHandler) importBatch(c *gin.Context) { func (h *proxyHandler) importBatch(c *gin.Context) {
@@ -128,7 +128,7 @@ func (h *proxyHandler) importBatch(c *gin.Context) {
// @Summary 手动重测代理出口地区,同步返回最新视图 // @Summary 手动重测代理出口地区,同步返回最新视图
// @Tags 设置 // @Tags 设置
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Success 200 {object} map[string]any // @Success 200 {object} service.ProxyView
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/proxies/{id}/probe [post] // @Router /api/v1/proxies/{id}/probe [post]
func (h *proxyHandler) probe(c *gin.Context) { func (h *proxyHandler) probe(c *gin.Context) {
@@ -150,7 +150,7 @@ func (h *proxyHandler) probe(c *gin.Context) {
// @Tags 设置 // @Tags 设置
// @Param id path int true "代理 ID" // @Param id path int true "代理 ID"
// @Param body body object true "请求体 {\"ociConfigIds\": [1,2]}" // @Param body body object true "请求体 {\"ociConfigIds\": [1,2]}"
// @Success 200 {object} map[string]any "usedBy" // @Success 200 {object} usedByResponse "usedBy"
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/proxies/{id}/tenants [put] // @Router /api/v1/proxies/{id}/tenants [put]
func (h *proxyHandler) setTenants(c *gin.Context) { func (h *proxyHandler) setTenants(c *gin.Context) {
+6 -4
View File
@@ -6,6 +6,8 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
_ "oci-portal/internal/service" // swagger 注解引用
"oci-portal/internal/oci" "oci-portal/internal/oci"
) )
@@ -13,7 +15,7 @@ import (
// //
// @Summary 返回本地维护的完整区域表 // @Summary 返回本地维护的完整区域表
// @Tags 租户配置 // @Tags 租户配置
// @Success 200 {object} map[string]any // @Success 200 {array} oci.RegionInfo
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/regions [get] // @Router /api/v1/regions [get]
func listRegions(c *gin.Context) { func listRegions(c *gin.Context) {
@@ -28,7 +30,7 @@ func listRegions(c *gin.Context) {
// @Summary 区域订阅列表 // @Summary 区域订阅列表
// @Tags 租户配置 // @Tags 租户配置
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Success 200 {object} map[string]any // @Success 200 {array} service.RegionSubscriptionView
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/region-subscriptions [get] // @Router /api/v1/oci-configs/{id}/region-subscriptions [get]
func (h *ociConfigHandler) regionSubscriptions(c *gin.Context) { func (h *ociConfigHandler) regionSubscriptions(c *gin.Context) {
@@ -52,7 +54,7 @@ type subscribeRegionRequest struct {
// @Tags 租户配置 // @Tags 租户配置
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param body body subscribeRegionRequest true "请求体" // @Param body body subscribeRegionRequest true "请求体"
// @Success 200 {object} map[string]any // @Success 200 {array} service.RegionSubscriptionView
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/region-subscriptions [post] // @Router /api/v1/oci-configs/{id}/region-subscriptions [post]
func (h *ociConfigHandler) subscribeRegion(c *gin.Context) { func (h *ociConfigHandler) subscribeRegion(c *gin.Context) {
@@ -76,7 +78,7 @@ func (h *ociConfigHandler) subscribeRegion(c *gin.Context) {
// @Summary 服务限额查询 // @Summary 服务限额查询
// @Tags 租户配置 // @Tags 租户配置
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Success 200 {object} map[string]any // @Success 200 {array} oci.LimitValue
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/limits [get] // @Router /api/v1/oci-configs/{id}/limits [get]
func (h *ociConfigHandler) limits(c *gin.Context) { func (h *ociConfigHandler) limits(c *gin.Context) {
+8
View File
@@ -15,6 +15,10 @@ func registerAiGateway(r *gin.Engine, aiGateway *service.AiGatewayService) {
ai.POST("/responses", aih.responses) ai.POST("/responses", aih.responses)
ai.POST("/messages", aih.messages) ai.POST("/messages", aih.messages)
ai.POST("/embeddings", aih.embeddings) ai.POST("/embeddings", aih.embeddings)
ai.POST("/audio/speech", aih.audioSpeech)
ai.POST("/tts", aih.tts)
ai.POST("/rerank", aih.rerank)
ai.POST("/moderations", aih.moderations)
ai.GET("/models", aih.listModels) ai.GET("/models", aih.listModels)
} }
@@ -32,7 +36,11 @@ func registerAiAdmin(secured *gin.RouterGroup, aiGateway *service.AiGatewayServi
secured.DELETE("/ai-channels/:id", aiadmin.deleteChannel) secured.DELETE("/ai-channels/:id", aiadmin.deleteChannel)
secured.POST("/ai-channels/:id/probe", aiadmin.probeChannel) secured.POST("/ai-channels/:id/probe", aiadmin.probeChannel)
secured.POST("/ai-channels/:id/sync-models", aiadmin.syncChannelModels) secured.POST("/ai-channels/:id/sync-models", aiadmin.syncChannelModels)
secured.GET("/ai-channels/:id/models", aiadmin.listChannelModels)
secured.POST("/ai-channels/:id/test-model", aiadmin.testChannelModel)
secured.GET("/ai-models", aiadmin.gatewayModels) secured.GET("/ai-models", aiadmin.gatewayModels)
secured.GET("/ai-settings", aiadmin.aiSettings)
secured.PUT("/ai-settings", aiadmin.updateAiSettings)
secured.GET("/ai-blacklist", aiadmin.listBlacklist) secured.GET("/ai-blacklist", aiadmin.listBlacklist)
secured.POST("/ai-blacklist", aiadmin.addBlacklist) secured.POST("/ai-blacklist", aiadmin.addBlacklist)
secured.DELETE("/ai-blacklist/:id", aiadmin.removeBlacklist) secured.DELETE("/ai-blacklist/:id", aiadmin.removeBlacklist)
+1 -1
View File
@@ -12,7 +12,7 @@ func registerAuthPublic(v1 *gin.RouterGroup, auth *service.AuthService, oauth *s
v1.POST("/auth/login", ah.login) v1.POST("/auth/login", ah.login)
// 外部身份登录:provider 列表 / 授权跳转(bind 模式 handler 内校验 JWT)/ 回调 // 外部身份登录:provider 列表 / 授权跳转(bind 模式 handler 内校验 JWT)/ 回调
ax := &authxHandler{auth: auth, oauth: oauth} ax := &authxHandler{auth: auth, oauth: oauth, logs: systemLogs}
v1.GET("/auth/oauth/providers", ax.oauthProviders) v1.GET("/auth/oauth/providers", ax.oauthProviders)
v1.GET("/auth/oauth/:provider/authorize", ax.oauthAuthorize) v1.GET("/auth/oauth/:provider/authorize", ax.oauthAuthorize)
v1.GET("/auth/oauth/:provider/callback", ax.oauthCallback) v1.GET("/auth/oauth/:provider/callback", ax.oauthCallback)
+11 -11
View File
@@ -19,7 +19,7 @@ type settingsHandler struct {
// //
// @Summary 返回脱敏后的 Telegram 配置,绝不回 token 明文 // @Summary 返回脱敏后的 Telegram 配置,绝不回 token 明文
// @Tags 设置 // @Tags 设置
// @Success 200 {object} map[string]any // @Success 200 {object} service.TelegramView
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/settings/telegram [get] // @Router /api/v1/settings/telegram [get]
func (h *settingsHandler) getTelegram(c *gin.Context) { func (h *settingsHandler) getTelegram(c *gin.Context) {
@@ -44,7 +44,7 @@ type updateTelegramRequest struct {
// @Summary 保存配置并返回最新脱敏视图 // @Summary 保存配置并返回最新脱敏视图
// @Tags 设置 // @Tags 设置
// @Param body body updateTelegramRequest true "请求体" // @Param body body updateTelegramRequest true "请求体"
// @Success 200 {object} map[string]any // @Success 200 {object} service.TelegramView
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/settings/telegram [put] // @Router /api/v1/settings/telegram [put]
func (h *settingsHandler) updateTelegram(c *gin.Context) { func (h *settingsHandler) updateTelegram(c *gin.Context) {
@@ -84,7 +84,7 @@ func (h *settingsHandler) testTelegram(c *gin.Context) {
// //
// @Summary 返回全部通知渠道的脱敏视图 // @Summary 返回全部通知渠道的脱敏视图
// @Tags 设置 // @Tags 设置
// @Success 200 {object} map[string]any // @Success 200 {object} itemsResponse[service.NotifyChannelView]
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/settings/notify-channels [get] // @Router /api/v1/settings/notify-channels [get]
func (h *settingsHandler) listNotifyChannels(c *gin.Context) { func (h *settingsHandler) listNotifyChannels(c *gin.Context) {
@@ -119,7 +119,7 @@ type updateNotifyChannelRequest struct {
// @Tags 设置 // @Tags 设置
// @Param type path string true "渠道类型(webhook/ntfy/bark/smtp)" // @Param type path string true "渠道类型(webhook/ntfy/bark/smtp)"
// @Param body body updateNotifyChannelRequest true "请求体" // @Param body body updateNotifyChannelRequest true "请求体"
// @Success 200 {object} map[string]any // @Success 200 {object} itemsResponse[service.NotifyChannelView]
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/settings/notify-channels/{type} [put] // @Router /api/v1/settings/notify-channels/{type} [put]
func (h *settingsHandler) updateNotifyChannel(c *gin.Context) { func (h *settingsHandler) updateNotifyChannel(c *gin.Context) {
@@ -160,7 +160,7 @@ func (h *settingsHandler) testNotifyChannel(c *gin.Context) {
// //
// @Summary 返回全部通知事件开关 // @Summary 返回全部通知事件开关
// @Tags 设置 // @Tags 设置
// @Success 200 {object} map[string]any // @Success 200 {object} service.NotifyEventsView
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/settings/notify-events [get] // @Router /api/v1/settings/notify-events [get]
func (h *settingsHandler) getNotifyEvents(c *gin.Context) { func (h *settingsHandler) getNotifyEvents(c *gin.Context) {
@@ -178,7 +178,7 @@ func (h *settingsHandler) getNotifyEvents(c *gin.Context) {
// @Summary 全量保存五个事件开关并返回最新值 // @Summary 全量保存五个事件开关并返回最新值
// @Tags 设置 // @Tags 设置
// @Param body body service.NotifyEventsView true "请求体" // @Param body body service.NotifyEventsView true "请求体"
// @Success 200 {object} map[string]any // @Success 200 {object} service.NotifyEventsView
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/settings/notify-events [put] // @Router /api/v1/settings/notify-events [put]
func (h *settingsHandler) updateNotifyEvents(c *gin.Context) { func (h *settingsHandler) updateNotifyEvents(c *gin.Context) {
@@ -198,7 +198,7 @@ func (h *settingsHandler) updateNotifyEvents(c *gin.Context) {
// //
// @Summary 返回全部通知模板 // @Summary 返回全部通知模板
// @Tags 设置 // @Tags 设置
// @Success 200 {object} map[string]any // @Success 200 {object} itemsResponse[service.NotifyTemplateView]
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/settings/notify-templates [get] // @Router /api/v1/settings/notify-templates [get]
func (h *settingsHandler) listNotifyTemplates(c *gin.Context) { func (h *settingsHandler) listNotifyTemplates(c *gin.Context) {
@@ -263,7 +263,7 @@ func (h *settingsHandler) testNotifyTemplate(c *gin.Context) {
// //
// @Summary 返回任务行为设置 // @Summary 返回任务行为设置
// @Tags 设置 // @Tags 设置
// @Success 200 {object} map[string]any // @Success 200 {object} service.TaskSettingsView
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/settings/task [get] // @Router /api/v1/settings/task [get]
func (h *settingsHandler) getTaskSettings(c *gin.Context) { func (h *settingsHandler) getTaskSettings(c *gin.Context) {
@@ -280,7 +280,7 @@ func (h *settingsHandler) getTaskSettings(c *gin.Context) {
// @Summary 保存任务行为设置并返回最新值 // @Summary 保存任务行为设置并返回最新值
// @Tags 设置 // @Tags 设置
// @Param body body service.TaskSettingsView true "请求体" // @Param body body service.TaskSettingsView true "请求体"
// @Success 200 {object} map[string]any // @Success 200 {object} service.TaskSettingsView
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/settings/task [put] // @Router /api/v1/settings/task [put]
func (h *settingsHandler) updateTaskSettings(c *gin.Context) { func (h *settingsHandler) updateTaskSettings(c *gin.Context) {
@@ -304,7 +304,7 @@ func (h *settingsHandler) updateTaskSettings(c *gin.Context) {
// //
// @Summary 返回安全设置 // @Summary 返回安全设置
// @Tags 设置 // @Tags 设置
// @Success 200 {object} map[string]any // @Success 200 {object} service.SecuritySettings
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/settings/security [get] // @Router /api/v1/settings/security [get]
func (h *settingsHandler) getSecurity(c *gin.Context) { func (h *settingsHandler) getSecurity(c *gin.Context) {
@@ -321,7 +321,7 @@ func (h *settingsHandler) getSecurity(c *gin.Context) {
// @Summary 保存安全设置并返回最新值 // @Summary 保存安全设置并返回最新值
// @Tags 设置 // @Tags 设置
// @Param body body service.SecuritySettings true "请求体" // @Param body body service.SecuritySettings true "请求体"
// @Success 200 {object} map[string]any // @Success 200 {object} service.SecuritySettings
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/settings/security [put] // @Router /api/v1/settings/security [put]
func (h *settingsHandler) updateSecurity(c *gin.Context) { func (h *settingsHandler) updateSecurity(c *gin.Context) {
+5 -3
View File
@@ -4,12 +4,14 @@ import (
"net/http" "net/http"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
_ "oci-portal/internal/oci" // swagger 注解引用
) )
// @Summary 订阅列表 // @Summary 订阅列表
// @Tags 租户配置 // @Tags 租户配置
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Success 200 {object} map[string]any // @Success 200 {array} oci.SubscriptionInfo
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/subscriptions [get] // @Router /api/v1/oci-configs/{id}/subscriptions [get]
func (h *ociConfigHandler) subscriptions(c *gin.Context) { func (h *ociConfigHandler) subscriptions(c *gin.Context) {
@@ -29,7 +31,7 @@ func (h *ociConfigHandler) subscriptions(c *gin.Context) {
// @Tags 租户配置 // @Tags 租户配置
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param subscriptionId path string true "subscriptionId" // @Param subscriptionId path string true "subscriptionId"
// @Success 200 {object} map[string]any // @Success 200 {object} oci.SubscriptionDetail
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/subscriptions/{subscriptionId} [get] // @Router /api/v1/oci-configs/{id}/subscriptions/{subscriptionId} [get]
func (h *ociConfigHandler) subscriptionDetail(c *gin.Context) { func (h *ociConfigHandler) subscriptionDetail(c *gin.Context) {
@@ -48,7 +50,7 @@ func (h *ociConfigHandler) subscriptionDetail(c *gin.Context) {
// @Summary 限额服务列表 // @Summary 限额服务列表
// @Tags 租户配置 // @Tags 租户配置
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Success 200 {object} map[string]any // @Success 200 {array} oci.LimitService
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/limits/services [get] // @Router /api/v1/oci-configs/{id}/limits/services [get]
func (h *ociConfigHandler) limitServices(c *gin.Context) { func (h *ociConfigHandler) limitServices(c *gin.Context) {
+176
View File
@@ -0,0 +1,176 @@
package api
import (
"encoding/json"
"time"
"oci-portal/internal/model"
"oci-portal/internal/oci"
"oci-portal/internal/service"
)
// 本文件的类型仅供 swagger 文档渲染(@Success/@Failure 注解引用),
// 运行时代码不使用;字段与各 handler 返回的 gin.H 外壳保持一致。
// errorResponse 是统一错误响应外壳。
type errorResponse struct {
Error string `json:"error"`
}
// itemsResponse 是 {"items": [...]} 列表外壳。
type itemsResponse[T any] struct {
Items []T `json:"items"`
}
// pagedResponse 是 {"items": [...], "total": n} 分页外壳。
type pagedResponse[T any] struct {
Items []T `json:"items"`
Total int64 `json:"total"`
}
// itemResponse 是 {"item": {...}} 单项外壳。
type itemResponse[T any] struct {
Item T `json:"item"`
}
// triggerResponse 是任务触发受理响应。
type triggerResponse struct {
Triggered bool `json:"triggered"`
}
// tokenResponse 是登录 / 换发令牌响应。
type tokenResponse struct {
Token string `json:"token"`
ExpiresAt time.Time `json:"expiresAt"`
}
// totpRequiredResponse 是密码通过但需两步验证码的 428 响应。
type totpRequiredResponse struct {
Error string `json:"error"`
TotpRequired bool `json:"totpRequired"`
}
// enabledResponse 是布尔开关查询响应。
type enabledResponse struct {
Enabled bool `json:"enabled"`
}
// totpSetupResponse 是 TOTP 初始化响应。
type totpSetupResponse struct {
Secret string `json:"secret"`
OtpauthUri string `json:"otpauthUri"`
}
// credentialsResponse 是当前登录账号信息。
type credentialsResponse struct {
Username string `json:"username"`
PasswordLoginDisabled bool `json:"passwordLoginDisabled"`
}
// oauthProvidersResponse 是外部登录 provider 列表。
type oauthProvidersResponse struct {
Providers []service.ProviderInfo `json:"providers"`
PasswordLoginDisabled bool `json:"passwordLoginDisabled"`
}
// urlResponse 是跳转地址响应。
type urlResponse struct {
URL string `json:"url"`
}
// aboutResponse 是「设置 · 关于」页构建与运行信息。
type aboutResponse struct {
Version string `json:"version"`
BuildTime string `json:"buildTime"`
GoVersion string `json:"goVersion"`
Platform string `json:"platform"`
StartedAt string `json:"startedAt"`
UptimeSeconds int64 `json:"uptimeSeconds"`
Resources aboutResources `json:"resources"`
}
// aboutResources 是进程资源占用快照。
type aboutResources struct {
CpuAvgPercent float64 `json:"cpuAvgPercent"`
NumCpu int `json:"numCpu"`
Goroutines int `json:"goroutines"`
MemHeapBytes uint64 `json:"memHeapBytes"`
MemSysBytes uint64 `json:"memSysBytes"`
DbEngine string `json:"dbEngine"`
DbBytes int64 `json:"dbBytes"`
}
// publicIpResponse 是换绑公网 IP 结果。
type publicIpResponse struct {
PublicIp string `json:"publicIp"`
}
// ipv6AddressResponse 是实例新增 IPv6 结果。
type ipv6AddressResponse struct {
Ipv6Address string `json:"ipv6Address"`
}
// addressResponse 是 VNIC 新增 IPv6 结果。
type addressResponse struct {
Address string `json:"address"`
}
// ipv6StepsResponse 是 VCN 开启 IPv6 的分步结果。
type ipv6StepsResponse struct {
Steps []oci.IPv6Step `json:"steps"`
}
// configChangesResponse 是租户配置校验 / 更新结果(config 与字段变更对照)。
type configChangesResponse struct {
Config *model.OciConfig `json:"config"`
Changes service.Changes `json:"changes"`
}
// aiKeyCreateResponse 是 AI 密钥创建结果;key 为明文,仅本次返回。
type aiKeyCreateResponse struct {
Key string `json:"key"`
Item model.AiKey `json:"item"`
}
// usedByResponse 是代理关联租户结果(关联数)。
type usedByResponse struct {
UsedBy int64 `json:"usedBy"`
}
// rawDetailResponse 是审计事件原文响应。
type rawDetailResponse struct {
Raw json.RawMessage `json:"raw"`
}
// passwordResponse 是租户用户重置密码结果(一次性明文)。
type passwordResponse struct {
Password string `json:"password"`
}
// deletedTotpResponse 是清除 MFA 设备结果。
type deletedTotpResponse struct {
DeletedTotpDevices int `json:"deletedTotpDevices"`
}
// deletedApiKeysResponse 是清理用户 API Key 结果。
type deletedApiKeysResponse struct {
DeletedApiKeys int `json:"deletedApiKeys"`
}
// createInstancesResponse 是批量创建实例结果;部分成功仍 201,errors 为逐台失败信息。
type createInstancesResponse struct {
Instances []oci.Instance `json:"instances"`
Errors []string `json:"errors"`
}
// logWebhookStatusResponse 是日志回传 webhook 状态。
type logWebhookStatusResponse struct {
Exists bool `json:"exists"`
Webhook *service.LogWebhookInfo `json:"webhook,omitempty"`
}
// webConsoleSessionResponse 是网页控制台会话创建结果。
type webConsoleSessionResponse struct {
SessionId string `json:"sessionId"`
Type string `json:"type"`
}
+2 -1
View File
@@ -6,6 +6,7 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
_ "oci-portal/internal/model" // swagger 注解引用
"oci-portal/internal/service" "oci-portal/internal/service"
) )
@@ -18,7 +19,7 @@ type systemLogHandler struct {
// //
// @Summary 系统操作日志列表 // @Summary 系统操作日志列表
// @Tags 设置 // @Tags 设置
// @Success 200 {object} map[string]any "items 与 total" // @Success 200 {object} pagedResponse[model.SystemLog] "items 与 total"
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/system-logs [get] // @Router /api/v1/system-logs [get]
func (h *systemLogHandler) list(c *gin.Context) { func (h *systemLogHandler) list(c *gin.Context) {
+8 -7
View File
@@ -8,6 +8,7 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
_ "oci-portal/internal/model" // swagger 注解引用
"oci-portal/internal/service" "oci-portal/internal/service"
) )
@@ -33,7 +34,7 @@ type updateTaskRequest struct {
// @Summary 创建任务 // @Summary 创建任务
// @Tags 任务与日志回传 // @Tags 任务与日志回传
// @Param body body createTaskRequest true "任务定义(类型/cron/payload)" // @Param body body createTaskRequest true "任务定义(类型/cron/payload)"
// @Success 201 {object} map[string]any // @Success 201 {object} model.Task
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/tasks [post] // @Router /api/v1/tasks [post]
func (h *taskHandler) create(c *gin.Context) { func (h *taskHandler) create(c *gin.Context) {
@@ -57,7 +58,7 @@ func (h *taskHandler) create(c *gin.Context) {
// @Summary 任务列表 // @Summary 任务列表
// @Tags 任务与日志回传 // @Tags 任务与日志回传
// @Success 200 {array} map[string]any // @Success 200 {array} model.Task
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/tasks [get] // @Router /api/v1/tasks [get]
func (h *taskHandler) list(c *gin.Context) { func (h *taskHandler) list(c *gin.Context) {
@@ -72,7 +73,7 @@ func (h *taskHandler) list(c *gin.Context) {
// @Summary 任务详情 // @Summary 任务详情
// @Tags 任务与日志回传 // @Tags 任务与日志回传
// @Param id path int true "任务 ID" // @Param id path int true "任务 ID"
// @Success 200 {object} map[string]any // @Success 200 {object} model.Task
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/tasks/{id} [get] // @Router /api/v1/tasks/{id} [get]
func (h *taskHandler) get(c *gin.Context) { func (h *taskHandler) get(c *gin.Context) {
@@ -92,7 +93,7 @@ func (h *taskHandler) get(c *gin.Context) {
// @Tags 任务与日志回传 // @Tags 任务与日志回传
// @Param id path int true "任务 ID" // @Param id path int true "任务 ID"
// @Param body body updateTaskRequest true "可更新字段" // @Param body body updateTaskRequest true "可更新字段"
// @Success 200 {object} map[string]any // @Success 200 {object} model.Task
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/tasks/{id} [put] // @Router /api/v1/tasks/{id} [put]
func (h *taskHandler) update(c *gin.Context) { func (h *taskHandler) update(c *gin.Context) {
@@ -139,7 +140,7 @@ func (h *taskHandler) remove(c *gin.Context) {
// @Summary 任务执行日志 // @Summary 任务执行日志
// @Tags 任务与日志回传 // @Tags 任务与日志回传
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Success 200 {object} map[string]any // @Success 200 {array} model.TaskLog
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/tasks/{id}/logs [get] // @Router /api/v1/tasks/{id}/logs [get]
func (h *taskHandler) logs(c *gin.Context) { func (h *taskHandler) logs(c *gin.Context) {
@@ -159,8 +160,8 @@ func (h *taskHandler) logs(c *gin.Context) {
// @Summary 立即执行任务(异步触发,结果经任务日志轮询获取) // @Summary 立即执行任务(异步触发,结果经任务日志轮询获取)
// @Tags 任务与日志回传 // @Tags 任务与日志回传
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Success 202 {object} map[string]any // @Success 202 {object} triggerResponse
// @Failure 409 {object} map[string]any "任务正在执行中" // @Failure 409 {object} errorResponse "任务正在执行中"
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/tasks/{id}/run [post] // @Router /api/v1/tasks/{id}/run [post]
func (h *taskHandler) run(c *gin.Context) { func (h *taskHandler) run(c *gin.Context) {
+18 -18
View File
@@ -18,7 +18,7 @@ import (
// @Tags 计算 // @Tags 计算
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param instanceId path string true "instanceId" // @Param instanceId path string true "instanceId"
// @Success 200 {object} map[string]any // @Success 200 {object} oci.InstanceTraffic
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/instances/{instanceId}/traffic [get] // @Router /api/v1/oci-configs/{id}/instances/{instanceId}/traffic [get]
func (h *ociConfigHandler) instanceTraffic(c *gin.Context) { func (h *ociConfigHandler) instanceTraffic(c *gin.Context) {
@@ -38,7 +38,7 @@ func (h *ociConfigHandler) instanceTraffic(c *gin.Context) {
// @Summary 配置成本快照 // @Summary 配置成本快照
// @Tags 成本 // @Tags 成本
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Success 200 {object} map[string]any // @Success 200 {array} oci.CostItem
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/costs [get] // @Router /api/v1/oci-configs/{id}/costs [get]
func (h *ociConfigHandler) costs(c *gin.Context) { func (h *ociConfigHandler) costs(c *gin.Context) {
@@ -75,7 +75,7 @@ func (h *ociConfigHandler) costs(c *gin.Context) {
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param cursor query string false "续查游标(上次响应原样带回)" // @Param cursor query string false "续查游标(上次响应原样带回)"
// @Param limit query int false "单批目标条数,缺省 100,上限 200" // @Param limit query int false "单批目标条数,缺省 100,上限 200"
// @Success 200 {object} map[string]any // @Success 200 {object} service.AuditEventsView
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/audit-events [get] // @Router /api/v1/oci-configs/{id}/audit-events [get]
func (h *ociConfigHandler) getAuditEvents(c *gin.Context) { func (h *ociConfigHandler) getAuditEvents(c *gin.Context) {
@@ -103,7 +103,7 @@ func (h *ociConfigHandler) getAuditEvents(c *gin.Context) {
// @Summary 按 eventId 取回原始事件 JSON:缓存命中秒开, // @Summary 按 eventId 取回原始事件 JSON:缓存命中秒开,
// @Tags 租户 IAM // @Tags 租户 IAM
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Success 200 {object} map[string]any // @Success 200 {object} rawDetailResponse "raw 为事件原文 JSON"
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/audit-events/detail [get] // @Router /api/v1/oci-configs/{id}/audit-events/detail [get]
func (h *ociConfigHandler) getAuditEventDetail(c *gin.Context) { func (h *ociConfigHandler) getAuditEventDetail(c *gin.Context) {
@@ -145,7 +145,7 @@ type createTenantUserRequest struct {
// @Summary 租户身份域列表 // @Summary 租户身份域列表
// @Tags 租户 IAM // @Tags 租户 IAM
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Success 200 {object} map[string]any // @Success 200 {array} oci.IdentityDomain
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/domains [get] // @Router /api/v1/oci-configs/{id}/domains [get]
func (h *ociConfigHandler) listIdentityDomains(c *gin.Context) { func (h *ociConfigHandler) listIdentityDomains(c *gin.Context) {
@@ -165,7 +165,7 @@ func (h *ociConfigHandler) listIdentityDomains(c *gin.Context) {
// @Tags 租户 IAM // @Tags 租户 IAM
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param domainId query string false "身份域 OCID(缺省 Default 域)" // @Param domainId query string false "身份域 OCID(缺省 Default 域)"
// @Success 200 {object} map[string]any // @Success 200 {array} oci.TenantUser
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/users [get] // @Router /api/v1/oci-configs/{id}/users [get]
func (h *ociConfigHandler) listTenantUsers(c *gin.Context) { func (h *ociConfigHandler) listTenantUsers(c *gin.Context) {
@@ -186,7 +186,7 @@ func (h *ociConfigHandler) listTenantUsers(c *gin.Context) {
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param domainId query string false "身份域 OCID(缺省 Default 域)" // @Param domainId query string false "身份域 OCID(缺省 Default 域)"
// @Param userId path string true "userId" // @Param userId path string true "userId"
// @Success 200 {object} map[string]any // @Success 200 {object} oci.TenantUserDetail
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/users/{userId} [get] // @Router /api/v1/oci-configs/{id}/users/{userId} [get]
func (h *ociConfigHandler) getTenantUserDetail(c *gin.Context) { func (h *ociConfigHandler) getTenantUserDetail(c *gin.Context) {
@@ -207,7 +207,7 @@ func (h *ociConfigHandler) getTenantUserDetail(c *gin.Context) {
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param domainId query string false "身份域 OCID(缺省 Default 域)" // @Param domainId query string false "身份域 OCID(缺省 Default 域)"
// @Param body body createTenantUserRequest true "请求体" // @Param body body createTenantUserRequest true "请求体"
// @Success 201 {object} map[string]any // @Success 201 {object} oci.TenantUser
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/users [post] // @Router /api/v1/oci-configs/{id}/users [post]
func (h *ociConfigHandler) createTenantUser(c *gin.Context) { func (h *ociConfigHandler) createTenantUser(c *gin.Context) {
@@ -253,7 +253,7 @@ type updateTenantUserRequest struct {
// @Param domainId query string false "身份域 OCID(缺省 Default 域)" // @Param domainId query string false "身份域 OCID(缺省 Default 域)"
// @Param userId path string true "userId" // @Param userId path string true "userId"
// @Param body body updateTenantUserRequest true "请求体" // @Param body body updateTenantUserRequest true "请求体"
// @Success 200 {object} map[string]any // @Success 200 {object} oci.TenantUser
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/users/{userId} [put] // @Router /api/v1/oci-configs/{id}/users/{userId} [put]
func (h *ociConfigHandler) updateTenantUser(c *gin.Context) { func (h *ociConfigHandler) updateTenantUser(c *gin.Context) {
@@ -306,7 +306,7 @@ func (h *ociConfigHandler) deleteTenantUser(c *gin.Context) {
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param domainId query string false "身份域 OCID(缺省 Default 域)" // @Param domainId query string false "身份域 OCID(缺省 Default 域)"
// @Param userId path string true "userId" // @Param userId path string true "userId"
// @Success 200 {object} map[string]any // @Success 200 {object} passwordResponse "一次性明文密码"
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/users/{userId}/reset-password [post] // @Router /api/v1/oci-configs/{id}/users/{userId}/reset-password [post]
func (h *ociConfigHandler) resetTenantUserPassword(c *gin.Context) { func (h *ociConfigHandler) resetTenantUserPassword(c *gin.Context) {
@@ -327,7 +327,7 @@ func (h *ociConfigHandler) resetTenantUserPassword(c *gin.Context) {
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param domainId query string false "身份域 OCID(缺省 Default 域)" // @Param domainId query string false "身份域 OCID(缺省 Default 域)"
// @Param userId path string true "userId" // @Param userId path string true "userId"
// @Success 200 {object} map[string]any // @Success 200 {object} deletedTotpResponse
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/users/{userId}/mfa-devices [delete] // @Router /api/v1/oci-configs/{id}/users/{userId}/mfa-devices [delete]
func (h *ociConfigHandler) deleteTenantUserMfa(c *gin.Context) { func (h *ociConfigHandler) deleteTenantUserMfa(c *gin.Context) {
@@ -347,7 +347,7 @@ func (h *ociConfigHandler) deleteTenantUserMfa(c *gin.Context) {
// @Tags 租户 IAM // @Tags 租户 IAM
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param userId path string true "userId" // @Param userId path string true "userId"
// @Success 200 {object} map[string]any // @Success 200 {object} deletedApiKeysResponse
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/users/{userId}/api-keys [delete] // @Router /api/v1/oci-configs/{id}/users/{userId}/api-keys [delete]
func (h *ociConfigHandler) deleteTenantUserApiKeys(c *gin.Context) { func (h *ociConfigHandler) deleteTenantUserApiKeys(c *gin.Context) {
@@ -370,7 +370,7 @@ func (h *ociConfigHandler) deleteTenantUserApiKeys(c *gin.Context) {
// @Tags 租户 IAM // @Tags 租户 IAM
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param domainId query string false "身份域 OCID(缺省 Default 域)" // @Param domainId query string false "身份域 OCID(缺省 Default 域)"
// @Success 200 {object} map[string]any // @Success 200 {object} oci.NotificationRecipients
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/notification-recipients [get] // @Router /api/v1/oci-configs/{id}/notification-recipients [get]
func (h *ociConfigHandler) getNotificationRecipients(c *gin.Context) { func (h *ociConfigHandler) getNotificationRecipients(c *gin.Context) {
@@ -391,7 +391,7 @@ func (h *ociConfigHandler) getNotificationRecipients(c *gin.Context) {
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param domainId query string false "身份域 OCID(缺省 Default 域)" // @Param domainId query string false "身份域 OCID(缺省 Default 域)"
// @Param body body object true "请求体(见接口说明)" // @Param body body object true "请求体(见接口说明)"
// @Success 200 {object} map[string]any // @Success 200 {object} oci.NotificationRecipients
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/notification-recipients [put] // @Router /api/v1/oci-configs/{id}/notification-recipients [put]
func (h *ociConfigHandler) updateNotificationRecipients(c *gin.Context) { func (h *ociConfigHandler) updateNotificationRecipients(c *gin.Context) {
@@ -418,7 +418,7 @@ func (h *ociConfigHandler) updateNotificationRecipients(c *gin.Context) {
// @Tags 租户 IAM // @Tags 租户 IAM
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param domainId query string false "身份域 OCID(缺省 Default 域)" // @Param domainId query string false "身份域 OCID(缺省 Default 域)"
// @Success 200 {object} map[string]any // @Success 200 {array} oci.PasswordPolicyInfo
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/password-policies [get] // @Router /api/v1/oci-configs/{id}/password-policies [get]
func (h *ociConfigHandler) listPasswordPolicies(c *gin.Context) { func (h *ociConfigHandler) listPasswordPolicies(c *gin.Context) {
@@ -440,7 +440,7 @@ func (h *ociConfigHandler) listPasswordPolicies(c *gin.Context) {
// @Param domainId query string false "身份域 OCID(缺省 Default 域)" // @Param domainId query string false "身份域 OCID(缺省 Default 域)"
// @Param policyId path string true "policyId" // @Param policyId path string true "policyId"
// @Param body body object true "请求体(见接口说明)" // @Param body body object true "请求体(见接口说明)"
// @Success 200 {object} map[string]any // @Success 200 {object} oci.PasswordPolicyInfo
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/password-policies/{policyId} [put] // @Router /api/v1/oci-configs/{id}/password-policies/{policyId} [put]
func (h *ociConfigHandler) updatePasswordPolicy(c *gin.Context) { func (h *ociConfigHandler) updatePasswordPolicy(c *gin.Context) {
@@ -473,7 +473,7 @@ func (h *ociConfigHandler) updatePasswordPolicy(c *gin.Context) {
// @Tags 租户 IAM // @Tags 租户 IAM
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param domainId query string false "身份域 OCID(缺省 Default 域)" // @Param domainId query string false "身份域 OCID(缺省 Default 域)"
// @Success 200 {object} map[string]any // @Success 200 {object} oci.IdentitySettingInfo
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/identity-settings [get] // @Router /api/v1/oci-configs/{id}/identity-settings [get]
func (h *ociConfigHandler) getIdentitySetting(c *gin.Context) { func (h *ociConfigHandler) getIdentitySetting(c *gin.Context) {
@@ -494,7 +494,7 @@ func (h *ociConfigHandler) getIdentitySetting(c *gin.Context) {
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param domainId query string false "身份域 OCID(缺省 Default 域)" // @Param domainId query string false "身份域 OCID(缺省 Default 域)"
// @Param body body object true "请求体(见接口说明)" // @Param body body object true "请求体(见接口说明)"
// @Success 200 {object} map[string]any // @Success 200 {object} oci.IdentitySettingInfo
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/identity-settings [put] // @Router /api/v1/oci-configs/{id}/identity-settings [put]
func (h *ociConfigHandler) updateIdentitySetting(c *gin.Context) { func (h *ociConfigHandler) updateIdentitySetting(c *gin.Context) {
+1 -1
View File
@@ -29,7 +29,7 @@ type createConsoleSessionRequest struct {
// @Param id path int true "配置 ID" // @Param id path int true "配置 ID"
// @Param instanceId path string true "实例 OCID" // @Param instanceId path string true "实例 OCID"
// @Param body body object true "{type: serial|vnc}" // @Param body body object true "{type: serial|vnc}"
// @Success 200 {object} map[string]any "sessionId 与 wsPath" // @Success 201 {object} webConsoleSessionResponse "sessionId 与 type"
// @Security BearerAuth // @Security BearerAuth
// @Router /api/v1/oci-configs/{id}/instances/{instanceId}/console-sessions [post] // @Router /api/v1/oci-configs/{id}/instances/{instanceId}/console-sessions [post]
func (h *consoleHandler) create(c *gin.Context) { func (h *consoleHandler) create(c *gin.Context) {
+1 -1
View File
@@ -53,7 +53,7 @@ type webhookHandler struct {
// @Param secret path string true "面板生成的回传密钥(鉴权凭据)" // @Param secret path string true "面板生成的回传密钥(鉴权凭据)"
// @Param body body object true "ONS 消息原文(SubscriptionConfirmation / Notification)" // @Param body body object true "ONS 消息原文(SubscriptionConfirmation / Notification)"
// @Success 200 "已受理" // @Success 200 "已受理"
// @Failure 403 {object} map[string]string "时间戳超窗或证书源非 Oracle 域" // @Failure 403 {object} errorResponse "时间戳超窗或证书源非 Oracle 域"
// @Failure 404 "secret 无效(不暴露端点存在性)" // @Failure 404 "secret 无效(不暴露端点存在性)"
// @Router /api/v1/webhooks/oci-logs/{secret} [post] // @Router /api/v1/webhooks/oci-logs/{secret} [post]
func (h *webhookHandler) handle(c *gin.Context) { func (h *webhookHandler) handle(c *gin.Context) {
+7 -3
View File
@@ -268,12 +268,16 @@ type AiChannel struct {
LastProbeAt *time.Time `json:"lastProbeAt"` LastProbeAt *time.Time `json:"lastProbeAt"`
ProbeStatus string `gorm:"size:16" json:"probeStatus"` // ok / no_service / no_quota / error ProbeStatus string `gorm:"size:16" json:"probeStatus"` // ok / no_service / no_quota / error
ProbeError string `gorm:"size:512" json:"probeError"` ProbeError string `gorm:"size:512" json:"probeError"`
CreatedAt time.Time `json:"createdAt"` // ProbeModel 是用户测试通过后固定的探测验证模型名;探测时置于候选首位
UpdatedAt time.Time `json:"updatedAt"` ProbeModel string `gorm:"size:96" json:"probeModel"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
// ModelCount 是渠道模型缓存计数,列表查询回填,不落库
ModelCount int64 `gorm:"-" json:"modelCount"`
} }
// AiModelCache 是渠道区域的可用模型缓存(整渠道覆盖式同步)。 // AiModelCache 是渠道区域的可用模型缓存(整渠道覆盖式同步)。
// Capability 为 CHAT / EMBEDDING;存量空串视为 CHAT(加列前只同步对话模型)。 // Capability 为 CHAT / EMBEDDING / RERANK / TTS;存量空串视为 CHAT(加列前只同步对话模型)。
type AiModelCache struct { type AiModelCache struct {
ID uint `gorm:"primaryKey" json:"-"` ID uint `gorm:"primaryKey" json:"-"`
ChannelID uint `gorm:"index" json:"channelId"` ChannelID uint `gorm:"index" json:"channelId"`
+6
View File
@@ -106,6 +106,12 @@ type Client interface {
GenAiCompatResponses(ctx context.Context, cred Credentials, region string, body []byte) ([]byte, error) GenAiCompatResponses(ctx context.Context, cred Credentials, region string, body []byte) ([]byte, error)
// GenAiCompatResponsesStream 流式直通 /actions/v1/responses,建立成功返回 SSE body。 // GenAiCompatResponsesStream 流式直通 /actions/v1/responses,建立成功返回 SSE body。
GenAiCompatResponsesStream(ctx context.Context, cred Credentials, region string, body []byte) (io.ReadCloser, error) GenAiCompatResponsesStream(ctx context.Context, cred Credentials, region string, body []byte) (io.ReadCloser, error)
// GenAiCompatSpeech 直通 OpenAI Audio Speech 请求体到 /openai/v1/audio/speech,返回音频与 Content-Type。
GenAiCompatSpeech(ctx context.Context, cred Credentials, region string, body []byte) ([]byte, string, error)
// GenAiRerank 文档重排,返回按相关度排序的下标与得分。
GenAiRerank(ctx context.Context, cred Credentials, region, modelOcid, query string, documents []string, topN *int) ([]RerankRank, error)
// GenAiApplyGuardrails 对单条文本执行内容审核 / PII / 提示注入检测。
GenAiApplyGuardrails(ctx context.Context, cred Credentials, region, text string) (*GuardrailsOutcome, error)
// 控制台连接:创建(VNC/串口连接串)、列出、删除。 // 控制台连接:创建(VNC/串口连接串)、列出、删除。
CreateConsoleConnection(ctx context.Context, cred Credentials, region, instanceID, sshPublicKey string) (ConsoleConnection, error) CreateConsoleConnection(ctx context.Context, cred Credentials, region, instanceID, sshPublicKey string) (ConsoleConnection, error)
ListConsoleConnections(ctx context.Context, cred Credentials, region, instanceID string) ([]ConsoleConnection, error) ListConsoleConnections(ctx context.Context, cred Credentials, region, instanceID string) ([]ConsoleConnection, error)
+9 -3
View File
@@ -131,6 +131,11 @@ func modelCapability(m generativeai.ModelSummary) string {
return "CHAT" return "CHAT"
case generativeai.ModelCapabilityTextEmbeddings: case generativeai.ModelCapabilityTextEmbeddings:
capability = "EMBEDDING" capability = "EMBEDDING"
case generativeai.ModelCapabilityTextRerank:
capability = "RERANK"
case generativeai.ModelCapabilityEnum("TEXT_TO_AUDIO"):
// SDK v65.120 尚无该枚举常量,按原始字符串匹配(xai.grok-tts)
capability = "TTS"
} }
} }
return capability return capability
@@ -144,11 +149,12 @@ func capStrings(caps []generativeai.ModelCapabilityEnum) []string {
return out return out
} }
// GenAiProbeChat 实现 Client:经 OpenAI 兼容面(直通同链路)发一次极小请求探测渠道;配额探测专用的最小聊天(maxTokens=1),返回 HTTP 状态码; // GenAiProbeChat 实现 Client:经 OpenAI 兼容面(直通同链路)发一次极小请求探测渠道;
// modelName 决定请求格式(cohere.* 走 COHERE)。 // 配额探测专用的最小聊天,返回 HTTP 状态码。max_output_tokens 取 16:
// openai.gpt-oss 系列要求 >=16,其余模型均兼容,成本差异可忽略。
func (c *RealClient) GenAiProbeChat(ctx context.Context, cred Credentials, region, modelOcid, modelName string) (int, error) { func (c *RealClient) GenAiProbeChat(ctx context.Context, cred Credentials, region, modelOcid, modelName string) (int, error) {
body, err := json.Marshal(map[string]any{"model": modelName, "input": "hi", body, err := json.Marshal(map[string]any{"model": modelName, "input": "hi",
"max_output_tokens": 1, "store": false}) "max_output_tokens": 16, "store": false})
if err != nil { if err != nil {
return 0, err return 0, err
} }
+127
View File
@@ -0,0 +1,127 @@
package oci
import (
"context"
"fmt"
"github.com/oracle/oci-go-sdk/v65/common"
"github.com/oracle/oci-go-sdk/v65/generativeaiinference"
)
// RerankRank 是重排结果的一项:index 指向入参 documents 下标。
type RerankRank struct {
Index int
Score float64
}
// GuardrailCategory 是内容审核分类得分(OVERALL / BLOCKLIST)。
type GuardrailCategory struct {
Name string
Score float64
}
// GuardrailPiiHit 是一处 PII 命中(片段原文与位置)。
type GuardrailPiiHit struct {
Text string
Label string
Score float64
Offset int
Length int
}
// GuardrailsOutcome 汇总 ApplyGuardrails 三能力结果。
type GuardrailsOutcome struct {
Categories []GuardrailCategory
Pii []GuardrailPiiHit
PromptInjectionScore *float64
}
// GenAiRerank 实现 Client:文档重排(on-demand serving),返回按相关度排序的下标与得分。
func (c *RealClient) GenAiRerank(ctx context.Context, cred Credentials, region, modelOcid, query string, documents []string, topN *int) ([]RerankRank, error) {
ic, err := c.genAiInferenceClient(cred, region)
if err != nil {
return nil, err
}
resp, err := ic.RerankText(ctx, generativeaiinference.RerankTextRequest{
RerankTextDetails: generativeaiinference.RerankTextDetails{
CompartmentId: &cred.TenancyOCID,
ServingMode: generativeaiinference.OnDemandServingMode{ModelId: &modelOcid},
Input: &query,
Documents: documents,
TopN: topN,
},
})
if err != nil {
return nil, fmt.Errorf("genai rerank: %w", err)
}
ranks := make([]RerankRank, 0, len(resp.DocumentRanks))
for _, r := range resp.DocumentRanks {
if r.Index == nil || r.RelevanceScore == nil {
continue
}
ranks = append(ranks, RerankRank{Index: *r.Index, Score: *r.RelevanceScore})
}
return ranks, nil
}
// GenAiApplyGuardrails 实现 Client:对单条文本执行内容审核 / PII / 提示注入三检测。
func (c *RealClient) GenAiApplyGuardrails(ctx context.Context, cred Credentials, region, text string) (*GuardrailsOutcome, error) {
ic, err := c.genAiInferenceClient(cred, region)
if err != nil {
return nil, err
}
resp, err := ic.ApplyGuardrails(ctx, generativeaiinference.ApplyGuardrailsRequest{
ApplyGuardrailsDetails: generativeaiinference.ApplyGuardrailsDetails{
CompartmentId: &cred.TenancyOCID,
Input: generativeaiinference.GuardrailsTextInput{Content: common.String(text)},
GuardrailConfigs: &generativeaiinference.GuardrailConfigs{
ContentModerationConfig: &generativeaiinference.ContentModerationConfiguration{Categories: []string{"OVERALL"}},
PersonallyIdentifiableInformationConfig: &generativeaiinference.PersonallyIdentifiableInformationConfiguration{Types: []string{}},
PromptInjectionConfig: &generativeaiinference.PromptInjectionConfiguration{},
},
},
})
if err != nil {
return nil, fmt.Errorf("genai guardrails: %w", err)
}
return guardrailsOutcome(resp.Results), nil
}
// guardrailsOutcome 把 SDK 结果换算为 IR;空段置空切片,得分缺失跳过。
func guardrailsOutcome(r *generativeaiinference.GuardrailsResults) *GuardrailsOutcome {
out := &GuardrailsOutcome{}
if r == nil {
return out
}
if r.ContentModeration != nil {
for _, cat := range r.ContentModeration.Categories {
if cat.Name == nil || cat.Score == nil {
continue
}
out.Categories = append(out.Categories, GuardrailCategory{Name: *cat.Name, Score: *cat.Score})
}
}
for _, hit := range r.PersonallyIdentifiableInformation {
h := GuardrailPiiHit{}
if hit.Text != nil {
h.Text = *hit.Text
}
if hit.Label != nil {
h.Label = *hit.Label
}
if hit.Score != nil {
h.Score = *hit.Score
}
if hit.Offset != nil {
h.Offset = *hit.Offset
}
if hit.Length != nil {
h.Length = *hit.Length
}
out.Pii = append(out.Pii, h)
}
if r.PromptInjection != nil && r.PromptInjection.Score != nil {
out.PromptInjectionScore = r.PromptInjection.Score
}
return out
}
+3 -3
View File
@@ -14,9 +14,9 @@ import (
const compatResponsesLimit = int64(8 << 20) const compatResponsesLimit = int64(8 << 20)
// GenAiCompatResponses 实现 Client:把 OpenAI Responses 请求体直通到 OCI // GenAiCompatResponses 实现 Client:把 OpenAI Responses 请求体直通到 OCI
// `/20231130/actions/v1/responses`(IAM 签名)。该端点实测可执行 xAI 服务端工具 // `/20231130/actions/v1/responses`(IAM 签名)。xAI 服务端工具(web_search /
// (web_search / x_search),但不在 Oracle 文档化工具白名单内,行为可能随服务 // x_search / code_interpreter)与 mcp 已被 Oracle 文档正式支持,工具参数与限制
// 版本、模型或区域变化;调用方须自行校验并改写请求体(store/stream)。 // 遵循 xAI 规格;调用方须自行校验并改写请求体(store/stream)。
func (c *RealClient) GenAiCompatResponses(ctx context.Context, cred Credentials, region string, body []byte) ([]byte, error) { func (c *RealClient) GenAiCompatResponses(ctx context.Context, cred Credentials, region string, body []byte) ([]byte, error) {
ic, err := c.genAiInferenceClient(cred, region) ic, err := c.genAiInferenceClient(cred, region)
if err != nil { if err != nil {
+44
View File
@@ -0,0 +1,44 @@
package oci
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"github.com/oracle/oci-go-sdk/v65/common"
)
// compatSpeechLimit 限制 TTS 音频响应体大小(长文本 mp3 给足余量)。
const compatSpeechLimit = int64(64 << 20)
// GenAiCompatSpeech 实现 Client:把 OpenAI Audio Speech 请求体直通到 OCI
// 兼容面 `/openai/v1/audio/speech`(IAM 签名,BasePath 置空——该面与
// /20231130/actions 面并存,实测仅前者承载 TTS)。返回音频字节与 Content-Type。
func (c *RealClient) GenAiCompatSpeech(ctx context.Context, cred Credentials, region string, body []byte) ([]byte, string, error) {
ic, err := c.genAiInferenceClient(cred, region)
if err != nil {
return nil, "", err
}
client := ic.BaseClient
common.UpdateEndpointTemplateForOptions(&client)
common.SetMissingTemplateParams(&client)
client.BasePath = ""
request, err := http.NewRequestWithContext(ctx, http.MethodPost, "/openai/v1/audio/speech", bytes.NewReader(body))
if err != nil {
return nil, "", fmt.Errorf("build compat speech request: %w", err)
}
request.Header.Set("Content-Type", "application/json")
request.Header.Set("opc-compartment-id", cred.TenancyOCID)
response, err := client.Call(ctx, request)
if err != nil {
return nil, "", err
}
defer response.Body.Close()
payload, err := io.ReadAll(io.LimitReader(response.Body, compatSpeechLimit))
if err != nil {
return nil, "", fmt.Errorf("read compat speech body: %w", err)
}
return payload, response.Header.Get("Content-Type"), nil
}
+148 -15
View File
@@ -12,6 +12,7 @@ import (
"sort" "sort"
"strings" "strings"
"sync" "sync"
"sync/atomic"
"time" "time"
"gorm.io/gorm" "gorm.io/gorm"
@@ -58,11 +59,39 @@ type AiGatewayService struct {
lastTouch map[uint]time.Time lastTouch map[uint]time.Time
// onChannelsChanged 在渠道增删后触发,由 main 装配为探测任务同步钩子 // onChannelsChanged 在渠道增删后触发,由 main 装配为探测任务同步钩子
onChannelsChanged func(context.Context) onChannelsChanged func(context.Context)
// filterDeprecated 是「过滤弃用模型」开关(内存镜像,持久化在 settings 表)
filterDeprecated atomic.Bool
} }
// NewAiGatewayService 组装依赖;调用 StartCleanup 后开始调用日志周期清理。 // NewAiGatewayService 组装依赖;调用 StartCleanup 后开始调用日志周期清理。
func NewAiGatewayService(db *gorm.DB, configs *OciConfigService, client oci.Client) *AiGatewayService { func NewAiGatewayService(db *gorm.DB, configs *OciConfigService, client oci.Client) *AiGatewayService {
return &AiGatewayService{db: db, configs: configs, client: client, lastTouch: map[uint]time.Time{}} s := &AiGatewayService{db: db, configs: configs, client: client, lastTouch: map[uint]time.Time{}}
var row model.Setting
if err := db.Where("key = ?", settingAiFilterDeprecated).First(&row).Error; err == nil {
s.filterDeprecated.Store(row.Value == "1")
}
return s
}
// settingAiFilterDeprecated 是「过滤弃用模型」开关的配置键,值 "1"/"0",缺省关闭。
const settingAiFilterDeprecated = "ai_filter_deprecated"
// FilterDeprecated 返回「过滤弃用模型」开关状态。
func (s *AiGatewayService) FilterDeprecated() bool { return s.filterDeprecated.Load() }
// SetFilterDeprecated 持久化并即时生效开关:开启后已宣布弃用
// (deprecated_at 非空,即使未退役)的模型从列表与路由中排除。
func (s *AiGatewayService) SetFilterDeprecated(ctx context.Context, on bool) error {
value := "0"
if on {
value = "1"
}
err := s.db.WithContext(ctx).Save(&model.Setting{Key: settingAiFilterDeprecated, Value: value}).Error
if err != nil {
return fmt.Errorf("保存过滤弃用模型开关: %w", err)
}
s.filterDeprecated.Store(on)
return nil
} }
// SetOnChannelsChanged 注册渠道数量变化钩子(渠道创建/删除成功后调用)。 // SetOnChannelsChanged 注册渠道数量变化钩子(渠道创建/删除成功后调用)。
@@ -239,11 +268,34 @@ func valueOr(p *int, def int) int {
return def return def
} }
// Channels 列出全部渠道。 // Channels 列出全部渠道并回填各自的模型缓存计数
func (s *AiGatewayService) Channels(ctx context.Context) ([]model.AiChannel, error) { func (s *AiGatewayService) Channels(ctx context.Context) ([]model.AiChannel, error) {
var chs []model.AiChannel var chs []model.AiChannel
err := s.db.WithContext(ctx).Order("priority ASC, id ASC").Find(&chs).Error if err := s.db.WithContext(ctx).Order("priority ASC, id ASC").Find(&chs).Error; err != nil {
return chs, err return nil, err
}
var rows []struct {
ChannelID uint
N int64
}
q := s.db.WithContext(ctx).Model(&model.AiModelCache{}).
Select("channel_id, COUNT(*) AS n").
Where("name NOT IN (SELECT name FROM ai_model_blacklists)")
if s.FilterDeprecated() {
q = q.Where("deprecated_at IS NULL")
}
err := q.Group("channel_id").Scan(&rows).Error
if err != nil {
return nil, err
}
counts := make(map[uint]int64, len(rows))
for _, r := range rows {
counts[r.ChannelID] = r.N
}
for i := range chs {
chs[i].ModelCount = counts[chs[i].ID]
}
return chs, nil
} }
// UpdateChannel 修改渠道名称 / 分组 / 启停 / 优先级 / 权重。 // UpdateChannel 修改渠道名称 / 分组 / 启停 / 优先级 / 权重。
@@ -286,7 +338,7 @@ func (s *AiGatewayService) DeleteChannel(ctx context.Context, id uint) error {
// ---- 探测与模型同步 ---- // ---- 探测与模型同步 ----
// ProbeChannel 探测渠道可用性:服务可见性 → 模型同步 → maxTokens=1 配额试调。 // ProbeChannel 探测渠道可用性:服务可见性 → 模型同步 → 极小 max_tokens 配额试调。
func (s *AiGatewayService) ProbeChannel(ctx context.Context, id uint) (*model.AiChannel, error) { func (s *AiGatewayService) ProbeChannel(ctx context.Context, id uint) (*model.AiChannel, error) {
var ch model.AiChannel var ch model.AiChannel
if err := s.db.WithContext(ctx).First(&ch, id).Error; err != nil { if err := s.db.WithContext(ctx).First(&ch, id).Error; err != nil {
@@ -335,13 +387,15 @@ func (s *AiGatewayService) probe(ctx context.Context, cred oci.Credentials, ch *
return s.probeChat(ctx, cred, ch, models) return s.probeChat(ctx, cred, ch, models)
} }
// probeChat 按候选顺序试调(上限 8):遇「模型不可按需调用」(微调基座 400 / 实体 // probeChat 按候选顺序试调(上限 8,已验证的探测模型置首位):遇「模型不可按需
// 不存在 404)换下一个候选,错误信息带模型名供用户加入黑名单;401/403 与鉴权类 404 // 调用」(微调基座 400 / 实体不存在 404)换下一个候选,错误信息带模型名供用户加入
// 属租户级直接定论 no_quota;其余错误(元数据标 CHAT 但实际不可对话等)累计 3 次止损。 // 黑名单;401/403 与鉴权类 404 可能只是模型级无权限,记录后继续换候选,全部候选
// 失败且出现过鉴权拒绝才定论 no_quota;其余错误累计 3 次止损。
func (s *AiGatewayService) probeChat(ctx context.Context, cred oci.Credentials, ch *model.AiChannel, models []oci.GenAiModel) (string, string) { func (s *AiGatewayService) probeChat(ctx context.Context, cred oci.Credentials, ch *model.AiChannel, models []oci.GenAiModel) (string, string) {
status, detail := "error", "无可试调对话模型" status, detail := "error", "无可试调对话模型"
quotaDetail := ""
errBudget := 3 errBudget := 3
for _, m := range probeCandidates(models) { for _, m := range probeCandidates(ch.ProbeModel, models) {
code, err := s.client.GenAiProbeChat(ctx, cred, ch.Region, m.Ocid, m.Name) code, err := s.client.GenAiProbeChat(ctx, cred, ch.Region, m.Ocid, m.Name)
switch { switch {
case code == 200 || code == 429: case code == 200 || code == 429:
@@ -349,7 +403,7 @@ func (s *AiGatewayService) probeChat(ctx context.Context, cred oci.Credentials,
case oci.IsModelUnavailable(err): case oci.IsModelUnavailable(err):
status, detail = "error", truncateErr(fmt.Sprintf("%s: 不可按需调用,建议加入模型黑名单", m.Name)) status, detail = "error", truncateErr(fmt.Sprintf("%s: 不可按需调用,建议加入模型黑名单", m.Name))
case code == 401 || code == 403 || code == 404: case code == 401 || code == 403 || code == 404:
return "no_quota", truncateErr(oci.CompactError(err)) quotaDetail = truncateErr(fmt.Sprintf("%s: %s", m.Name, oci.CompactError(err)))
default: default:
status, detail = "error", truncateErr(fmt.Sprintf("%s: %s", m.Name, oci.CompactError(err))) status, detail = "error", truncateErr(fmt.Sprintf("%s: %s", m.Name, oci.CompactError(err)))
if errBudget--; errBudget == 0 { if errBudget--; errBudget == 0 {
@@ -357,6 +411,9 @@ func (s *AiGatewayService) probeChat(ctx context.Context, cred oci.Credentials,
} }
} }
} }
if quotaDetail != "" {
return "no_quota", quotaDetail
}
return status, detail return status, detail
} }
@@ -364,13 +421,18 @@ func (s *AiGatewayService) probeChat(ctx context.Context, cred oci.Credentials,
// 不可按需调用的坏模型找到可用者;其他错误另有 3 次止损预算。 // 不可按需调用的坏模型找到可用者;其他错误另有 3 次止损预算。
const probeCandidateCap = 8 const probeCandidateCap = 8
// probeCandidates 只取对话模型,按可靠度排序后跨厂商取候选:主流文本模型优先; // probeCandidates 只取对话模型,按可靠度排序后跨厂商取候选:用户已验证的
// probeModel 固定放首位(不做能力过滤,测试通过即有效),其余主流文本模型优先;
// voice 等负分形态(元数据标 CHAT 但实际不可对话)直接排除,不浪费试调预算; // voice 等负分形态(元数据标 CHAT 但实际不可对话)直接排除,不浪费试调预算;
// 每厂商先取最高分再按分数补位——部分区域某厂商全为微调基座(调用必失败), // 每厂商先取最高分再按分数补位——部分区域某厂商全为微调基座(调用必失败),
// 不能让单一厂商占满候选名额拖垮整个渠道的探测结论。 // 不能让单一厂商占满候选名额拖垮整个渠道的探测结论。
func probeCandidates(models []oci.GenAiModel) []oci.GenAiModel { func probeCandidates(probeModel string, models []oci.GenAiModel) []oci.GenAiModel {
var sorted []oci.GenAiModel var pinned, sorted []oci.GenAiModel
for _, m := range models { for _, m := range models {
if probeModel != "" && m.Name == probeModel {
pinned = append(pinned, m)
continue
}
if (m.Capability == "" || m.Capability == "CHAT") && probeScore(m.Name) >= 0 { if (m.Capability == "" || m.Capability == "CHAT") && probeScore(m.Name) >= 0 {
sorted = append(sorted, m) sorted = append(sorted, m)
} }
@@ -378,7 +440,7 @@ func probeCandidates(models []oci.GenAiModel) []oci.GenAiModel {
sort.SliceStable(sorted, func(i, j int) bool { sort.SliceStable(sorted, func(i, j int) bool {
return probeScore(sorted[i].Name) > probeScore(sorted[j].Name) return probeScore(sorted[i].Name) > probeScore(sorted[j].Name)
}) })
return diversifyByVendor(sorted, probeCandidateCap) return append(pinned, diversifyByVendor(sorted, probeCandidateCap)...)
} }
// diversifyByVendor 从已排序列表先每厂商各取一个,不足 limit 再按原序补位。 // diversifyByVendor 从已排序列表先每厂商各取一个,不足 limit 再按原序补位。
@@ -497,12 +559,80 @@ func (s *AiGatewayService) replaceModels(ctx context.Context, channelID uint, mo
}) })
} }
// channelModels 列出渠道模型缓存;黑名单模型查询层兜底过滤
// (拉黑即删缓存,正常不会残留,防御旧数据 / 并发窗口);
// 「过滤弃用模型」开关开启时同样剔除已宣布弃用者(数据保留,展示口径过滤)。
func (s *AiGatewayService) channelModels(ctx context.Context, channelID uint) ([]model.AiModelCache, error) { func (s *AiGatewayService) channelModels(ctx context.Context, channelID uint) ([]model.AiModelCache, error) {
q := s.db.WithContext(ctx).Where("channel_id = ?", channelID).
Where("name NOT IN (SELECT name FROM ai_model_blacklists)")
if s.FilterDeprecated() {
q = q.Where("deprecated_at IS NULL")
}
var rows []model.AiModelCache var rows []model.AiModelCache
err := s.db.WithContext(ctx).Where("channel_id = ?", channelID).Order("name ASC").Find(&rows).Error err := q.Order("name ASC").Find(&rows).Error
return rows, err return rows, err
} }
// ChannelModels 列出渠道的模型缓存(名称排序),渠道不存在时报错。
func (s *AiGatewayService) ChannelModels(ctx context.Context, id uint) ([]model.AiModelCache, error) {
var n int64
if err := s.db.WithContext(ctx).Model(&model.AiChannel{}).Where("id = ?", id).Count(&n).Error; err != nil {
return nil, err
}
if n == 0 {
return nil, fmt.Errorf("渠道不存在")
}
return s.channelModels(ctx, id)
}
// TestChannelModel 对渠道缓存中的指定模型发极小试调;通过时把该模型设
// 为渠道探测验证模型(此后探测置于候选首位),渠道探测状态不为 ok 时顺带置 ok 并
// 复位熔断;未通过仅返回错误,不改动渠道状态。
func (s *AiGatewayService) TestChannelModel(ctx context.Context, id uint, name string) (*model.AiChannel, error) {
var ch model.AiChannel
if err := s.db.WithContext(ctx).First(&ch, id).Error; err != nil {
return nil, fmt.Errorf("渠道不存在")
}
var mc model.AiModelCache
err := s.db.WithContext(ctx).Where("channel_id = ? AND name = ?", id, name).First(&mc).Error
if err != nil {
return nil, fmt.Errorf("模型不在该渠道缓存中,请先同步模型")
}
cred, err := s.configs.credentialsByID(ctx, ch.OciConfigID)
if err != nil {
return nil, err
}
code, err := s.client.GenAiProbeChat(ctx, cred, ch.Region, mc.ModelOcid, mc.Name)
if code != 200 && code != 429 {
msg := fmt.Sprintf("HTTP %d", code)
if err != nil {
msg = oci.CompactError(err)
}
return nil, fmt.Errorf("测试未通过:%s", truncateErr(msg))
}
return s.adoptProbeModel(ctx, &ch, name)
}
// adoptProbeModel 记录探测验证模型并返回更新后的渠道;
// 状态不为 ok 时一并置 ok 并复位熔断。
func (s *AiGatewayService) adoptProbeModel(ctx context.Context, ch *model.AiChannel, name string) (*model.AiChannel, error) {
updates := map[string]any{"probe_model": name}
if ch.ProbeStatus != "ok" {
updates["probe_status"] = "ok"
updates["probe_error"] = ""
updates["last_probe_at"] = time.Now()
updates["fail_count"] = 0
updates["disabled_until"] = gorm.Expr("NULL")
}
if err := s.db.WithContext(ctx).Model(&model.AiChannel{}).Where("id = ?", ch.ID).Updates(updates).Error; err != nil {
return nil, err
}
// 重读用新变量:gorm 扫描 NULL 列到已有值的结构体时会保留旧值
var fresh model.AiChannel
err := s.db.WithContext(ctx).First(&fresh, ch.ID).Error
return &fresh, err
}
// GatewayModels 聚合启用渠道的可用模型(按名称去重),供 /ai/v1/models; // GatewayModels 聚合启用渠道的可用模型(按名称去重),供 /ai/v1/models;
// group 非空时仅聚合该分组渠道(与密钥分组路由口径一致)。 // group 非空时仅聚合该分组渠道(与密钥分组路由口径一致)。
func (s *AiGatewayService) GatewayModels(ctx context.Context, group string) (aiwire.ModelList, error) { func (s *AiGatewayService) GatewayModels(ctx context.Context, group string) (aiwire.ModelList, error) {
@@ -511,6 +641,9 @@ func (s *AiGatewayService) GatewayModels(ctx context.Context, group string) (aiw
if group != "" { if group != "" {
q = q.Where("ai_channels.channel_group = ?", group) q = q.Where("ai_channels.channel_group = ?", group)
} }
if s.FilterDeprecated() {
q = q.Where("ai_model_caches.deprecated_at IS NULL")
}
var rows []model.AiModelCache var rows []model.AiModelCache
err := q.Order("ai_model_caches.name ASC").Find(&rows).Error err := q.Order("ai_model_caches.name ASC").Find(&rows).Error
list := aiwire.ModelList{Object: "list", Data: []aiwire.Model{}} list := aiwire.ModelList{Object: "list", Data: []aiwire.Model{}}
+3
View File
@@ -164,6 +164,9 @@ func (s *AiGatewayService) modelChannels(ctx context.Context, modelName, capabil
} else { } else {
q = q.Where("capability = ?", capability) q = q.Where("capability = ?", capability)
} }
if s.FilterDeprecated() {
q = q.Where("deprecated_at IS NULL")
}
var rows []model.AiModelCache var rows []model.AiModelCache
if err := q.Find(&rows).Error; err != nil { if err := q.Find(&rows).Error; err != nil {
return nil, nil, err return nil, nil, err
+284
View File
@@ -0,0 +1,284 @@
package service
import (
"context"
"encoding/json"
"fmt"
"strings"
"time"
"oci-portal/internal/aiwire"
"oci-portal/internal/model"
"oci-portal/internal/oci"
)
// moderationsMaxInputs 限制单次审核条数,防止批量滥用拖垮渠道配额。
const moderationsMaxInputs = 8
// SpeechBodyNormalize 校验并规范化 TTS 请求体:model / input 必填;
// xAI 上游把 language 当必填(实测缺失返回 422),缺省注入 "auto"。
// 其余字段(voice / response_format / extra_body 平铺项)原样保留。
func SpeechBodyNormalize(raw []byte) (string, []byte, error) {
dec := json.NewDecoder(strings.NewReader(string(raw)))
dec.UseNumber()
var body map[string]any
if err := dec.Decode(&body); err != nil {
return "", nil, fmt.Errorf("解析请求体: %w", err)
}
modelName, _ := body["model"].(string)
input, _ := body["input"].(string)
if strings.TrimSpace(modelName) == "" || strings.TrimSpace(input) == "" {
return "", nil, fmt.Errorf("model 与 input 不能为空")
}
if lang, ok := body["language"].(string); !ok || strings.TrimSpace(lang) == "" {
body["language"] = "auto"
}
out, err := json.Marshal(body)
if err != nil {
return "", nil, fmt.Errorf("重组请求体: %w", err)
}
return modelName, out, nil
}
// ttsDefaultModel 是 /ai/v1/tts 缺省注入的模型(xAI 官方格式无 model 字段)。
const ttsDefaultModel = "xai.grok-tts"
// TtsBodyConvert 把 xAI 官方 TTS 格式转换为上游 OpenAI 兼容 audio/speech 形态:
// text→input、voice_id→voice,text 与 language 必填(对齐 xAI 官方);
// model 为网关扩展字段,缺省注入 ttsDefaultModel;其余字段原样保留。
func TtsBodyConvert(raw []byte) (string, []byte, error) {
dec := json.NewDecoder(strings.NewReader(string(raw)))
dec.UseNumber()
var body map[string]any
if err := dec.Decode(&body); err != nil {
return "", nil, fmt.Errorf("解析请求体: %w", err)
}
text, _ := body["text"].(string)
language, _ := body["language"].(string)
if strings.TrimSpace(text) == "" || strings.TrimSpace(language) == "" {
return "", nil, fmt.Errorf("text 与 language 不能为空")
}
modelName, _ := body["model"].(string)
if strings.TrimSpace(modelName) == "" {
modelName = ttsDefaultModel
body["model"] = modelName
}
delete(body, "text")
body["input"] = text
if voice, ok := body["voice_id"].(string); ok && strings.TrimSpace(voice) != "" {
body["voice"] = voice
}
delete(body, "voice_id")
out, err := json.Marshal(body)
if err != nil {
return "", nil, fmt.Errorf("重组请求体: %w", err)
}
return modelName, out, nil
}
// Speech 编排 TTS 调用:按 TTS 能力选渠道,可重试错误换渠道(上限 3 次)。
func (s *AiGatewayService) Speech(ctx context.Context, modelName string, body []byte, group string) ([]byte, string, ChatMeta, error) {
meta := ChatMeta{}
excluded := map[uint]bool{}
var lastErr error
for attempt := 0; attempt < 3; attempt++ {
cand, err := s.pick(ctx, modelName, group, "TTS", excluded)
if err != nil {
return nil, "", meta, firstErr(lastErr, err)
}
meta.ChannelID, meta.ChannelName = cand.ch.ID, cand.ch.Name
cred, err := s.configs.credentialsByID(ctx, cand.ch.OciConfigID)
if err != nil {
return nil, "", meta, err
}
audio, contentType, err := s.client.GenAiCompatSpeech(ctx, cred, cand.ch.Region, body)
if err == nil {
s.markSuccess(ctx, cand.ch.ID)
return audio, contentType, meta, nil
}
if done := s.retryStep(ctx, cand.ch.ID, err, excluded, &meta, &lastErr); done {
return nil, "", meta, err
}
}
return nil, "", meta, lastErr
}
// Rerank 编排文档重排:按 RERANK 能力选渠道,装配 Jina 风格响应。
func (s *AiGatewayService) Rerank(ctx context.Context, req aiwire.RerankRequest, group string) (*aiwire.RerankResponse, ChatMeta, error) {
meta := ChatMeta{}
excluded := map[uint]bool{}
var lastErr error
for attempt := 0; attempt < 3; attempt++ {
cand, err := s.pick(ctx, req.Model, group, "RERANK", excluded)
if err != nil {
return nil, meta, firstErr(lastErr, err)
}
meta.ChannelID, meta.ChannelName = cand.ch.ID, cand.ch.Name
cred, err := s.configs.credentialsByID(ctx, cand.ch.OciConfigID)
if err != nil {
return nil, meta, err
}
ranks, err := s.client.GenAiRerank(ctx, cred, cand.ch.Region, cand.modelOcid, req.Query, req.Documents, req.TopN)
if err == nil {
s.markSuccess(ctx, cand.ch.ID)
return rerankResponse(req, ranks), meta, nil
}
if done := s.retryStep(ctx, cand.ch.ID, err, excluded, &meta, &lastErr); done {
return nil, meta, err
}
}
return nil, meta, lastErr
}
// retryStep 统一处理换渠道重试:不可重试返回 true 终止,可重试记罚并排除渠道。
func (s *AiGatewayService) retryStep(ctx context.Context, chID uint, err error, excluded map[uint]bool, meta *ChatMeta, lastErr *error) bool {
retry, penalize := switchable(err)
if !retry {
return true
}
if penalize {
s.markFailure(ctx, chID)
}
excluded[chID] = true
meta.Retries++
*lastErr = err
return false
}
// rerankResponse 把上游排序结果装配为对外响应;return_documents 时回填原文。
func rerankResponse(req aiwire.RerankRequest, ranks []oci.RerankRank) *aiwire.RerankResponse {
out := &aiwire.RerankResponse{Model: req.Model, Results: make([]aiwire.RerankResult, 0, len(ranks))}
withDoc := req.ReturnDocuments != nil && *req.ReturnDocuments
for _, r := range ranks {
if r.Index < 0 || r.Index >= len(req.Documents) {
continue
}
item := aiwire.RerankResult{Index: r.Index, RelevanceScore: r.Score}
if withDoc {
item.Document = &aiwire.RerankDocument{Text: req.Documents[r.Index]}
}
out.Results = append(out.Results, item)
}
return out
}
// ModerationInputs 解析 moderations 的 input 字段:string 或 []string,
// 条数与空值校验(上限 moderationsMaxInputs)。
func ModerationInputs(raw json.RawMessage) ([]string, error) {
var single string
if err := json.Unmarshal(raw, &single); err == nil {
if strings.TrimSpace(single) == "" {
return nil, fmt.Errorf("input 不能为空")
}
return []string{single}, nil
}
var many []string
if err := json.Unmarshal(raw, &many); err != nil {
return nil, fmt.Errorf("input 需为字符串或字符串数组")
}
if len(many) == 0 || len(many) > moderationsMaxInputs {
return nil, fmt.Errorf("input 条数需在 1~%d 之间", moderationsMaxInputs)
}
for _, item := range many {
if strings.TrimSpace(item) == "" {
return nil, fmt.Errorf("input 含空条目")
}
}
return many, nil
}
// Moderations 编排内容审核:guardrails 为服务级 API 无模型维度,
// 按分组选启用渠道(整批同渠道),可重试错误换渠道(上限 3 次)。
func (s *AiGatewayService) Moderations(ctx context.Context, id string, inputs []string, group string) (*aiwire.ModerationsResponse, ChatMeta, error) {
meta := ChatMeta{}
excluded := map[uint]bool{}
var lastErr error
for attempt := 0; attempt < 3; attempt++ {
ch, err := s.pickGuardChannel(ctx, group, excluded)
if err != nil {
return nil, meta, firstErr(lastErr, err)
}
meta.ChannelID, meta.ChannelName = ch.ID, ch.Name
resp, err := s.moderateOnce(ctx, ch, id, inputs)
if err == nil {
s.markSuccess(ctx, ch.ID)
return resp, meta, nil
}
if done := s.retryStep(ctx, ch.ID, err, excluded, &meta, &lastErr); done {
return nil, meta, err
}
}
return nil, meta, lastErr
}
// pickGuardChannel 按分组挑一个启用且未熔断的渠道(权重加成,不查模型缓存)。
func (s *AiGatewayService) pickGuardChannel(ctx context.Context, group string, excluded map[uint]bool) (model.AiChannel, error) {
q := s.db.WithContext(ctx).Where("enabled = ?", true)
if group != "" {
q = q.Where("channel_group = ?", group)
}
var channels []model.AiChannel
if err := q.Find(&channels).Error; err != nil {
return model.AiChannel{}, err
}
now := time.Now()
avail := channels[:0]
for _, ch := range channels {
if excluded[ch.ID] || (ch.DisabledUntil != nil && ch.DisabledUntil.After(now)) {
continue
}
avail = append(avail, ch)
}
if len(avail) == 0 {
return model.AiChannel{}, ErrAiNoChannel
}
return weightedPick(topPriority(avail)), nil
}
// moderateOnce 在单渠道上逐条审核并装配 OpenAI moderations 外壳。
func (s *AiGatewayService) moderateOnce(ctx context.Context, ch model.AiChannel, id string, inputs []string) (*aiwire.ModerationsResponse, error) {
cred, err := s.configs.credentialsByID(ctx, ch.OciConfigID)
if err != nil {
return nil, err
}
out := &aiwire.ModerationsResponse{ID: id, Model: "oci-guardrails",
Results: make([]aiwire.ModerationResult, 0, len(inputs))}
for _, text := range inputs {
outcome, err := s.client.GenAiApplyGuardrails(ctx, cred, ch.Region, text)
if err != nil {
return nil, err
}
out.Results = append(out.Results, moderationResult(outcome))
}
return out, nil
}
// moderationFlagThreshold 是判定违规的得分阈值(上游 CM / PI 为二值得分)。
const moderationFlagThreshold = 0.5
// moderationResult 把 guardrails 结果映射为 OpenAI moderations 条目:
// flagged 由内容审核与提示注入判定,PII 命中只作扩展信息不参与 flagged。
func moderationResult(outcome *oci.GuardrailsOutcome) aiwire.ModerationResult {
res := aiwire.ModerationResult{Categories: map[string]bool{}, CategoryScores: map[string]float64{}}
for _, cat := range outcome.Categories {
key := strings.ToLower(cat.Name)
res.Categories[key] = cat.Score >= moderationFlagThreshold
res.CategoryScores[key] = cat.Score
if res.Categories[key] {
res.Flagged = true
}
}
if outcome.PromptInjectionScore != nil {
hit := *outcome.PromptInjectionScore >= moderationFlagThreshold
res.Categories["prompt_injection"] = hit
res.CategoryScores["prompt_injection"] = *outcome.PromptInjectionScore
if hit {
res.Flagged = true
}
}
for _, p := range outcome.Pii {
res.Pii = append(res.Pii, aiwire.ModerationPii{Text: p.Text, Label: p.Label,
Score: p.Score, Offset: p.Offset, Length: p.Length})
}
return res
}
+222
View File
@@ -0,0 +1,222 @@
package service
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
"time"
"oci-portal/internal/aiwire"
"oci-portal/internal/model"
"oci-portal/internal/oci"
)
// TestSpeechBodyNormalize 断言 TTS 请求体校验与 language 缺省注入。
func TestSpeechBodyNormalize(t *testing.T) {
tests := []struct {
name string
raw string
wantErr bool
wantLang string
}{
{"缺 model 拒绝", `{"input":"你好"}`, true, ""},
{"缺 input 拒绝", `{"model":"xai.grok-tts"}`, true, ""},
{"language 缺省注入 auto", `{"model":"xai.grok-tts","input":"你好","voice":"ara"}`, false, "auto"},
{"language 已有保留", `{"model":"xai.grok-tts","input":"你好","language":"zh"}`, false, "zh"},
{"非 JSON 拒绝", `<html>`, true, ""},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
modelName, body, err := SpeechBodyNormalize([]byte(tt.raw))
if (err != nil) != tt.wantErr {
t.Fatalf("err = %v, wantErr %v", err, tt.wantErr)
}
if err != nil {
return
}
var out map[string]any
_ = json.Unmarshal(body, &out)
if modelName != "xai.grok-tts" || out["language"] != tt.wantLang {
t.Fatalf("model=%s language=%v, want %s", modelName, out["language"], tt.wantLang)
}
})
}
}
// TestTtsBodyConvert 断言 xAI 官方 TTS 格式到 OpenAI 兼容形态的转换。
func TestTtsBodyConvert(t *testing.T) {
tests := []struct {
name string
raw string
wantErr bool
wantModel string
}{
{"缺 text 拒绝", `{"language":"zh"}`, true, ""},
{"缺 language 拒绝", `{"text":"你好"}`, true, ""},
{"缺省注入默认模型", `{"text":"你好","language":"zh"}`, false, "xai.grok-tts"},
{"model 扩展字段可覆盖", `{"model":"xai.other-tts","text":"你好","language":"auto"}`, false, "xai.other-tts"},
{"非 JSON 拒绝", `<html>`, true, ""},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
modelName, _, err := TtsBodyConvert([]byte(tt.raw))
if (err != nil) != tt.wantErr {
t.Fatalf("err = %v, wantErr %v", err, tt.wantErr)
}
if err != nil {
return
}
if modelName != tt.wantModel {
t.Fatalf("model = %s, want %s", modelName, tt.wantModel)
}
})
}
}
// TestTtsBodyConvertMapping 断言字段映射与未知字段保留。
func TestTtsBodyConvertMapping(t *testing.T) {
raw := `{"text":"你好","language":"zh","voice_id":"ara","speed":1.2,` +
`"output_format":{"codec":"mp3","sample_rate":44100}}`
_, body, err := TtsBodyConvert([]byte(raw))
if err != nil {
t.Fatalf("err = %v", err)
}
var out map[string]any
_ = json.Unmarshal(body, &out)
if out["input"] != "你好" || out["voice"] != "ara" {
t.Fatalf("input/voice 映射错误: %v", out)
}
if _, ok := out["text"]; ok {
t.Fatal("text 字段应被移除")
}
if _, ok := out["voice_id"]; ok {
t.Fatal("voice_id 字段应被移除")
}
of, _ := out["output_format"].(map[string]any)
if of == nil || of["codec"] != "mp3" {
t.Fatalf("output_format 应原样保留: %v", out["output_format"])
}
if out["language"] != "zh" || out["speed"] == nil {
t.Fatalf("language/speed 应保留: %v", out)
}
}
// TestModerationInputs 断言 input 的 string / []string 解析与边界校验。
func TestModerationInputs(t *testing.T) {
tests := []struct {
name string
raw string
wantN int
wantErr bool
}{
{"单字符串", `"hello"`, 1, false},
{"数组", `["a","b"]`, 2, false},
{"空字符串拒绝", `""`, 0, true},
{"空数组拒绝", `[]`, 0, true},
{"含空条目拒绝", `["a",""]`, 0, true},
{"超上限拒绝", `["1","2","3","4","5","6","7","8","9"]`, 0, true},
{"非法类型拒绝", `{"x":1}`, 0, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := ModerationInputs(json.RawMessage(tt.raw))
if (err != nil) != tt.wantErr || len(got) != tt.wantN {
t.Fatalf("got %v (err=%v), want n=%d wantErr=%v", got, err, tt.wantN, tt.wantErr)
}
})
}
}
// TestModerationResultMapping 断言 guardrails 结果到 OpenAI 外壳的映射与 flagged 判定。
func TestModerationResultMapping(t *testing.T) {
one := 1.0
zero := 0.0
tests := []struct {
name string
outcome oci.GuardrailsOutcome
wantFlagged bool
wantPii int
}{
{"内容审核命中", oci.GuardrailsOutcome{Categories: []oci.GuardrailCategory{{Name: "OVERALL", Score: 1}}}, true, 0},
{"提示注入命中", oci.GuardrailsOutcome{PromptInjectionScore: &one}, true, 0},
{"仅 PII 不 flag", oci.GuardrailsOutcome{Categories: []oci.GuardrailCategory{{Name: "OVERALL", Score: 0}},
PromptInjectionScore: &zero, Pii: []oci.GuardrailPiiHit{{Text: "Jane", Label: "PERSON", Score: 0.99}}}, false, 1},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
res := moderationResult(&tt.outcome)
if res.Flagged != tt.wantFlagged || len(res.Pii) != tt.wantPii {
t.Fatalf("res = %+v, want flagged=%v pii=%d", res, tt.wantFlagged, tt.wantPii)
}
})
}
}
// TestAiRerank 断言重排编排:能力路由、top_n 透传、return_documents 回填与越界防御。
func TestAiRerank(t *testing.T) {
client := &gatewayStubClient{
fakeClient: &fakeClient{tenancy: oci.TenancyInfo{Name: "t"}},
rerankRanks: []oci.RerankRank{{Index: 1, Score: 0.9}, {Index: 0, Score: 0.4}, {Index: 9, Score: 0.1}},
}
gw, svc := newTestGateway(t, client)
cfg := importAliveConfig(t, svc)
ch := seedChannel(t, gw, cfg.ID, "us-chicago-1", 1, 1)
gw.db.Create(&model.AiModelCache{ChannelID: ch.ID, ModelOcid: "ocid1..rr", Name: "cohere.rerank-v4.0-fast",
Vendor: "cohere", Capability: "RERANK", SyncedAt: time.Now()})
ctx := context.Background()
yes := true
req := aiwire.RerankRequest{Model: "cohere.rerank-v4.0-fast", Query: "q", Documents: []string{"d0", "d1"}, ReturnDocuments: &yes}
resp, _, err := gw.Rerank(ctx, req, "")
if err != nil || len(resp.Results) != 2 {
t.Fatalf("Rerank = %+v, %v(越界 index 应被丢弃)", resp, err)
}
if resp.Results[0].Index != 1 || resp.Results[0].Document == nil || resp.Results[0].Document.Text != "d1" {
t.Fatalf("results[0] = %+v", resp.Results[0])
}
// 对话模型名打 rerank:能力不匹配 → 未知模型
if _, _, err := gw.Rerank(ctx, aiwire.RerankRequest{Model: "meta.llama-3.3-70b-instruct", Query: "q", Documents: []string{"d"}}, ""); !errors.Is(err, ErrAiUnknownModel) {
t.Errorf("chat 模型走 rerank err = %v, want ErrAiUnknownModel", err)
}
}
// TestAiSpeech 断言 TTS 编排走 TTS 能力路由并透传音频与 Content-Type。
func TestAiSpeech(t *testing.T) {
client := &gatewayStubClient{
fakeClient: &fakeClient{tenancy: oci.TenancyInfo{Name: "t"}},
speechAudio: []byte{0xFF, 0xF3}, speechCT: "audio/mpeg",
}
gw, svc := newTestGateway(t, client)
cfg := importAliveConfig(t, svc)
ch := seedChannel(t, gw, cfg.ID, "us-chicago-1", 1, 1)
gw.db.Create(&model.AiModelCache{ChannelID: ch.ID, ModelOcid: "ocid1..tts", Name: "xai.grok-tts",
Vendor: "xai", Capability: "TTS", SyncedAt: time.Now()})
audio, ct, _, err := gw.Speech(context.Background(), "xai.grok-tts", []byte(`{"model":"xai.grok-tts","input":"你好","language":"auto"}`), "")
if err != nil || ct != "audio/mpeg" || len(audio) != 2 {
t.Fatalf("Speech = %d bytes, ct=%s, %v", len(audio), ct, err)
}
}
// TestAiModerations 断言审核编排:无模型维度按分组选渠道,多条输入逐条聚合。
func TestAiModerations(t *testing.T) {
one := 1.0
client := &gatewayStubClient{
fakeClient: &fakeClient{tenancy: oci.TenancyInfo{Name: "t"}},
guardOutcome: &oci.GuardrailsOutcome{Categories: []oci.GuardrailCategory{{Name: "OVERALL", Score: 1}}, PromptInjectionScore: &one},
}
gw, svc := newTestGateway(t, client)
cfg := importAliveConfig(t, svc)
seedChannel(t, gw, cfg.ID, "us-chicago-1", 1, 1)
resp, meta, err := gw.Moderations(context.Background(), "modr_test", []string{"a", "b"}, "")
if err != nil || len(resp.Results) != 2 || !resp.Results[0].Flagged || resp.ID != "modr_test" {
t.Fatalf("Moderations = %+v, meta=%+v, %v", resp, meta, err)
}
if !strings.Contains(resp.Model, "guardrails") {
t.Errorf("model = %s", resp.Model)
}
// 分组不匹配 → 无可用渠道
if _, _, err := gw.Moderations(context.Background(), "modr_x", []string{"a"}, "ghost-group"); !errors.Is(err, ErrAiNoChannel) {
t.Errorf("ghost 分组 err = %v, want ErrAiNoChannel", err)
}
}
+213 -4
View File
@@ -61,6 +61,26 @@ type gatewayStubClient struct {
passErrs []error passErrs []error
passCalls int passCalls int
passRegions []string passRegions []string
speechAudio []byte
speechCT string
speechErr error
rerankRanks []oci.RerankRank
rerankErr error
guardOutcome *oci.GuardrailsOutcome
guardErr error
}
func (f *gatewayStubClient) GenAiCompatSpeech(ctx context.Context, cred oci.Credentials, region string, body []byte) ([]byte, string, error) {
return f.speechAudio, f.speechCT, f.speechErr
}
func (f *gatewayStubClient) GenAiRerank(ctx context.Context, cred oci.Credentials, region, modelOcid, query string, documents []string, topN *int) ([]oci.RerankRank, error) {
return f.rerankRanks, f.rerankErr
}
func (f *gatewayStubClient) GenAiApplyGuardrails(ctx context.Context, cred oci.Credentials, region, text string) (*oci.GuardrailsOutcome, error) {
return f.guardOutcome, f.guardErr
} }
func (f *gatewayStubClient) GenAiCompatResponses(ctx context.Context, cred oci.Credentials, region string, body []byte) ([]byte, error) { func (f *gatewayStubClient) GenAiCompatResponses(ctx context.Context, cred oci.Credentials, region string, body []byte) ([]byte, error) {
@@ -116,7 +136,7 @@ func (f *gatewayStubClient) GenAiProbeChat(ctx context.Context, cred oci.Credent
func newTestGateway(t *testing.T, client oci.Client) (*AiGatewayService, *OciConfigService) { func newTestGateway(t *testing.T, client oci.Client) (*AiGatewayService, *OciConfigService) {
t.Helper() t.Helper()
svc := newTestService(t, client) svc := newTestService(t, client)
if err := svc.db.AutoMigrate(&model.AiKey{}, &model.AiChannel{}, &model.AiModelCache{}, &model.AiModelBlacklist{}, &model.AiCallLog{}); err != nil { if err := svc.db.AutoMigrate(&model.Setting{}, &model.AiKey{}, &model.AiChannel{}, &model.AiModelCache{}, &model.AiModelBlacklist{}, &model.AiCallLog{}); err != nil {
t.Fatalf("auto migrate ai tables: %v", err) t.Fatalf("auto migrate ai tables: %v", err)
} }
return NewAiGatewayService(svc.db, svc, client), svc return NewAiGatewayService(svc.db, svc, client), svc
@@ -208,6 +228,46 @@ func seedChannel(t *testing.T, gw *AiGatewayService, cfgID uint, region string,
return ch return ch
} }
// TestFilterDeprecatedModels 断言「过滤弃用模型」开关对列表 / 路由的过滤与持久化。
func TestFilterDeprecatedModels(t *testing.T) {
gw, svc := newTestGateway(t, &gatewayStubClient{fakeClient: &fakeClient{tenancy: oci.TenancyInfo{Name: "t"}}})
cfg := importAliveConfig(t, svc)
ch := seedChannel(t, gw, cfg.ID, "eu-frankfurt-1", 1, 1)
dep := time.Now().Add(-24 * time.Hour)
old := &model.AiModelCache{ChannelID: ch.ID, ModelOcid: "ocid1..dep", Name: "meta.llama-old",
Vendor: "meta", SyncedAt: time.Now(), DeprecatedAt: &dep}
if err := gw.db.Create(old).Error; err != nil {
t.Fatalf("seed deprecated cache: %v", err)
}
ctx := context.Background()
list, _ := gw.GatewayModels(ctx, "")
if len(list.Data) != 2 {
t.Fatalf("开关关:应含弃用模型,got %d", len(list.Data))
}
if err := gw.SetFilterDeprecated(ctx, true); err != nil {
t.Fatalf("SetFilterDeprecated: %v", err)
}
list, _ = gw.GatewayModels(ctx, "")
if len(list.Data) != 1 || list.Data[0].ID != "meta.llama-3.3-70b-instruct" {
t.Fatalf("开关开:弃用模型应被过滤,got %+v", list.Data)
}
if _, err := gw.pick(ctx, "meta.llama-old", "", "CHAT", map[uint]bool{}); !errors.Is(err, ErrAiUnknownModel) {
t.Errorf("开关开:弃用模型路由应不可达,err = %v", err)
}
// 持久化:重建 service 后开关仍生效
gw2 := NewAiGatewayService(gw.db, svc, &gatewayStubClient{})
if !gw2.FilterDeprecated() {
t.Error("重建后开关状态应保持开启")
}
if err := gw.SetFilterDeprecated(ctx, false); err != nil {
t.Fatalf("关闭开关: %v", err)
}
if list, _ = gw.GatewayModels(ctx, ""); len(list.Data) != 2 {
t.Errorf("开关关:弃用模型应恢复,got %d", len(list.Data))
}
}
func TestPickPriorityAndBreaker(t *testing.T) { func TestPickPriorityAndBreaker(t *testing.T) {
gw, svc := newTestGateway(t, &gatewayStubClient{fakeClient: &fakeClient{tenancy: oci.TenancyInfo{Name: "t"}}}) gw, svc := newTestGateway(t, &gatewayStubClient{fakeClient: &fakeClient{tenancy: oci.TenancyInfo{Name: "t"}}})
cfg := importAliveConfig(t, svc) cfg := importAliveConfig(t, svc)
@@ -393,7 +453,7 @@ func TestProbeCandidates(t *testing.T) {
{Ocid: "o3", Name: "meta.llama-3.3-70b-instruct"}, {Ocid: "o3", Name: "meta.llama-3.3-70b-instruct"},
{Ocid: "o4", Name: "google.gemini-2.5-flash"}, {Ocid: "o4", Name: "google.gemini-2.5-flash"},
} }
got := probeCandidates(models) got := probeCandidates("", models)
if len(got) != 3 || got[0].Name != "meta.llama-3.3-70b-instruct" || got[1].Name != "google.gemini-2.5-flash" { if len(got) != 3 || got[0].Name != "meta.llama-3.3-70b-instruct" || got[1].Name != "google.gemini-2.5-flash" {
t.Errorf("候选排序 = %+v", got) t.Errorf("候选排序 = %+v", got)
} }
@@ -413,7 +473,7 @@ func TestProbeCandidatesVendorDiversity(t *testing.T) {
{Ocid: "c1", Name: "cohere.command-a-03-2025"}, {Ocid: "c1", Name: "cohere.command-a-03-2025"},
{Ocid: "g1", Name: "xai.grok-4"}, {Ocid: "g1", Name: "xai.grok-4"},
} }
got := probeCandidates(models) got := probeCandidates("", models)
if len(got) != 5 || got[0].Name != "meta.llama-3-70b-instruct" { if len(got) != 5 || got[0].Name != "meta.llama-3-70b-instruct" {
t.Fatalf("上限内全量返回且最高分居首: %+v", got) t.Fatalf("上限内全量返回且最高分居首: %+v", got)
} }
@@ -429,11 +489,38 @@ func TestProbeCandidatesVendorDiversity(t *testing.T) {
for i := 0; i < 12; i++ { for i := 0; i < 12; i++ {
many = append(many, oci.GenAiModel{Ocid: fmt.Sprintf("m%d", i), Name: fmt.Sprintf("meta.llama-%d", i)}) many = append(many, oci.GenAiModel{Ocid: fmt.Sprintf("m%d", i), Name: fmt.Sprintf("meta.llama-%d", i)})
} }
if capped := probeCandidates(many); len(capped) != probeCandidateCap { if capped := probeCandidates("", many); len(capped) != probeCandidateCap {
t.Errorf("候选应截断到 %d: got %d", probeCandidateCap, len(capped)) t.Errorf("候选应截断到 %d: got %d", probeCandidateCap, len(capped))
} }
} }
// TestProbeCandidatesPinsProbeModel 断言探测验证模型置首位且不占常规候选逻辑。
func TestProbeCandidatesPinsProbeModel(t *testing.T) {
models := []oci.GenAiModel{
{Ocid: "o2", Name: "cohere.command-r-plus"},
{Ocid: "o3", Name: "meta.llama-3.3-70b-instruct"},
{Ocid: "o4", Name: "xai.grok-4"},
}
tests := []struct {
name string
probeModel string
wantFirst string
wantLen int
}{
{"验证模型置首位", "xai.grok-4", "xai.grok-4", 3},
{"未设置走常规排序", "", "meta.llama-3.3-70b-instruct", 3},
{"验证模型已不在缓存则忽略", "gone.model", "meta.llama-3.3-70b-instruct", 3},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := probeCandidates(tt.probeModel, models)
if len(got) != tt.wantLen || got[0].Name != tt.wantFirst {
t.Errorf("probeCandidates(%q) = %+v, want first %q", tt.probeModel, got, tt.wantFirst)
}
})
}
}
// entityNotFoundErr 模拟「实体不存在」404(模型在区域内无按需供给)。 // entityNotFoundErr 模拟「实体不存在」404(模型在区域内无按需供给)。
func entityNotFoundErr() stubServiceError { func entityNotFoundErr() stubServiceError {
return stubServiceError{status: 404, return stubServiceError{status: 404,
@@ -500,6 +587,128 @@ func TestProbeAuth404StillNoQuota(t *testing.T) {
} }
} }
// TestChannelModelsExcludeBlacklist 断言模型列表与数量统计对黑名单做查询层兜底过滤。
func TestChannelModelsExcludeBlacklist(t *testing.T) {
gw, svc := newTestGateway(t, &gatewayStubClient{fakeClient: &fakeClient{tenancy: oci.TenancyInfo{Name: "t"}}})
cfg := importAliveConfig(t, svc)
ch := seedChannel(t, gw, cfg.ID, "eu-frankfurt-1", 1, 1)
ctx := context.Background()
// 直插黑名单行但保留缓存,模拟脏数据 / 并发窗口
gw.db.Create(&model.AiModelBlacklist{Name: "meta.llama-3.3-70b-instruct"})
rows, err := gw.ChannelModels(ctx, ch.ID)
if err != nil || len(rows) != 0 {
t.Errorf("黑名单模型应被过滤: %+v, %v", rows, err)
}
chs, err := gw.Channels(ctx)
if err != nil || len(chs) != 1 || chs[0].ModelCount != 0 {
t.Errorf("模型数量统计应剔除黑名单: %+v, %v", chs, err)
}
}
// TestChannelModelsFilterDeprecated 断言「过滤弃用模型」开关同样作用于
// 渠道模型列表与数量统计(数据保留,展示口径过滤)。
func TestChannelModelsFilterDeprecated(t *testing.T) {
gw, svc := newTestGateway(t, &gatewayStubClient{fakeClient: &fakeClient{tenancy: oci.TenancyInfo{Name: "t"}}})
cfg := importAliveConfig(t, svc)
ch := seedChannel(t, gw, cfg.ID, "eu-frankfurt-1", 1, 1)
dep := time.Now().Add(-24 * time.Hour)
gw.db.Create(&model.AiModelCache{ChannelID: ch.ID, ModelOcid: "ocid1..dep", Name: "xai.grok-3",
Vendor: "xai", SyncedAt: time.Now(), DeprecatedAt: &dep})
ctx := context.Background()
rows, _ := gw.ChannelModels(ctx, ch.ID)
if len(rows) != 2 {
t.Fatalf("开关关:弃用模型应在列,got %d", len(rows))
}
if err := gw.SetFilterDeprecated(ctx, true); err != nil {
t.Fatalf("SetFilterDeprecated: %v", err)
}
rows, _ = gw.ChannelModels(ctx, ch.ID)
if len(rows) != 1 || rows[0].Name != "meta.llama-3.3-70b-instruct" {
t.Errorf("开关开:弃用模型应被过滤,got %+v", rows)
}
chs, _ := gw.Channels(ctx)
if len(chs) != 1 || chs[0].ModelCount != 1 {
t.Errorf("开关开:数量统计应同口径,got %+v", chs)
}
}
// TestProbe403ContinuesToNextCandidate 断言模型级 403 不再武断定论渠道无配额:
// 后续候选成功 → ok;全部候选鉴权拒绝 → 仍 no_quota。
func TestProbe403ContinuesToNextCandidate(t *testing.T) {
deny := probeResult{403, stubServiceError{status: 403, msg: "NotAuthorizedOrNotFound"}}
tests := []struct {
name string
seq []probeResult
wantStatus string
}{
{"403 后换候选成功", []probeResult{deny, {200, nil}}, "ok"},
{"403 后换候选限流也算可用", []probeResult{deny, {429, stubServiceError{status: 429}}}, "ok"},
{"全部候选 403", []probeResult{deny, deny}, "no_quota"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
client := &gatewayStubClient{
fakeClient: &fakeClient{tenancy: oci.TenancyInfo{Name: "t"}},
models: []oci.GenAiModel{
{Ocid: "m1", Name: "meta.llama-3.3-70b-instruct", Vendor: "meta"},
{Ocid: "m2", Name: "cohere.command-a-03-2025", Vendor: "cohere"},
},
probeSeq: tt.seq,
}
gw, svc := newTestGateway(t, client)
cfg := importAliveConfig(t, svc)
ctx := context.Background()
ch, _ := gw.CreateChannel(ctx, ChannelInput{OciConfigID: cfg.ID, Region: "eu-frankfurt-1"})
probed, err := gw.ProbeChannel(ctx, ch.ID)
if err != nil || probed.ProbeStatus != tt.wantStatus {
t.Fatalf("ProbeChannel = %+v, %v, want %q", probed, err, tt.wantStatus)
}
})
}
}
// TestChannelModelTest 断言单模型试调:通过时写探测验证模型并翻转状态,失败不动。
func TestChannelModelTest(t *testing.T) {
client := &gatewayStubClient{fakeClient: &fakeClient{tenancy: oci.TenancyInfo{Name: "t"}}}
gw, svc := newTestGateway(t, client)
cfg := importAliveConfig(t, svc)
ch := seedChannel(t, gw, cfg.ID, "eu-frankfurt-1", 1, 1)
gw.db.Model(ch).Updates(map[string]any{"probe_status": "no_quota", "probe_error": "旧错误", "fail_count": 6})
ctx := context.Background()
if _, err := gw.TestChannelModel(ctx, ch.ID, "not.exists"); err == nil {
t.Error("缓存外模型应报错")
}
client.probeCode, client.probeErr = 403, stubServiceError{status: 403}
if _, err := gw.TestChannelModel(ctx, ch.ID, "meta.llama-3.3-70b-instruct"); err == nil {
t.Error("403 试调应报测试未通过")
}
var still model.AiChannel
gw.db.First(&still, ch.ID)
if still.ProbeStatus != "no_quota" || still.ProbeModel != "" {
t.Errorf("失败不应改动渠道: %+v", still)
}
client.probeCode, client.probeErr = 200, nil
fresh, err := gw.TestChannelModel(ctx, ch.ID, "meta.llama-3.3-70b-instruct")
if err != nil {
t.Fatalf("TestChannelModel: %v", err)
}
if fresh.ProbeModel != "meta.llama-3.3-70b-instruct" || fresh.ProbeStatus != "ok" ||
fresh.ProbeError != "" || fresh.FailCount != 0 {
t.Errorf("通过后应写验证模型并置可用: %+v", fresh)
}
// 已 ok 渠道再测另一模型:仅更新验证模型,不重写探测时间
cache2 := &model.AiModelCache{ChannelID: ch.ID, ModelOcid: "ocid1..m2", Name: "xai.grok-4", Vendor: "xai", SyncedAt: time.Now()}
gw.db.Create(cache2)
fresh2, err := gw.TestChannelModel(ctx, ch.ID, "xai.grok-4")
if err != nil || fresh2.ProbeModel != "xai.grok-4" {
t.Fatalf("已可用渠道更新验证模型: %+v, %v", fresh2, err)
}
}
func TestAiChatFinetuneSwitchesChannelWithoutPenalty(t *testing.T) { func TestAiChatFinetuneSwitchesChannelWithoutPenalty(t *testing.T) {
// 微调基座 400 换渠道重试成功,且不计入熔断失败 // 微调基座 400 换渠道重试成功,且不计入熔断失败
client := &gatewayStubClient{ client := &gatewayStubClient{
+452 -20
View File
@@ -22,50 +22,460 @@ func respRejectStateful(req aiwire.RespRequest) error {
return nil return nil
} }
// RespServerTools 报告工具列表是否含 xAI 服务端工具(web_search / x_search)。
func RespServerTools(tools []aiwire.RespTool) bool {
for _, t := range tools {
if t.Type == "web_search" || t.Type == "x_search" {
return true
}
}
return false
}
// RespPassthroughValidate 校验直通请求:模型必填,有状态特性不支持,工具类型 // RespPassthroughValidate 校验直通请求:模型必填,有状态特性不支持,工具类型
// 放行 function 与已实测的 web_search / x_search;流式仅在含服务端工具时拒绝 // 放行 function、Oracle 文档化的服务端工具(web_search / x_search /
// (工具流式事件形态未实测,不放开)。 // code_interpreter / mcp)与 codex 特有形态(namespace 工具分组、custom 自由
// 格式,上游不识别,转发前拍平/转换)。
func RespPassthroughValidate(req aiwire.RespRequest) error { func RespPassthroughValidate(req aiwire.RespRequest) error {
if strings.TrimSpace(req.Model) == "" { if strings.TrimSpace(req.Model) == "" {
return fmt.Errorf("model 不能为空") return fmt.Errorf("model 不能为空")
} }
if req.Stream && RespServerTools(req.Tools) {
return fmt.Errorf("服务端工具暂不支持流式:请去掉 stream 或改用 function 工具")
}
if err := respRejectStateful(req); err != nil { if err := respRejectStateful(req); err != nil {
return err return err
} }
for _, t := range req.Tools { for _, t := range req.Tools {
switch t.Type { switch t.Type {
case "function", "web_search", "x_search": case "function", "web_search", "x_search", "code_interpreter", "mcp", "namespace", "custom", "tool_search":
default: default:
return fmt.Errorf("不支持的工具类型 %q:服务端工具仅支持 web_search / x_search", t.Type) return fmt.Errorf("不支持的工具类型 %q:服务端工具仅支持 web_search / x_search / code_interpreter / mcp", t.Type)
} }
} }
return nil return nil
} }
// RespNsRef 一条拍平映射:限定名对应的原 namespace 与短名。codex 的回程路由
// 依赖 function_call 项上的 name+namespace 双字段,响应侧按此映射还原。
type RespNsRef struct {
Namespace string
Name string
}
// RespCompat 是直通请求 codex 兼容改写的结果:Flattened/Converted/Dropped 供
// 调用方记日志;NsRefs / CustomNames 非空表示响应侧需做工具调用项还原。
type RespCompat struct {
Flattened []string
Converted []string
Dropped []string
NsRefs map[string]RespNsRef
CustomNames map[string]struct{}
}
// NeedRestore 报告响应是否需要做工具调用项还原。
func (c RespCompat) NeedRestore() bool {
return len(c.NsRefs) > 0 || len(c.CustomNames) > 0
}
// RespPassthroughBody 以原始请求体为基构造上游 body:强制 store:false(禁上游 // RespPassthroughBody 以原始请求体为基构造上游 body:强制 store:false(禁上游
// 存态),stream 原样保留(流式直通);用 json.Number 保真未知字段与数值。 // 存态),stream 原样保留(流式直通);用 json.Number 保真未知字段与数值。
func RespPassthroughBody(raw []byte) ([]byte, error) { // 同时做 codex 兼容改写(namespace 拍平、多轮历史与 tool_choice 重限定)。
func RespPassthroughBody(raw []byte) ([]byte, RespCompat, error) {
dec := json.NewDecoder(strings.NewReader(string(raw))) dec := json.NewDecoder(strings.NewReader(string(raw)))
dec.UseNumber() dec.UseNumber()
var body map[string]any var body map[string]any
if err := dec.Decode(&body); err != nil { if err := dec.Decode(&body); err != nil {
return nil, fmt.Errorf("解析请求体: %w", err) return nil, RespCompat{}, fmt.Errorf("解析请求体: %w", err)
} }
body["store"] = false body["store"] = false
return json.Marshal(body) compat := respCompatTools(body)
respCompatInputCalls(body)
respCompatToolChoice(body)
out, err := json.Marshal(body)
return out, compat, err
}
// respCompatTools 对 tools 做 codex 兼容改写(上游实测行为见任务档案):
// namespace 工具组上游 422,拆平为限定名 function 工具;custom(自由格式)上游
// 同样 422,apply_patch 丢弃(grok 系未训练该补丁格式,失败编辑不如 shell 回退),
// 其余转 function 包装;web_search 的 external_web_access 参数上游 400,false 是
// "仅缓存检索"降权模式,按不越权原则连工具剥离,true 等价默认行为仅删键;
// 剔空后删 tools,并连删 tool_choice 与 parallel_tool_calls(上游拒绝无 tools
// 带 tool_choice)。
func respCompatTools(body map[string]any) RespCompat {
tools, ok := body["tools"].([]any)
if !ok {
return RespCompat{}
}
compat := RespCompat{NsRefs: map[string]RespNsRef{}, CustomNames: map[string]struct{}{}}
kept := make([]any, 0, len(tools))
for _, item := range tools {
tool, _ := item.(map[string]any)
switch {
case tool != nil && tool["type"] == "namespace":
ns, _ := tool["name"].(string)
compat.Flattened = append(compat.Flattened, "namespace:"+ns)
kept = append(kept, respFlattenNsTool(ns, tool, &compat)...)
continue
case tool != nil && tool["type"] == "custom":
name, _ := tool["name"].(string)
if name == "apply_patch" {
compat.Dropped = append(compat.Dropped, "custom:apply_patch")
continue
}
respConvertCustomTool(tool)
if name != "" {
compat.CustomNames[name] = struct{}{}
compat.Converted = append(compat.Converted, "custom:"+name)
}
kept = append(kept, tool)
continue
}
if desc, drop := respToolDrop(tool); drop {
compat.Dropped = append(compat.Dropped, desc)
continue
}
kept = append(kept, item)
}
if len(kept) == 0 {
delete(body, "tools")
delete(body, "tool_choice")
delete(body, "parallel_tool_calls")
} else {
body["tools"] = kept
}
return compat
}
// respConvertCustomTool 把 custom(自由格式)工具改写为 function:补 input 包装
// schema(custom 工具本无 parameters),模型以 {"input": 文本} 形态调用,响应侧
// 按 CustomNames 回转;custom 专有的 format(语法约束)字段一并移除。
func respConvertCustomTool(tool map[string]any) {
tool["type"] = "function"
delete(tool, "format")
if _, ok := tool["parameters"]; !ok {
tool["parameters"] = map[string]any{
"type": "object",
"properties": map[string]any{"input": map[string]any{"type": "string"}},
"required": []any{"input"},
}
}
}
// respFlattenNsTool 把 namespace 组内子工具上提为顶层工具:限定改名、缺
// parameters 补空 schema(上游必填),映射写入 NsRefs 供响应侧还原;非
// function 子工具(如 custom)上游同样不认,剥离并记录。
func respFlattenNsTool(ns string, tool map[string]any, compat *RespCompat) []any {
children, _ := tool["tools"].([]any)
out := make([]any, 0, len(children))
for _, c := range children {
child, _ := c.(map[string]any)
if child == nil {
continue
}
short, _ := child["name"].(string)
if t, _ := child["type"].(string); t != "" && t != "function" {
compat.Dropped = append(compat.Dropped, ns+"."+short+"(type="+t+")")
continue
}
qualified := respQualifyNsName(ns, short)
if qualified == "" {
continue
}
child["name"] = qualified
if _, ok := child["parameters"]; !ok {
child["parameters"] = map[string]any{"type": "object", "properties": map[string]any{}}
}
compat.NsRefs[qualified] = RespNsRef{Namespace: ns, Name: short}
out = append(out, child)
}
return out
}
// respQualifyNsName 生成拍平后的限定名,与响应侧还原互逆(对齐 CLIProxyAPI):
// mcp__ 开头的子工具名自带全局前缀不再限定;ns 以 __ 结尾直接拼接;已带前缀
// 不重复添加。
func respQualifyNsName(ns, name string) string {
ns, name = strings.TrimSpace(ns), strings.TrimSpace(name)
if ns == "" || name == "" || strings.HasPrefix(name, "mcp__") {
return name
}
prefix := ns
if !strings.HasSuffix(prefix, "__") {
prefix += "__"
}
if strings.HasPrefix(name, prefix) {
return name
}
return prefix + name
}
// respCompatInputCalls 改写多轮历史 input:function_call 的 namespace 字段重限定
// (上游不认识该字段);custom_tool_call / custom_tool_call_output 转换为上游
// 认识的 function_call(_output) 形态(上游 item 变体表不含 custom 系)。
func respCompatInputCalls(body map[string]any) {
input, _ := body["input"].([]any)
for _, it := range input {
item, _ := it.(map[string]any)
if item == nil {
continue
}
switch item["type"] {
case "function_call":
respQualifyCallField(item)
case "custom_tool_call":
item["type"] = "function_call"
item["arguments"] = respCustomCallArguments(item["input"])
delete(item, "input")
case "custom_tool_call_output":
item["type"] = "function_call_output"
item["output"] = respCustomCallOutput(item["output"])
}
}
}
// respCustomCallArguments 把 custom_tool_call 的 input 包装为 function_call 的
// arguments JSON 串(对齐 CLIProxyAPI):input 串本身是 JSON 对象则直用,普通
// 文本包一层 {"input": 文本};对象取序列化;缺失为 {}。与响应侧
// respUnwrapCustomInput 互逆,保证多轮往返无损。
func respCustomCallArguments(input any) string {
switch v := input.(type) {
case string:
trimmed := strings.TrimSpace(v)
var probe map[string]any
if json.Unmarshal([]byte(trimmed), &probe) == nil && probe != nil {
return trimmed
}
enc, err := json.Marshal(v)
if err != nil {
return "{}"
}
return `{"input":` + string(enc) + `}`
case nil:
return "{}"
default:
enc, err := json.Marshal(v)
if err != nil {
return "{}"
}
return string(enc)
}
}
// respCustomCallOutput 归一 output 为字符串:非字符串时序列化保底。
func respCustomCallOutput(output any) any {
if _, ok := output.(string); ok {
return output
}
if output == nil {
return ""
}
enc, err := json.Marshal(output)
if err != nil {
return ""
}
return string(enc)
}
// respCompatToolChoice 限定化对象形态的 tool_choice 及其 allowed_tools 列表
// (上游不认 tool_choice 上的 namespace 字段)。
func respCompatToolChoice(body map[string]any) {
tc, _ := body["tool_choice"].(map[string]any)
if tc == nil {
return
}
if tc["type"] == "function" {
respQualifyCallField(tc)
}
list, _ := tc["tools"].([]any)
for _, it := range list {
if sub, _ := it.(map[string]any); sub != nil && sub["type"] == "function" {
respQualifyCallField(sub)
}
}
}
// respQualifyCallField 把一个带 name/namespace 的对象改写为限定名形态。
func respQualifyCallField(m map[string]any) {
ns, _ := m["namespace"].(string)
if strings.TrimSpace(ns) == "" {
return
}
name, _ := m["name"].(string)
if q := respQualifyNsName(ns, name); q != "" {
m["name"] = q
}
delete(m, "namespace")
}
// respToolDrop 判定单个工具是否剥离。web_search 的 external_web_access 参数
// 上游 400:false 表示 OpenAI 的"仅缓存检索"降权模式,上游无对应能力,按不
// 越权原则整个工具剥离;true 等价上游默认行为,仅删键放行。tool_search(codex
// 的工具目录搜索)上游不识别,且 namespace 已全量拍平上送、搜索语义冗余,剥离。
func respToolDrop(tool map[string]any) (string, bool) {
if tool == nil {
return "", false
}
switch tool["type"] {
case "tool_search":
return "tool_search", true
case "web_search":
access, has := tool["external_web_access"]
if !has {
return "", false
}
delete(tool, "external_web_access")
if access == false {
return "web_search(external_web_access=false)", true
}
}
return "", false
}
// RespStreamUpgradeLimit 是流式直通的请求体安全上限。实测(2026-07,xai 面):
// 超过 ~82KB 的流式请求上游会在推理阶段掐断流(非流式不受影响,纯体积触发,
// 与工具构成无关),预留余量取 76KB;超限时网关改走非流式上游并合成 SSE。
const RespStreamUpgradeLimit = 76 * 1024
// RespDisableStream 把请求体的 stream 改为 false(流式升级回退用),其余字段
// 原样保留。
func RespDisableStream(body []byte) ([]byte, error) {
dec := json.NewDecoder(strings.NewReader(string(body)))
dec.UseNumber()
var m map[string]any
if err := dec.Decode(&m); err != nil {
return nil, fmt.Errorf("解析请求体: %w", err)
}
m["stream"] = false
return json.Marshal(m)
}
// RespSynthSSEEvents 把一份非流式响应合成为最小 SSE 事件序列:created →
// 每个输出项一条 output_item.done → completed。流式升级回退用,客户端拿到
// 完整事件语义但无增量;输出项与 usage 原样承载。
func RespSynthSSEEvents(payload []byte) ([][]byte, error) {
dec := json.NewDecoder(strings.NewReader(string(payload)))
dec.UseNumber()
var resp map[string]any
if err := dec.Decode(&resp); err != nil {
return nil, fmt.Errorf("解析上游响应: %w", err)
}
output, _ := resp["output"].([]any)
status, hadStatus := resp["status"]
resp["status"], resp["output"] = "in_progress", []any{}
created, err := json.Marshal(map[string]any{"type": "response.created", "response": resp})
if err != nil {
return nil, err
}
if hadStatus {
resp["status"] = status
} else {
delete(resp, "status")
}
resp["output"] = output
events := [][]byte{created}
for i, item := range output {
ev, err := json.Marshal(map[string]any{"type": "response.output_item.done", "output_index": i, "item": item})
if err != nil {
return nil, err
}
events = append(events, ev)
}
completed, err := json.Marshal(map[string]any{"type": "response.completed", "response": resp})
if err != nil {
return nil, err
}
return append(events, completed), nil
}
// RespRestoreToolCalls 非流式响应还原:output 数组中命中 NsRefs 的 function_call
// 把限定名还原为短名并补回 namespace 字段(codex 以该双字段路由);命中
// CustomNames 的回转 custom_tool_call(codex 期望 input 字段形态)。无需还原或
// 解析失败时返回原字节,不破坏直通。
func RespRestoreToolCalls(payload []byte, compat RespCompat) []byte {
if !compat.NeedRestore() {
return payload
}
dec := json.NewDecoder(strings.NewReader(string(payload)))
dec.UseNumber()
var body map[string]any
if dec.Decode(&body) != nil {
return payload
}
if !respRestoreOutput(body["output"], compat) {
return payload
}
out, err := json.Marshal(body)
if err != nil {
return payload
}
return out
}
// RespRestoreToolCallsEvent 流式单事件还原:处理事件顶层 item(output_item.*)
// 与 response.output(created/completed 等快照)。返回还原后数据与是否改动;
// 未改动时调用方转发原始行,保持字节级直通。
func RespRestoreToolCallsEvent(data []byte, compat RespCompat) ([]byte, bool) {
if !compat.NeedRestore() {
return data, false
}
dec := json.NewDecoder(strings.NewReader(string(data)))
dec.UseNumber()
var ev map[string]any
if dec.Decode(&ev) != nil {
return data, false
}
changed := respRestoreCallItem(ev["item"], compat)
if resp, _ := ev["response"].(map[string]any); resp != nil {
changed = respRestoreOutput(resp["output"], compat) || changed
}
if !changed {
return data, false
}
out, err := json.Marshal(ev)
if err != nil {
return data, false
}
return out, true
}
// respRestoreOutput 还原一个 output 数组,返回是否有改动。
func respRestoreOutput(v any, compat RespCompat) bool {
items, _ := v.([]any)
changed := false
for _, it := range items {
if respRestoreCallItem(it, compat) {
changed = true
}
}
return changed
}
// respRestoreCallItem 还原单个 function_call 项,返回是否改动。namespace 还原与
// custom 回转互斥:custom 工具不参与 namespace 拍平。
func respRestoreCallItem(v any, compat RespCompat) bool {
item, _ := v.(map[string]any)
if item == nil || item["type"] != "function_call" {
return false
}
name, _ := item["name"].(string)
if ref, ok := compat.NsRefs[name]; ok {
item["name"] = ref.Name
item["namespace"] = ref.Namespace
return true
}
if _, ok := compat.CustomNames[name]; ok {
item["type"] = "custom_tool_call"
item["input"] = respUnwrapCustomInput(item["arguments"])
delete(item, "arguments")
return true
}
return false
}
// respUnwrapCustomInput 解包 arguments:形如 {"input": 串} 取其 input(非串取该
// 值原文),其余情况整串返回。与请求侧 respCustomCallArguments 互逆。
func respUnwrapCustomInput(arguments any) string {
s, _ := arguments.(string)
var probe map[string]json.RawMessage
if json.Unmarshal([]byte(s), &probe) == nil {
if raw, ok := probe["input"]; ok {
var str string
if json.Unmarshal(raw, &str) == nil {
return str
}
return string(raw)
}
}
return s
} }
// RespPassthroughUsage 从直通响应提取用量;缺失时返回 nil(日志记零)。 // RespPassthroughUsage 从直通响应提取用量;缺失时返回 nil(日志记零)。
@@ -104,3 +514,25 @@ func RespStreamCompletedUsage(data []byte) *aiwire.Usage {
} }
return RespPassthroughUsage(ev.Response) return RespPassthroughUsage(ev.Response)
} }
// RespStreamErrorMsg 从一行 SSE data JSON 中提取 error / response.failed 事件的
// 错误消息;非错误事件返回空串。流式直通据此把上游错误写入调用日志。
func RespStreamErrorMsg(data []byte) string {
var ev respStreamEvent
if json.Unmarshal(data, &ev) != nil {
return ""
}
switch ev.Type {
case "error":
if ev.Message != "" {
return ev.Message
}
return "上游返回错误事件 error"
case "response.failed":
if m := respErrorMsg(ev.Response); m != "" {
return m
}
return "上游返回错误事件 response.failed"
}
return ""
}
+371 -25
View File
@@ -2,6 +2,7 @@ package service
import ( import (
"encoding/json" "encoding/json"
"slices"
"strings" "strings"
"testing" "testing"
@@ -24,27 +25,6 @@ func deref(p *int) int {
return *p return *p
} }
func TestRespServerTools(t *testing.T) {
tests := []struct {
name string
tools []aiwire.RespTool
want bool
}{
{"web_search", []aiwire.RespTool{{Type: "web_search"}}, true},
{"x_search混用", []aiwire.RespTool{{Type: "function", Name: "f"}, {Type: "x_search"}}, true},
{"仅function", []aiwire.RespTool{{Type: "function", Name: "f"}}, false},
{"空", nil, false},
{"其他类型", []aiwire.RespTool{{Type: "code_interpreter"}}, false},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if got := RespServerTools(test.tools); got != test.want {
t.Fatalf("got %v, want %v", got, test.want)
}
})
}
}
func TestRespPassthroughValidate(t *testing.T) { func TestRespPassthroughValidate(t *testing.T) {
prev := "resp_1" prev := "resp_1"
bg := true bg := true
@@ -56,12 +36,17 @@ func TestRespPassthroughValidate(t *testing.T) {
{"合法", aiwire.RespRequest{Model: "m", Tools: []aiwire.RespTool{{Type: "web_search"}}}, false}, {"合法", aiwire.RespRequest{Model: "m", Tools: []aiwire.RespTool{{Type: "web_search"}}}, false},
{"混用function", aiwire.RespRequest{Model: "m", Tools: []aiwire.RespTool{{Type: "web_search"}, {Type: "function", Name: "f"}}}, false}, {"混用function", aiwire.RespRequest{Model: "m", Tools: []aiwire.RespTool{{Type: "web_search"}, {Type: "function", Name: "f"}}}, false},
{"缺model", aiwire.RespRequest{Tools: []aiwire.RespTool{{Type: "web_search"}}}, true}, {"缺model", aiwire.RespRequest{Tools: []aiwire.RespTool{{Type: "web_search"}}}, true},
{"工具流式拒绝", aiwire.RespRequest{Model: "m", Stream: true, Tools: []aiwire.RespTool{{Type: "web_search"}}}, true}, {"服务端工具流式放行", aiwire.RespRequest{Model: "m", Stream: true, Tools: []aiwire.RespTool{{Type: "web_search"}}}, false},
{"无工具流式放行", aiwire.RespRequest{Model: "m", Stream: true}, false}, {"无工具流式放行", aiwire.RespRequest{Model: "m", Stream: true}, false},
{"function工具流式放行", aiwire.RespRequest{Model: "m", Stream: true, Tools: []aiwire.RespTool{{Type: "function", Name: "f"}}}, false}, {"function工具流式放行", aiwire.RespRequest{Model: "m", Stream: true, Tools: []aiwire.RespTool{{Type: "function", Name: "f"}}}, false},
{"code_interpreter放行", aiwire.RespRequest{Model: "m", Tools: []aiwire.RespTool{{Type: "code_interpreter"}}}, false},
{"mcp流式放行", aiwire.RespRequest{Model: "m", Stream: true, Tools: []aiwire.RespTool{{Type: "mcp"}}}, false},
{"有状态拒绝", aiwire.RespRequest{Model: "m", PreviousResponseID: prev}, true}, {"有状态拒绝", aiwire.RespRequest{Model: "m", PreviousResponseID: prev}, true},
{"background拒绝", aiwire.RespRequest{Model: "m", Background: &bg}, true}, {"background拒绝", aiwire.RespRequest{Model: "m", Background: &bg}, true},
{"未知工具拒绝", aiwire.RespRequest{Model: "m", Tools: []aiwire.RespTool{{Type: "web_search"}, {Type: "mcp"}}}, true}, {"未知工具拒绝", aiwire.RespRequest{Model: "m", Tools: []aiwire.RespTool{{Type: "web_search"}, {Type: "file_search"}}}, true},
{"namespace放行", aiwire.RespRequest{Model: "m", Tools: []aiwire.RespTool{{Type: "namespace", Name: "multi_agent_v1"}}}, false},
{"custom放行", aiwire.RespRequest{Model: "m", Tools: []aiwire.RespTool{{Type: "custom", Name: "run_script"}}}, false},
{"tool_search放行", aiwire.RespRequest{Model: "m", Tools: []aiwire.RespTool{{Type: "tool_search"}}}, false},
} }
for _, test := range tests { for _, test := range tests {
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
@@ -75,10 +60,13 @@ func TestRespPassthroughValidate(t *testing.T) {
func TestRespPassthroughBody(t *testing.T) { func TestRespPassthroughBody(t *testing.T) {
raw := []byte(`{"model":"m","input":"hi","stream":true,"store":true,"max_output_tokens":128,"custom_field":{"a":1.5}}`) raw := []byte(`{"model":"m","input":"hi","stream":true,"store":true,"max_output_tokens":128,"custom_field":{"a":1.5}}`)
out, err := RespPassthroughBody(raw) out, compat, err := RespPassthroughBody(raw)
if err != nil { if err != nil {
t.Fatalf("RespPassthroughBody: %v", err) t.Fatalf("RespPassthroughBody: %v", err)
} }
if len(compat.Dropped) != 0 || len(compat.Flattened) != 0 || len(compat.NsRefs) != 0 {
t.Errorf("无 codex 工具不应有兼容改写: %+v", compat)
}
var body map[string]any var body map[string]any
if err := json.Unmarshal(out, &body); err != nil { if err := json.Unmarshal(out, &body); err != nil {
t.Fatalf("unmarshal out: %v", err) t.Fatalf("unmarshal out: %v", err)
@@ -95,11 +83,206 @@ func TestRespPassthroughBody(t *testing.T) {
if !strings.Contains(string(out), `"custom_field"`) { if !strings.Contains(string(out), `"custom_field"`) {
t.Errorf("未知字段应保留: %s", out) t.Errorf("未知字段应保留: %s", out)
} }
if _, err := RespPassthroughBody([]byte("not-json")); err == nil { if _, _, err := RespPassthroughBody([]byte("not-json")); err == nil {
t.Error("非法 JSON 应报错") t.Error("非法 JSON 应报错")
} }
} }
// TestRespQualifyNsName 断言限定名生成规则与 CLIProxyAPI 对齐。
func TestRespQualifyNsName(t *testing.T) {
tests := []struct{ name, ns, tool, want string }{
{"常规拼接", "multi_agent_v1", "spawn_agent", "multi_agent_v1__spawn_agent"},
{"mcp子工具不加前缀", "mcp__sites", "mcp__sites__create_site", "mcp__sites__create_site"},
{"ns以双下划线结尾", "codex_app__", "update", "codex_app__update"},
{"已带前缀不重复", "ns1", "ns1__tool", "ns1__tool"},
{"空ns原样", "", "tool", "tool"},
{"空名返回空", "ns1", "", ""},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if got := respQualifyNsName(test.ns, test.tool); got != test.want {
t.Fatalf("respQualifyNsName(%q,%q) = %q, want %q", test.ns, test.tool, got, test.want)
}
})
}
}
// TestRespPassthroughBodyCompatTools 断言 codex 工具兼容改写:namespace 拍平为
// 限定名 function 并建映射,web_search 降权剥离,剔空连删 tool_choice。
func TestRespPassthroughBodyCompatTools(t *testing.T) {
tests := []struct {
name string
raw string
wantFlattened []string
wantDropped []string
wantRefs map[string]RespNsRef
wantContains []string
wantAbsent []string
}{
{
"namespace拍平保留function",
`{"model":"m","tools":[{"type":"function","name":"exec"},{"type":"namespace","name":"multi_agent_v1","tools":[{"type":"function","name":"spawn_agent","parameters":{"type":"object"}}]}]}`,
[]string{"namespace:multi_agent_v1"},
nil,
map[string]RespNsRef{"multi_agent_v1__spawn_agent": {Namespace: "multi_agent_v1", Name: "spawn_agent"}},
[]string{`"name":"multi_agent_v1__spawn_agent"`, `"name":"exec"`},
[]string{`"type":"namespace"`},
},
{
"mcp子工具保名并补parameters",
`{"model":"m","tools":[{"type":"namespace","name":"mcp__sites","tools":[{"type":"function","name":"mcp__sites__create"}]}]}`,
[]string{"namespace:mcp__sites"},
nil,
map[string]RespNsRef{"mcp__sites__create": {Namespace: "mcp__sites", Name: "mcp__sites__create"}},
[]string{`"name":"mcp__sites__create"`, `"parameters":{"properties":{},"type":"object"}`},
[]string{`"type":"namespace"`},
},
{
"非function子工具剥离",
`{"model":"m","tools":[{"type":"namespace","name":"ns1","tools":[{"type":"custom","name":"patch"},{"type":"function","name":"run"}]}]}`,
[]string{"namespace:ns1"},
[]string{"ns1.patch(type=custom)"},
map[string]RespNsRef{"ns1__run": {Namespace: "ns1", Name: "run"}},
[]string{`"name":"ns1__run"`},
[]string{"patch"},
},
{
"剔空连删tool_choice",
`{"model":"m","tool_choice":"auto","parallel_tool_calls":false,"tools":[{"type":"web_search","external_web_access":false}]}`,
nil,
[]string{"web_search(external_web_access=false)"},
nil,
nil,
[]string{`"tools"`, `"tool_choice"`, `"parallel_tool_calls"`},
},
{
"web_search全访问仅删键",
`{"model":"m","tools":[{"type":"web_search","external_web_access":true}]}`,
nil,
nil,
nil,
[]string{`"tools":[{"type":"web_search"}]`},
[]string{"external_web_access"},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
out, compat, err := RespPassthroughBody([]byte(test.raw))
if err != nil {
t.Fatalf("RespPassthroughBody: %v", err)
}
if !slices.Equal(compat.Flattened, test.wantFlattened) {
t.Errorf("Flattened = %v, want %v", compat.Flattened, test.wantFlattened)
}
if !slices.Equal(compat.Dropped, test.wantDropped) {
t.Errorf("Dropped = %v, want %v", compat.Dropped, test.wantDropped)
}
for q, ref := range test.wantRefs {
if compat.NsRefs[q] != ref {
t.Errorf("NsRefs[%s] = %+v, want %+v", q, compat.NsRefs[q], ref)
}
}
for _, s := range test.wantContains {
if !strings.Contains(string(out), s) {
t.Errorf("应包含 %s: %s", s, out)
}
}
for _, s := range test.wantAbsent {
if strings.Contains(string(out), s) {
t.Errorf("不应包含 %s: %s", s, out)
}
}
})
}
}
// TestRespCompatHistoryAndToolChoice 断言多轮历史 function_call 与对象 tool_choice
// 的 namespace 字段被重限定并删除。
func TestRespCompatHistoryAndToolChoice(t *testing.T) {
raw := `{"model":"m",
"tool_choice":{"type":"function","name":"spawn_agent","namespace":"multi_agent_v1"},
"input":[
{"type":"function_call","name":"spawn_agent","namespace":"multi_agent_v1","call_id":"c1","arguments":"{}"},
{"type":"function_call","name":"exec","call_id":"c2","arguments":"{}"},
{"type":"function_call_output","call_id":"c1","output":"ok"}
],
"tools":[{"type":"namespace","name":"multi_agent_v1","tools":[{"type":"function","name":"spawn_agent","parameters":{}}]}]}`
out, _, err := RespPassthroughBody([]byte(raw))
if err != nil {
t.Fatalf("RespPassthroughBody: %v", err)
}
s := string(out)
if !strings.Contains(s, `"tool_choice":{"name":"multi_agent_v1__spawn_agent","type":"function"}`) {
t.Errorf("tool_choice 应限定化: %s", s)
}
if strings.Contains(s, `"namespace":"multi_agent_v1"`) {
t.Errorf("namespace 字段应全部删除: %s", s)
}
if !strings.Contains(s, `"name":"exec"`) {
t.Errorf("无 namespace 的历史项应原样: %s", s)
}
if c := strings.Count(s, "multi_agent_v1__spawn_agent"); c != 3 {
t.Errorf("限定名应出现 3 次(tools/input/tool_choice), got %d: %s", c, s)
}
}
// TestRespRestoreNamespace 断言非流式响应把限定名还原为短名+namespace 双字段。
func TestRespRestoreNamespace(t *testing.T) {
compat := RespCompat{NsRefs: map[string]RespNsRef{"multi_agent_v1__spawn_agent": {Namespace: "multi_agent_v1", Name: "spawn_agent"}}}
payload := []byte(`{"id":"r1","output":[{"type":"function_call","name":"multi_agent_v1__spawn_agent","call_id":"c1","arguments":"{}"},{"type":"message","content":[]}],"usage":{"total_tokens":7}}`)
out := RespRestoreToolCalls(payload, compat)
s := string(out)
if !strings.Contains(s, `"name":"spawn_agent"`) || !strings.Contains(s, `"namespace":"multi_agent_v1"`) {
t.Errorf("应还原短名并补 namespace: %s", s)
}
if !strings.Contains(s, `"total_tokens":7`) {
t.Errorf("其余字段应保真: %s", s)
}
for name, payload := range map[string][]byte{
"未命中原样": []byte(`{"output":[{"type":"function_call","name":"other","call_id":"c"}]}`),
"非法JSON": []byte(`xx`),
} {
if got := RespRestoreToolCalls(payload, compat); string(got) != string(payload) {
t.Errorf("%s: 应返回原字节, got %s", name, got)
}
}
if got := RespRestoreToolCalls(payload, RespCompat{}); string(got) != string(payload) {
t.Error("无需还原时应返回原字节")
}
}
// TestRespRestoreNamespaceEvent 断言流式事件还原覆盖 item 与 response.output
// 两个位置,无关事件保持未改动。
func TestRespRestoreNamespaceEvent(t *testing.T) {
compat := RespCompat{NsRefs: map[string]RespNsRef{"ns1__run": {Namespace: "ns1", Name: "run"}}}
tests := []struct {
name string
data string
wantChanged bool
wantSub string
}{
{"output_item.done", `{"type":"response.output_item.done","item":{"type":"function_call","name":"ns1__run","call_id":"c1"}}`, true, `"namespace":"ns1"`},
{"completed快照", `{"type":"response.completed","response":{"output":[{"type":"function_call","name":"ns1__run"}],"usage":{"total_tokens":1}}}`, true, `"name":"run"`},
{"文本增量不动", `{"type":"response.output_text.delta","delta":"hi"}`, false, ""},
{"未命中不动", `{"type":"response.output_item.done","item":{"type":"function_call","name":"exec"}}`, false, ""},
{"非法JSON不动", `not-json`, false, ""},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
out, changed := RespRestoreToolCallsEvent([]byte(test.data), compat)
if changed != test.wantChanged {
t.Fatalf("changed = %v, want %v", changed, test.wantChanged)
}
if !changed && string(out) != test.data {
t.Fatalf("未改动应返回原字节: %s", out)
}
if test.wantSub != "" && !strings.Contains(string(out), test.wantSub) {
t.Fatalf("应包含 %s: %s", test.wantSub, out)
}
})
}
}
func TestRespPassthroughUsage(t *testing.T) { func TestRespPassthroughUsage(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
@@ -145,3 +328,166 @@ func TestRespStreamCompletedUsage(t *testing.T) {
} }
} }
} }
// TestRespDisableStream 断言流式升级回退把 stream 置 false 且其余字段保留。
func TestRespDisableStream(t *testing.T) {
out, err := RespDisableStream([]byte(`{"model":"m","stream":true,"max_output_tokens":64}`))
if err != nil {
t.Fatalf("RespDisableStream: %v", err)
}
if !strings.Contains(string(out), `"stream":false`) || !strings.Contains(string(out), `"max_output_tokens":64`) {
t.Fatalf("字段不符: %s", out)
}
if _, err := RespDisableStream([]byte("x")); err == nil {
t.Error("非法 JSON 应报错")
}
}
// TestRespSynthSSEEvents 断言合成事件序列:created(in_progress,空 output)→
// 逐项 output_item.done → completed(完整响应)。
func TestRespSynthSSEEvents(t *testing.T) {
payload := []byte(`{"id":"r1","status":"completed","output":[{"type":"reasoning","summary":[]},{"type":"function_call","name":"run","call_id":"c1"}],"usage":{"total_tokens":9}}`)
events, err := RespSynthSSEEvents(payload)
if err != nil {
t.Fatalf("RespSynthSSEEvents: %v", err)
}
if len(events) != 4 {
t.Fatalf("事件数 = %d, want 4", len(events))
}
first := string(events[0])
if !strings.Contains(first, `"type":"response.created"`) || !strings.Contains(first, `"status":"in_progress"`) || !strings.Contains(first, `"output":[]`) {
t.Errorf("created 事件不符: %s", first)
}
if !strings.Contains(string(events[1]), `"type":"response.output_item.done"`) || !strings.Contains(string(events[1]), `"output_index":0`) {
t.Errorf("item.done 事件不符: %s", events[1])
}
if !strings.Contains(string(events[2]), `"name":"run"`) {
t.Errorf("第二项应为 function_call: %s", events[2])
}
last := string(events[3])
if !strings.Contains(last, `"type":"response.completed"`) || !strings.Contains(last, `"status":"completed"`) ||
!strings.Contains(last, `"total_tokens":9`) || !strings.Contains(last, `"name":"run"`) {
t.Errorf("completed 事件不符: %s", last)
}
if _, err := RespSynthSSEEvents([]byte("x")); err == nil {
t.Error("非法 JSON 应报错")
}
}
// TestRespCompatCustomTools 断言 custom 工具转换:apply_patch 丢弃,其余转
// function 并补 input 包装 schema、记入 CustomNames;format 字段移除。
func TestRespCompatCustomTools(t *testing.T) {
raw := `{"model":"m","tools":[
{"type":"custom","name":"apply_patch","description":"edit files"},
{"type":"custom","name":"run_script","description":"run it","format":{"type":"grammar"}},
{"type":"function","name":"exec","parameters":{}}]}`
out, compat, err := RespPassthroughBody([]byte(raw))
if err != nil {
t.Fatalf("RespPassthroughBody: %v", err)
}
if !slices.Equal(compat.Dropped, []string{"custom:apply_patch"}) {
t.Errorf("Dropped = %v", compat.Dropped)
}
if !slices.Equal(compat.Converted, []string{"custom:run_script"}) {
t.Errorf("Converted = %v", compat.Converted)
}
if _, ok := compat.CustomNames["run_script"]; !ok {
t.Errorf("CustomNames 缺 run_script: %v", compat.CustomNames)
}
s := string(out)
if strings.Contains(s, "apply_patch") || strings.Contains(s, `"type":"custom"`) || strings.Contains(s, "grammar") {
t.Errorf("apply_patch/custom/format 应消失: %s", s)
}
if !strings.Contains(s, `"required":["input"]`) || !strings.Contains(s, `"input":{"type":"string"}`) {
t.Errorf("run_script 应补 input 包装 schema: %s", s)
}
}
// TestRespCompatCustomHistory 断言 input 历史的 custom_tool_call(_output) 转换
// 与 arguments 包装三分支。
func TestRespCompatCustomHistory(t *testing.T) {
raw := `{"model":"m","input":[
{"type":"custom_tool_call","call_id":"c1","name":"run_script","input":"plain text"},
{"type":"custom_tool_call","call_id":"c2","name":"run_script","input":"{\"a\":1}"},
{"type":"custom_tool_call","call_id":"c3","name":"run_script"},
{"type":"custom_tool_call_output","call_id":"c1","output":"done"},
{"type":"custom_tool_call_output","call_id":"c2","output":{"ok":true}}]}`
out, _, err := RespPassthroughBody([]byte(raw))
if err != nil {
t.Fatalf("RespPassthroughBody: %v", err)
}
s := string(out)
if strings.Contains(s, "custom_tool_call") {
t.Fatalf("custom_tool_call 系应全部转换: %s", s)
}
for _, want := range []string{
`"arguments":"{\"input\":\"plain text\"}"`,
`"arguments":"{\"a\":1}"`,
`"arguments":"{}"`,
`"output":"done"`,
`"output":"{\"ok\":true}"`,
} {
if !strings.Contains(s, want) {
t.Errorf("应包含 %s: %s", want, s)
}
}
}
// TestRespRestoreCustomToolCalls 断言响应侧回转:命中 CustomNames 的
// function_call 变 custom_tool_call 且 input 解包;流式事件同样生效。
func TestRespRestoreCustomToolCalls(t *testing.T) {
compat := RespCompat{CustomNames: map[string]struct{}{"run_script": {}}}
payload := []byte(`{"output":[{"type":"function_call","name":"run_script","call_id":"c1","arguments":"{\"input\":\"echo hi\"}"},{"type":"function_call","name":"exec","call_id":"c2","arguments":"{}"}]}`)
s := string(RespRestoreToolCalls(payload, compat))
if !strings.Contains(s, `"type":"custom_tool_call"`) || !strings.Contains(s, `"input":"echo hi"`) {
t.Errorf("应回转 custom_tool_call 并解包 input: %s", s)
}
if strings.Contains(s, `"arguments":"{\"input\":\"echo hi\"}"`) {
t.Errorf("arguments 应删除: %s", s)
}
if !strings.Contains(s, `"name":"exec"`) || strings.Count(s, "custom_tool_call") != 1 {
t.Errorf("非转换名不应动: %s", s)
}
ev := []byte(`{"type":"response.output_item.done","item":{"type":"function_call","name":"run_script","arguments":"not-json"}}`)
got, changed := RespRestoreToolCallsEvent(ev, compat)
if !changed || !strings.Contains(string(got), `"input":"not-json"`) {
t.Errorf("非 JSON arguments 应整串作 input: %s", got)
}
}
// TestRespUnwrapCustomInput 断言解包分支:input 键取值、非串取原文、其余整串。
func TestRespUnwrapCustomInput(t *testing.T) {
tests := []struct {
name string
args any
want string
}{
{"包装取input", `{"input":"hello"}`, "hello"},
{"input非串取原文", `{"input":{"x":1}}`, `{"x":1}`},
{"无input键整串", `{"cmd":"ls"}`, `{"cmd":"ls"}`},
{"非JSON整串", "raw text", "raw text"},
{"非串类型空串", 42, ""},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if got := respUnwrapCustomInput(test.args); got != test.want {
t.Fatalf("respUnwrapCustomInput(%v) = %q, want %q", test.args, got, test.want)
}
})
}
}
// TestRespCompatToolSearchDrop 断言 tool_search 剥离(拍平后语义冗余,上游不识别)。
func TestRespCompatToolSearchDrop(t *testing.T) {
raw := `{"model":"m","tools":[{"type":"tool_search"},{"type":"function","name":"exec"}]}`
out, compat, err := RespPassthroughBody([]byte(raw))
if err != nil {
t.Fatalf("RespPassthroughBody: %v", err)
}
if !slices.Equal(compat.Dropped, []string{"tool_search"}) {
t.Errorf("Dropped = %v", compat.Dropped)
}
if strings.Contains(string(out), "tool_search") || !strings.Contains(string(out), `"name":"exec"`) {
t.Errorf("tool_search 应剥离且 function 保留: %s", out)
}
}
+124 -6
View File
@@ -258,7 +258,7 @@ type AnthEvent struct {
// AnthRespBridge 把直通 SSE 事件流桥接为 Anthropic 事件序列: // AnthRespBridge 把直通 SSE 事件流桥接为 Anthropic 事件序列:
// message_start → content_block_start/delta/stop(text 与 tool_use 分块)→ message_delta → message_stop。 // message_start → content_block_start/delta/stop(text 与 tool_use 分块)→ message_delta → message_stop。
// reasoning 系列事件丢弃。 // reasoning 系列事件丢弃;上游 error / response.failed 转 Anthropic error 事件透传
type AnthRespBridge struct { type AnthRespBridge struct {
id, model string id, model string
started bool started bool
@@ -267,6 +267,11 @@ type AnthRespBridge struct {
blockIndex int blockIndex int
stopReason string stopReason string
usage aiwire.AnthUsage usage aiwire.AnthUsage
// sawTerminal 标记收到过终态事件(completed/incomplete/failed);
// 上游流提前 EOF 时据此发 error 事件而非伪装正常结束
sawTerminal bool
// errMsg 记录上游错误消息,非空即本流已失败(供调用日志)
errMsg string
} }
// NewAnthRespBridge 构造桥;id 为响应消息 ID。 // NewAnthRespBridge 构造桥;id 为响应消息 ID。
@@ -278,6 +283,7 @@ func NewAnthRespBridge(id, model string) *AnthRespBridge {
type respStreamEvent struct { type respStreamEvent struct {
Type string `json:"type"` Type string `json:"type"`
Delta string `json:"delta"` Delta string `json:"delta"`
Message string `json:"message"`
Item *respOutputItem `json:"item"` Item *respOutputItem `json:"item"`
Response *respPayload `json:"response"` Response *respPayload `json:"response"`
} }
@@ -288,27 +294,130 @@ func (st *AnthRespBridge) Feed(data []byte) []AnthEvent {
if json.Unmarshal(data, &ev) != nil { if json.Unmarshal(data, &ev) != nil {
return nil return nil
} }
var events []AnthEvent if ev.Type == "error" || ev.Type == "response.failed" {
if !st.started { return st.failWith(ev)
st.started = true
events = append(events, st.startEvent())
} }
// message_start 延迟到首个可见输出事件:created / reasoning 阶段不向客户端
// 写任何字节,上游此段断流时 handler 才有降级非流式重做的无感窗口
var events []AnthEvent
switch ev.Type { switch ev.Type {
case "response.output_item.added": case "response.output_item.added":
if ev.Item != nil && ev.Item.Type == "function_call" { if ev.Item != nil && ev.Item.Type == "function_call" {
events = append(events, st.ensureStarted()...)
events = append(events, st.openBlock(true, ev.Item.CallID, ev.Item.Name)...) events = append(events, st.openBlock(true, ev.Item.CallID, ev.Item.Name)...)
st.stopReason = "tool_use" st.stopReason = "tool_use"
} }
case "response.output_text.delta": case "response.output_text.delta":
events = append(events, st.ensureStarted()...)
events = append(events, st.textDelta(ev.Delta)...) events = append(events, st.textDelta(ev.Delta)...)
case "response.function_call_arguments.delta": case "response.function_call_arguments.delta":
events = append(events, st.argsDelta(ev.Delta)...) events = append(events, st.argsDelta(ev.Delta)...)
case "response.completed", "response.incomplete", "response.failed": case "response.completed", "response.incomplete":
st.sawTerminal = true
st.finishFrom(ev.Response) st.finishFrom(ev.Response)
} }
return events return events
} }
// ensureStarted 在首个可见输出事件前补发 message_start(仅一次)。
func (st *AnthRespBridge) ensureStarted() []AnthEvent {
if st.started {
return nil
}
st.started = true
return []AnthEvent{st.startEvent()}
}
// failWith 记录上游错误并产出 Anthropic error 事件(每流至多一次)。
func (st *AnthRespBridge) failWith(ev respStreamEvent) []AnthEvent {
if st.errMsg != "" {
return nil
}
st.sawTerminal = true
msg := ev.Message
if ev.Type == "response.failed" {
st.finishFrom(ev.Response)
if m := respErrorMsg(ev.Response); m != "" {
msg = m
}
}
if msg == "" {
msg = "上游返回错误事件 " + ev.Type
}
st.errMsg = msg
return []AnthEvent{st.errorEvent()}
}
// respErrorMsg 提取 response.failed 载荷中的错误消息。
func respErrorMsg(resp *respPayload) string {
if resp == nil || resp.Error == nil {
return ""
}
return (*resp.Error)["message"]
}
// errorEvent 按 Anthropic 流式协议产出 error 事件。
func (st *AnthRespBridge) errorEvent() AnthEvent {
return AnthEvent{Event: "error", Data: map[string]any{
"type": "error",
"error": map[string]string{"type": "api_error", "message": st.errMsg},
}}
}
// Err 返回上游错误消息;空串表示流正常(供调用日志)。
func (st *AnthRespBridge) Err() string { return st.errMsg }
// SawTerminal 报告是否收到过终态事件;false 即上游流提前终止。
func (st *AnthRespBridge) SawTerminal() bool { return st.sawTerminal }
// AnthMessageEvents 把完整 Messages 响应展开为标准事件序列,
// 供流式上游断流后的非流式降级结果推送(客户端协议不变)。
func AnthMessageEvents(m *aiwire.MessagesResponse) []AnthEvent {
events := []AnthEvent{{Event: "message_start", Data: map[string]any{
"type": "message_start",
"message": map[string]any{
"id": m.ID, "type": "message", "role": m.Role, "model": m.Model,
"content": []any{}, "stop_reason": nil,
"usage": map[string]int{"input_tokens": 0, "output_tokens": 0},
},
}}}
for i, b := range m.Content {
events = append(events, anthBlockEvents(i, b)...)
}
usage := map[string]int{"input_tokens": m.Usage.InputTokens, "output_tokens": m.Usage.OutputTokens}
if m.Usage.CacheReadInputTokens > 0 {
usage["cache_read_input_tokens"] = m.Usage.CacheReadInputTokens
}
events = append(events,
AnthEvent{Event: "message_delta", Data: map[string]any{
"type": "message_delta",
"delta": map[string]any{"stop_reason": m.StopReason, "stop_sequence": nil},
"usage": usage,
}},
AnthEvent{Event: "message_stop", Data: map[string]any{"type": "message_stop"}})
return events
}
// anthBlockEvents 把一个内容块展开为 start / delta / stop 三事件。
func anthBlockEvents(index int, b aiwire.AnthBlock) []AnthEvent {
var start, delta map[string]any
if b.Type == "tool_use" {
start = map[string]any{"type": "tool_use", "id": b.ID, "name": b.Name, "input": map[string]any{}}
delta = map[string]any{"type": "input_json_delta", "partial_json": string(b.Input)}
} else {
start = map[string]any{"type": "text", "text": ""}
delta = map[string]any{"type": "text_delta", "text": b.Text}
}
return []AnthEvent{
{Event: "content_block_start", Data: map[string]any{
"type": "content_block_start", "index": index, "content_block": start}},
{Event: "content_block_delta", Data: map[string]any{
"type": "content_block_delta", "index": index, "delta": delta}},
{Event: "content_block_stop", Data: map[string]any{
"type": "content_block_stop", "index": index}},
}
}
func (st *AnthRespBridge) textDelta(delta string) []AnthEvent { func (st *AnthRespBridge) textDelta(delta string) []AnthEvent {
var events []AnthEvent var events []AnthEvent
if !st.blockOpen || st.blockIsTool { if !st.blockOpen || st.blockIsTool {
@@ -378,7 +487,16 @@ func (st *AnthRespBridge) closeBlockEvent() AnthEvent {
} }
// Finish 在上游流结束后收尾:关块 → message_delta(stop_reason+usage)→ message_stop。 // Finish 在上游流结束后收尾:关块 → message_delta(stop_reason+usage)→ message_stop。
// 已发过 error 事件的流不再补终态;未见终态事件即 EOF 视为上游提前终止,
// 发 error 事件而非伪装正常结束(否则客户端拿到"成功的空消息")。
func (st *AnthRespBridge) Finish() []AnthEvent { func (st *AnthRespBridge) Finish() []AnthEvent {
if st.errMsg != "" {
return nil
}
if !st.sawTerminal {
st.errMsg = "上游流提前终止,未返回终态事件"
return []AnthEvent{st.errorEvent()}
}
var events []AnthEvent var events []AnthEvent
if !st.started { if !st.started {
st.started = true st.started = true
+100 -5
View File
@@ -164,10 +164,105 @@ func TestAnthRespBridge(t *testing.T) {
} }
} }
// TestAnthRespBridgeEmpty 断言空流也产出完整事件骨架。 // TestAnthRespBridgeFailure 断言异常流的错误透传:上游 error / response.failed
func TestAnthRespBridgeEmpty(t *testing.T) { // 事件转 Anthropic error 事件,提前 EOF(未见终态)不再伪装正常结束。
st := NewAnthRespBridge("msg_1", "m1") func TestAnthRespBridgeFailure(t *testing.T) {
if got := bridgeEventTypes(st.Finish()); got != "message_start,message_delta,message_stop" { cases := []struct {
t.Errorf("空流事件序列 = %s", got) name string
lines []string
wantKinds string
wantErr string
}{
{
name: "上游 error 事件透传",
lines: []string{`{"type":"error","message":"model overloaded"}`},
wantKinds: "error",
wantErr: "model overloaded",
},
{
name: "response.failed 提取错误消息",
lines: []string{
`{"type":"response.output_text.delta","delta":"你"}`,
`{"type":"response.failed","response":{"status":"failed","error":{"message":"content filtered"}}}`,
},
wantKinds: "message_start,content_block_start,content_block_delta,error",
wantErr: "content filtered",
},
{
name: "空流提前终止",
lines: nil,
wantKinds: "error",
wantErr: "上游流提前终止,未返回终态事件",
},
{
name: "输出中途 EOF 无终态",
lines: []string{
`{"type":"response.output_text.delta","delta":"你"}`,
},
wantKinds: "message_start,content_block_start,content_block_delta,error",
wantErr: "上游流提前终止,未返回终态事件",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
st := NewAnthRespBridge("msg_1", "m1")
var events []AnthEvent
for _, l := range tc.lines {
events = append(events, st.Feed([]byte(l))...)
}
events = append(events, st.Finish()...)
if got := bridgeEventTypes(events); got != tc.wantKinds {
t.Fatalf("事件序列 = %s, want %s", got, tc.wantKinds)
}
if st.Err() != tc.wantErr {
t.Fatalf("Err() = %q, want %q", st.Err(), tc.wantErr)
}
})
}
}
// TestRespStreamErrorMsg 断言直通流错误事件消息提取。
func TestRespStreamErrorMsg(t *testing.T) {
cases := []struct {
name string
data string
want string
}{
{name: "error 事件", data: `{"type":"error","message":"boom"}`, want: "boom"},
{name: "error 无消息用占位", data: `{"type":"error"}`, want: "上游返回错误事件 error"},
{name: "failed 事件", data: `{"type":"response.failed","response":{"error":{"message":"bad"}}}`, want: "bad"},
{name: "正常事件返回空", data: `{"type":"response.completed","response":{}}`, want: ""},
{name: "非 JSON 返回空", data: `<html>`, want: ""},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := RespStreamErrorMsg([]byte(tc.data)); got != tc.want {
t.Fatalf("RespStreamErrorMsg = %q, want %q", got, tc.want)
}
})
}
}
// TestAnthMessageEvents 断言非流式降级结果展开的事件序列与 usage。
func TestAnthMessageEvents(t *testing.T) {
msg := &aiwire.MessagesResponse{
ID: "msg_1", Type: "message", Role: "assistant", Model: "m1",
Content: []aiwire.AnthBlock{
{Type: "text", Text: "好"},
{Type: "tool_use", ID: "c1", Name: "f", Input: json.RawMessage(`{"a":1}`)},
},
StopReason: "tool_use",
Usage: aiwire.AnthUsage{InputTokens: 9, OutputTokens: 3, CacheReadInputTokens: 5},
}
events := AnthMessageEvents(msg)
want := "message_start,content_block_start,content_block_delta,content_block_stop," +
"content_block_start,content_block_delta,content_block_stop,message_delta,message_stop"
if got := bridgeEventTypes(events); got != want {
t.Fatalf("事件序列:\n got %s\nwant %s", got, want)
}
delta := events[len(events)-2].Data.(map[string]any)
usage := delta["usage"].(map[string]int)
if usage["input_tokens"] != 9 || usage["output_tokens"] != 3 || usage["cache_read_input_tokens"] != 5 {
t.Fatalf("usage = %+v", usage)
} }
} }
+29
View File
@@ -358,3 +358,32 @@ func (b *ChatRespBridge) Finish() []aiwire.ChatChunk {
// Usage 返回聚合到的用量(供调用日志),上游未报告时为 nil。 // Usage 返回聚合到的用量(供调用日志),上游未报告时为 nil。
func (b *ChatRespBridge) Usage() *aiwire.Usage { return b.usage } func (b *ChatRespBridge) Usage() *aiwire.Usage { return b.usage }
// ChatResponseChunks 把完整 Chat 响应展开为 chunk 序列(内容与工具调用 →
// 终块 → 可选 usage 块),供流式上游断流后的非流式降级结果推送。
func ChatResponseChunks(resp *aiwire.ChatResponse, includeUsage bool) []aiwire.ChatChunk {
if len(resp.Choices) == 0 {
return nil
}
choice := resp.Choices[0]
mk := func(delta aiwire.Delta, finish *string) aiwire.ChatChunk {
return aiwire.ChatChunk{ID: resp.ID, Object: "chat.completion.chunk", Created: resp.Created,
Model: resp.Model, Choices: []aiwire.ChunkChoice{{Index: 0, Delta: delta, FinishReason: finish}}}
}
delta := aiwire.Delta{Role: "assistant", Content: choice.Message.Content.Text}
for i, tc := range choice.Message.ToolCalls {
delta.ToolCalls = append(delta.ToolCalls, aiwire.ToolCallDelta{Index: i, ID: tc.ID,
Type: "function", Function: aiwire.FunctionCallDelta{Name: tc.Function.Name, Arguments: tc.Function.Arguments}})
}
finish := choice.FinishReason
chunks := []aiwire.ChatChunk{mk(delta, nil), mk(aiwire.Delta{}, &finish)}
if includeUsage {
usage := resp.Usage
if usage == nil {
usage = &aiwire.Usage{}
}
chunks = append(chunks, aiwire.ChatChunk{ID: resp.ID, Object: "chat.completion.chunk",
Created: resp.Created, Model: resp.Model, Choices: []aiwire.ChunkChoice{}, Usage: usage})
}
return chunks
}
+6 -6
View File
@@ -187,7 +187,7 @@ type externalIdentity struct {
// HandleCallback 完成授权码回调:换取身份后,bind 模式写绑定、login 模式签发 JWT; // HandleCallback 完成授权码回调:换取身份后,bind 模式写绑定、login 模式签发 JWT;
// token 仅 login 模式非空;mode 尽力返回(state 无效时为空),供 api 决定错误回跳页面。 // token 仅 login 模式非空;mode 尽力返回(state 无效时为空),供 api 决定错误回跳页面。
func (o *OAuthService) HandleCallback(ctx context.Context, provider, state, code string) (token, display, mode string, err error) { func (o *OAuthService) HandleCallback(ctx context.Context, provider, state, code string) (token, username, mode string, err error) {
p, err := o.takeState(provider, state) p, err := o.takeState(provider, state)
if err != nil { if err != nil {
return "", "", "", err return "", "", "", err
@@ -198,14 +198,14 @@ func (o *OAuthService) HandleCallback(ctx context.Context, provider, state, code
} }
if p.mode == "bind" { if p.mode == "bind" {
if err := o.bind(ctx, p.username, provider, ident); err != nil { if err := o.bind(ctx, p.username, provider, ident); err != nil {
return "", ident.Display, p.mode, err return "", p.username, p.mode, err
} }
// 绑定属敏感变更:版本递增使旧令牌失效,同时为操作者签新令牌随回跳带回 // 绑定属敏感变更:版本递增使旧令牌失效,同时为操作者签新令牌随回跳带回
token, _, err := o.auth.RevokeSessions(ctx, p.username) token, _, err := o.auth.RevokeSessions(ctx, p.username)
return token, ident.Display, p.mode, err return token, p.username, p.mode, err
} }
token, display, err = o.loginByIdentity(ctx, provider, ident) token, username, err = o.loginByIdentity(ctx, provider, ident)
return token, display, p.mode, err return token, username, p.mode, err
} }
// fetchIdentity 用授权码向 provider 换取稳定 subject 与展示名。 // fetchIdentity 用授权码向 provider 换取稳定 subject 与展示名。
@@ -311,7 +311,7 @@ func (o *OAuthService) loginByIdentity(ctx context.Context, provider string, ide
return "", "", fmt.Errorf("find bound user: %w", err) return "", "", fmt.Errorf("find bound user: %w", err)
} }
token, _, err := o.auth.signToken(user.Username, user.TokenVersion) token, _, err := o.auth.signToken(user.Username, user.TokenVersion)
return token, ident.Display, err return token, user.Username, err
} }
// Identities 列出账号已绑定的外部身份。 // Identities 列出账号已绑定的外部身份。
+3 -3
View File
@@ -169,12 +169,12 @@ func TestOAuthBindLoginUnbind(t *testing.T) {
t.Errorf("重复绑定 err = %v, want ErrOAuthBound", err) t.Errorf("重复绑定 err = %v, want ErrOAuthBound", err)
} }
// 已绑定身份可登录并拿到有效 JWT // 已绑定身份可登录并拿到有效 JWT
token, display, err := o.loginByIdentity(ctx, "github", externalIdentity{Subject: "10086", Display: "octocat"}) token, loginUser, err := o.loginByIdentity(ctx, "github", externalIdentity{Subject: "10086", Display: "octocat"})
if err != nil || token == "" { if err != nil || token == "" {
t.Fatalf("loginByIdentity: %v", err) t.Fatalf("loginByIdentity: %v", err)
} }
if display != "octocat" { if loginUser != "admin" {
t.Errorf("display = %q", display) t.Errorf("loginUser = %q, want admin", loginUser)
} }
if username, err := auth.ParseToken(context.Background(), token); err != nil || username != "admin" { if username, err := auth.ParseToken(context.Background(), token); err != nil || username != "admin" {
t.Errorf("token 应属 admin, got %q (%v)", username, err) t.Errorf("token 应属 admin, got %q (%v)", username, err)