mirror of
https://github.com/jasonxu114514/opencode2api.git
synced 2026-12-05 08:02:53 +00:00
fix: correct free-model probes and add adaptive reasoning (#54)
This commit is contained in:
1 parent
ab2451da2a
commit
ef2df3f056
12 files changed
+390
-151
No files matched your search
@@ -164,7 +164,7 @@ For streaming, add `"stream": true` to the body and use `curl -N`. Responses inc
|
||||
curl http://localhost:8080/v1/systemone \
|
||||
-H "Authorization: Bearer YOUR_LOCAL_API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"model":"MODEL_ID","state":"...","questions":[...]}'
|
||||
-d '{"model":"MODEL_ID","state":"1 + 1 = 2","questions":{"arithmetic":{"type":"noul","instructions":"Is 1 + 1 equal to 2?"}}}'
|
||||
```
|
||||
|
||||
System One pairs a free-form state with typed questions and returns typed answers, so the payload shares no shape with the chat/responses bridge and is relayed verbatim, never translated. Only models whose native protocol is System One are served here; a decision payload submitted on a message endpoint (`/v1/chat/completions`, `/v1/responses`) is likewise relayed verbatim instead of converted. Streaming upstream replies are relayed as-is without reset recovery.
|
||||
@@ -221,9 +221,11 @@ When only anonymous access is configured, `/v1/models` exposes only models eligi
|
||||
|
||||
### Free model availability
|
||||
|
||||
The gateway probes models whose IDs contain `free` (case-insensitive), or whose metadata reports zero input/output cost without deprecation, with a short streaming inference request. It tries the enabled anonymous lane first and then one configured Zen Key. A valid completed response on either lane keeps the model enabled; if every attempted lane fails, the model is disabled in discovery and routing. Probe traffic does not alter production key/proxy cooldowns or request statistics. It still reaches the upstream and may consume its free allowance.
|
||||
The gateway probes models whose IDs contain `free` (case-insensitive), or whose metadata reports zero input/output cost without deprecation, with a short request using its native protocol. It tries the enabled anonymous lane first and then one configured Zen Key. A valid completed response on either lane keeps the model enabled; the model is disabled in discovery and routing only when every attempted lane explicitly reports that the model does not exist or has been retired. Authentication errors, rate limits, timeouts, transport errors, 5xx responses, and malformed replies are inconclusive: they do not create a new disable, and are checked again in one hour. Probe traffic does not alter production key/proxy cooldowns or request statistics. It still reaches the upstream and may consume its free allowance.
|
||||
|
||||
The intervals are fixed: enabled models are checked every **1 hour**, failed models every **24 hours**. A successful recheck restores the model automatically. The WebUI **Free model availability** page can restore it immediately, with its next check one hour later. An in-flight probe cannot undo a manual restore. Models without a usable Zen/anonymous lane, or without a supported inference protocol, are skipped.
|
||||
System One models use a native `noul` question asking whether 1 + 1 equals 2; they are never sent chat/tool payloads. Model discovery includes `native_protocol` and `supported_endpoints`; rotation aliases are listed only when Go keys and eligible models exist. Legacy v1.3.6 disables are cleared on load and scheduled for immediate recheck because those probes used invalid session IDs.
|
||||
|
||||
The intervals are fixed: enabled models are checked every **1 hour**, models confirmed unavailable every **24 hours**. A successful recheck restores the model automatically. The WebUI **Free model availability** page can restore it immediately, with its next check one hour later. An in-flight probe cannot undo a manual restore. Models without a usable Zen/anonymous lane, or without a supported inference protocol, are skipped.
|
||||
|
||||
State survives restarts in `config.json.<upstream-fingerprint>.availability.json`, separated by the Zen upstream URL. The background scheduler checks for due models once per minute and probes sequentially, with a 60-second timeout per lane. No channels available means no automatic disable.
|
||||
|
||||
@@ -482,6 +484,14 @@ npm run check:web
|
||||
|
||||
Thanks to the [LINUX DO](https://linux.do) community for its support.
|
||||
|
||||
### Adaptive reasoning effort
|
||||
|
||||
Set `reasoning.effort` (or a per-model override) to `auto` to use the highest effort successfully validated by the free-model probe. Existing concrete levels retain their meaning and client-specified effort takes precedence. No model-name allowlist is maintained.
|
||||
|
||||
After a baseline succeeds, reasoning-capable models are probed in `max`, `xhigh`, `high`, `medium`, `low`, `minimal` order. Only an explicit reasoning-parameter rejection advances to a lower level. Transient failures stop the search and cannot be interpreted as a lower capability ceiling. If every level is rejected, no reasoning override is injected.
|
||||
|
||||
Observations are persisted by upstream URL, model and native protocol, displayed in the availability page, and used for at most two hours. Active probes cover only free Zen/anonymous models; Go/paid models, unknown capabilities and unverified levels receive no automatic override. Setting `auto` does not expand the probe scope or guarantee that upstreams enforce every accepted field. Probing may require several small requests per model and uses upstream allowance.
|
||||
|
||||
## License
|
||||
|
||||
SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
+28
-18
@@ -164,7 +164,7 @@ curl http://localhost:8080/v1/messages \
|
||||
curl http://localhost:8080/v1/systemone \
|
||||
-H "Authorization: Bearer YOUR_LOCAL_API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"model":"MODEL_ID","state":"...","questions":[...]}'
|
||||
-d '{"model":"MODEL_ID","state":"1 + 1 = 2","questions":{"arithmetic":{"type":"noul","instructions":"Is 1 + 1 equal to 2?"}}}'
|
||||
```
|
||||
|
||||
System One 将自由文本状态与类型化问题配对,并返回类型化答案,因此其负载与 chat/responses 桥接结构完全不同,只做原样转发,不做任何转换。只有原生协议为 System One 的模型才能在本接口提供服务;在消息接口(`/v1/chat/completions`、`/v1/responses`)上提交的决策负载同样原样转发,而不经过转换。上游的流式回复按原样透传,不做中断恢复。
|
||||
@@ -221,9 +221,11 @@ System One 将自由文本状态与类型化问题配对,并返回类型化答
|
||||
|
||||
### 免费模型可用性
|
||||
|
||||
只探测 ID 含 `free`(不区分大小写),或元数据输入、输出价格均为零且未弃用的模型,发送简短的流式推理请求。先尝试已启用的匿名通道,再尝试一个配置的 Zen Key;任一通道返回完整有效响应即视为可用,所有实际尝试的通道均失败后自动禁用,从模型列表与路由中移除。探测不修改生产 Key / 代理的冷却状态,也不计入请求统计,但仍会访问上游并可能消耗免费额度。
|
||||
只探测 ID 含 `free`(不区分大小写),或元数据输入、输出价格均为零且未弃用的模型,按模型原生协议发送简短探测请求。先尝试已启用的匿名通道,再尝试一个配置的 Zen Key;任一通道返回完整有效响应即视为可用,只有所有实际尝试的通道都明确返回模型不存在或已下架时才自动禁用,从模型列表与路由中移除。认证失败、429、超时、网络错误、5xx 和响应格式异常均视为结果不确定,不新增禁用,1 小时后复测。探测不修改生产 Key / 代理的冷却状态,也不计入请求统计,但仍会访问上游并可能消耗免费额度。
|
||||
|
||||
周期硬编码:正常模型每 **1 小时**探测,失败模型每 **24 小时**复测。复测成功自动恢复;也可在 WebUI「免费模型可用性」页立即恢复启用,下一次探测在 1 小时后。手动恢复不会被已经在途的旧探测结果覆盖。没有可用 Zen / 匿名通道,或推理协议不支持探测时跳过,不自动禁用。
|
||||
System One 使用原生 `noul` 类型询问“1+1 是否等于 2”,不注入聊天或工具字段。模型列表标明 `native_protocol` 和 `supported_endpoints`;仅在配置 Go Key 且有可用模型时展示轮转别名。升级时解除 v1.3.6 旧探测生成的禁用并立即安排复测,避免非法会话 ID 造成的误判继续保留。
|
||||
|
||||
周期硬编码:正常模型每 **1 小时**探测,明确失效模型每 **24 小时**复测。复测成功自动恢复;也可在 WebUI「免费模型可用性」页立即恢复启用,下一次探测在 1 小时后。手动恢复不会被已经在途的旧探测结果覆盖。没有可用 Zen / 匿名通道,或推理协议不支持探测时跳过,不自动禁用。
|
||||
|
||||
状态保存在 `config.json.<上游地址指纹>.availability.json`,重启后保留,按 Zen 上游 URL 隔离。后台每分钟检查到期项,串行探测,每条通道最多等待 60 秒。
|
||||
|
||||
@@ -245,21 +247,21 @@ Key 初始化时均衡分配到代理。真实流量可以触发代理检查、K
|
||||
|
||||
### Key、监听地址与路由
|
||||
|
||||
| 字段 | 默认值或要求 |
|
||||
| --------------------------- | ----------------------------------------------------------------------------- |
|
||||
| `listen` | `127.0.0.1:8080`。 |
|
||||
| `server_keys` | 至少一个本地 Key。 |
|
||||
| `zen_keys`、`go_keys` | 未启用匿名模式时,至少需要一个上游 Key。 |
|
||||
| `anonymous` | `false`。 |
|
||||
| `prefer` | `go`;可选 `go`、`zen`。 |
|
||||
| `upstream.zen` | `https://opencode.ai/zen`。 |
|
||||
| `upstream.go` | `https://opencode.ai/zen/go`。 |
|
||||
| `proxies` | 两个代理来源都为空时,使用 `["direct"]`。 |
|
||||
| `proxyfile` | 可选;相对路径基于配置文件所在目录解析。 |
|
||||
| `models.refresh_seconds` | `300`;最小为 1。 |
|
||||
| `models.protocols` | `{}`;按模型 ID 覆盖原生协议。 |
|
||||
| `reasoning.effort` | 空(关闭);可选 `minimal`、`low`、`medium`、`high`、`xhigh`、`max`、`none`。 |
|
||||
| `reasoning.effort_by_model` | `{}`;按模型 ID 覆盖 `reasoning.effort`。 |
|
||||
| 字段 | 默认值或要求 |
|
||||
| --------------------------- | ------------------------------------------------------------------------------------- |
|
||||
| `listen` | `127.0.0.1:8080`。 |
|
||||
| `server_keys` | 至少一个本地 Key。 |
|
||||
| `zen_keys`、`go_keys` | 未启用匿名模式时,至少需要一个上游 Key。 |
|
||||
| `anonymous` | `false`。 |
|
||||
| `prefer` | `go`;可选 `go`、`zen`。 |
|
||||
| `upstream.zen` | `https://opencode.ai/zen`。 |
|
||||
| `upstream.go` | `https://opencode.ai/zen/go`。 |
|
||||
| `proxies` | 两个代理来源都为空时,使用 `["direct"]`。 |
|
||||
| `proxyfile` | 可选;相对路径基于配置文件所在目录解析。 |
|
||||
| `models.refresh_seconds` | `300`;最小为 1。 |
|
||||
| `models.protocols` | `{}`;按模型 ID 覆盖原生协议。 |
|
||||
| `reasoning.effort` | 空(关闭);可选 `auto`、`minimal`、`low`、`medium`、`high`、`xhigh`、`max`、`none`。 |
|
||||
| `reasoning.effort_by_model` | `{}`;按模型 ID 覆盖 `reasoning.effort`。 |
|
||||
|
||||
### 强制思考强度
|
||||
|
||||
@@ -477,6 +479,14 @@ npm run check:web
|
||||
|
||||
感谢 [LINUX DO](https://linux.do) 社区的支持。
|
||||
|
||||
### 自适应思考强度
|
||||
|
||||
将 `reasoning.effort` 或按模型覆盖值设置为 `auto`,即可使用免费模型探测实际验证过的最高可用档。已有具体档位语义不变,客户端显式指定的强度始终优先,不维护模型名称白名单。
|
||||
|
||||
基础请求成功后,对能力目录标记支持 reasoning 的模型依次验证 `max`、`xhigh`、`high`、`medium`、`low`、`minimal`。只有明确的思考参数不支持错误才尝试下一档;429、超时等临时失败会停止搜索,不能据此判断模型档位上限。全部档位均被拒绝时,不注入思考覆盖。
|
||||
|
||||
结果按上游 URL、模型与原生协议持久化,在可用性页展示,最多使用两小时内的验证结果。主动探测仍只覆盖免费 Zen/匿名模型;Go/付费模型、能力未知或尚未验证的模型不猜测档位。开启 `auto` 不扩大探测范围,也不能证明上游一定执行了所有接受的字段;每个模型可能增加数次简短请求并消耗上游额度。
|
||||
|
||||
## 许可证
|
||||
|
||||
SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
@@ -291,10 +291,10 @@ func normalizeReasoning(cfg *Config) error {
|
||||
// plus an empty string, which means "not forced".
|
||||
func validateEffort(name, value string) error {
|
||||
switch value {
|
||||
case "", "minimal", "low", "medium", "high", "xhigh", "max", "none":
|
||||
case "", "auto", "minimal", "low", "medium", "high", "xhigh", "max", "none":
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("%s must be one of minimal, low, medium, high, xhigh, max, none, or empty to disable the override", name)
|
||||
return fmt.Errorf("%s must be one of auto, minimal, low, medium, high, xhigh, max, none, or empty to disable the override", name)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,18 +2,12 @@ package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"time"
|
||||
|
||||
"opencode2api/internal/config"
|
||||
"opencode2api/internal/identity"
|
||||
"opencode2api/internal/models"
|
||||
wire "opencode2api/internal/protocol"
|
||||
)
|
||||
|
||||
func (m *RuntimeManager) AvailabilitySnapshot() []models.Availability {
|
||||
@@ -71,110 +65,18 @@ func (m *RuntimeManager) checkFreeModels(ctx context.Context) {
|
||||
if time.Now().Before(item.NextCheck) {
|
||||
continue
|
||||
}
|
||||
ok, reason, channel, attempted := r.gateway.probeFreeModel(ctx, item.Model)
|
||||
if !attempted || ctx.Err() != nil {
|
||||
result := r.gateway.probeFreeModel(ctx, item.Model)
|
||||
if !result.attempted || ctx.Err() != nil {
|
||||
continue
|
||||
}
|
||||
// Config changes may replace credentials or endpoints during a probe.
|
||||
m.updateMu.Lock()
|
||||
if m.current.Load() == r {
|
||||
if err := r.availability.Record(item.Model, item.Generation, ok, reason, channel, time.Now().UTC()); err != nil {
|
||||
if err := r.availability.Record(item.Model, item.Generation, result.success, result.reason, result.channel, time.Now().UTC(), result.effort); err != nil {
|
||||
m.logger.Warn("model availability state save failed", "error", err)
|
||||
}
|
||||
m.logger.Info("free model availability checked", "component", "models", "event", "availability_checked", "model", item.Model, "available", ok, "reason", reason, "channel", channel)
|
||||
m.logger.Info("free model availability checked", "component", "models", "event", "availability_checked", "model", item.Model, "available", result.success, "reason", result.reason, "channel", result.channel)
|
||||
}
|
||||
m.updateMu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
func (g *Gateway) probeFreeModel(ctx context.Context, model string) (success bool, reason, channel string, attempted bool) {
|
||||
if !g.catalog.IsFreeModel(model) {
|
||||
return false, "not_free", "", false
|
||||
}
|
||||
d := g.catalog.Diagnostic(model, wire.Chat, g.zenNodes.Len() > 0, false, g.cfg.Anonymous)
|
||||
protocol := d.NativeProtocols[config.TierZen]
|
||||
if !d.AvailableZen || !g.catalog.Supported(model) || protocol == wire.SystemOne {
|
||||
return false, "unsupported_probe", "", false
|
||||
}
|
||||
payload := map[string]any{"model": model, "stream": true, "max_tokens": 64, "messages": []any{map[string]any{"role": "user", "content": "Reply with OK."}}}
|
||||
converted, err := wire.ConvertRequest(wire.Chat, protocol, payload)
|
||||
if err != nil {
|
||||
return false, "request_conversion_error", "", false
|
||||
}
|
||||
b, err := json.Marshal(converted)
|
||||
if err != nil {
|
||||
return false, "request_conversion_error", "", false
|
||||
}
|
||||
b = prepareAnonymousBody(b, protocol)
|
||||
type lane struct {
|
||||
key, name string
|
||||
client *http.Client
|
||||
}
|
||||
var lanes []lane
|
||||
if g.cfg.Anonymous {
|
||||
cursor := g.anonymous.CursorFor("availability:" + model)
|
||||
if node := cursor.Next(); node != nil {
|
||||
lanes = append(lanes, lane{anonymousZenKey, "anonymous", node.proxy.client})
|
||||
}
|
||||
}
|
||||
cursor := g.zenNodes.CursorFor("availability:" + model)
|
||||
if node := cursor.Next(); node != nil {
|
||||
if proxy := g.zenNodes.Proxy(node); proxy != nil {
|
||||
lanes = append(lanes, lane{node.key, "zen", proxy.client})
|
||||
}
|
||||
}
|
||||
for _, lane := range lanes {
|
||||
if ctx.Err() != nil {
|
||||
return false, "canceled", "", false
|
||||
}
|
||||
attempted, channel = true, lane.name
|
||||
probeCtx, cancel := context.WithTimeout(ctx, 60*time.Second)
|
||||
req, err := newUpstreamRequest(probeCtx, g.cfg.Upstream.Zen, protocol, b, identity.RequestIDs{Session: "availability:" + model}, lane.key)
|
||||
if err == nil {
|
||||
// Probe traffic never updates production key/proxy cooldowns or usage.
|
||||
var resp *http.Response
|
||||
resp, err = lane.client.Do(req)
|
||||
if err == nil {
|
||||
reason = fmt.Sprintf("http_%d", resp.StatusCode)
|
||||
if resp.StatusCode/100 == 2 {
|
||||
if strings.Contains(strings.ToLower(resp.Header.Get("Content-Type")), "text/event-stream") {
|
||||
_, err = wire.CollapseStream(io.LimitReader(resp.Body, 1<<20), protocol, model)
|
||||
} else {
|
||||
var document map[string]any
|
||||
err = json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&document)
|
||||
if err == nil && (document == nil || document["error"] != nil) {
|
||||
err = errors.New("invalid response")
|
||||
}
|
||||
if err == nil {
|
||||
field := "choices"
|
||||
if protocol == wire.Anthropic {
|
||||
field = "content"
|
||||
} else if protocol == wire.Responses {
|
||||
field = "output"
|
||||
}
|
||||
if _, ok := document[field].([]any); !ok {
|
||||
err = errors.New("invalid response schema")
|
||||
}
|
||||
}
|
||||
}
|
||||
success = err == nil
|
||||
if !success {
|
||||
reason = "invalid_or_incomplete_response"
|
||||
}
|
||||
}
|
||||
resp.Body.Close()
|
||||
} else {
|
||||
reason = "transport_error"
|
||||
}
|
||||
}
|
||||
if probeCtx.Err() != nil {
|
||||
success = false
|
||||
reason = "probe_timeout"
|
||||
}
|
||||
cancel()
|
||||
if success {
|
||||
return true, "probe_succeeded", channel, true
|
||||
}
|
||||
}
|
||||
return success, reason, channel, attempted
|
||||
}
|
||||
+15
-10
@@ -28,15 +28,16 @@ const maxRequestBody = 32 << 20
|
||||
const anonymousZenKey = "public"
|
||||
|
||||
type Gateway struct {
|
||||
rotation *rotation.Manager
|
||||
cfg config.Config
|
||||
logger *slog.Logger
|
||||
transports *transportPool
|
||||
zenNodes *nodePool
|
||||
goNodes *nodePool
|
||||
anonymous *anonymousPool
|
||||
catalog *models.Catalog
|
||||
monitor *telemetry.Monitor
|
||||
rotation *rotation.Manager
|
||||
cfg config.Config
|
||||
logger *slog.Logger
|
||||
transports *transportPool
|
||||
zenNodes *nodePool
|
||||
goNodes *nodePool
|
||||
anonymous *anonymousPool
|
||||
catalog *models.Catalog
|
||||
monitor *telemetry.Monitor
|
||||
availability *models.AvailabilityStore
|
||||
}
|
||||
|
||||
func New(cfg config.Config, logger *slog.Logger, monitor *telemetry.Monitor) (*Gateway, error) {
|
||||
@@ -162,6 +163,10 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc {
|
||||
// only address /v1/chat/completions or /v1/responses — for example a
|
||||
// gateway whose OpenAI platform pins every request to Responses.
|
||||
if route.Protocol == wire.SystemOne {
|
||||
if len(jsonutil.MapAt(payload, "questions")) == 0 || payload["state"] == nil {
|
||||
wire.WriteError(w, external, http.StatusBadRequest, "this model uses System One decisions, not chat; send state and typed questions to /v1/systemone", "invalid_request_error", "model")
|
||||
return
|
||||
}
|
||||
g.forwardSystemOne(w, r, body, payload, model, route)
|
||||
return
|
||||
}
|
||||
@@ -421,7 +426,7 @@ func (g *Gateway) prepareRouteBodies(from wire.Protocol, route models.Route, inp
|
||||
}
|
||||
return nil, fmt.Errorf("prepare %s upstream request: %w", tier, err)
|
||||
}
|
||||
if effort := g.cfg.ForcedEffort(jsonutil.StringAt(upstreamPayload, "model")); effort != "" {
|
||||
if effort := g.resolvedEffort(jsonutil.StringAt(upstreamPayload, "model"), tier, protocol); effort != "" {
|
||||
wire.ForcedEffort(protocol, upstreamPayload, effort)
|
||||
}
|
||||
encoded, err := json.Marshal(upstreamPayload)
|
||||
|
||||
@@ -5,8 +5,10 @@ import (
|
||||
"time"
|
||||
|
||||
"opencode2api/internal/buildinfo"
|
||||
"opencode2api/internal/config"
|
||||
"opencode2api/internal/httpx"
|
||||
modelcatalog "opencode2api/internal/models"
|
||||
wire "opencode2api/internal/protocol"
|
||||
)
|
||||
|
||||
type healthResponse struct {
|
||||
@@ -127,7 +129,13 @@ func (g *Gateway) handleModels(w http.ResponseWriter, _ *http.Request) {
|
||||
md := g.catalog.MetadataForTier(model, route.Tier)
|
||||
entry := map[string]any{
|
||||
"id": model, "object": "model", "created": now, "owned_by": "opencode",
|
||||
"metadata": md,
|
||||
"metadata": md,
|
||||
"native_protocol": route.Protocol,
|
||||
}
|
||||
if route.Protocol == wire.SystemOne {
|
||||
entry["supported_endpoints"] = []string{"/v1/systemone"}
|
||||
} else {
|
||||
entry["supported_endpoints"] = []string{"/v1/chat/completions", "/v1/responses", "/v1/messages"}
|
||||
}
|
||||
// Top-level OpenAI-standard fields: discovery clients (jcode, Pi, …)
|
||||
// read context/reasoning at the top level of each model entry.
|
||||
@@ -154,6 +162,19 @@ func (g *Gateway) handleModels(w http.ResponseWriter, _ *http.Request) {
|
||||
data = append(data, entry)
|
||||
}
|
||||
for _, group := range g.rotation.Snapshot().Groups {
|
||||
if g.goNodes.Len() == 0 {
|
||||
continue
|
||||
}
|
||||
available := false
|
||||
for _, model := range group.Order {
|
||||
if route, err := g.catalog.RouteForTier(model, config.TierGo, false, true); err == nil && route.Protocol != wire.SystemOne {
|
||||
available = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !available {
|
||||
continue
|
||||
}
|
||||
data = append(data, map[string]any{"id": group.Alias, "object": "model", "created": now, "owned_by": "opencode-go-rotation"})
|
||||
}
|
||||
httpx.WriteJSON(w, http.StatusOK, map[string]any{"object": "list", "data": data})
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"opencode2api/internal/config"
|
||||
"opencode2api/internal/identity"
|
||||
"opencode2api/internal/jsonutil"
|
||||
"opencode2api/internal/models"
|
||||
wire "opencode2api/internal/protocol"
|
||||
)
|
||||
|
||||
type probeResult struct {
|
||||
success, attempted, effortRejected bool
|
||||
reason, channel string
|
||||
effort models.EffortProbe
|
||||
}
|
||||
|
||||
func (g *Gateway) resolvedEffort(model string, tier config.Tier, protocol wire.Protocol) string {
|
||||
effort := g.cfg.ForcedEffort(model)
|
||||
if effort != "auto" {
|
||||
return effort
|
||||
}
|
||||
// Only the free Zen lane is actively probed. Never transfer observations
|
||||
// to a different protocol/tier, or guess a level for an unprobed model.
|
||||
if tier != config.TierZen || protocol == wire.SystemOne || g.availability == nil || !g.catalog.IsFreeModel(model) {
|
||||
return ""
|
||||
}
|
||||
item := g.availability.Get(model)
|
||||
if !g.catalog.MetadataForTier(model, tier).Reasoning || item.AutoEffort.Effort == "none" {
|
||||
return "" // Do not inject reasoning into a model that only accepted the baseline.
|
||||
}
|
||||
if item.Disabled || item.AutoEffort.Protocol != string(protocol) || time.Since(item.EffortCheckedAt) > 2*models.FreeModelCheckInterval {
|
||||
return ""
|
||||
}
|
||||
return item.AutoEffort.Effort
|
||||
}
|
||||
|
||||
func probePayload(model string, protocol wire.Protocol, effort string) ([]byte, error) {
|
||||
if protocol == wire.SystemOne {
|
||||
// TypeSafe's native boolean type is "noul", not JSON Schema boolean.
|
||||
return json.Marshal(map[string]any{"model": model, "state": "1 + 1 = 2", "questions": map[string]any{
|
||||
"arithmetic": map[string]any{"type": "noul", "instructions": "Is 1 + 1 equal to 2?"},
|
||||
}})
|
||||
}
|
||||
payload := map[string]any{"model": model, "stream": true, "max_tokens": 64, "messages": []any{map[string]any{"role": "user", "content": "Reply with OK."}}}
|
||||
converted, err := wire.ConvertRequest(wire.Chat, protocol, payload)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if effort != "" {
|
||||
wire.ForcedEffort(protocol, converted, effort)
|
||||
}
|
||||
b, err := json.Marshal(converted)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return prepareAnonymousBody(b, protocol), nil
|
||||
}
|
||||
|
||||
func (g *Gateway) probeFreeModel(ctx context.Context, model string) probeResult {
|
||||
if !g.catalog.IsFreeModel(model) {
|
||||
return probeResult{reason: "not_free"}
|
||||
}
|
||||
d := g.catalog.Diagnostic(model, wire.Chat, g.zenNodes.Len() > 0, false, g.cfg.Anonymous)
|
||||
protocol := d.NativeProtocols[config.TierZen]
|
||||
if !d.AvailableZen || !g.catalog.Supported(model) {
|
||||
return probeResult{reason: "unsupported_probe"}
|
||||
}
|
||||
ids := identity.RequestIDs{Session: identity.CanonicalSessionID("availability:" + model), Project: identity.StableID("prj", "opencode2api:default-project")}
|
||||
type lane struct {
|
||||
key, name string
|
||||
client *http.Client
|
||||
}
|
||||
var lanes []lane
|
||||
if g.cfg.Anonymous {
|
||||
cursor := g.anonymous.CursorFor(ids.Session)
|
||||
if node := cursor.Next(); node != nil {
|
||||
lanes = append(lanes, lane{anonymousZenKey, "anonymous", node.proxy.client})
|
||||
}
|
||||
}
|
||||
cursor := g.zenNodes.CursorFor(ids.Session)
|
||||
if node := cursor.Next(); node != nil {
|
||||
if proxy := g.zenNodes.Proxy(node); proxy != nil {
|
||||
lanes = append(lanes, lane{node.key, "zen", proxy.client})
|
||||
}
|
||||
}
|
||||
result := probeResult{reason: "no_probe_channel"}
|
||||
inconclusive := ""
|
||||
for _, lane := range lanes {
|
||||
if ctx.Err() != nil {
|
||||
return probeResult{reason: "canceled"}
|
||||
}
|
||||
run := func(effort string) probeResult {
|
||||
return g.probeAttempt(ctx, lane.client, lane.key, model, protocol, ids, effort)
|
||||
}
|
||||
result = run("")
|
||||
result.channel = lane.name
|
||||
if result.success {
|
||||
if g.cfg.ForcedEffort(model) == "auto" && protocol != wire.SystemOne {
|
||||
if !g.catalog.MetadataForTier(model, config.TierZen).Reasoning {
|
||||
result.effort = models.EffortProbe{Effort: "none", Protocol: string(protocol)}
|
||||
} else {
|
||||
for _, effort := range []string{"max", "xhigh", "high", "medium", "low", "minimal", "none"} {
|
||||
if effort == "none" {
|
||||
// Baseline already succeeded without an effort field.
|
||||
result.effort = models.EffortProbe{Effort: "none", Protocol: string(protocol)}
|
||||
break
|
||||
}
|
||||
trial := run(effort)
|
||||
if trial.success {
|
||||
result.effort = models.EffortProbe{Effort: effort, Protocol: string(protocol)}
|
||||
break
|
||||
}
|
||||
// A rate limit or timeout gives no evidence that a lower
|
||||
// reasoning level is required. Keep previous observations.
|
||||
if !trial.effortRejected {
|
||||
break
|
||||
}
|
||||
// Once higher levels were explicitly rejected, do not
|
||||
// retain an older ceiling if the next trial is inconclusive.
|
||||
result.effort = models.EffortProbe{Reset: true}
|
||||
}
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
if result.reason != "model_unavailable" {
|
||||
inconclusive = result.reason
|
||||
}
|
||||
}
|
||||
// One lane's auth/transient failure cannot establish global unavailability.
|
||||
if inconclusive != "" {
|
||||
result.reason = inconclusive
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func (g *Gateway) probeAttempt(parent context.Context, client *http.Client, key, model string, protocol wire.Protocol, ids identity.RequestIDs, effort string) probeResult {
|
||||
b, err := probePayload(model, protocol, effort)
|
||||
if err != nil {
|
||||
return probeResult{reason: "request_conversion_error"}
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(parent, 60*time.Second)
|
||||
defer cancel()
|
||||
ids.Request = identity.RandomID("req", 16)
|
||||
req, err := newUpstreamRequest(ctx, g.cfg.Upstream.Zen, protocol, b, ids, key)
|
||||
if err != nil {
|
||||
return probeResult{reason: "request_creation_error"}
|
||||
}
|
||||
result := probeResult{attempted: true}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
result.reason = "transport_error"
|
||||
if ctx.Err() != nil {
|
||||
result.reason = "probe_timeout"
|
||||
}
|
||||
return result
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode/100 != 2 {
|
||||
body, readErr := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
|
||||
result.reason = fmt.Sprintf("http_%d", resp.StatusCode)
|
||||
if readErr == nil {
|
||||
result.effortRejected = isEffortRejection(resp.StatusCode, string(body))
|
||||
if isModelUnavailable(resp.StatusCode, string(body)) {
|
||||
result.reason = "model_unavailable"
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
reader := io.LimitReader(resp.Body, 1<<20)
|
||||
if strings.Contains(strings.ToLower(resp.Header.Get("Content-Type")), "text/event-stream") && protocol != wire.SystemOne {
|
||||
_, err = wire.CollapseStream(reader, protocol, model)
|
||||
} else {
|
||||
var document map[string]any
|
||||
err = json.NewDecoder(reader).Decode(&document)
|
||||
if err == nil && (document == nil || document["error"] != nil) {
|
||||
err = fmt.Errorf("upstream error envelope: %v", document["error"])
|
||||
}
|
||||
if err == nil {
|
||||
switch protocol {
|
||||
case wire.SystemOne:
|
||||
answer := jsonutil.MapAt(document, "answers", "arithmetic")
|
||||
probability, ok := answer["noul"].(float64)
|
||||
if !ok || probability < 0 || probability > 1 || answer["type"] != "noul" {
|
||||
err = fmt.Errorf("invalid System One answer")
|
||||
}
|
||||
default:
|
||||
field := "choices"
|
||||
if protocol == wire.Anthropic {
|
||||
field = "content"
|
||||
} else if protocol == wire.Responses {
|
||||
field = "output"
|
||||
}
|
||||
if _, ok := document[field].([]any); !ok {
|
||||
err = fmt.Errorf("invalid response schema")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
result.success = err == nil && ctx.Err() == nil
|
||||
result.reason = "probe_succeeded"
|
||||
if !result.success {
|
||||
result.reason = "invalid_or_incomplete_response"
|
||||
if err != nil {
|
||||
result.effortRejected = isEffortRejection(400, err.Error())
|
||||
if isModelUnavailable(400, err.Error()) {
|
||||
result.reason = "model_unavailable"
|
||||
}
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
result.reason = "probe_timeout"
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func isModelUnavailable(status int, body string) bool {
|
||||
if status != 400 && status != 404 && status != 410 && status != 422 {
|
||||
return false
|
||||
}
|
||||
text := strings.ToLower(body)
|
||||
for _, marker := range []string{"model_not_found", "model_not_available", "model_retired", "model_deprecated", "unknown model", "model does not exist", "model has been retired", "model is no longer available"} {
|
||||
if strings.Contains(text, marker) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func isEffortRejection(status int, body string) bool {
|
||||
if status != 400 && status != 422 {
|
||||
return false
|
||||
}
|
||||
text := strings.ToLower(body)
|
||||
if !strings.Contains(text, "effort") && !strings.Contains(text, "thinking") && !strings.Contains(text, "reasoning") {
|
||||
return false
|
||||
}
|
||||
for _, marker := range []string{"invalid", "unsupported", "not support", "not allowed", "must be", "allowed values"} {
|
||||
if strings.Contains(text, marker) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -23,7 +23,7 @@ import (
|
||||
func (g *Gateway) syncRotation() {
|
||||
available := map[string]bool{}
|
||||
for _, model := range g.catalog.List() {
|
||||
if _, err := g.catalog.RouteForTier(model, config.TierGo, false, g.goNodes.Len() > 0); err == nil {
|
||||
if route, err := g.catalog.RouteForTier(model, config.TierGo, false, g.goNodes.Len() > 0); err == nil && route.Protocol != wire.SystemOne {
|
||||
available[model] = true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -135,6 +135,7 @@ func (m *RuntimeManager) build(cfg config.Config) (*gatewayRuntime, error) {
|
||||
}
|
||||
gateway.catalog.SetPricingStore(m.metadata)
|
||||
gateway.catalog.SetAvailabilityStore(availability)
|
||||
gateway.availability = availability
|
||||
gateway.catalog.SetCachePath(modelcatalog.CatalogCachePath(m.configPath))
|
||||
return &gatewayRuntime{config: cfg, gateway: gateway, availability: availability, handler: gateway.Handler(), cancel: func() {}}, nil
|
||||
}
|
||||
|
||||
@@ -11,14 +11,23 @@ import (
|
||||
const FreeModelCheckInterval = time.Hour
|
||||
const FailedModelCheckInterval = 24 * time.Hour
|
||||
|
||||
type EffortProbe struct {
|
||||
Effort string `json:"effort,omitempty"`
|
||||
Protocol string `json:"protocol,omitempty"`
|
||||
Reset bool `json:"-"`
|
||||
}
|
||||
|
||||
type Availability struct {
|
||||
Model string `json:"model"`
|
||||
Disabled bool `json:"disabled"`
|
||||
CheckedAt time.Time `json:"checked_at,omitempty"`
|
||||
NextCheck time.Time `json:"next_check"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
Channel string `json:"channel,omitempty"`
|
||||
Generation uint64 `json:"-"`
|
||||
Model string `json:"model"`
|
||||
Disabled bool `json:"disabled"`
|
||||
CheckedAt time.Time `json:"checked_at,omitempty"`
|
||||
NextCheck time.Time `json:"next_check"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
Channel string `json:"channel,omitempty"`
|
||||
Generation uint64 `json:"-"`
|
||||
ProbeVersion int `json:"probe_version,omitempty"`
|
||||
AutoEffort EffortProbe `json:"auto_effort,omitempty"`
|
||||
EffortCheckedAt time.Time `json:"effort_checked_at,omitempty"`
|
||||
}
|
||||
|
||||
type AvailabilityStore struct {
|
||||
@@ -42,6 +51,16 @@ func NewAvailabilityStore(path string) (*AvailabilityStore, error) {
|
||||
if s.items == nil {
|
||||
s.items = map[string]Availability{}
|
||||
}
|
||||
// Legacy probes used invalid session IDs and treated temporary errors as
|
||||
// permanent failures. These records cannot establish model unavailability.
|
||||
for model, item := range s.items {
|
||||
if item.ProbeVersion == 0 && item.Disabled {
|
||||
item.Disabled = false
|
||||
item.NextCheck = time.Time{}
|
||||
item.Reason = "legacy_probe_recheck"
|
||||
s.items[model] = item
|
||||
}
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
@@ -64,6 +83,7 @@ func (s *AvailabilityStore) Restore(model string, now time.Time) error {
|
||||
item.Model, item.Disabled, item.Reason = model, false, "manually_enabled"
|
||||
item.NextCheck = now.Add(FreeModelCheckInterval)
|
||||
item.Generation++
|
||||
item.ProbeVersion = 1
|
||||
s.items[model] = item
|
||||
if err := s.saveLocked(); err != nil {
|
||||
if existed {
|
||||
@@ -76,17 +96,28 @@ func (s *AvailabilityStore) Restore(model string, now time.Time) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *AvailabilityStore) Record(model string, generation uint64, success bool, reason, channel string, now time.Time) error {
|
||||
func (s *AvailabilityStore) Record(model string, generation uint64, success bool, reason, channel string, now time.Time, effort EffortProbe) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
item := s.items[model]
|
||||
if item.Generation != generation {
|
||||
return nil
|
||||
}
|
||||
item.Model, item.Disabled = model, !success
|
||||
item.Model = model
|
||||
if success {
|
||||
item.Disabled = false
|
||||
} else if reason == "model_unavailable" {
|
||||
item.Disabled = true
|
||||
}
|
||||
item.CheckedAt, item.Reason, item.Channel = now, reason, channel
|
||||
item.ProbeVersion = 1
|
||||
if success && effort.Effort != "" {
|
||||
item.AutoEffort, item.EffortCheckedAt = effort, now
|
||||
} else if success && effort.Reset {
|
||||
item.AutoEffort, item.EffortCheckedAt = EffortProbe{}, time.Time{}
|
||||
}
|
||||
interval := FreeModelCheckInterval
|
||||
if !success {
|
||||
if !success && reason == "model_unavailable" {
|
||||
interval = FailedModelCheckInterval
|
||||
}
|
||||
item.NextCheck = now.Add(interval)
|
||||
|
||||
+4
-1
@@ -12,7 +12,7 @@ let csrf = "",
|
||||
logRenderPending = false,
|
||||
toastTimer = null;
|
||||
const pages = {
|
||||
availability: ["13", "免费模型可用性", "每小时探测,失败后禁用并每 24 小时复测。"],
|
||||
availability: ["13", "免费模型可用性", "每小时探测,明确失效后禁用并每 24 小时复测。"],
|
||||
rotation: ["12", "模型轮转", "共享当前模型、故障切换与尝试记录。"],
|
||||
overview: ["01", "运行桌面", "最近一小时、进程累计与当前资源状态。"],
|
||||
guide: ["02", "首次运行", "用六个检查点完成从配置到首个请求。"],
|
||||
@@ -1401,6 +1401,9 @@ async function loadAvailability() {
|
||||
item.model,
|
||||
item.disabled ? "已禁用" : "已启用",
|
||||
[item.channel, item.reason].filter(Boolean).join(" / ") || "待探测",
|
||||
item.auto_effort?.effort
|
||||
? `${item.auto_effort.effort}(${date(item.effort_checked_at)})`
|
||||
: "未验证",
|
||||
date(item.checked_at),
|
||||
date(item.next_check),
|
||||
]) {
|
||||
|
||||
+5
-1
@@ -96,7 +96,9 @@
|
||||
</div>
|
||||
<p>
|
||||
检查名称含 free 或元数据零价格且未弃用的模型。优先匿名通道,再尝试 Zen
|
||||
Key;全部失败后禁用,24 小时后复测。成功或手动恢复后,下一次探测在 1 小时后。
|
||||
Key;明确模型失效才禁用并在 24 小时后复测。限流、超时、网络和服务端错误不新增禁用,1
|
||||
小时后重试。 System One 使用专用的 1+1 决策问题。设置 auto
|
||||
强度后,显示探测验证过的最高档位。
|
||||
</p>
|
||||
<p id="availability-error" role="status"></p>
|
||||
<div class="table-wrap">
|
||||
@@ -106,6 +108,7 @@
|
||||
<th>模型</th>
|
||||
<th>状态</th>
|
||||
<th>通道 / 结果</th>
|
||||
<th>已验证思考档位</th>
|
||||
<th>上次探测</th>
|
||||
<th>下次探测</th>
|
||||
<th>操作</th>
|
||||
@@ -598,6 +601,7 @@
|
||||
<label>默认强度</label
|
||||
><select id="c-reasoning-effort">
|
||||
<option value="">跟随客户端</option>
|
||||
<option value="auto">auto(探测最高可用档)</option>
|
||||
<option value="minimal">minimal</option>
|
||||
<option value="low">low</option>
|
||||
<option value="medium">medium</option>
|
||||
|
||||
Reference in new issue
Block a user