Files
magpie/internal/provider/detect.go
T
yetone c9b7f95f90 providers: Detect APIs asks every picked model on each API and shows model by API, and a model's right-click Test says the API it answered on (01huadalang on Discord: 右键选择测试只能测试出是不是通的,不能说什么协议是通的。检测协议的结果看不出对应的模型支持协议情况…有的仅支持 response 有的双协议) — Detect APIs asked one model (typed, or one picked from the vendor's list for each API), so a relay serving some models on Responses only and others on both read as "chat works, responses doesn't", and the right-click Test said only that a model answered. Detect APIs now has "Each picked model" (逐个检测已选模型): provider/detect with detectModels asks each picked model (the first provider.DetectMax, 30; an image model left out, it is asked on the images API) on Chat, Responses and Anthropic at the URLs Detect asks, provider.DetectWide (8) requests at a time, each waiting 12 s, the whole within 2 minutes (a probe not started by then is "not asked: out of time" and sent nowhere), and answers model by model plus, by API, the first model it served. The editor shows a model × API grid, each cell a ✓ with the time or a ✗ with the status and why (the whole in its title). Its "Use these" sets the URLs of the APIs that answered and gives each model that answered on one API only (of two or more asked) that API, staged in Names & levels as draft.modelPrefs like the rest of b0dc82c4 — "unsaved", nothing sent until the Save, Cancel drops it — while a model answering on two stays Auto; the hint under the grid names them ("m-resp: Responses only"). Detect for one model is as it was (its body now Provider.detecting and detectOne, shared). A chip's right-click Test now says the API it was asked on: "gpt-5.5 answered via Responses in 123 ms", the dot's title "Answered via Responses in …", a failure "didn't answer via OpenAI: …". TestDetectModels (a fake relay serving gpt-both on Chat and Responses, gpt-resp on Responses, glm-chat on Chat, claude-only on Anthropic: each model's ✓/✗ on each API, 12 requests for 4 models, the image model not asked, by API the first served; 35 models asked as 30, never more than 8 at once) and TestDetectModelsOutOfTime are new; provider-detect-models.test.cjs (WebKit, en and zh: the models posted, the grid, Use these staging m-resp on Responses and m-chat on OpenAI with m-both left Auto and nothing sent, the Save's modelPrefs, the right-click Test's "via Responses", no click scrolling, no left-border accent, every string's Chinese). provider-detect, provider-levels-save, provider-levels-scroll, model-test-one, model-test-why and click-scroll pass in WebKit. go vet ./internal/..., go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui -count=1 ./... under a temp HOME pass (TestFXInState's known TempDir cleanup flake aside).
2026-10-02 23:10:11 +08:00

289 lines
8.2 KiB
Go

package provider
import (
"context"
"errors"
"net/url"
"slices"
"strings"
"sync"
"time"
"github.com/yetone/magpie/internal/catalog"
)
// Which APIs a vendor or relay serves behind the one URL the user typed is
// found by asking (01huadalang on Discord: 一键检测支持什么协议,发一个最小
// 请求看是否返回200): each of the three magpie speaks upstream — Chat
// Completions, Responses and Anthropic Messages — is sent the smallest
// request Test sends, at that URL as the API takes it, and what answered
// is what the provider can be given. Gemini's isn't among them: magpie
// serves it to clients but never asks a vendor on it, so a URL for it
// would be one the provider has nowhere to keep.
// Detection is what one API answered at the URL it was asked at.
type Detection struct {
Result
// Base is the URL the provider keeps for it, as the editor's fields
// take it: …/v1 for OpenAI's two, the root for Anthropic's.
Base string `json:"base"`
}
// DetectBase is base as proto takes it: an endpoint pasted whole (…/v1/chat/
// completions) cut to its base, then the root for Anthropic, which adds
// /v1/messages itself, and …/v1 for OpenAI's two when base is a bare host —
// the editor's respellURL, in Go.
func DetectBase(base string, proto Protocol) string {
u := strings.TrimRight(strings.TrimSpace(base), "/")
for _, end := range []string{"/chat/completions", "/responses", "/v1/messages", "/messages"} {
u = strings.TrimSuffix(u, end)
}
if u == "" {
return ""
}
if proto == Anthropic {
return strings.TrimSuffix(u, "/v1")
}
if pu, err := url.Parse(u); err == nil && strings.Trim(pu.Path, "/") == "" {
return u + "/v1"
}
return u
}
// ErrNoURL is a detection with no URL to ask at.
var ErrNoURL = errors.New("type the base URL first")
// Detect asks each of Chat, Responses and Anthropic at the URL p has for
// it, else at base as it takes it (DetectBase), the smallest request, and
// says what each answered, in that order. model is asked on all three;
// with none, one from p's list is picked for each — a Claude model on
// Anthropic's, an OpenAI one on Responses — and with no list, the vendor
// is asked for one first (a GET of its models, which costs nothing).
// Only those URLs are asked, and only a key's provider: a sign-in's API
// is its agent's.
func (p Provider) Detect(ctx context.Context, base, model string) ([]Detection, error) {
q, err := p.detecting(base)
if err != nil {
return nil, err
}
ctx = q.Via(ctx)
model = strings.TrimSpace(model)
var ids []string
if model == "" {
ids = q.detectModels(ctx)
}
out := make([]Detection, len(Protocols))
var wg sync.WaitGroup
for i, proto := range Protocols {
m := model
if m == "" {
m = detectModel(ids, proto)
}
var ask func(context.Context) Result
out[i], ask = q.detectOne(proto, m, testWait)
if ask == nil {
continue
}
wg.Add(1)
go func() {
defer wg.Done()
out[i].Result = ask(ctx)
}()
}
wg.Wait()
return out, nil
}
// detecting is p with the URL it would be asked at for each API: its own,
// else base as that API takes it.
func (p Provider) detecting(base string) (Provider, error) {
if p.Account != nil {
return p, errors.New("a sign-in is asked on its agent's own API; there is nothing to detect")
}
q := p
for _, proto := range Protocols {
u := strings.TrimSpace(p.Base(proto))
if u == "" {
u = DetectBase(base, proto)
}
if u != "" {
if pu, err := url.Parse(u); err != nil || (pu.Scheme != "http" && pu.Scheme != "https") || pu.Host == "" {
return p, errors.New("the base URL must start with http:// or https://, not " + u)
}
}
switch proto {
case Chat:
q.Chat = u
case Responses:
q.Responses = u
case Anthropic:
q.Anthropic = u
}
}
if len(q.Speaks()) == 0 {
return p, ErrNoURL
}
return q, nil
}
// detectOne is model's detection on proto as far as it can be told
// without asking, and, when it can be asked, the ask (nil when not).
func (q Provider) detectOne(proto Protocol, m string, wait time.Duration) (Detection, func(context.Context) Result) {
d := Detection{Result: Result{Protocol: proto, Model: m}, Base: q.Base(proto)}
if d.Base == "" {
d.Error = "no URL to ask"
return d, nil
}
if m == "" {
d.Error = "no model to try: type one the vendor serves"
return d, nil
}
k, ok := q.keyFor(proto)
if !ok {
d.Error = "no key is on for this endpoint"
return d, nil
}
return d, func(ctx context.Context) Result {
u, body := tiny(k, proto, UpstreamName(q, m))
return probe(ctx, k, proto, u, k.Prepare([]byte(body)), m, wait)
}
}
// ModelDetection is what each API answered for one model
// (01huadalang on Discord: 应该能看出来选择的模型支持情况…有的仅支持
// response 有的双协议).
type ModelDetection struct {
Model string `json:"model"`
Results []Detection `json:"results"`
}
// A detection of many models asks at most DetectMax of them, DetectWide
// requests at a time, each waiting detectWait for its answer.
const (
DetectMax = 30
DetectWide = 8
detectWait = 12 * time.Second
)
// DetectModels asks each of models (the first DetectMax, an image model
// left out: it is asked on the images API) on each of Chat, Responses and
// Anthropic at the URL p has for it, else at base as it takes it, and
// says what each answered, model by model; and, by API, the first answer
// from a model it served, else the first model's — what Detect says for
// one. A probe not started before ctx ends says so, unasked.
func (p Provider) DetectModels(ctx context.Context, base string, models []string) ([]ModelDetection, []Detection, error) {
q, err := p.detecting(base)
if err != nil {
return nil, nil, err
}
var ids []string
for _, m := range models {
if m = strings.TrimSpace(m); m != "" && !slices.Contains(ids, m) {
ids = append(ids, m)
}
}
if len(ids) == 0 {
return nil, nil, errors.New("no model to try: type one the vendor serves")
}
if len(ids) > DetectMax {
ids = ids[:DetectMax]
}
ctx = q.Via(ctx)
out := make([]ModelDetection, len(ids))
sem := make(chan struct{}, DetectWide)
var wg sync.WaitGroup
for i, m := range ids {
out[i] = ModelDetection{Model: m, Results: make([]Detection, len(Protocols))}
for j, proto := range Protocols {
d, ask := q.detectOne(proto, m, detectWait)
if ask != nil && catalog.ImagesAPI(m) {
d.Error, ask = "an image model: asked on the images API, not here", nil
}
out[i].Results[j] = d
if ask == nil {
continue
}
wg.Add(1)
go func() {
defer wg.Done()
select {
case sem <- struct{}{}:
case <-ctx.Done():
out[i].Results[j].Error = "not asked: out of time"
return
}
defer func() { <-sem }()
if ctx.Err() != nil {
out[i].Results[j].Error = "not asked: out of time"
return
}
out[i].Results[j].Result = ask(ctx)
}()
}
}
wg.Wait()
sum := make([]Detection, len(Protocols))
for j := range Protocols {
sum[j] = out[0].Results[j]
for _, md := range out {
if md.Results[j].OK {
sum[j] = md.Results[j]
break
}
}
}
return out, sum, nil
}
// detectModels are the models a detection may ask for: those p exposes and
// lists, else the vendor's list, asked for now and not kept.
func (p Provider) detectModels(ctx context.Context) []string {
var ids []string
if p.ID != "" {
for _, ms := range [][]catalog.Model{p.Exposed(), p.Available()} {
for _, m := range ms {
if !slices.Contains(ids, m.ID) {
ids = append(ids, m.ID)
}
}
}
}
if len(ids) > 0 {
return ids
}
ms, _, err := p.fetchOne(ctx)
if err != nil {
return nil
}
for _, m := range ms {
ids = append(ids, m.ID)
}
return ids
}
// detectModel is the model of ids to ask proto for: one made for it — a
// Claude model on Anthropic's, an OpenAI one on Responses, any other on
// Chat — else the first that chats.
func detectModel(ids []string, proto Protocol) string {
made := func(id string) bool {
switch proto {
case Anthropic:
return isClaude(id)
case Responses:
return openAIModel(id)
}
return !isClaude(id)
}
for _, want := range []func(string) bool{made, func(string) bool { return true }} {
for _, id := range ids {
if want(id) && !catalog.ImagesAPI(id) {
return id
}
}
}
if len(ids) > 0 {
return ids[0]
}
return ""
}