diff --git a/docs/reference.md b/docs/reference.md index 2a07d07bb..b2d8e9618 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -419,7 +419,7 @@ and models with custom names. These appear as decision models rather than chat models. A bare provider id such as `office` asks the first listed decision model; it does not pick another model to satisfy a key's limits. If the key permits only another model, use its full `office/provider/model` -id to avoid a 403. Embeddings and rerank requests use the remote's corresponding +id to avoid a 403. Embeddings, rerank and speech-to-text requests use the remote's corresponding APIs, and its exposed retrieval models are kept when fetching its list. These remain in agent model lists as on the remote; being listed does not mean an embedding or rerank model can hold a conversation. @@ -1572,6 +1572,7 @@ It exposes: | `/v1/messages` | Anthropic Messages | | `/v1/messages/count_tokens` | Anthropic token counting | | `/v1beta/models/{model}:generateContent` | Google Gemini (also `:streamGenerateContent`, `:countTokens`) | +| `/v1/audio/transcriptions`, `/v1/audio/translations` | OpenAI speech to text (multipart, passed through) | | `/v1/models`, `/v1beta/models` | the catalog | | `/v1/codex/models` | the catalog as Codex's `model_catalog_url` reads it ([Codex on another computer](#providers-and-the-gateway)) | @@ -1598,6 +1599,15 @@ models are named `provider/model`. it goes to the routing group magpie found for it, which asks them in the order of the Providers page and falls over to the next. With found groups off, it goes to the first of them in that order alone. +- Speech to text (`/v1/audio/transcriptions`, `/v1/audio/translations`) + takes OpenAI's multipart form, its `model` a magpie id such as + `openai/whisper-1`, `groq/whisper-large-v3` or a custom provider's own + (a vLLM `qwen3-asr`). The form goes to that provider's OpenAI-style base + as it was sent, the audio byte for byte; only the model is set to the + provider's own id, and a `prompt` masked as your redaction settings say. + The answer comes back in the vendor's own format (`json`, `text`, `srt`, + `vtt`). A provider with no OpenAI-style API is refused; one that has no + such endpoint answers its own 404. Text to speech is not served. - Every reply names who answered in `X-Magpie-Provider` (the provider) and `X-Magpie-Model` (`provider/model`), and so does the usage log. diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 31ccbaf85..6a3be5192 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -143,8 +143,8 @@ recorded as a prediction failure (`noPrediction`). ## Remote magpie APIs A remote provider serves the conversation, token-counting, System One, -embeddings, rerank, image generation/edit and video creation/status/content -APIs. Gemini clients enter through the local Gemini adapter and follow the +embeddings, rerank, speech-to-text, image generation/edit and video +creation/status/content APIs. Gemini clients enter through the local Gemini adapter and follow the same model routing as other conversation clients. Responses uses HTTP/SSE; its WebSocket route still answers 426. Discovery and older-peer behavior are described in [Providers and accounts](providers-accounts.md#remote-magpie). @@ -177,7 +177,10 @@ way (`askDecisionGroup`, `decideRefused` carrying the vendor's status). A decision group is kept out of the agents' catalog (`groupEntries`), and a conversation asked of it is refused 400 pointing at `/v1/systemone`. [`embeddings.go`](../../internal/gateway/embeddings.go) relays retrieval -bodies and options, [`draw.go`](../../internal/gateway/draw.go) sends images +bodies and options (`serveRetrieval`), and +[`transcribe.go`](../../internal/gateway/transcribe.go) speech-to-text's +multipart forms through it as sent, rewriting only the model and a masked +prompt under the form's own boundary (#2053), [`draw.go`](../../internal/gateway/draw.go) sends images to the remote's images API, and [`video.go`](../../internal/gateway/video.go) wraps remote task ids for later polls and downloads. `passOnCaller` in [`remote_magpie.go`](../../internal/gateway/remote_magpie.go) supplies diff --git a/internal/gateway/cors_test.go b/internal/gateway/cors_test.go index 6743e3153..a7dc84d77 100644 --- a/internal/gateway/cors_test.go +++ b/internal/gateway/cors_test.go @@ -237,6 +237,7 @@ func TestForeignPagesRefused(t *testing.T) { {"POST", "/v1beta/models/plan/m1:generateContent", `{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`}, {"POST", "/v1/embeddings", `{"model":"plan/m1","input":"hi"}`}, {"POST", "/v1/rerank", `{"model":"plan/m1","query":"hi","documents":["a"]}`}, + {"POST", "/v1/audio/transcriptions", "--b\r\nContent-Disposition: form-data; name=\"model\"\r\n\r\nplan/m1\r\n--b--\r\n"}, {"POST", "/v1/images/generations", `{"model":"plan/m1","prompt":"hi"}`}, {"POST", "/v1/videos", `{"model":"plan/m1","prompt":"hi"}`}, {"POST", CodexPath + "/responses", `{"model":"plan/m1","input":"hi"}`}, diff --git a/internal/gateway/embeddings.go b/internal/gateway/embeddings.go index 211ba4767..81b08125b 100644 --- a/internal/gateway/embeddings.go +++ b/internal/gateway/embeddings.go @@ -43,156 +43,198 @@ func (s *Server) retrieve(path, operation string) http.HandlerFunc { writeError(w, provider.Chat, 400, "name the model: \"model\" is a magpie model id, as /v1/models lists them") return } - who := callerOf(r) - call := Call{Time: start, From: provider.Chat, Agent: who.agent, Via: who.via, Model: asked} - usage.Saw(agentOf(r)) - // a model the user disabled (#1867), or a group of them all - if msg, off := idOff(asked); off { + s.serveRetrieval(w, r, path, operation, start, asked, &jsonRetrieval{req: req}) + } +} + +// retrieval is a retrieval request as read: what goes to a vendor for each +// model it may be asked of. +type retrieval interface { + // mask masks what goes to the vendors, and gives the writer that puts + // the masked values back in their answer + mask(w http.ResponseWriter) (http.ResponseWriter, func()) + // forModel is the body and its Content-Type for the provider's own id + // of the model + forModel(model string) ([]byte, string, error) + // answerType is the Content-Type the vendor's answer goes back with, + // given the one it came with + answerType(got string) string +} + +// jsonRetrieval is an embeddings or rerank body: a JSON object. +type jsonRetrieval struct{ req map[string]json.RawMessage } + +func (j *jsonRetrieval) mask(w http.ResponseWriter) (http.ResponseWriter, func()) { + // masked once, as the settings say: a document a reranker gives back + // has its secrets again + all, _ := json.Marshal(j.req) + w, all, done := redacted(w, all) + json.Unmarshal(all, &j.req) + return w, done +} + +// answerType is JSON, whatever a vendor labels it. +func (j *jsonRetrieval) answerType(string) string { return "application/json" } + +func (j *jsonRetrieval) forModel(model string) ([]byte, string, error) { + j.req["model"], _ = json.Marshal(model) + out, err := json.Marshal(j.req) + return out, "application/json", err +} + +// serveRetrieval routes a retrieval request for the model asked to its +// provider, or over a group's members, and passes the answer back. +func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, operation string, start time.Time, asked string, req retrieval) { + who := callerOf(r) + call := Call{Time: start, From: provider.Chat, Agent: who.agent, Via: who.via, Model: asked} + usage.Saw(agentOf(r)) + // a model the user disabled (#1867), or a group of them all + if msg, off := idOff(asked); off { + call.Status, call.Error = 403, msg + writeError(w, provider.Chat, 403, msg) + s.record(call) + return + } + p, model, ok := resolveRetrievalModel(asked) + if _, _, isGroup := provider.FindGroup(asked); ok && !isGroup { + if msg, off := modelOff(p, model, asked); off { call.Status, call.Error = 403, msg writeError(w, provider.Chat, 403, msg) s.record(call) return } - p, model, ok := resolveRetrievalModel(asked) - if _, _, isGroup := provider.FindGroup(asked); ok && !isGroup { - if msg, off := modelOff(p, model, asked); off { - call.Status, call.Error = 403, msg - writeError(w, provider.Chat, 403, msg) - s.record(call) - return - } + } + if !ok { + msg := unknownModel(asked, "") + if off, isOff := provider.SwitchedOff(asked); isOff { + msg = switchedOff(off, asked) } - if !ok { - msg := unknownModel(asked, "") - if off, isOff := provider.SwitchedOff(asked); isOff { - msg = switchedOff(off, asked) - } - call.Status, call.Error = 404, msg - writeError(w, provider.Chat, 404, msg) + call.Status, call.Error = 404, msg + writeError(w, provider.Chat, 404, msg) + s.record(call) + return + } + g, ms, isGroup := provider.FindGroup(asked) + if keyWho, held := keyHolds(r); held && (isGroup && !groupAllowed(keyWho, g, ms) || !isGroup && !modelAllowed(keyWho, p, model)) { + msg := keyModelError(keyWho, asked) + call.Status, call.Error = 403, msg + writeError(w, provider.Chat, 403, msg) + s.record(call) + return + } + if isGroup { + // a model a pause rule holds for now is left out, as for a chat + var paused []provider.Paused + if ms, paused = provider.PausedOut(g.Live(), ms, agentOf(r), "", ruleClock()); len(ms) == 0 && len(paused) > 0 { + msg := pausedError(asked, paused) + call.Status, call.Error = 503, msg + writeError(w, provider.Chat, 503, msg) s.record(call) return + } else if len(paused) > 0 { + p, model = ms[0].Provider, ms[0].Model // not the paused one, when planning finds none } - g, ms, isGroup := provider.FindGroup(asked) - if keyWho, held := keyHolds(r); held && (isGroup && !groupAllowed(keyWho, g, ms) || !isGroup && !modelAllowed(keyWho, p, model)) { - msg := keyModelError(keyWho, asked) - call.Status, call.Error = 403, msg - writeError(w, provider.Chat, 403, msg) - s.record(call) - return - } - if isGroup { - // a model a pause rule holds for now is left out, as for a chat - var paused []provider.Paused - if ms, paused = provider.PausedOut(g.Live(), ms, agentOf(r), "", ruleClock()); len(ms) == 0 && len(paused) > 0 { - msg := pausedError(asked, paused) - call.Status, call.Error = 503, msg - writeError(w, provider.Chat, 503, msg) - s.record(call) - return - } else if len(paused) > 0 { - p, model = ms[0].Provider, ms[0].Model // not the paused one, when planning finds none - } - } - call.To = provider.Chat - // a routing group's members are tried as its routing orders them, - // each account or key of theirs too (#773), the next asked when one - // fails: a member that serves no such API (404), one out of quota - // (429) or one whose vendor fails; a model is asked on its own - tries := []candidate{{p: p, model: model}} - if isGroup { - if cs, _ := s.planGroup(g.Live(), ms, provider.Chat); len(cs) > 0 { - tries = cs - } - } else { - // a model of one provider goes over its keys or accounts as a - // chat does, never on one whose own list of models leaves it - // out (#1657) - cs, code, msg := s.onKeys(r, p, model, asked) - if code != 0 { - call.Status, call.Error = code, msg - writeError(w, provider.Chat, code, msg) - s.record(call) - return - } + } + call.To = provider.Chat + // a routing group's members are tried as its routing orders them, + // each account or key of theirs too (#773), the next asked when one + // fails: a member that serves no such API (404), one out of quota + // (429) or one whose vendor fails; a model is asked on its own + tries := []candidate{{p: p, model: model}} + if isGroup { + if cs, _ := s.planGroup(g.Live(), ms, provider.Chat); len(cs) > 0 { tries = cs } - // the accounts or keys the calling key may not use are left out of - // the tries too (#905): a group's members through it no less - if keyWho, held := accountHolds(r); held { - tries = slices.DeleteFunc(tries, func(c candidate) bool { return !accountAllowed(keyWho, c) }) - if len(tries) == 0 { - msg := keyAccountsError(keyWho, asked) - call.Status, call.Error = 403, msg - writeError(w, provider.Chat, 403, msg) - s.record(call) - return - } - } - tries = probeOne(tries) // of those resting, only the one back soonest (#1799) - var skipped []string - // masked once, as the settings say: a document a reranker gives - // back has its secrets again - all, _ := json.Marshal(req) - // unless every try is on this machine or the local network, set - // to go unmasked (provider.SkipsRedaction) - if slices.ContainsFunc(tries, func(c candidate) bool { return !c.p.SkipsRedaction() }) { - var done func() - w, all, done = redacted(w, all) - defer done() - json.Unmarshal(all, &req) - } - for i, c := range tries { - last := i == len(tries)-1 - call.Provider = c.p.ID - base := strings.TrimRight(c.p.Base(provider.Chat), "/") - if base == "" { - msg := fmt.Sprintf("%s has no OpenAI-style API for %s", c.p.Name, path) - if !last { - skipped = append(skipped, c.label()+": "+msg) - continue - } - call.Status, call.Error, call.Millis = 400, msg, time.Since(start).Milliseconds() - call.Fallback = strings.Join(skipped, "; ") - writeError(w, provider.Chat, 400, msg) - s.record(call) - return - } - req["model"], _ = json.Marshal(c.model) - out, _ := json.Marshal(req) - ctx, cancel := context.WithTimeout(r.Context(), retrieveTimeout) - b, code, err := s.retrieveFrom(ctx, c.p, base+path, out) - cancel() - call.Millis = time.Since(start).Milliseconds() - if err != nil && !last && r.Context().Err() == nil { - skipped = append(skipped, c.label()+": "+err.Error()) - continue - } - call.Status = code - in := retrievedTokens(b) - call.Usage.Input = in - call.Fallback = strings.Join(skipped, "; ") - providerKeyID, providerKeyName := "", "" - if c.p.Account == nil && c.p.Key != "" { - providerKeyID, providerKeyName = provider.KeyID(c.p.Key), c.p.KeyName - } - appendUsage(r, usage.Record{Operation: operation, Time: start, Agent: call.Agent, Via: call.Via, Provider: c.p.ID, Host: c.p.Where(), Model: c.model, Requested: asked, ProviderKeyID: providerKeyID, ProviderKeyName: providerKeyName, ProviderAccount: accountOf(c.p), - Input: in, Millis: call.Millis, Status: code, Session: sessionOf(r.Header)}) - if err != nil { - call.Error = err.Error() - s.record(call) - msg := err.Error() - if len(skipped) > 0 { - msg += " (tried first: " + call.Fallback + ")" - } - writeError(w, provider.Chat, code, msg) - return - } + } else { + // a model of one provider goes over its keys or accounts as a + // chat does, never on one whose own list of models leaves it + // out (#1657) + cs, code, msg := s.onKeys(r, p, model, asked) + if code != 0 { + call.Status, call.Error = code, msg + writeError(w, provider.Chat, code, msg) s.record(call) - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(code) - w.Write(b) return } + tries = cs + } + // the accounts or keys the calling key may not use are left out of + // the tries too (#905): a group's members through it no less + if keyWho, held := accountHolds(r); held { + tries = slices.DeleteFunc(tries, func(c candidate) bool { return !accountAllowed(keyWho, c) }) + if len(tries) == 0 { + msg := keyAccountsError(keyWho, asked) + call.Status, call.Error = 403, msg + writeError(w, provider.Chat, 403, msg) + s.record(call) + return + } + } + tries = probeOne(tries) // of those resting, only the one back soonest (#1799) + var skipped []string + // unless every try is on this machine or the local network, set + // to go unmasked (provider.SkipsRedaction) + if slices.ContainsFunc(tries, func(c candidate) bool { return !c.p.SkipsRedaction() }) { + var done func() + w, done = req.mask(w) + defer done() + } + for i, c := range tries { + last := i == len(tries)-1 + call.Provider = c.p.ID + base := strings.TrimRight(c.p.Base(provider.Chat), "/") + if base == "" { + msg := fmt.Sprintf("%s has no OpenAI-style API for %s", c.p.Name, path) + if !last { + skipped = append(skipped, c.label()+": "+msg) + continue + } + call.Status, call.Error, call.Millis = 400, msg, time.Since(start).Milliseconds() + call.Fallback = strings.Join(skipped, "; ") + writeError(w, provider.Chat, 400, msg) + s.record(call) + return + } + out, ctype, err := req.forModel(c.model) + if err != nil { + call.Status, call.Error, call.Millis = 400, err.Error(), time.Since(start).Milliseconds() + writeError(w, provider.Chat, 400, err.Error()) + s.record(call) + return + } + ctx, cancel := context.WithTimeout(r.Context(), retrieveTimeout) + b, got, code, err := s.retrieveAs(ctx, c.p, base+path, ctype, out) + cancel() + call.Millis = time.Since(start).Milliseconds() + if err != nil && !last && r.Context().Err() == nil { + skipped = append(skipped, c.label()+": "+err.Error()) + continue + } + call.Status = code + in, outTokens := retrievedTokens(b), answeredTokens(b) + call.Usage.Input, call.Usage.Output = in, outTokens + call.Fallback = strings.Join(skipped, "; ") + providerKeyID, providerKeyName := "", "" + if c.p.Account == nil && c.p.Key != "" { + providerKeyID, providerKeyName = provider.KeyID(c.p.Key), c.p.KeyName + } + appendUsage(r, usage.Record{Operation: operation, Time: start, Agent: call.Agent, Via: call.Via, Provider: c.p.ID, Host: c.p.Where(), Model: c.model, Requested: asked, ProviderKeyID: providerKeyID, ProviderKeyName: providerKeyName, ProviderAccount: accountOf(c.p), + Input: in, Output: outTokens, Millis: call.Millis, Status: code, Session: sessionOf(r.Header)}) + if err != nil { + call.Error = err.Error() + s.record(call) + msg := err.Error() + if len(skipped) > 0 { + msg += " (tried first: " + call.Fallback + ")" + } + writeError(w, provider.Chat, code, msg) + return + } + s.record(call) + w.Header().Set("Content-Type", req.answerType(got)) + w.WriteHeader(code) + w.Write(b) + return } } @@ -222,13 +264,22 @@ func resolveRetrievalModel(id string) (provider.Provider, string, bool) { // retrieveFrom posts body to url as the provider signs its requests, and // reads the answer; a failure's code is the vendor's, with its message. func (s *Server) retrieveFrom(ctx context.Context, p provider.Provider, url string, body []byte) ([]byte, int, error) { + b, _, code, err := s.retrieveAs(ctx, p, url, "application/json", body) + return b, code, err +} + +// retrieveAs is retrieveFrom with a body of its own Content-Type, a +// multipart form's with its boundary; it also gives the answer's. +func (s *Server) retrieveAs(ctx context.Context, p provider.Provider, url, ctype string, body []byte) ([]byte, string, int, error) { ctx = s.metered(p.Via(ctx), p, "") // counted against its MaxRPM (rpm.go) req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body)) if err != nil { - return nil, 500, err + return nil, "", 500, err + } + req.Header.Set("Content-Type", ctype) + if ctype == "application/json" { + req.Header.Set("Accept", "application/json") } - req.Header.Set("Content-Type", "application/json") - req.Header.Set("Accept", "application/json") // magpie's, or the agent's own where the provider passes it on (#1851) stampUA(ctx, p, req.Header) if p.IsRemoteMagpie() { @@ -236,28 +287,29 @@ func (s *Server) retrieveFrom(ctx context.Context, p provider.Provider, url stri passOnCaller(ctx, req) } if err := p.Sign(ctx, req, provider.Chat, body); err != nil { - return nil, 502, err + return nil, "", 502, err } res, err := p.Do(s.client, req) if err != nil { if ctx.Err() != nil { - return nil, 504, fmt.Errorf("%s didn't answer in %s", p.Name, retrieveTimeout) + return nil, "", 504, fmt.Errorf("%s didn't answer in %s", p.Name, retrieveTimeout) } - return nil, 502, err + return nil, "", 502, err } defer res.Body.Close() b, err := io.ReadAll(io.LimitReader(res.Body, 256<<20)) if err != nil { - return nil, 502, err + return nil, "", 502, err } + got := res.Header.Get("Content-Type") if res.StatusCode >= 300 { hint := "" if res.StatusCode == http.StatusNotFound || res.StatusCode == http.StatusMethodNotAllowed { hint = " — " + p.Name + " may not serve this API" } - return b, res.StatusCode, fmt.Errorf("%s: %d %s%s%s", provider.HostOf(url), res.StatusCode, http.StatusText(res.StatusCode), vendorSaid(vendorMessage(b)), hint) + return b, got, res.StatusCode, fmt.Errorf("%s: %d %s%s%s", provider.HostOf(url), res.StatusCode, http.StatusText(res.StatusCode), vendorSaid(vendorMessage(b)), hint) } - return b, res.StatusCode, nil + return b, got, res.StatusCode, nil } // retrievedTokens is what an answer says it counted: OpenAI's diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 92c6e61c9..f370ebc98 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -579,6 +579,11 @@ func (s *Server) Handler() http.Handler { mux.HandleFunc("POST /embeddings", s.retrieve("/embeddings", "embeddings")) mux.HandleFunc("POST /v1/rerank", s.retrieve("/rerank", "rerank")) mux.HandleFunc("POST /rerank", s.retrieve("/rerank", "rerank")) + // speech to text, for a client's voice input (#2053) + mux.HandleFunc("POST /v1/audio/transcriptions", s.transcribe("/audio/transcriptions", "transcriptions")) + mux.HandleFunc("POST /audio/transcriptions", s.transcribe("/audio/transcriptions", "transcriptions")) + mux.HandleFunc("POST /v1/audio/translations", s.transcribe("/audio/translations", "translations")) + mux.HandleFunc("POST /audio/translations", s.transcribe("/audio/translations", "translations")) mux.HandleFunc("POST /v1/videos", s.videosCreate) mux.HandleFunc("POST /videos", s.videosCreate) mux.HandleFunc("GET /v1/videos/{id}", s.videosGet) @@ -594,7 +599,7 @@ func (s *Server) Handler() http.Handler { mux.HandleFunc("GET /v1beta/models", s.geminiModels) mux.HandleFunc("POST /v1beta/models/{call...}", s.gemini) mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - writeError(w, provider.Chat, http.StatusNotFound, "magpie serves /v1/chat/completions, /v1/responses, /v1/messages, /v1/systemone, /v1/images/generations, /v1/images/edits, /v1/videos, /v1/embeddings, /v1/rerank and /v1beta/models/*") + writeError(w, provider.Chat, http.StatusNotFound, "magpie serves /v1/chat/completions, /v1/responses, /v1/messages, /v1/systemone, /v1/images/generations, /v1/images/edits, /v1/videos, /v1/embeddings, /v1/rerank, /v1/audio/transcriptions, /v1/audio/translations and /v1beta/models/*") }) return s.counted(corsGuard(callerGuard(withCaller(keyLimited(mux))))) } @@ -616,7 +621,7 @@ func responsesOverHTTP(w http.ResponseWriter, r *http.Request) { func (s *Server) info(w http.ResponseWriter, r *http.Request) { writeJSON(w, 200, map[string]any{"name": "magpie", "version": Version, "models": len(provider.Catalog()), "window": Window, - "apis": []string{"/v1/chat/completions", "/v1/responses", "/v1/messages", "/v1/systemone", "/v1beta/models/{model}:generateContent", "/v1/images/generations", "/v1/images/edits", "/v1/videos", "/v1/embeddings", "/v1/rerank", "/v1/magpie/quotas", "/v1/magpie/quotas/history", "/v1/magpie/usage", "/v1/magpie/usage/requests", "/v1/magpie/route", SearchMCPPath, VisionMCPPath}}) + "apis": []string{"/v1/chat/completions", "/v1/responses", "/v1/messages", "/v1/systemone", "/v1beta/models/{model}:generateContent", "/v1/images/generations", "/v1/images/edits", "/v1/videos", "/v1/embeddings", "/v1/rerank", "/v1/audio/transcriptions", "/v1/audio/translations", "/v1/magpie/quotas", "/v1/magpie/quotas/history", "/v1/magpie/usage", "/v1/magpie/usage/requests", "/v1/magpie/route", SearchMCPPath, VisionMCPPath}}) } // quotas is what is left of every subscription, plan and key magpie has, diff --git a/internal/gateway/lan_test.go b/internal/gateway/lan_test.go index ad47dc69a..84caeb9dc 100644 --- a/internal/gateway/lan_test.go +++ b/internal/gateway/lan_test.go @@ -341,6 +341,7 @@ func TestNetworkGatewayGuardsEveryRoute(t *testing.T) { {"POST", "/v1/systemone"}, {"POST", "/v1/images/generations"}, {"POST", "/v1/images/edits"}, {"POST", "/v1/embeddings"}, {"POST", "/v1/rerank"}, + {"POST", "/v1/audio/transcriptions"}, {"POST", "/v1/audio/translations"}, {"POST", "/v1/videos"}, {"GET", "/v1/videos/v1"}, {"GET", "/v1/videos/v1/content"}, {"POST", "/_magpie/claude-mcp/tok"}, {"POST", "/mcp/neon"}, {"POST", CodexPath + "/responses"}, {"GET", CodexCatalogPath}, diff --git a/internal/gateway/transcribe.go b/internal/gateway/transcribe.go new file mode 100644 index 000000000..fc5ab6c86 --- /dev/null +++ b/internal/gateway/transcribe.go @@ -0,0 +1,170 @@ +package gateway + +import ( + "bytes" + "encoding/json" + "errors" + "io" + "mime" + "mime/multipart" + "net/http" + "strings" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// transcribe serves OpenAI's speech-to-text APIs (#2053): +// POST /v1/audio/transcriptions and /v1/audio/translations. The body is the +// multipart form OpenAI's take (file, model, language, prompt, +// response_format…); it goes to the model's provider at its OpenAI-style +// base + path as the client sent it, boundary and all, and the vendor's +// answer comes back as it said it, in its own type (json, text, srt, vtt). +// Only the form's model, the provider's own id of it, and a prompt masked +// as the settings say are ever rewritten. It is routed, limited and +// recorded as an embeddings call is (serveRetrieval). +func (s *Server) transcribe(path, operation string) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + body, admitted := s.requestBody(w, r, provider.Chat) + if !admitted { + return + } + start := time.Now() + a, err := readAudioForm(r.Header.Get("Content-Type"), body) + if err != nil { + writeError(w, provider.Chat, 400, err.Error()) + return + } + if a.model == "" { + writeError(w, provider.Chat, 400, "name the model: the form's \"model\" is a magpie model id, provider/model (openai/whisper-1, groq/whisper-large-v3)") + return + } + s.serveRetrieval(w, r, path, operation, start, a.model, a) + } +} + +// audioForm is a speech-to-text request: its multipart body as sent, and +// the fields magpie reads or may rewrite. +type audioForm struct { + raw []byte + ctype string // as sent, its boundary in it + boundary string + model string + prompt string + // masked is the prompt as it goes to a vendor, when masking changed it + masked *string +} + +// readAudioForm reads the form's model and prompt; the rest of it, the +// audio among it, is left as it is. +func readAudioForm(ctype string, body []byte) (*audioForm, error) { + mt, params, err := mime.ParseMediaType(ctype) + if err != nil || mt != "multipart/form-data" || params["boundary"] == "" { + return nil, errors.New("send the audio as multipart/form-data, as OpenAI's /v1/audio/transcriptions takes it: a file and a model") + } + a := &audioForm{raw: body, ctype: ctype, boundary: params["boundary"]} + mr := multipart.NewReader(bytes.NewReader(body), a.boundary) + for { + p, err := mr.NextRawPart() + if err == io.EOF { + break + } + if err != nil { + return nil, errors.New("the multipart form doesn't parse: " + err.Error()) + } + switch p.FormName() { + case "model", "prompt": + if p.FileName() != "" { + continue + } + v, err := io.ReadAll(io.LimitReader(p, 1<<20)) + if err != nil { + return nil, errors.New("the multipart form doesn't parse: " + err.Error()) + } + if p.FormName() == "model" { + a.model = strings.TrimSpace(string(v)) + } else { + a.prompt = string(v) + } + } + } + return a, nil +} + +// mask masks the prompt, the form's only text a vendor is sent; the +// audio can't be, and the transcript gets the masked values back. +func (a *audioForm) mask(w http.ResponseWriter) (http.ResponseWriter, func()) { + if a.prompt == "" { + return w, func() {} + } + w, masked, done := redactedPrompt(w, a.prompt) + if masked != a.prompt { + a.masked = &masked + } + return w, done +} + +// forModel is the form as sent when nothing in it changes; otherwise it is +// written again part by part, under the same boundary, with the model the +// provider's own id and the prompt masked. +func (a *audioForm) forModel(model string) ([]byte, string, error) { + if model == a.model && a.masked == nil { + return a.raw, a.ctype, nil + } + var buf bytes.Buffer + mw := multipart.NewWriter(&buf) + if err := mw.SetBoundary(a.boundary); err != nil { + return nil, "", err + } + mr := multipart.NewReader(bytes.NewReader(a.raw), a.boundary) + for { + p, err := mr.NextRawPart() + if err == io.EOF { + break + } + if err != nil { + return nil, "", errors.New("the multipart form doesn't parse: " + err.Error()) + } + pw, err := mw.CreatePart(p.Header) + if err != nil { + return nil, "", err + } + switch { + case p.FormName() == "model" && p.FileName() == "": + io.WriteString(pw, model) + case p.FormName() == "prompt" && p.FileName() == "" && a.masked != nil: + io.WriteString(pw, *a.masked) + default: + if _, err := io.Copy(pw, p); err != nil { + return nil, "", err + } + } + } + if err := mw.Close(); err != nil { + return nil, "", err + } + return buf.Bytes(), mw.FormDataContentType(), nil +} + +// answerType is the vendor's own: a transcript asked as text, srt or vtt +// is no JSON. +func (a *audioForm) answerType(got string) string { + if got == "" { + return "application/json" + } + return got +} + +// answeredTokens is the output tokens an answer says it counted: +// gpt-4o-transcribe's usage.output_tokens; whisper's answer counts none. +func answeredTokens(b []byte) int { + var a struct { + Usage struct { + Output int `json:"output_tokens"` + } `json:"usage"` + } + if json.Unmarshal(b, &a) != nil { + return 0 + } + return a.Usage.Output +} diff --git a/internal/gateway/transcribe_test.go b/internal/gateway/transcribe_test.go new file mode 100644 index 000000000..0318e5336 --- /dev/null +++ b/internal/gateway/transcribe_test.go @@ -0,0 +1,261 @@ +package gateway + +import ( + "bytes" + "io" + "mime" + "mime/multipart" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" + "github.com/yetone/magpie/internal/usage" +) + +// scribe is a vendor with OpenAI's speech-to-text APIs; what each path was +// sent, and with which Content-Type, is kept. +type scribe struct { + mu sync.Mutex + sent map[string][][]byte + types map[string][]string +} + +func (sc *scribe) ServeHTTP(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + sc.mu.Lock() + if sc.sent == nil { + sc.sent, sc.types = map[string][][]byte{}, map[string][]string{} + } + sc.sent[r.URL.Path] = append(sc.sent[r.URL.Path], body) + sc.types[r.URL.Path] = append(sc.types[r.URL.Path], r.Header.Get("Content-Type")) + sc.mu.Unlock() + if r.Header.Get("Authorization") != "Bearer key" { + w.WriteHeader(401) + return + } + switch r.URL.Path { + case "/v1/audio/transcriptions", "/v1/audio/translations": + default: + w.WriteHeader(404) + return + } + r.Body = io.NopCloser(bytes.NewReader(body)) // read once above + if err := r.ParseMultipartForm(32 << 20); err != nil { + w.WriteHeader(400) + io.WriteString(w, `{"error":{"message":"`+err.Error()+`"}}`) + return + } + // what OpenAI answers: JSON by default, the bare text when asked + if r.FormValue("response_format") == "text" { + w.Header().Set("Content-Type", "text/plain; charset=utf-8") + io.WriteString(w, "Hello from the magpie.\n") + return + } + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"text":"Hello from the magpie.","usage":{"type":"tokens","input_tokens":14,"input_token_details":{"text_tokens":0,"audio_tokens":14},"output_tokens":7,"total_tokens":21}}`) +} + +func (sc *scribe) got(path string) ([][]byte, []string) { + sc.mu.Lock() + defer sc.mu.Unlock() + return append([][]byte(nil), sc.sent[path]...), append([]string(nil), sc.types[path]...) +} + +func scribed(t *testing.T) (*Server, *scribe) { + t.Helper() + fresh(t) + sc := &scribe{} + up := httptest.NewServer(sc) + t.Cleanup(up.Close) + if err := provider.Save(provider.Provider{ID: "ears", Name: "Ears", Chat: up.URL + "/v1", Key: "key", Models: []string{"whisper-1"}}); err != nil { + t.Fatal(err) + } + return New(), sc +} + +// voice is audio as a recorder writes it: bytes no text field has, a +// stray CRLF and dashes among them. +var voice = append([]byte("\x1aE\xdf\xa3\x9fB\x86\x81\x01webm\x00\x00\r\n--\xff\xfe"), bytes.Repeat([]byte{0, 0x81, 0x7f, '\r', '\n', '-'}, 512)...) + +// audioForm builds the form as curl -F sends it. +func audioFormBody(t *testing.T, fields ...string) ([]byte, string) { + t.Helper() + var b bytes.Buffer + mw := multipart.NewWriter(&b) + if err := mw.SetBoundary("------------------------d74496d66958873e"); err != nil { + t.Fatal(err) + } + h := make(map[string][]string) + h["Content-Disposition"] = []string{`form-data; name="file"; filename="voice.webm"`} + h["Content-Type"] = []string{"audio/webm"} + fw, err := mw.CreatePart(h) + if err != nil { + t.Fatal(err) + } + fw.Write(voice) + for i := 0; i+1 < len(fields); i += 2 { + mw.WriteField(fields[i], fields[i+1]) + } + mw.Close() + return b.Bytes(), mw.FormDataContentType() +} + +func postAudio(t *testing.T, s *Server, path, ctype string, body []byte) (int, http.Header, string) { + t.Helper() + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", path, bytes.NewReader(body)) + req.Header.Set("Content-Type", ctype) + s.Handler().ServeHTTP(rec, req) + return rec.Code, rec.Header(), rec.Body.String() +} + +// formOf reads a form the vendor was sent. +func formOf(t *testing.T, ctype string, body []byte) (map[string]string, []byte) { + t.Helper() + _, params, err := mime.ParseMediaType(ctype) + if err != nil { + t.Fatal(err) + } + f, err := multipart.NewReader(bytes.NewReader(body), params["boundary"]).ReadForm(32 << 20) + if err != nil { + t.Fatal(err) + } + vals := map[string]string{} + for k, v := range f.Value { + vals[k] = v[0] + } + var audio []byte + if fh := f.File["file"]; len(fh) == 1 { + rd, _ := fh[0].Open() + audio, _ = io.ReadAll(rd) + vals["filename"] = fh[0].Filename + vals["file type"] = fh[0].Header.Get("Content-Type") + } + return vals, audio +} + +// #2053: a transcription goes to the model's provider as the client sent +// it, the model its own id and the audio byte for byte under the same +// boundary, and the vendor's answer comes back; it is in the usage ledger. +func TestTranscriptionGoesToTheModelsProvider(t *testing.T) { + s, sc := scribed(t) + body, ctype := audioFormBody(t, "model", "ears/whisper-1", "language", "zh", "prompt", "magpie", "response_format", "json", "temperature", "0") + code, _, raw := postAudio(t, s, "/v1/audio/transcriptions", ctype, body) + if code != 200 || !strings.Contains(raw, `"text":"Hello from the magpie."`) { + t.Fatalf("%d %s", code, raw) + } + sent, types := sc.got("/v1/audio/transcriptions") + if len(sent) != 1 || types[0] != ctype { + t.Fatalf("vendor was sent %d bodies as %v, not %s", len(sent), types, ctype) + } + vals, audio := formOf(t, types[0], sent[0]) + if !bytes.Equal(audio, voice) || vals["filename"] != "voice.webm" || vals["file type"] != "audio/webm" { + t.Fatalf("audio arrived as %d bytes %q (%s), not the %d sent", len(audio), vals["filename"], vals["file type"], len(voice)) + } + if vals["model"] != "whisper-1" || vals["language"] != "zh" || vals["prompt"] != "magpie" || vals["response_format"] != "json" || vals["temperature"] != "0" { + t.Fatalf("vendor's form %v", vals) + } + var recs []usage.Record + for i := 0; i < 50; i++ { + if recs = usage.Load(time.Time{}); len(recs) >= 1 { + break + } + time.Sleep(20 * time.Millisecond) + } + if len(recs) != 1 || recs[0].Operation != "transcriptions" || recs[0].Provider != "ears" || recs[0].Model != "whisper-1" || recs[0].Requested != "ears/whisper-1" || recs[0].Input != 14 || recs[0].Output != 7 || recs[0].Status != 200 { + t.Fatalf("usage %+v", recs) + } +} + +// A form whose model is the vendor's own id goes as it came, every byte; +// the bare /audio/... path an SDK given magpie's root posts to as well, +// and translations alike. +func TestTranscriptionFormGoesAsSent(t *testing.T) { + s, sc := scribed(t) + body, ctype := audioFormBody(t, "model", "whisper-1") + for _, path := range []string{"/v1/audio/transcriptions", "/audio/transcriptions", "/v1/audio/translations", "/audio/translations"} { + if code, _, raw := postAudio(t, s, path, ctype, body); code != 200 { + t.Fatalf("%s: %d %s", path, code, raw) + } + } + for _, path := range []string{"/v1/audio/transcriptions", "/v1/audio/translations"} { + sent, types := sc.got(path) + if len(sent) != 2 { + t.Fatalf("%s: vendor was sent %d bodies", path, len(sent)) + } + for i := range sent { + if !bytes.Equal(sent[i], body) || types[i] != ctype { + t.Fatalf("%s: vendor was sent a body of its own (%s)", path, types[i]) + } + } + } +} + +// response_format text, srt or vtt comes back as the vendor sent it, in +// its own type, not as JSON. +func TestTranscriptAsTextKeepsItsType(t *testing.T) { + s, _ := scribed(t) + body, ctype := audioFormBody(t, "model", "ears/whisper-1", "response_format", "text") + code, h, raw := postAudio(t, s, "/v1/audio/transcriptions", ctype, body) + if code != 200 || raw != "Hello from the magpie.\n" || h.Get("Content-Type") != "text/plain; charset=utf-8" { + t.Fatalf("%d %q %q", code, h.Get("Content-Type"), raw) + } +} + +// A request magpie can't route is told why, and nothing reaches a vendor. +func TestTranscriptionRefusals(t *testing.T) { + s, sc := scribed(t) + if err := provider.Save(provider.Provider{ID: "anth", Name: "Anth", Anthropic: "http://127.0.0.1:9/", Key: "key", Models: []string{"m"}}); err != nil { + t.Fatal(err) + } + body, _ := audioFormBody(t, "model", "ears/whisper-1") + if code, _, raw := postAudio(t, s, "/v1/audio/transcriptions", "application/json", []byte(`{"model":"ears/whisper-1"}`)); code != 400 || !strings.Contains(raw, "multipart/form-data") { + t.Fatalf("json: %d %s", code, raw) + } + nameless, nctype := audioFormBody(t, "language", "en") + if code, _, raw := postAudio(t, s, "/v1/audio/transcriptions", nctype, nameless); code != 400 || !strings.Contains(raw, "name the model") { + t.Fatalf("no model: %d %s", code, raw) + } + none, ntype := audioFormBody(t, "model", "nobody/whisper-1") + if code, _, raw := postAudio(t, s, "/v1/audio/transcriptions", ntype, none); code != 404 || !strings.Contains(raw, "nobody/whisper-1") { + t.Fatalf("unknown: %d %s", code, raw) + } + anth, atype := audioFormBody(t, "model", "anth/m") + if code, _, raw := postAudio(t, s, "/v1/audio/transcriptions", atype, anth); code != 400 || !strings.Contains(raw, "has no OpenAI-style API") { + t.Fatalf("Anthropic-only: %d %s", code, raw) + } + // a boundary that isn't the body's + if code, _, raw := postAudio(t, s, "/v1/audio/transcriptions", "multipart/form-data; boundary=elsewhere", body); code != 400 { + t.Fatalf("wrong boundary: %d %s", code, raw) + } + if sent, _ := sc.got("/v1/audio/transcriptions"); len(sent) != 0 { + t.Fatalf("vendor was sent %d", len(sent)) + } +} + +// With secrets kept, the prompt goes out masked and the transcript gets +// them back; the audio still goes byte for byte. +func TestTranscriptionPromptRedacted(t *testing.T) { + s, sc := scribed(t) + if err := settings.Save(settings.Settings{Redact: true}); err != nil { + t.Fatal(err) + } + secret := "sk-ant-api03-" + strings.Repeat("Ab3x", 20) + body, ctype := audioFormBody(t, "model", "whisper-1", "prompt", "key "+secret) + if code, _, raw := postAudio(t, s, "/v1/audio/transcriptions", ctype, body); code != 200 { + t.Fatalf("%d %s", code, raw) + } + sent, types := sc.got("/v1/audio/transcriptions") + if len(sent) != 1 || bytes.Contains(sent[0], []byte(secret)) { + t.Fatalf("vendor was sent the secret") + } + vals, audio := formOf(t, types[0], sent[0]) + if !bytes.Equal(audio, voice) || vals["model"] != "whisper-1" || !strings.HasPrefix(vals["prompt"], "key ") { + t.Fatalf("vendor's form %v, %d audio bytes", vals, len(audio)) + } +} diff --git a/internal/provider/remote_magpie.go b/internal/provider/remote_magpie.go index e5203131d..1c54f718b 100644 --- a/internal/provider/remote_magpie.go +++ b/internal/provider/remote_magpie.go @@ -93,6 +93,7 @@ func (p *Provider) remoteMagpieEndpoints() { "/v1/messages/count_tokens", "/v1/messages", "/v1/chat/completions", "/v1/responses", "/v1/systemone", "/v1/embeddings", "/v1/rerank", + "/v1/audio/transcriptions", "/v1/audio/translations", "/v1/images/generations", "/v1/images/edits", "/v1/videos", "/v1", } { diff --git a/site/public/docs/ja/remote.html b/site/public/docs/ja/remote.html index 7477a7aa8..4377e86bd 100644 --- a/site/public/docs/ja/remote.html +++ b/site/public/docs/ja/remote.html @@ -122,7 +122,7 @@ magpie provider refresh office # 一覧を再取得すべての API。リクエストはエージェントが使った API のまま転送されます(Anthropic Messages とトークン計数、Responses、Chat Completions)。共有側のプロバイダが別の API でしか提供しないモデルは、変換が 1 回だけ行われ、両方のコンピューターで変換されることはありません。Responses は WebSocket ではなく HTTP(SSE を含む)で送られます。
/v1/systemone につながり、チャットモデルではなく決定モデルとして現れます。新しいものはプロバイダの一覧を更新すると見つかります。office だけを指定すると一覧の最初の決定モデルに問い合わせます。/v1/systemone and appear as decision models, not chat models. Refresh the provider’s list to find new ones. A bare office asks the first decision model listed./v1/systemone,作为决策模型而不是对话模型出现。刷新供应商列表可以发现新的。只写 office 时使用列表里的第一个决策模型。