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).
162 lines
4.9 KiB
Go
162 lines
4.9 KiB
Go
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
|
|
}
|