gateway: serve OpenAI's text to speech, POST /v1/audio/speech

liuyuexue2020 on X (tweet 2115742181734445238) wanted audio models
(Mistral among them) behind magpie, and the gateway had no
/v1/audio/speech.

POST /v1/audio/speech (and the bare /audio/speech) takes OpenAI's JSON
body and goes through serveRetrieval, as transcriptions (#2053) and
embeddings do: routed (a group's members, a provider's keys and
accounts, pause rules, key limits), metered against MaxRPM, recorded
(usage operation "speech", Routing, recent calls). Only "model" is
rewritten to the provider's own id; every other field goes as sent, so
Mistral's voice_id and ref_audio pass too.

The answer is never held whole: a speech request's 2xx answer is left
unread by the new retrieveOpen (retrieveAs now wraps it) and copied to
the client as it comes, flushed per read, in the vendor's own
Content-Type: audio (mp3/opus/aac/flac/wav/pcm), SSE for
stream_format=sse, or a vendor's JSON (Mistral answers
{"audio_data": base64}). No Accept: application/json is sent for it.
The usage in SSE's speech.audio.done event is counted from the last
16KB. A vendor's error is read and passed on as before, and a failing
member still falls over to the next.

Masking: "input" and "instructions" are masked as the settings say,
as text (maskTextHits), each where it sits; nothing else in the body
is (voice, formats, a voice-cloning clip are no text of the user's).
Nothing is put back: the answer is audio, so a masked value is read
aloud as its placeholder (docs/reference.md says so).

Mistral: its API has POST https://api.mistral.ai/v1/audio/speech
(voxtral-mini-tts-3-0), at the OpenAI path but not OpenAI's shape:
voice_id instead of voice, and JSON {"audio_data": base64} back, not
raw audio. Both pass through as sent; a client must speak Mistral's
shape to it. OpenAI, Groq and other OpenAI-style TTS vendors (vLLM-Omni
included) are served as they are.

Also: the 404 message's list, /v1's "apis", remote_magpie's suffix
list, cors_test and lan_test route lists, docs/reference.md,
gateway-routing.md, plugin-runtime.md, site remote.html (en/zh/ja).

Run (mote-run, at this commit):
- go vet ./... (darwin), GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./..., go build ./...: ok; gofmt -l clean
- go test -timeout 45m -count=1 ./internal/gateway ./internal/provider at 7bc52d44e^{tree} (= this tree, origin/main 65bd4e4f7): gateway ok 497.9s, provider ok 88.7s
- go test ./internal/gateway -run 'Speech|Transcri|Embedding|Rerank|CORS|LAN|ReplyHeaders': ok

Broken by hand (mote-run, each red, then restored):
- the two mux lines removed: all five TestSpeech* red
- streams() false (answer read whole): TestSpeechStreamsAsItComes red
  (first event never reached the client while the vendor held the rest)
- "instructions" left out of the masked fields: TestSpeechInputMasked red

Not tried: a real vendor (OpenAI, Groq, Mistral) through a sandbox
magpie; only the fake upstream in speech_test.go. Not run on the
Windows or Linux boxes (vet only).
This commit is contained in:
yetone
2026-10-29 19:25:40 +08:00
parent 65bd4e4f72
commit f6263439af
13 changed files with 502 additions and 30 deletions
+14 -1
View File
@@ -1961,6 +1961,7 @@ It exposes:
| `/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/audio/speech` | OpenAI text to speech (JSON in, the vendor's audio or SSE streamed back) |
| `/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)) |
| `/api/version`, `/api/tags`, `/api/show` | the catalog as an Ollama server lists it, for a client that takes a custom endpoint only as Ollama (below) |
@@ -2024,7 +2025,19 @@ models are named `provider/model`.
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.
such endpoint answers its own 404.
- Text to speech (`/v1/audio/speech`) takes OpenAI's JSON body
(`model`, `input`, `voice`, `response_format`, `speed`, `instructions`,
`stream_format`), its `model` a magpie id such as
`openai/gpt-4o-mini-tts` or `groq/playai-tts`. The body goes to that
provider's OpenAI-style base with only the model set to the provider's
own id; any other field (Mistral's `voice_id`) goes as sent. The answer
is passed on as it comes, in the vendor's own type: audio (`mp3`,
`opus`, `aac`, `flac`, `wav`, `pcm`), SSE for `stream_format: "sse"`,
or the vendor's own JSON (Mistral answers `{"audio_data": base64}`).
`input` and `instructions` are masked as your redaction settings say;
the answer is audio, so a masked value is read aloud as its
placeholder.
- Every reply names who answered in `X-Magpie-Provider` (the provider)
and `X-Magpie-Model` (`provider/model`), and so does the usage log.
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -225,7 +225,7 @@ failure policy, in [`internal/gwmw`](../../internal/gwmw/gwmw.go):
| --- | --- | --- |
| `gwmw.Agent` | A middleware on a request an agent sent, in the agent's own API, before the gateway routes it, and on its reply as the agent gets it: `Begin(Info) Run`, and the run's `Request` (a `Reject` ends the request in the agent's error shape), `Wrap` and `End`. `Use(a)` registers one until its remove; `Agents` lists them in order. `serveAgent` runs each in turn; with none it calls `serve` directly. It fails open, as the JS middleware always did. | [`gwmw.go`](../../internal/gwmw/gwmw.go), [`middleware.go`](../../internal/gateway/middleware.go) |
| `plugins/middleware` | Requires `gateway`, Essential. Apply registers `middleware.Chain`, the JS gateway middleware ([Gateway middleware](gateway-middleware.md)), whose place, API, limits and fail-open policy are unchanged. `InUse` is `middleware.On()`, the middleware plugins.json has on. Off, agents' requests go as they came and no middleware is called, while plugins.json is left as it is. The gateway's `KeepFresh` watches plugins.json too, so a middleware added from the CLI or the window turns it on within 2s, and a request before then asks the gate's refresh itself (`gwmw.AgentsWanted`: with no agent middleware registered and `middleware.On()` above 0, at most once a second), so the middleware runs on that request, as it did within a second before it was a plugin. | [`middleware.go`](../../plugins/middleware/middleware.go), [`run.go`](../../internal/middleware/run.go) |
| `gwmw.Masker` | Masks what magpie sends a vendor and puts the values back in what comes back: `JSON`, `Text`, `Restore` and `Writer`. `Mask(m)` serves one until its remove (the last registered serves). It fails closed: `Masking(wanted)` is the masker for a request, or `ErrUnmasked` when the settings ask for masking and none serves, and `Safely` makes a masker that panics an error. The gateway's call sites (`serve`, count_tokens, embeddings and audio, transcriptions, images, video, the search stand-ins and their queries, the Codex backend) answer either with 503 "…nothing was sent", and the vendor gets nothing. `Served`, with none, asks the gate's refresh (the gateway's is `pluginrt.Refresh`, set by `gwmw.Refresh` in `ListenAndServe`) at most once a second and never from inside one, then looks again, so masking turned on a moment ago turns the plugin on for the request that needs it. | [`gwmw.go`](../../internal/gwmw/gwmw.go), [`redact.go`](../../internal/gateway/redact.go), [`gateway.go`](../../internal/gateway/gateway.go) |
| `gwmw.Masker` | Masks what magpie sends a vendor and puts the values back in what comes back: `JSON`, `Text`, `Restore` and `Writer`. `Mask(m)` serves one until its remove (the last registered serves). It fails closed: `Masking(wanted)` is the masker for a request, or `ErrUnmasked` when the settings ask for masking and none serves, and `Safely` makes a masker that panics an error. The gateway's call sites (`serve`, count_tokens, embeddings and audio, transcriptions, text to speech, images, video, the search stand-ins and their queries, the Codex backend) answer either with 503 "…nothing was sent", and the vendor gets nothing. `Served`, with none, asks the gate's refresh (the gateway's is `pluginrt.Refresh`, set by `gwmw.Refresh` in `ListenAndServe`) at most once a second and never from inside one, then looks again, so masking turned on a moment ago turns the plugin on for the request that needs it. | [`gwmw.go`](../../internal/gwmw/gwmw.go), [`redact.go`](../../internal/gateway/redact.go), [`gateway.go`](../../internal/gateway/gateway.go) |
| `gwmw.Teller` | What a masker can say besides masking: `JSONHits` and `TextHits` mask as `JSON` and `Text` do and also return each placeholder made or reused (`Hit`: placeholder, kind, finder, head, length), and `Value` is what a placeholder stood for while this masker remembers it. Optional: the gateway records a request's masking only when the served masker is one (`masking.Masker` is), and Settings → Privacy's records and values need it; a masker without it masks the same and leaves no record. | [`gwmw.go`](../../internal/gwmw/gwmw.go), [`masked.go`](../../internal/gateway/masked.go), [`masking.go`](../../internal/masking/masking.go) |
| `plugins/redact` | Requires `settings` and `gateway`, Essential. Apply serves `masking.Masker`, which reads settings.json on each call and masks with `internal/redact` as before (it lives in `internal/masking` because `settings` imports `redact`). `InUse` is `masking.Wanted`: *Mask secrets*, *Mask personal data* or a word of the user's own; settings.json that can't be read is an error, so it stays on. Since it is in use whenever masking is asked for, it can only be off while nothing is; the 503 is for a refresh not yet seen or a plugins.yml edited by hand. | [`redact.go`](../../plugins/redact/redact.go), [`masking.go`](../../internal/masking/masking.go) |
+1
View File
@@ -239,6 +239,7 @@ func TestForeignPagesRefused(t *testing.T) {
{"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/audio/speech", `{"model":"plan/m1","input":"hi","voice":"coral"}`},
{"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"}`},
+67 -18
View File
@@ -199,7 +199,8 @@ func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, op
return
}
what := "embeddings"
if _, audio := req.(*audioForm); audio {
switch req.(type) {
case *audioForm, *speechRequest:
what = "audio"
}
// the record names the try that had it last, not the first
@@ -240,8 +241,20 @@ func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, op
// the headers of the vendor's reply passed on (#4145)
var heard heardHeaders
ctx = withReplySink(ctx, c.p.ID, heard.put)
b, got, code, err := s.retrieveAs(ctx, c.p, base+path, ctype, out)
cancel()
var b []byte
var got string
var code int
var res *http.Response // a streamed answer, not read yet
if st, ok := req.(streamedRetrieval); ok && st.streams() {
res, b, got, code, err = s.retrieveOpen(ctx, c.p, base+path, ctype, "", out)
} else {
b, got, code, err = s.retrieveAs(ctx, c.p, base+path, ctype, out)
}
if res == nil {
cancel()
} else {
defer cancel() // once the answer is copied
}
tried(code, err)
call.Millis = time.Since(start).Milliseconds()
if err != nil && !last && r.Context().Err() == nil {
@@ -250,6 +263,19 @@ func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, op
}
call.Status = code
in, outTokens := retrievedTokens(b), answeredTokens(b)
if res != nil {
// passed on as it comes: audio, or SSE, is never held whole
heard.into(w.Header())
w.Header().Set("Content-Type", req.answerType(got))
w.WriteHeader(code)
var cut error
in, outTokens, cut = copyAnswer(w, res.Body)
res.Body.Close()
call.Millis = time.Since(start).Milliseconds()
if cut != nil {
call.Error = "the answer was cut off: " + cut.Error()
}
}
call.Usage.Input, call.Usage.Output = in, outTokens
call.Fallback = strings.Join(skipped, "; ")
providerKeyID, providerKeyName := "", ""
@@ -271,6 +297,9 @@ func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, op
return
}
s.record(call)
if res != nil {
return
}
heard.into(w.Header())
w.Header().Set("Content-Type", req.answerType(got))
w.WriteHeader(code)
@@ -312,14 +341,34 @@ func (s *Server) retrieveFrom(ctx context.Context, p provider.Provider, url stri
// 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) {
accept := ""
if ctype == "application/json" {
accept = "application/json"
}
res, b, got, code, err := s.retrieveOpen(ctx, p, url, ctype, accept, body)
if res == nil {
return b, got, code, err
}
defer res.Body.Close()
b, err = io.ReadAll(io.LimitReader(res.Body, 256<<20))
if err != nil {
return nil, "", 502, err
}
return b, got, code, nil
}
// retrieveOpen posts body as retrieveAs does, with an Accept of its own
// (none when empty). A success's answer is left unread in res, for the
// caller to read and close; a failure's is read into b, res nil.
func (s *Server) retrieveOpen(ctx context.Context, p provider.Provider, url, ctype, accept string, body []byte) (*http.Response, []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, nil, "", 500, err
}
req.Header.Set("Content-Type", ctype)
if ctype == "application/json" {
req.Header.Set("Accept", "application/json")
if accept != "" {
req.Header.Set("Accept", accept)
}
// magpie's, or the agent's own where the provider passes it on (#1851)
stampUA(ctx, p, req.Header)
@@ -328,30 +377,30 @@ func (s *Server) retrieveAs(ctx context.Context, p provider.Provider, url, ctype
passOnCaller(ctx, req)
}
if err := p.Sign(ctx, req, provider.Chat, body); err != nil {
return nil, "", 502, err
return nil, nil, "", 502, err
}
res, err := p.Do(s.client, req)
heardReply(ctx, p, res)
if err != nil {
if ctx.Err() != nil {
return nil, "", 504, fmt.Errorf("%s didn't answer in %s", p.Name, retrieveTimeout)
return nil, nil, "", 504, fmt.Errorf("%s didn't answer in %s", p.Name, retrieveTimeout)
}
return nil, "", 502, err
return nil, nil, "", 502, err
}
got := res.Header.Get("Content-Type")
if res.StatusCode < 300 {
return res, nil, got, res.StatusCode, nil
}
defer res.Body.Close()
b, err := io.ReadAll(io.LimitReader(res.Body, 256<<20))
if err != nil {
return nil, "", 502, err
return nil, 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, got, res.StatusCode, fmt.Errorf("%s: %d %s%s%s", provider.HostOf(url), res.StatusCode, http.StatusText(res.StatusCode), errorSaid(b), hint)
hint := ""
if res.StatusCode == http.StatusNotFound || res.StatusCode == http.StatusMethodNotAllowed {
hint = " — " + p.Name + " may not serve this API"
}
return b, got, res.StatusCode, nil
return nil, b, got, res.StatusCode, fmt.Errorf("%s: %d %s%s%s", provider.HostOf(url), res.StatusCode, http.StatusText(res.StatusCode), errorSaid(b), hint)
}
// retrievedTokens is what an answer says it counted: OpenAI's
+4 -2
View File
@@ -822,6 +822,8 @@ func (s *Server) Handler() http.Handler {
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/audio/speech", s.speak)
mux.HandleFunc("POST /audio/speech", s.speak)
mux.HandleFunc("POST /v1/videos", s.videosCreate)
mux.HandleFunc("POST /videos", s.videosCreate)
mux.HandleFunc("GET /v1/videos/{id}", s.videosGet)
@@ -843,7 +845,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, /v1/audio/transcriptions, /v1/audio/translations 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, /v1/audio/speech and /v1beta/models/*")
})
// the goroutine dump first, ahead of every lock the rest can be stuck
// on (dumpFirst)
@@ -874,7 +876,7 @@ var catalogSize stamped[struct{}, int]
func (s *Server) info(w http.ResponseWriter, r *http.Request) {
out := map[string]any{"name": "magpie", "version": Version, "models": catalogSize.get(struct{}{}, func() int { return 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/audio/transcriptions", "/v1/audio/translations", "/v1/magpie/quotas", "/v1/magpie/quotas/history", "/v1/magpie/usage", "/v1/magpie/usage/requests", "/v1/magpie/route", "/v1/magpie/trace", SearchMCPPath, VisionMCPPath, ImageMCPPath, ToolsMCPPath, HubMCPAll, HubMCPPath + "{agent}"}}
"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/audio/speech", "/v1/magpie/quotas", "/v1/magpie/quotas/history", "/v1/magpie/usage", "/v1/magpie/usage/requests", "/v1/magpie/route", "/v1/magpie/trace", SearchMCPPath, VisionMCPPath, ImageMCPPath, ToolsMCPPath, HubMCPAll, HubMCPPath + "{agent}"}}
// which process serves, for another magpie on this computer to name it
// on its Routing page (#2606); not told to another machine
if local(r) {
+1 -1
View File
@@ -342,7 +342,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/audio/transcriptions"}, {"POST", "/v1/audio/translations"}, {"POST", "/v1/audio/speech"},
{"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},
+161
View File
@@ -0,0 +1,161 @@
package gateway
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"time"
"github.com/yetone/magpie/internal/provider"
)
// speak serves OpenAI's text-to-speech API: POST /v1/audio/speech. The
// body is JSON ({model, input, voice, response_format, speed,
// instructions, stream_format…}); it goes to the model's provider at its
// OpenAI-style base + path with only the model rewritten to the
// provider's own id, and input and instructions masked as the settings
// say. The answer is audio (mp3, opus, aac, flac, wav, pcm), SSE when
// stream_format is sse, or a vendor's own JSON (Mistral's audio_data):
// it comes back as it comes, in the vendor's own type, never held whole.
// It is routed, limited and recorded as an embeddings call is
// (serveRetrieval).
func (s *Server) speak(w http.ResponseWriter, r *http.Request) {
body, admitted := s.requestBody(w, r, provider.Chat)
if !admitted {
return
}
start := time.Now()
var req map[string]json.RawMessage
if json.Unmarshal(body, &req) != nil || req == nil {
writeError(w, provider.Chat, 400, "the body isn't a JSON object: /v1/audio/speech takes {\"model\", \"input\", \"voice\"…} as OpenAI's does")
return
}
var asked string
json.Unmarshal(req["model"], &asked)
if asked == "" {
writeError(w, provider.Chat, 400, "name the model: \"model\" is a magpie model id, provider/model (openai/gpt-4o-mini-tts, groq/playai-tts)")
return
}
s.serveRetrieval(w, r, "/audio/speech", "speech", start, asked, &speechRequest{req: req})
}
// speechRequest is a text-to-speech body: a JSON object, its text fields
// the only ones masked.
type speechRequest struct{ req map[string]json.RawMessage }
// spoken are the fields of a speech request that carry the user's text:
// what is read aloud, and OpenAI's instructions for how. Nothing else is
// masked: a voice, a format or a voice-cloning clip is no text of theirs.
var spoken = []string{"input", "instructions"}
// mask masks input and instructions where they are strings. The answer is
// audio, so nothing is put back: a masked value is read aloud as its
// placeholder.
func (sp *speechRequest) mask(ctx context.Context, w http.ResponseWriter) (http.ResponseWriter, func(), maskHits, string, error) {
var all maskHits
var sent []string
for _, k := range spoken {
var v string
if json.Unmarshal(sp.req[k], &v) != nil || v == "" {
continue
}
_, masked, h, err := maskTextHits(ctx, v)
if err != nil {
return w, func() {}, maskHits{}, "", err
}
all.add(h)
sent = append(sent, masked)
if masked != v {
sp.req[k], _ = json.Marshal(masked)
}
}
text := ""
for i, t := range sent {
if i > 0 {
text += "\n\n"
}
text += t
}
return w, func() {}, all, text, nil
}
func (sp *speechRequest) forModel(model string) ([]byte, string, error) {
sp.req["model"], _ = json.Marshal(model)
out, err := json.Marshal(sp.req)
return out, "application/json", err
}
// answerType is the vendor's; OpenAI's default format is mp3.
func (sp *speechRequest) answerType(got string) string {
if got == "" {
return "audio/mpeg"
}
return got
}
// streams: the answer is copied to the client as it comes.
func (sp *speechRequest) streams() bool { return true }
// streamedRetrieval is a retrieval whose answer goes to the client as it comes,
// not read whole first (serveRetrieval).
type streamedRetrieval interface{ streams() bool }
// speechTail is how much of an answer's end is kept to read its usage:
// gpt-4o-mini-tts's SSE ends with a speech.audio.done event that has it.
const speechTail = 16 << 10
// copyAnswer copies an answer to w as it comes, flushing each read, and
// gives the tokens its last event says it counted, and the error that cut
// it short, if any.
func copyAnswer(w http.ResponseWriter, body io.Reader) (in, out int, err error) {
rc := http.NewResponseController(w)
var tail []byte
buf := make([]byte, 32<<10)
for {
n, rerr := body.Read(buf)
if n > 0 {
if _, werr := w.Write(buf[:n]); werr != nil {
return 0, 0, werr
}
rc.Flush()
tail = append(tail, buf[:n]...)
if len(tail) > speechTail {
tail = append(tail[:0], tail[len(tail)-speechTail:]...)
}
}
if rerr == io.EOF {
break
}
if rerr != nil {
return 0, 0, rerr
}
}
in, out = speechUsage(tail)
return in, out, nil
}
// speechUsage is the usage an answer's last JSON line or SSE data line
// says: {"type":"speech.audio.done","usage":{"input_tokens":…}}. Audio
// bytes say none.
func speechUsage(tail []byte) (int, int) {
lines := bytes.Split(tail, []byte("\n"))
for i := len(lines) - 1; i >= 0; i-- {
l := bytes.TrimSpace(lines[i])
l = bytes.TrimSpace(bytes.TrimPrefix(l, []byte("data:")))
if !bytes.Contains(l, []byte(`"usage"`)) {
continue
}
var a struct {
Usage struct {
Input int `json:"input_tokens"`
Output int `json:"output_tokens"`
} `json:"usage"`
}
if json.Unmarshal(l, &a) == nil {
return a.Usage.Input, a.Usage.Output
}
}
return 0, 0
}
+242
View File
@@ -0,0 +1,242 @@
package gateway
import (
"bufio"
"bytes"
"encoding/json"
"io"
"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"
)
// mp3 is audio as a vendor sends it: bytes no text has.
var mp3 = append([]byte("ID3\x04\x00\x00\x00\x00\x00\x00\xff\xfb\x90\x64"), bytes.Repeat([]byte{0, 0xff, 0xfb, '{', '}', '\r', '\n'}, 2048)...)
// speaker is a vendor with OpenAI's text-to-speech API. What it was sent
// is kept; an SSE answer sends its first event, then waits for more to be
// let through, so a test can see the first reach the client before the
// rest is written.
type speaker struct {
mu sync.Mutex
sent [][]byte
accepts []string
more chan struct{}
}
func (sp *speaker) ServeHTTP(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
sp.mu.Lock()
sp.sent = append(sp.sent, body)
sp.accepts = append(sp.accepts, r.Header.Get("Accept"))
sp.mu.Unlock()
if r.Header.Get("Authorization") != "Bearer key" {
w.WriteHeader(401)
return
}
if r.URL.Path != "/v1/audio/speech" {
w.WriteHeader(404)
return
}
var req map[string]any
json.Unmarshal(body, &req)
switch {
case req["model"] == "refused":
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(400)
io.WriteString(w, `{"error":{"message":"voice nova isn't one of this model's"}}`)
case req["stream_format"] == "sse":
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, "data: {\"type\":\"speech.audio.delta\",\"audio\":\"SUQz\"}\n\n")
w.(http.Flusher).Flush()
select {
case <-sp.more:
case <-time.After(30 * time.Second):
}
io.WriteString(w, "data: {\"type\":\"speech.audio.delta\",\"audio\":\"//uQ\"}\n\n")
io.WriteString(w, "data: {\"type\":\"speech.audio.done\",\"usage\":{\"input_tokens\":12,\"output_tokens\":340,\"total_tokens\":352}}\n\n")
case req["voice_id"] != nil:
// Mistral's: the audio as base64 in JSON
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"audio_data":"UklGRg=="}`)
default:
w.Header().Set("Content-Type", "audio/mpeg")
w.Write(mp3)
}
}
func (sp *speaker) got() ([][]byte, []string) {
sp.mu.Lock()
defer sp.mu.Unlock()
return append([][]byte(nil), sp.sent...), append([]string(nil), sp.accepts...)
}
func speakerUp(t *testing.T) (*Server, *speaker) {
t.Helper()
fresh(t)
sp := &speaker{more: make(chan struct{})}
up := httptest.NewServer(sp)
t.Cleanup(up.Close)
if err := provider.Save(provider.Provider{ID: "voice", Name: "Voice", Chat: up.URL + "/v1", Key: "key", Models: []string{"gpt-4o-mini-tts", "refused"}}); err != nil {
t.Fatal(err)
}
return New(), sp
}
func postSpeech(t *testing.T, s *Server, path, body string) (int, http.Header, []byte) {
t.Helper()
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", path, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
s.Handler().ServeHTTP(rec, req)
return rec.Code, rec.Header(), rec.Body.Bytes()
}
// A speech request goes to the model's provider with only its model
// rewritten, every other field as sent, and the vendor's audio comes back
// byte for byte in its own type; it is in the usage ledger. The bare
// /audio/speech path an SDK given magpie's root posts to works too.
func TestSpeechGoesToTheModelsProvider(t *testing.T) {
s, sp := speakerUp(t)
body := `{"model":"voice/gpt-4o-mini-tts","input":"Hello from the magpie.","voice":"coral","response_format":"mp3","speed":1.25,"instructions":"Speak cheerfully."}`
code, h, got := postSpeech(t, s, "/v1/audio/speech", body)
if code != 200 || !bytes.Equal(got, mp3) || h.Get("Content-Type") != "audio/mpeg" {
t.Fatalf("%d %q, %d bytes back of %d", code, h.Get("Content-Type"), len(got), len(mp3))
}
sent, accepts := sp.got()
if len(sent) != 1 || accepts[0] == "application/json" {
t.Fatalf("vendor was sent %d bodies, Accept %v", len(sent), accepts)
}
var vendor, asked map[string]any
json.Unmarshal(sent[0], &vendor)
json.Unmarshal([]byte(body), &asked)
asked["model"] = "gpt-4o-mini-tts"
a, _ := json.Marshal(asked)
v, _ := json.Marshal(vendor)
if !bytes.Equal(a, v) {
t.Fatalf("vendor was sent %s", sent[0])
}
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 != "speech" || recs[0].Provider != "voice" || recs[0].Model != "gpt-4o-mini-tts" || recs[0].Requested != "voice/gpt-4o-mini-tts" || recs[0].Status != 200 {
t.Fatalf("usage %+v", recs)
}
// the bare path, and a field only one vendor has (Mistral's voice_id)
// with its JSON answer passed on as JSON
code, h, got = postSpeech(t, s, "/audio/speech", `{"model":"voice/gpt-4o-mini-tts","input":"hi","voice_id":"gb_jane_neutral","response_format":"wav"}`)
if code != 200 || string(got) != `{"audio_data":"UklGRg=="}` || h.Get("Content-Type") != "application/json" {
t.Fatalf("Mistral's shape: %d %q %s", code, h.Get("Content-Type"), got)
}
if sent, _ = sp.got(); len(sent) != 2 || !bytes.Contains(sent[1], []byte(`"voice_id":"gb_jane_neutral"`)) || !bytes.Contains(sent[1], []byte(`"model":"gpt-4o-mini-tts"`)) {
t.Fatalf("vendor was sent %s", sent[len(sent)-1])
}
}
// stream_format sse: each event reaches the client as the vendor sends
// it, before the vendor has sent the rest, and the done event's usage is
// counted.
func TestSpeechStreamsAsItComes(t *testing.T) {
s, sp := speakerUp(t)
gw := httptest.NewServer(s.Handler())
t.Cleanup(gw.Close)
res, err := http.Post(gw.URL+"/v1/audio/speech", "application/json", strings.NewReader(`{"model":"voice/gpt-4o-mini-tts","input":"hi","voice":"coral","stream_format":"sse"}`))
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
if res.StatusCode != 200 || res.Header.Get("Content-Type") != "text/event-stream" {
t.Fatalf("%d %q", res.StatusCode, res.Header.Get("Content-Type"))
}
rd := bufio.NewReader(res.Body)
first := make(chan string, 1)
go func() {
l, _ := rd.ReadString('\n')
first <- l
}()
select {
case l := <-first:
if !strings.Contains(l, `"audio":"SUQz"`) {
t.Fatalf("first line %q", l)
}
case <-time.After(20 * time.Second):
close(sp.more)
t.Fatal("the first event didn't reach the client while the vendor held the rest: the answer was held whole")
}
close(sp.more)
rest, _ := io.ReadAll(rd)
if !bytes.Contains(rest, []byte(`"audio":"//uQ"`)) || !bytes.Contains(rest, []byte("speech.audio.done")) {
t.Fatalf("rest %q", rest)
}
var recs []usage.Record
for i := 0; i < 100; i++ {
if recs = usage.Load(time.Time{}); len(recs) >= 1 {
break
}
time.Sleep(20 * time.Millisecond)
}
if len(recs) != 1 || recs[0].Operation != "speech" || recs[0].Input != 12 || recs[0].Output != 340 {
t.Fatalf("usage %+v", recs)
}
}
// A vendor's refusal comes back as an error with its status and message.
func TestSpeechVendorRefusalPassedOn(t *testing.T) {
s, _ := speakerUp(t)
code, _, got := postSpeech(t, s, "/v1/audio/speech", `{"model":"voice/refused","input":"hi","voice":"nova"}`)
if code != 400 || !strings.Contains(string(got), "voice nova isn't one of this model's") {
t.Fatalf("%d %s", code, got)
}
}
// A request magpie can't route is told why, and nothing reaches a vendor.
func TestSpeechRefusals(t *testing.T) {
s, sp := speakerUp(t)
if code, _, got := postSpeech(t, s, "/v1/audio/speech", `not json`); code != 400 || !strings.Contains(string(got), "JSON object") {
t.Fatalf("not json: %d %s", code, got)
}
if code, _, got := postSpeech(t, s, "/v1/audio/speech", `{"input":"hi"}`); code != 400 || !strings.Contains(string(got), "name the model") {
t.Fatalf("no model: %d %s", code, got)
}
if code, _, got := postSpeech(t, s, "/v1/audio/speech", `{"model":"nobody/tts-1","input":"hi"}`); code != 404 || !strings.Contains(string(got), "nobody/tts-1") {
t.Fatalf("unknown: %d %s", code, got)
}
if sent, _ := sp.got(); len(sent) != 0 {
t.Fatalf("vendor was sent %d", len(sent))
}
}
// With secrets kept, input and instructions go out masked, wherever in
// them the secret is; the voice and the rest go as sent.
func TestSpeechInputMasked(t *testing.T) {
s, sp := speakerUp(t)
if err := settings.Save(settings.Settings{Redact: true}); err != nil {
t.Fatal(err)
}
secret := "sk-ant-api03-" + strings.Repeat("Ab3x", 20)
other := "sk-ant-api03-" + strings.Repeat("Zq9w", 20)
body, _ := json.Marshal(map[string]any{"model": "voice/gpt-4o-mini-tts", "input": "Read this: " + secret, "instructions": "never say " + other, "voice": "coral"})
if code, _, got := postSpeech(t, s, "/v1/audio/speech", string(body)); code != 200 || !bytes.Equal(got, mp3) {
t.Fatalf("%d, %d bytes", code, len(got))
}
sent, _ := sp.got()
if len(sent) != 1 || bytes.Contains(sent[0], []byte(secret)) || bytes.Contains(sent[0], []byte(other)) {
t.Fatalf("vendor was sent a secret: %s", sent)
}
var vendor map[string]string
json.Unmarshal(sent[0], &vendor)
if !strings.HasPrefix(vendor["input"], "Read this: ") || !strings.HasPrefix(vendor["instructions"], "never say ") || vendor["voice"] != "coral" || vendor["model"] != "gpt-4o-mini-tts" {
t.Fatalf("vendor was sent %v", vendor)
}
}
+1 -1
View File
@@ -93,7 +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/audio/transcriptions", "/v1/audio/translations", "/v1/audio/speech",
"/v1/images/generations", "/v1/images/edits",
"/v1/videos", "/v1",
} {
+1 -1
View File
@@ -123,7 +123,7 @@ magpie provider refresh office <span class="c"># 一覧を再取得</span></pr
<li><b>すべての API。</b>リクエストはエージェントが使った API のまま転送されます(Anthropic Messages とトークン計数、Responses、Chat Completions)。共有側のプロバイダが別の API でしか提供しないモデルは、変換が 1 回だけ行われ、両方のコンピューターで変換されることはありません。Responses は WebSocket ではなく HTTP(SSE を含む)で送られます。</li>
<li><b>画像と動画。</b>画像・動画モデルは自動で見つかり、向こうの画像生成・編集・動画 API を通して使えます。</li>
<li><b>System One。</b>決定モデル(Jev、Clef、自分で名前を付けたモデル)は向こうの <code>/v1/systemone</code> につながり、チャットモデルではなく決定モデルとして現れます。新しいものはプロバイダの一覧を更新すると見つかります。<code>office</code> だけを指定すると一覧の最初の決定モデルに問い合わせます。</li>
<li><b>Embeddings、rerank、音声の文字起こし</b>は向こうの対応する API に送られます。エージェントの一覧ではリモートでの扱いのままです。一覧にあっても会話に使えるわけではありません。</li>
<li><b>Embeddings、rerank、音声の文字起こしと音声合成</b>は向こうの対応する API に送られます。エージェントの一覧ではリモートでの扱いのままです。一覧にあっても会話に使えるわけではありません。</li>
<li><b>価格。</b>各モデルは共有する magpie の計算どおり(向こうで手動設定した価格、なければプロバイダの定価)になるので、2 台の集計は一致します。このコンピューターで設定した価格が優先されます。</li>
</ul>
+1 -1
View File
@@ -123,7 +123,7 @@ magpie provider refresh office <span class="c"># fetch its list again</span></
<li><b>Every API.</b> A request goes on in the API the agent spoke (Anthropic Messages and token counting, Responses, Chat Completions). A model that the shared magpie’s provider serves on another API only is turned into that API once, never on both computers. Responses go over HTTP, SSE included, not WebSocket.</li>
<li><b>Images and video.</b> Its image and video models are found by themselves and served through its image generation and edit, and video, APIs.</li>
<li><b>System One.</b> Its decision models (Jev, Clef, and models with names of your own) are set up at its <code>/v1/systemone</code> and appear as decision models, not chat models. Refresh the provider’s list to find new ones. A bare <code>office</code> asks the first decision model listed.</li>
<li><b>Embeddings, rerank and speech to text</b> go to its matching APIs. They stay in agents’ lists as they are on the remote; being listed doesn’t make them able to hold a conversation.</li>
<li><b>Embeddings, rerank, speech to text and text to speech</b> go to its matching APIs. They stay in agents’ lists as they are on the remote; being listed doesn’t make them able to hold a conversation.</li>
<li><b>Prices.</b> Each model costs here what the shared magpie counts it at (a price set there by hand, else its provider’s list price), so the two computers count the same. A price you set here comes first.</li>
</ul>
+1 -1
View File
@@ -123,7 +123,7 @@ magpie provider refresh office <span class="c"># 重新获取列表</span></pr
<li><b>所有 API。</b>请求按 Agent 使用的 API 原样转发(Anthropic Messages 和 token 计数、Responses、Chat Completions)。共享 magpie 的供应商只用另一种 API 提供的模型,只转换一次,不会在两台电脑上各转一次。Responses 走 HTTP(包括 SSE),不走 WebSocket。</li>
<li><b>图像和视频。</b>它的图像和视频模型会被自动识别,经由它的图像生成、编辑和视频 API 提供。</li>
<li><b>System One。</b>它的决策模型(Jev、Clef,以及你自己命名的模型)接到它的 <code>/v1/systemone</code>,作为决策模型而不是对话模型出现。刷新供应商列表可以发现新的。只写 <code>office</code> 时使用列表里的第一个决策模型。</li>
<li><b>Embeddings、rerank 和语音转文字</b>发往它对应的 API。它们在 Agent 列表里保持远程上的样子;出现在列表里并不代表能用来对话。</li>
<li><b>Embeddings、rerank、语音转文字和文字转语音</b>发往它对应的 API。它们在 Agent 列表里保持远程上的样子;出现在列表里并不代表能用来对话。</li>
<li><b>价格。</b>每个模型在本机按共享 magpie 的计价(那边手动设的价格,否则是供应商的标价),两台电脑算出来一样。在本机设的价格优先。</li>
</ul>