mirror of
https://github.com/jasonxu114514/opencode2api.git
synced 2026-12-06 00:03:11 +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
@@ -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)
|
||||
|
||||
Reference in new issue
Block a user