niyoh120 asked for an OpenAI-style speech-to-text endpoint so a client's voice input can go through magpie like its chat does. magpie had no /v1/audio route, so the request 404ed. What changed: - POST /v1/audio/transcriptions and /v1/audio/translations (and the /audio/... spellings) route through the same core as embeddings and rerank. embeddings.go's routing is pulled out into serveRetrieval, so disabled models, key access, groups, pause rules, account holds, failover, redaction and usage records are shared rather than copied. - transcribe.go reads the multipart form only to find `model` (as provider/model) and `prompt`. The form goes to the provider byte for byte; it is rebuilt part by part, under the same boundary, only when the model name is rewritten or the prompt was masked. The audio part is always copied as sent. - Only providers with an OpenAI-style base are tried; an Anthropic-only provider gets a 400 saying so. A body that isn't multipart, a form with no model, or one that doesn't parse gets a 400 and nothing is sent. - The vendor's answer type passes through (response_format text/srt/vtt stays text/plain). Usage records output tokens from usage.output_tokens. - The 404 message, the info api list, remote magpie's suffix list, the CORS and LAN tests, docs/reference.md, gateway-routing.md and the remote docs (en, zh, ja) name the new paths. What was run, at 9c36c3a0 (this change rebased on10f38770): - gofmt -l internal/gateway internal/provider: empty - go vet (darwin); GOOS=linux and GOOS=windows go vet -tags nogui on ./internal/gateway ./internal/provider: clean - go test -tags nogui -timeout 45m ./internal/gateway ./internal/provider: ok (1367s, 339s); also green on two earlier bases (b4fe6663, 06fbfd95) - Rebased again ona0ebe003(main had moved 5 commits, none in these files; routing.go's Factory rest is the nearest): gofmt, vet on darwin, linux (nogui) and windows (nogui) clean, and go test -tags nogui -run 'Transcri|Embed|Rerank|CORS|LAN|Lan|Factory| Retriev|NotFound|Info' ./internal/gateway ok. The full packages were not rerun on this last base. Break-checks, each turned red and restored: - routes removed (the old code): all 5 new tests fail - model never rewritten: TestTranscriptionGoesToTheModelsProvider and TestTranscriptionPromptRedacted fail - answer always labelled JSON: TestTranscriptAsTextKeepsItsType fails - rebuild truncates the audio part: Goes + PromptRedacted fail - prompt not masked: TestTranscriptionPromptRedacted fails - output tokens ignored: TestTranscriptionGoesToTheModelsProvider fails Real use: through magpie's real handler against aihubmix (https://aihubmix.com/v1) with a `say`-made m4a: whisper-1 json 200 {"text":"Hello from the Magpie Gateway."}, response_format=text 200, srt 200 text/plain with SRT cues, translations 200. Not tried: OpenAI direct (the key answers 429 "account is not active"), Groq, a local vLLM/whisper server, and any real client's voice input.
171 lines
4.9 KiB
Go
171 lines
4.9 KiB
Go
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
|
|
}
|