feat(models): 前端展示 OpenCode Go 的月度额度与训练策略

老板要求:模型清单里能直接看到「这个模型每月能调多少」「是否拿你的代码训练」。

数据源:官方 models 接口(与 1.0.6 的同步修复同源,无需鉴权)
  go.monthly_usage = {go, go-plus, go-teams}   # 官方口径:只用这一个模型时各套餐每月额度
  go.training      = false                     # 是否用你的请求训练
  go.zdr           = true                      # 零数据保留

为什么不写进 gateway.yaml:这是上游随时会变的市场信息,不属于网关静态配置,
也不该让每日同步脚本再背一层 plan/落盘逻辑。改为后端按需拉取 + 6 小时缓存:

- app/gomodels.py(新增):拉取 + 缓存 + 失败保留旧值(5 分钟后重试),
  任何异常都不影响 /v1/models(最坏就是前端不显示这一列)。
- app/main.py:_models_payload() 拆成 base + 合并层。
  base 仍按配置 mtime 缓存;合并层再按 (base 对象, go 缓存时间戳) 缓存,
  两个都没变时返回同一个对象(保持原有缓存身份语义),任一变化自动重拼。
  别名条目不重复挂 go(额度/训练口径就是目标模型的,前端按 alias_of 取)。
- 前端 Models.vue:新增「Go 额度」列 —— 默认档额度(如 $100)+ 训练徽章
  (不训练=绿 / 会训练=红),悬浮显示三档明细与零数据保留说明;
  非 OpenCode 供应商显示「—」。
- locales:中英文各补 8 个键(check:i18n 通过)。

验证:直接调 _models_payload() —— 83 个模型里 28 个带 go 字段、其余为 None;
前端 vite build 通过;api-gateway 重启后 /healthz 200。
This commit is contained in:
Jidekin committed 2026-11-19 08:23:15 +08:00
1 parent 1ed82f6d73
commit 9b36374bfc
5 files changed
+216 -1

No files matched your search

+98
View File
@@ -0,0 +1,98 @@
"""OpenCode Go 模型的套餐元数据(月度额度 / 是否用请求训练 / 零数据保留)。
**只用于展示,不参与路由与计费。** 数据来自官方 models 接口(实测无需鉴权):
GET https://opencode.ai/inference/go/v1/models
其中每个模型带 `go` 字段:
go: {
monthly_usage: {"go": 100, "go-plus": 200, "go-teams": 105},
training: false, # 是否用你的请求训练模型
zdr: true, # 零数据保留(不保留任何内容)
limited_regions: false,
}
官方口径(docs/console/go):`monthly_usage` 是「**只用这一个模型时,各套餐每月额度
能覆盖多少用量**」(文档举例用的是美元)。所以前端展示成「$100/月」这类形式。
设计取舍:
· 自带 6 小时缓存,失败后 5 分钟重试;
· 拉取失败一律返回**已有缓存或空 dict** —— `/v1/models` 绝不因此报错或变慢太多
(首次拉取加 6 秒上限;之后走内存)。
· 不写进 gateway.yaml:这是上游随时会变的市场信息,不属于网关的静态配置,
也不该让模型同步脚本再背一层。
"""
from __future__ import annotations
import json
import threading
import time
import urllib.request
_URL = "https://opencode.ai/inference/go/v1/models"
_TTL = 6 * 3600
_RETRY_AFTER_FAIL = 300
_TIMEOUT = 6
_lock = threading.Lock()
_cache: dict[str, dict] = {}
_at = 0.0
def _fetch() -> dict[str, dict]:
req = urllib.request.Request(
_URL,
headers={"Accept": "application/json", "User-Agent": "api-gateway/gomodels"},
)
with urllib.request.urlopen(req, timeout=_TIMEOUT) as resp: # noqa: S310
payload = json.loads(resp.read().decode("utf-8", "replace"))
out: dict[str, dict] = {}
for m in payload.get("data") or []:
mid = m.get("id")
g = m.get("go") or {}
usage = g.get("monthly_usage") or {}
if not mid or (not usage and g.get("training") is None):
continue
out[mid] = {
"monthly_usage": {k: int(v) for k, v in usage.items()
if isinstance(v, (int, float))},
"training": bool(g.get("training")),
"zdr": bool(g.get("zdr")),
}
return out
def cache_stamp() -> float:
"""上次成功刷新的时间戳(0 = 还没拿到过)。调用方可据此判断展示数据是否需要重拼。"""
return _at
def get_go_meta(force: bool = False) -> dict[str, dict]:
"""{model_id: {"monthly_usage": {...}, "training": bool, "zdr": bool}}。
过期才刷新;刷新失败保留旧数据,并推迟 `_RETRY_AFTER_FAIL` 秒再试。
"""
global _at
now = time.time()
if not force and _cache and now - _at < _TTL:
return _cache
if not _lock.acquire(blocking=False):
return _cache # 别的线程正在刷新,先用旧的
try:
if force or not _cache or time.time() - _at >= _TTL:
try:
fresh = _fetch()
except Exception: # noqa: BLE001 —— 展示数据,失败不重要
fresh = None
if fresh:
_cache.clear()
_cache.update(fresh)
_at = time.time()
else:
_at = time.time() - _TTL + _RETRY_AFTER_FAIL
finally:
_lock.release()
return _cache
+37 -1
View File
@@ -56,6 +56,8 @@ from app.sessions import SessionStore
from app.users import UsersStore, UserError, key_limit_for_role
from app.history import HistoryStore, HistoryError, MAX_ITEMS as HISTORY_CAP
from app.feedback import FeedbackStore, FeedbackError, MAX_ENTRIES as FEEDBACK_CAP
# 2026-11-19: OpenCode Go 套餐元数据(月度额度 / 是否训练 / 零保留),只用于前端展示
from app.gomodels import get_go_meta, cache_stamp as gomodels_cache_stamp
from app.video_owners import VideoOwnerStore
from app import settings as gw_settings
from app.agents import AgentStore, AgentsError
@@ -1494,7 +1496,7 @@ def _attach_cost(resp: dict, model: str, usage: dict, cfg) -> None:
# ─────────────────────────────────────
# GET /models + GET /v1/models(P1-7 / P0-3)
# ─────────────────────────────────────
def _models_payload():
def _models_payload_base():
cfg = _cfg()
# 优化: 目录按配置 mtime 缓存(热重载改配置才重建;静默期每次请求直接命中,省掉
# all_models() 的重复遍历与对象构建)。cfg 引用同一 config 对象,
@@ -1571,6 +1573,40 @@ def _models_payload():
return payload
def _models_payload():
"""在按 mtime 缓存的目录上,现拼 OpenCode Go 的套餐元数据。
2026-11-19(老板要求):前端要显示「这个模型每月能调多少」「是否拿你的代码训练」。
这两个字段来自官方 models 接口(有自己的 6 小时缓存,见 app/gomodels.py),
所以**不烤进** `_models_cache`(否则配置不变就永远停在第一次的快照)。
拼好后按 (配置 mtime, go 缓存时间戳) 再缓存一层 —— 两个都没变时返回**同一个对象**
(`test_models_payload_cached_and_invalidated_by_mtime` 依赖这个身份语义);
任一变化就重拼。拿不到 go 数据时直接原样返回 base。
"""
base = _models_payload_base()
go = get_go_meta()
if not go:
return base
# 缓存键带上 base 的对象 id(并**持有 base 的强引用**,保证 id 不会被复用)——
# 这样只要 base 被重建(配置热重载,或测试直接把 _models_cache 置 None 换 config),
# 合并层就跟着失效;go 数据刷新(时间戳变化)也会失效。
key = (id(base), gomodels_cache_stamp())
cached = _state.get("_models_cache_go")
if cached is not None and cached[0] == key and cached[2] is base:
return cached[1]
data = []
for item in base.get("data") or []:
mid = item.get("id")
# 别名(alias_of)不重复挂:它的额度/训练口径就是目标模型的,前端按目标取
if mid in go and "alias_of" not in item:
item = {**item, "go": go[mid]}
data.append(item)
payload = {**base, "data": data}
_state["_models_cache_go"] = (key, payload, base)
return payload
@app.get("/models")
async def list_models(request: Request, _auth=Depends(require_auth)):
return _models_payload()
+9
View File
@@ -616,6 +616,15 @@ export default {
providers: 'Providers',
loadErr: 'Failed to load models',
capability: 'Capability',
// 2026-11-19: OpenCode Go plan quota + training policy (from the official models API's go field)
goQuota: 'Go quota',
goQuotaHint: 'Monthly allowance each plan covers when you use only this model (official go.monthly_usage)',
goQuotaValues: 'Go ${go}/mo · Go Plus ${plus}/mo · Go Teams ${teams}/mo',
goQuotaFree: 'Free',
goTrainingNo: 'No training',
goTrainingYes: 'Trains',
goTrainingHint: 'Official go.training flag: whether this model trains on your requests',
goZdrHint: 'Zero data retention: upstream keeps none of your content',
visionTag: 'Vision',
freeTag: 'Free',
freeHint: 'Officially free model: no usage-based billing (quota is set by the vendor; both the Agnes and OpenCode Go free tiers are labelled)',
+9
View File
@@ -621,6 +621,15 @@ export default {
providers: '供应商',
loadErr: '加载模型失败',
capability: '能力',
// 2026-11-19:OpenCode Go 的套餐额度与训练策略(数据来自官方 models 接口的 go 字段)
goQuota: 'Go 额度',
goQuotaHint: '只用这一个模型时,各套餐每月额度能覆盖多少用量(官方 models 接口的 go.monthly_usage)',
goQuotaValues: 'Go ${go}/月 · Go Plus ${plus}/月 · Go Teams ${teams}/月',
goQuotaFree: '免费',
goTrainingNo: '不训练',
goTrainingYes: '会训练',
goTrainingHint: '官方 go.training:该模型是否用你的请求内容做训练',
goZdrHint: '零数据保留:上游不保留请求内容',
visionTag: '视觉',
freeTag: '免费',
freeHint: '官方免费模型:不按用量计费(额度以官方为准;Agnes 与 OpenCode Go 的免费档都会标出来)',
+63
View File
@@ -134,6 +134,26 @@
<span v-if="!row.vision && !paramKeys(row).length" class="muted-2">—</span>
</template>
</el-table-column>
<!-- 2026-11-19(老板要求):OpenCode Go 的套餐额度与训练策略。
额度 = 「只用这一个模型时,该套餐每月能覆盖多少用量」(官方 go.monthly_usage,美元);
训练 = 官方 go.training(false = 不拿你的请求训练)。
只有 OpenCode Go 的模型带这个字段,其余供应商显示「—」。 -->
<el-table-column width="150">
<template #header>
<el-tooltip :content="t('models.goQuotaHint')" placement="top">
<span class="proto-th">{{ t('models.goQuota') }}</span>
</el-tooltip>
</template>
<template #default="{ row }">
<template v-if="row.goMeta">
<span class="pill go-quota cap" :title="goQuotaHint(row)">{{ goQuotaText(row) }}</span>
<span class="pill cap" :class="goTrains(row) ? 'err' : 'ok'" :title="t('models.goTrainingHint')">
{{ goTrains(row) ? t('models.goTrainingYes') : t('models.goTrainingNo') }}
</span>
</template>
<span v-else class="muted-2">—</span>
</template>
</el-table-column>
<el-table-column :label="t('models.keySet')" width="90">
<template #default="{ row }">
<span class="pill" :class="row.key_set ? 'ok' : 'err'">
@@ -431,6 +451,10 @@ const textModelRows = computed(() =>
paramNote: paramKeys(m).length ? paramNote(m) : '',
// 支持的格式(第二十七轮):悬浮这一行就能看到「能用哪几条线 + 本次测速走的哪条」
formats: protocolsOf(m),
// 2026-11-19(老板要求):OpenCode Go 的套餐额度(每月能调多少)与训练策略。
// 后端 /v1/models 的 go 字段(app/gomodels.py 从官方 models 接口拉取,缓存 6 小时);
// 非 OpenCode 供应商没有这个字段 → 该列显示「—」。
goMeta: m.go || null,
})),
)
@@ -454,6 +478,43 @@ function freeHint(m: any): string {
return m && m.free_limited ? t('models.freeLimitedHint') : t('models.freeHint')
}
// ── OpenCode Go 套餐额度 / 训练策略(2026-11-19 老板要求)──
// 数据来自后端 /v1/models 的 go 字段(app/gomodels.py ← 官方 models 接口 go.monthly_usage)。
// 官方口径:monthly_usage 是「只用这一个模型时,各套餐每月额度能覆盖多少用量」(美元)。
// 单元格里只显示默认档(Go),三档明细与零保留说明放悬浮提示。
const GO_PLAN_KEYS = ['go', 'go-plus', 'go-teams'] as const
function goUsageOf(m: any): Record<string, number> {
return (m && m.goMeta && m.goMeta.monthly_usage) || {}
}
function goQuotaText(m: any): string {
const u = goUsageOf(m)
if (u.go) return `$${u.go}`
if (m && m.free) return t('models.goQuotaFree')
return '—'
}
function goQuotaHint(m: any): string {
const u = goUsageOf(m)
const parts: string[] = []
if (GO_PLAN_KEYS.some((k) => u[k])) {
parts.push(t('models.goQuotaValues', {
go: u.go ?? '—',
plus: u['go-plus'] ?? '—',
teams: u['go-teams'] ?? '—',
}))
} else {
parts.push(t('models.goQuotaHint'))
}
if (m && m.goMeta && m.goMeta.zdr) parts.push(t('models.goZdrHint'))
return parts.join(' · ')
}
function goTrains(m: any): boolean {
return !!(m && m.goMeta && m.goMeta.training)
}
// ── 模型级强制参数(第二十五轮)──
// 后端 /v1/models 在 params 里给出「该模型发往上游前会被强制覆盖的参数」
// (例:kimi-k2.7-code 只接受 temperature=1)。这里只做展示,不提供编辑入口。
@@ -597,6 +658,8 @@ onUnmounted(() => {
.plock { color: var(--warn); }
/* 免费模型:绿色系,跟「视觉」(主题色) / 「参数固定」(橙) 区分开;跟在模型名后面 */
.pill.free { background: rgba(16, 185, 129, 0.14); color: #059669; }
/* OpenCode Go 的套餐额度(2026-11-19):中性蓝,与免费(绿)/ 参数固定(橙)区分 */
.pill.go-quota { background: rgba(59, 130, 246, 0.12); color: #2563eb; }
/* 免费标注的间距(2026-09-24 老板:间隔不一样)——
表格单元格里是行内排布、没有 flex gap,靠这个 margin 与模型名分开;
测速行是 flex(.st-row gap: 8px),必须把 margin 归零:否则标签左侧 8+6=14px、