mirror of
https://github.com/jasonxu114514/opencode2api.git
synced 2026-12-05 08:02:53 +00:00
Merge pull request #1 from hanlap0503/fix/rotation-anonymous-2026-10-16
Fix/rotation anonymous 2026 10 16
This commit is contained in:
6 files changed
+114
-72
No files matched your search
@@ -171,6 +171,8 @@ curl http://localhost:8080/v1/systemone \
|
||||
|
||||
System One ghép một state tự do với các câu hỏi có kiểu và trả về câu trả lời có kiểu, nên payload này không dùng chung hình dạng với cầu nối chat/responses và được chuyển tiếp nguyên văn, không bao giờ dịch. Chỉ những mô hình có giao thức gốc là System One mới được phục vụ tại đây; một payload quyết định gửi tới endpoint message (`/v1/chat/completions`, `/v1/responses`) cũng được chuyển tiếp nguyên văn thay vì chuyển đổi. Câu trả lời streaming từ upstream được chuyển tiếp nguyên trạng, không khôi phục luồng.
|
||||
|
||||
Để kiểm tra các mô hình và lưu ID của những mô hình gọi thành công vào `working-models.txt`, chạy `bash scripts/check-models.sh`. Script dùng `config.json` để lấy `server_keys` và sẽ hỏi xác nhận trước khi gửi request; thêm `--yes` để bỏ qua xác nhận.
|
||||
|
||||
### Ranh giới tương thích
|
||||
|
||||
Request dùng giao thức gốc của upstream sẽ giữ nguyên các trường riêng của nhà cung cấp. Request đi qua nhiều giao thức sẽ đi qua một biểu diễn chung; không phải tuỳ chọn nào cũng có phần tương đương. Ví dụ, ràng buộc output JSON của Chat và `seed` không được chuyển tiếp sang Anthropic Messages. Nội dung hoặc loại tool không được hỗ trợ có thể bị từ chối.
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
"time"
|
||||
|
||||
"opencode2api/internal/buildinfo"
|
||||
"opencode2api/internal/config"
|
||||
"opencode2api/internal/httpx"
|
||||
modelcatalog "opencode2api/internal/models"
|
||||
wire "opencode2api/internal/protocol"
|
||||
@@ -208,12 +207,9 @@ 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 {
|
||||
if route, err := g.catalog.Route(model, len(g.cfg.ZenKeys) > 0, len(g.cfg.GoKeys) > 0, g.cfg.Anonymous); err == nil && route.Protocol != wire.SystemOne {
|
||||
available = true
|
||||
break
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ import (
|
||||
func (g *Gateway) syncRotation() {
|
||||
available := map[string]bool{}
|
||||
for _, model := range g.catalog.List() {
|
||||
if route, err := g.catalog.RouteForTier(model, config.TierGo, false, g.goNodes.Len() > 0); err == nil && route.Protocol != wire.SystemOne {
|
||||
if route, err := g.catalog.Route(model, len(g.cfg.ZenKeys) > 0, len(g.cfg.GoKeys) > 0, g.cfg.Anonymous); err == nil && route.Protocol != wire.SystemOne {
|
||||
available[model] = true
|
||||
}
|
||||
}
|
||||
@@ -81,7 +81,7 @@ func (g *Gateway) handleRotation(w http.ResponseWriter, r *http.Request, externa
|
||||
break
|
||||
}
|
||||
visited[token.Model] = true
|
||||
route, err := g.catalog.RouteForTier(token.Model, config.TierGo, false, g.goNodes.Len() > 0)
|
||||
route, err := g.catalog.Route(token.Model, len(g.cfg.ZenKeys) > 0, len(g.cfg.GoKeys) > 0, g.cfg.Anonymous)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
@@ -90,7 +90,7 @@ func (g *Gateway) handleRotation(w http.ResponseWriter, r *http.Request, externa
|
||||
total++
|
||||
if meta != nil {
|
||||
meta.Model = token.Model
|
||||
meta.Tier = "go"
|
||||
meta.Tier = string(route.Tier)
|
||||
meta.Protocol = route.Protocol
|
||||
meta.Attempts = total
|
||||
meta.Usage = wire.Usage{}
|
||||
@@ -181,36 +181,44 @@ func (g *Gateway) rotationAttempt(parent context.Context, w http.ResponseWriter,
|
||||
result.reason = "request_conversion_error"
|
||||
return result
|
||||
}
|
||||
body, shaped := g.shapeKeyBody(bodies[config.TierGo], route, config.TierGo)
|
||||
cursor := g.goNodes.CursorFor(ids.Session)
|
||||
var node *upstreamNode
|
||||
// Each group attempt is exactly one HTTP call. Key selection may change,
|
||||
// but there is no nested retry, stale-reasoning replay, or model-wide key ban.
|
||||
for n := 0; n < attempt; n++ {
|
||||
node = cursor.Next()
|
||||
var resp *http.Response
|
||||
var shaped bool
|
||||
if route.Anonymous {
|
||||
resp, err, _ = g.doAnonymousUpstream(ctx, route, bodies, ids, attempt-1)
|
||||
} else {
|
||||
body, keyShaped := g.shapeKeyBody(bodies[route.Tier], route, route.Tier)
|
||||
shaped = keyShaped
|
||||
pool, upstreamURL := g.zenNodes, g.cfg.Upstream.Zen
|
||||
if route.Tier == config.TierGo {
|
||||
pool, upstreamURL = g.goNodes, g.cfg.Upstream.Go
|
||||
}
|
||||
cursor := pool.CursorFor(ids.Session)
|
||||
var node *upstreamNode
|
||||
for n := 0; n < attempt; n++ {
|
||||
node = cursor.Next()
|
||||
}
|
||||
if node == nil {
|
||||
result.err = fmt.Errorf("no %s key", route.Tier)
|
||||
return result
|
||||
}
|
||||
proxy := pool.Proxy(node)
|
||||
if proxy == nil {
|
||||
result.err = errors.New("no proxy")
|
||||
return result
|
||||
}
|
||||
req, requestErr := newUpstreamRequest(ctx, upstreamURL, route.Protocol, body, ids, node.key)
|
||||
if requestErr != nil {
|
||||
result.err = requestErr
|
||||
return result
|
||||
}
|
||||
req.GetBody = nil
|
||||
client := *proxy.client
|
||||
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
|
||||
setRequestCredential(parent, route.Tier, config.KeyDisplayID(node.key), "key", false, proxy)
|
||||
started := time.Now()
|
||||
resp, err = client.Do(req)
|
||||
g.recordUpstreamAttempt(parent, route, ids, attempt, config.KeyDisplayID(node.key), "key", false, proxy, resp, err, time.Since(started))
|
||||
}
|
||||
if node == nil {
|
||||
result.err = errors.New("no Go key")
|
||||
return result
|
||||
}
|
||||
proxy := g.goNodes.Proxy(node)
|
||||
if proxy == nil {
|
||||
result.err = errors.New("no proxy")
|
||||
return result
|
||||
}
|
||||
req, err := newUpstreamRequest(ctx, g.cfg.Upstream.Go, route.Protocol, body, ids, node.key)
|
||||
if err != nil {
|
||||
result.err = err
|
||||
return result
|
||||
}
|
||||
// A reused connection must not cause net/http to implicitly replay POSTs.
|
||||
req.GetBody = nil
|
||||
client := *proxy.client
|
||||
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
|
||||
setRequestCredential(parent, config.TierGo, config.KeyDisplayID(node.key), "key", false, proxy)
|
||||
started := time.Now()
|
||||
resp, err := client.Do(req)
|
||||
g.recordUpstreamAttempt(parent, route, ids, attempt, config.KeyDisplayID(node.key), "key", false, proxy, resp, err, time.Since(started))
|
||||
if resp != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
@@ -294,7 +302,7 @@ func (g *Gateway) rotationAttempt(parent context.Context, w http.ResponseWriter,
|
||||
result.reason = "first_output_timeout"
|
||||
return result
|
||||
}
|
||||
if shaped {
|
||||
if route.Anonymous || shaped {
|
||||
b, err = wire.CollapseStream(bytes.NewReader(b), route.Protocol, route.ID)
|
||||
}
|
||||
var document map[string]any
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
@@ -52,7 +51,6 @@ type Manager struct {
|
||||
mu sync.Mutex
|
||||
path string
|
||||
state Snapshot
|
||||
cfg config.RotationConfig
|
||||
}
|
||||
|
||||
func New(path string, cfg config.RotationConfig) (*Manager, error) {
|
||||
@@ -86,19 +84,7 @@ func (m *Manager) Configure(cfg config.RotationConfig) {
|
||||
m.state.Groups = append(m.state.Groups, &Group{ID: id})
|
||||
}
|
||||
g := m.state.Groups[i]
|
||||
previous := m.cfg.SOTA
|
||||
if i == 1 {
|
||||
previous = m.cfg.Sweet
|
||||
}
|
||||
order := slices.Clone(g.Order)
|
||||
if len(order) == 0 || !slices.Equal(previous.Order, c.Order) {
|
||||
order = slices.Clone(c.Order)
|
||||
for _, v := range g.Order {
|
||||
if !slices.Contains(order, v) {
|
||||
order = append(order, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
order := slices.Clone(c.Order)
|
||||
if !slices.Equal(order, g.Order) || g.Alias != c.Alias {
|
||||
g.Generation++
|
||||
}
|
||||
@@ -107,12 +93,14 @@ func (m *Manager) Configure(cfg config.RotationConfig) {
|
||||
if g.Paused == nil {
|
||||
g.Paused = map[string]time.Time{}
|
||||
}
|
||||
if !slices.Contains(g.Order, g.Current) && len(g.Order) > 0 {
|
||||
g.Current = g.Order[0]
|
||||
if !slices.Contains(g.Order, g.Current) {
|
||||
g.Current = ""
|
||||
if len(g.Order) > 0 {
|
||||
g.Current = g.Order[0]
|
||||
}
|
||||
g.Generation++
|
||||
}
|
||||
}
|
||||
m.cfg = cfg
|
||||
m.state.FirstOutputSeconds = cfg.FirstOutputSeconds
|
||||
m.saveLocked()
|
||||
}
|
||||
@@ -123,24 +111,10 @@ func (m *Manager) Sync(available map[string]bool) {
|
||||
for _, g := range m.state.Groups {
|
||||
g.Available = map[string]bool{}
|
||||
for model := range available {
|
||||
if config.IsSOTA(model) == (g.ID == "sota") {
|
||||
if config.IsSOTA(model) == (g.ID == "sota") && slices.Contains(g.Order, model) {
|
||||
g.Available[model] = true
|
||||
}
|
||||
}
|
||||
added := []string{}
|
||||
for model := range g.Available {
|
||||
if !slices.Contains(g.Order, model) {
|
||||
added = append(added, model)
|
||||
}
|
||||
}
|
||||
sort.Strings(added)
|
||||
if len(g.Order) == 0 && slices.Contains(added, "glm-5.3-flash") {
|
||||
added = append([]string{"glm-5.3-flash"}, slices.Delete(added, slices.Index(added, "glm-5.3-flash"), slices.Index(added, "glm-5.3-flash")+1)...)
|
||||
}
|
||||
if len(added) > 0 {
|
||||
g.Order = append(g.Order, added...)
|
||||
changed = true
|
||||
}
|
||||
if g.Current == "" && len(g.Order) > 0 {
|
||||
g.Current = g.Order[0]
|
||||
g.Generation++
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package rotation
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"opencode2api/internal/config"
|
||||
)
|
||||
|
||||
func TestConfiguredOrderExcludesDiscoveredAndPersistedModels(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "rotation.json")
|
||||
initial := Snapshot{Groups: []*Group{
|
||||
{ID: "sota", Alias: "sota", Order: config.SOTAModels, Current: config.SOTAModels[0]},
|
||||
{ID: "sweet", Alias: "sweet", Order: []string{"configured-free", "persisted-free"}, Current: "persisted-free"},
|
||||
}}
|
||||
data, err := json.Marshal(initial)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(path, data, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
cfg := config.RotationConfig{
|
||||
Sweet: config.RotationGroup{Alias: "sweet", Order: []string{"configured-free"}},
|
||||
}
|
||||
manager, err := New(path, cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
manager.Sync(map[string]bool{
|
||||
"configured-free": true,
|
||||
"discovered-free": true,
|
||||
})
|
||||
|
||||
sweet := manager.Snapshot().Groups[1]
|
||||
if !reflect.DeepEqual(sweet.Order, []string{"configured-free"}) {
|
||||
t.Fatalf("Sweet order = %v, want only configured models", sweet.Order)
|
||||
}
|
||||
if sweet.Current != "configured-free" {
|
||||
t.Fatalf("Sweet current = %q, want configured-free", sweet.Current)
|
||||
}
|
||||
if !reflect.DeepEqual(sweet.Available, map[string]bool{"configured-free": true}) {
|
||||
t.Fatalf("Sweet available = %v, want only configured models", sweet.Available)
|
||||
}
|
||||
}
|
||||
+14
-1
@@ -33,7 +33,8 @@ fi
|
||||
BASE_URL=${BASE_URL%/}
|
||||
models_file=$(mktemp)
|
||||
response_file=$(mktemp)
|
||||
trap 'rm -f "$models_file" "$response_file"' EXIT
|
||||
working_models_tmp=$(mktemp ./.working-models.txt.tmp.XXXXXX)
|
||||
trap 'rm -f "$models_file" "$response_file" "$working_models_tmp"' EXIT
|
||||
|
||||
if ! curl -sS --fail-with-body "$BASE_URL/v1/models" \
|
||||
-H "Authorization: Bearer $API_KEY" -o "$models_file"; then
|
||||
@@ -50,7 +51,12 @@ fi
|
||||
|
||||
model_count=$(jq '.data | length' "$models_file")
|
||||
if [[ "$model_count" -eq 0 ]]; then
|
||||
if ! mv -f "$working_models_tmp" working-models.txt; then
|
||||
printf 'Could not write working-models.txt\n' >&2
|
||||
exit 1
|
||||
fi
|
||||
printf 'No models were returned by %s/v1/models\n' "$BASE_URL"
|
||||
printf 'An empty model list was saved to working-models.txt\n'
|
||||
exit 0
|
||||
fi
|
||||
|
||||
@@ -109,6 +115,7 @@ while IFS=$'\t' read -r model protocol; do
|
||||
if [[ "$curl_ok" == true && "$status" =~ ^2[0-9][0-9]$ ]] \
|
||||
&& jq -e 'type == "object" and (has("error") | not)' "$response_file" >/dev/null 2>&1; then
|
||||
printf 'PASS %s (%s, HTTP %s)\n' "$model" "$protocol" "$status"
|
||||
printf '%s\n' "$model" >> "$working_models_tmp"
|
||||
passed=$((passed + 1))
|
||||
else
|
||||
message=$(jq -r '.error.message // .message // empty' "$response_file" 2>/dev/null | head -c 200)
|
||||
@@ -121,8 +128,14 @@ while IFS=$'\t' read -r model protocol; do
|
||||
fi
|
||||
done < <(jq -r '.data[] | [.id, (.native_protocol // "chat")] | @tsv' "$models_file")
|
||||
|
||||
if ! mv -f "$working_models_tmp" working-models.txt; then
|
||||
printf 'Could not write working-models.txt\n' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
printf '\nSummary: %s passed, %s failed, %s skipped (total %s)\n' \
|
||||
"$passed" "$failed" "$skipped" "$model_count"
|
||||
printf 'Working model list saved to working-models.txt\n'
|
||||
if [[ "$failed" -gt 0 || "$skipped" -gt 0 ]]; then
|
||||
exit 1
|
||||
fi
|
||||
Reference in new issue
Block a user