diff --git a/internal/gateway/embeddings.go b/internal/gateway/embeddings.go index 95d5de0ad..ad9ce944f 100644 --- a/internal/gateway/embeddings.go +++ b/internal/gateway/embeddings.go @@ -255,10 +255,18 @@ func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, op base := strings.TrimRight(c.p.OpenAIBase(), "/") tried := side.try(c) msg := "" - if base == "" { - msg = fmt.Sprintf("%s has no OpenAI-style API for %s", c.p.Name, path) - } else if rr, ok := req.(refusingRetrieval); ok { - msg = rr.refuses(c.p) // never sent, so never a 404 of the vendor's + // asked in the vendor's own shape where it has no OpenAI-style one + // (Gemini's speech, speech_gemini.go) + var nat *vendorAsk + if nr, ok := req.(nativeRetrieval); ok { + nat, msg = nr.nativeAt(c.p, c.model) + } + if msg == "" && nat == nil { + if base == "" { + msg = fmt.Sprintf("%s has no OpenAI-style API for %s", c.p.Name, path) + } else if rr, ok := req.(refusingRetrieval); ok { + msg = rr.refuses(c.p) // never sent, so never a 404 of the vendor's + } } if msg != "" { tried(400, errors.New(msg)) @@ -274,6 +282,9 @@ func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, op return } out, ctype, err := req.forModel(c.model) + if nat != nil { + out, ctype = nat.body, "application/json" + } if err != nil { tried(400, err) side.end(c.p, c.model, 400, err, Usage{}) @@ -292,10 +303,18 @@ func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, op 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) + var natIn, natOut int + if st, ok := req.(streamedRetrieval); ok && st.streams() && nat == nil { + res, b, got, code, err = s.retrieveOpen(ctx, c.p, provider.Chat, base+path, ctype, "", out) + } else if nat != nil { + // whole, then put in the client's shape + if b, got, code, err = s.retrieveAs(ctx, c.p, nat.proto, nat.url, ctype, out); err == nil { + if b, got, natIn, natOut, err = nat.answer(b); err != nil { + code, err = 502, fmt.Errorf("%s: %v", provider.HostOf(nat.url), err) + } + } } else { - b, got, code, err = s.retrieveAs(ctx, c.p, base+path, ctype, out) + b, got, code, err = s.retrieveAs(ctx, c.p, provider.Chat, base+path, ctype, out) } if res == nil { cancel() @@ -310,6 +329,9 @@ func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, op } call.Status = code in, outTokens := retrievedTokens(b), answeredTokens(b) + if nat != nil { + in, outTokens = natIn, natOut + } var cached Usage // the cache's share, when the answer tells it if cr, ok := req.(countedRetrieval); ok && res == nil && err == nil { cached = cr.counted(b) @@ -391,18 +413,19 @@ func resolveRetrievalModel(id, kind 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) + b, _, code, err := s.retrieveAs(ctx, p, provider.Chat, 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) { +// multipart form's with its boundary, signed as a request of proto's; it +// also gives the answer's. +func (s *Server) retrieveAs(ctx context.Context, p provider.Provider, proto provider.Protocol, 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) + res, b, got, code, err := s.retrieveOpen(ctx, p, proto, url, ctype, accept, body) if res == nil { return b, got, code, err } @@ -417,7 +440,7 @@ func (s *Server) retrieveAs(ctx context.Context, p provider.Provider, url, ctype // 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) { +func (s *Server) retrieveOpen(ctx context.Context, p provider.Provider, proto provider.Protocol, 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 { @@ -434,7 +457,7 @@ func (s *Server) retrieveOpen(ctx context.Context, p provider.Provider, url, cty passOnCaller(ctx, req) passOnUA(req, callerUA(ctx)) } - if err := p.Sign(ctx, req, provider.Chat, body); err != nil { + if err := p.Sign(ctx, req, proto, body); err != nil { return nil, nil, "", 502, err } res, err := p.Do(s.client, req) diff --git a/internal/gateway/pipeline_check.go b/internal/gateway/pipeline_check.go index 5f8dc2d5d..866bf6683 100644 --- a/internal/gateway/pipeline_check.go +++ b/internal/gateway/pipeline_check.go @@ -3,7 +3,6 @@ package gateway import ( "bytes" "context" - "encoding/binary" "encoding/json" "mime/multipart" "net/http" @@ -260,21 +259,5 @@ func (s *Server) checkCall(ctx context.Context, c *PipelineCheck, path, ctype st // silentWAV is d of silence as a 16 kHz mono 16-bit WAV file. func silentWAV(d time.Duration) []byte { const rate = 16000 - n := int(d.Seconds()*rate) * 2 - var b bytes.Buffer - w := func(v any) { _ = binary.Write(&b, binary.LittleEndian, v) } - b.WriteString("RIFF") - w(uint32(36 + n)) - b.WriteString("WAVEfmt ") - w(uint32(16)) - w(uint16(1)) // PCM - w(uint16(1)) // mono - w(uint32(rate)) - w(uint32(rate * 2)) - w(uint16(2)) - w(uint16(16)) - b.WriteString("data") - w(uint32(n)) - b.Write(make([]byte, n)) - return b.Bytes() + return pcmWAV(make([]byte, int(d.Seconds()*rate)*2), rate) } diff --git a/internal/gateway/speech_gemini.go b/internal/gateway/speech_gemini.go new file mode 100644 index 000000000..3948c6a80 --- /dev/null +++ b/internal/gateway/speech_gemini.go @@ -0,0 +1,261 @@ +package gateway + +import ( + "bytes" + "encoding/base64" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "strconv" + "strings" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/provider" +) + +// nativeRetrieval is a retrieval some providers are asked in their own +// API's shape rather than OpenAI's: Gemini's text-to-speech, which Google +// serves on generateContent alone (Pedram on Discord: a Vertex AI TTS +// model added by hand was sent to …/audio/speech, which Google has not). +type nativeRetrieval interface { + // nativeAt is how p is asked for model in its own shape: nil when p + // takes the OpenAI shape, or why it can't be asked at all ("" when it + // can) + nativeAt(p provider.Provider, model string) (*vendorAsk, string) +} + +// vendorAsk is one request in a vendor's own shape: where it goes, the +// body, the API it is signed for, and how the vendor's whole answer is +// turned into what the client is given (bytes, Content-Type and the +// tokens it counted). +type vendorAsk struct { + url string + body []byte + proto provider.Protocol + answer func(b []byte) (out []byte, ctype string, in, outTokens int, err error) +} + +// geminiSpeechBase is the Gemini API base p is asked for model at, a +// Gemini TTS model (gemini-2.5-flash-preview-tts…), on Google's own +// generateContent; "" when it is asked on OpenAI's /audio/speech. That is +// Vertex AI's project, AI Studio (whose OpenAI-compatible API has no +// /audio/speech; its Gemini API beside it, as drawGemini asks), or a +// provider of keys with a Gemini API and no OpenAI-style one. A plugin +// puts the request in its vendor's shape itself, and a relay with an +// OpenAI-style API of its own is asked there. +func geminiSpeechBase(p provider.Provider, model string) string { + if p.IsPlugin() || p.IsRemoteMagpie() || p.Account != nil || catalog.ServesOf(model) != catalog.ServesSpeech || !strings.Contains(strings.ToLower(model), "gemini") { + return "" + } + switch { + case p.IsVertex(): + if provider.VertexPartner(model) || provider.VertexClaude(model) { + return "" + } + return p.Base(provider.Gemini) + case isGoogle(p): + return strings.TrimSuffix(strings.TrimRight(p.Base(provider.Chat), "/"), "/openai") + case p.OpenAIBase() == "": + return p.Base(provider.Gemini) + } + return "" +} + +// geminiVoices are Gemini's prebuilt voices, by their names in lower case. +var geminiVoices = func() map[string]string { + m := map[string]string{} + for _, v := range []string{"Zephyr", "Puck", "Charon", "Kore", "Fenrir", "Leda", "Orus", "Aoede", "Callirrhoe", "Autonoe", "Enceladus", "Iapetus", "Umbriel", "Algieba", "Despina", "Erinome", "Algenib", "Rasalgethi", "Laomedeia", "Achernar", "Alnilam", "Schedar", "Gacrux", "Pulcherrima", "Achird", "Zubenelgenubi", "Vindemiatrix", "Sadachbia", "Sadaltager", "Sulafat"} { + m[strings.ToLower(v)] = v + } + return m +}() + +// openAIVoices are OpenAI's voices, each given the Gemini voice nearest it +// as Google describes them (nova bright → Zephyr, onyx deep → Algenib +// gravelly, shimmer soft → Achernar…), so a client that names an OpenAI +// voice hears one of the same kind. +var openAIVoices = map[string]string{ + "alloy": "Kore", "ash": "Charon", "ballad": "Algieba", "coral": "Sulafat", + "echo": "Iapetus", "fable": "Puck", "onyx": "Algenib", "nova": "Zephyr", + "sage": "Vindemiatrix", "shimmer": "Achernar", "verse": "Rasalgethi", + "marin": "Aoede", "cedar": "Schedar", +} + +// defaultGeminiVoice is spoken in when the voice asked is none of Gemini's +// or OpenAI's: the one Google's own examples use. +const defaultGeminiVoice = "Kore" + +// geminiVoice is the Gemini voice for one an OpenAI client named: a Gemini +// voice by its name in any case, an OpenAI voice by the one nearest it, +// anything else Kore. +func geminiVoice(v string) string { + v = strings.ToLower(strings.TrimSpace(v)) + if g, ok := geminiVoices[v]; ok { + return g + } + if g, ok := openAIVoices[v]; ok { + return g + } + return defaultGeminiVoice +} + +// nativeAt asks a Gemini TTS model on generateContent: the input to read, +// after the instructions on how (Gemini takes them in the prompt: "Say +// cheerfully: …"), in one prebuilt voice, answered with audio alone. speed +// has no Gemini field and is left out. The answer is 24 kHz PCM, given back +// as a WAV, or raw for response_format pcm; mp3, opus, aac and flac are +// answered as a WAV too, with its own Content-Type, since magpie has no +// encoder for them and OpenAI's clients ask mp3 by default (a 400 would +// fail them all, while players read a WAV by its header). A streamed +// answer (stream_format sse) is turned away: generateContent's is whole. +func (sp *speechRequest) nativeAt(p provider.Provider, model string) (*vendorAsk, string) { + base := strings.TrimRight(geminiSpeechBase(p, model), "/") + if base == "" { + return nil, "" + } + str := func(k string) string { + var v string + json.Unmarshal(sp.req[k], &v) + return v + } + format := strings.ToLower(str("response_format")) + switch format { + case "", "wav", "pcm", "mp3", "opus", "aac", "flac": + default: + return nil, fmt.Sprintf("response_format %q isn't one Gemini's speech can be given back in: wav (the default) or pcm", format) + } + if str("stream_format") == "sse" { + return nil, "Gemini's speech comes whole from generateContent: ask without stream_format sse" + } + input := str("input") + if strings.TrimSpace(input) == "" { + return nil, "\"input\" is empty: there is nothing to read aloud" + } + text := input + if how := strings.TrimRight(strings.TrimSpace(str("instructions")), " :"); how != "" { + text = how + ": " + input + } + body, _ := json.Marshal(map[string]any{ + "contents": []map[string]any{{"role": "user", "parts": []map[string]string{{"text": text}}}}, + "generationConfig": map[string]any{ + "responseModalities": []string{"AUDIO"}, + "speechConfig": map[string]any{"voiceConfig": map[string]any{"prebuiltVoiceConfig": map[string]string{"voiceName": geminiVoice(str("voice"))}}}, + }, + }) + url := base + provider.GeminiPath(model, false) + if p.IsVertex() { + url = base + provider.VertexWholePath(model) + } + return &vendorAsk{url: url, body: body, proto: provider.Gemini, answer: func(b []byte) ([]byte, string, int, int, error) { + return geminiAudio(b, format == "pcm") + }}, "" +} + +// geminiAudio is the audio a generateContent answer holds, its inlineData +// parts' PCM (audio/L16;codec=pcm;rate=24000) one after another: in a WAV, +// or raw when pcm, with the tokens it counted. An answer with no audio is +// an error naming why Gemini stopped, and any text it gave instead. +func geminiAudio(b []byte, pcm bool) ([]byte, string, int, int, error) { + var res struct { + Candidates []struct { + FinishReason string `json:"finishReason"` + Content struct { + Parts []struct { + Text string `json:"text"` + InlineData *struct { + MimeType string `json:"mimeType"` + Data string `json:"data"` + } `json:"inlineData"` + } `json:"parts"` + } `json:"content"` + } `json:"candidates"` + PromptFeedback struct { + BlockReason string `json:"blockReason"` + } `json:"promptFeedback"` + Usage struct { + Prompt int `json:"promptTokenCount"` + Candidates int `json:"candidatesTokenCount"` + } `json:"usageMetadata"` + } + if err := json.Unmarshal(b, &res); err != nil { + return nil, "", 0, 0, fmt.Errorf("the answer isn't Gemini's generateContent: %v", err) + } + var audio []byte + rate := 24000 + var said, why []string + for _, c := range res.Candidates { + if c.FinishReason != "" && c.FinishReason != "STOP" { + why = append(why, c.FinishReason) + } + for _, part := range c.Content.Parts { + if part.InlineData == nil || !strings.HasPrefix(strings.ToLower(part.InlineData.MimeType), "audio/") { + if t := strings.TrimSpace(part.Text); t != "" { + said = append(said, t) + } + continue + } + data, err := base64.StdEncoding.DecodeString(part.InlineData.Data) + if err != nil { + return nil, "", 0, 0, fmt.Errorf("Gemini's audio isn't base64: %v", err) + } + if r := pcmRate(part.InlineData.MimeType); r > 0 { + rate = r + } + audio = append(audio, data...) + } + } + if len(audio) == 0 { + msg := "Gemini gave no audio" + if res.PromptFeedback.BlockReason != "" { + why = append(why, res.PromptFeedback.BlockReason) + } + if len(why) > 0 { + msg += " (" + strings.Join(why, ", ") + ")" + } + if len(said) > 0 { + msg += ": " + strings.Join(said, " ") + } + return nil, "", 0, 0, errors.New(msg) + } + in, out := res.Usage.Prompt, res.Usage.Candidates + if pcm { + return audio, "audio/pcm", in, out, nil + } + return pcmWAV(audio, rate), "audio/wav", in, out, nil +} + +// pcmRate is the rate a PCM type names (audio/L16;codec=pcm;rate=24000), +// 0 when it names none. +func pcmRate(mime string) int { + for _, f := range strings.Split(mime, ";") { + if v, ok := strings.CutPrefix(strings.TrimSpace(strings.ToLower(f)), "rate="); ok { + if n, err := strconv.Atoi(v); err == nil && n > 0 { + return n + } + } + } + return 0 +} + +// pcmWAV is 16-bit little-endian mono PCM at rate, as Gemini speaks it, in +// a WAV file. +func pcmWAV(pcm []byte, rate int) []byte { + var b bytes.Buffer + b.Grow(44 + len(pcm)) + w := func(v any) { _ = binary.Write(&b, binary.LittleEndian, v) } + b.WriteString("RIFF") + w(uint32(36 + len(pcm))) + b.WriteString("WAVEfmt ") + w(uint32(16)) + w(uint16(1)) // PCM + w(uint16(1)) // mono + w(uint32(rate)) + w(uint32(rate * 2)) + w(uint16(2)) + w(uint16(16)) + b.WriteString("data") + w(uint32(len(pcm))) + b.Write(pcm) + return b.Bytes() +} diff --git a/internal/gateway/speech_gemini_test.go b/internal/gateway/speech_gemini_test.go new file mode 100644 index 000000000..3b520e091 --- /dev/null +++ b/internal/gateway/speech_gemini_test.go @@ -0,0 +1,226 @@ +package gateway + +import ( + "bytes" + "encoding/base64" + "encoding/binary" + "encoding/json" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/tidwall/gjson" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" + "github.com/yetone/magpie/internal/usage" +) + +// geminiPCM is speech as Gemini's TTS gives it: 16-bit PCM, bytes no text +// has. +var geminiPCM = bytes.Repeat([]byte{0x01, 0xff, 0x7f, 0x80, '{', '}'}, 400) + +// geminiSpoken is a generateContent answer of a TTS model, in Google's +// shape: the PCM as base64 inlineData, audio tokens counted. +var geminiSpoken = `{"candidates":[{"content":{"parts":[{"inlineData":{"mimeType":"audio/L16;codec=pcm;rate=24000","data":"` + + base64.StdEncoding.EncodeToString(geminiPCM) + `"}}],"role":"model"},"finishReason":"STOP","index":0}],` + + `"usageMetadata":{"promptTokenCount":9,"candidatesTokenCount":87,"totalTokenCount":96,"promptTokensDetails":[{"modality":"TEXT","tokenCount":9}],"candidatesTokensDetails":[{"modality":"AUDIO","tokenCount":87}]},"modelVersion":"gemini-2.5-flash-preview-tts","responseId":"Q2t0aZ7bA4nV"}` + +// vertexSpeaker is a gateway with a Vertex AI provider at project proj-1 +// that has a Gemini TTS model added by hand, as Pedram did, backed by v +// answering each generateContent with a TTS model's answer. +func vertexSpeaker(t *testing.T) (*Server, *vertexUp) { + t.Helper() + v := &vertexUp{reply: func(int, map[string]any) (int, string) { return 200, geminiSpoken }} + vertexServe(t, v, `{}`) + creds := filepath.Join(t.TempDir(), "application_default_credentials.json") + os.WriteFile(creds, []byte(`{"type":"authorized_user","client_id":"test.apps.googleusercontent.com","client_secret":"test-secret","refresh_token":"1//test-refresh"}`), 0o600) + if err := provider.Save(provider.Provider{ID: "google-vertex", Name: "Google Vertex AI", Preset: provider.VertexPreset, + Vertex: &provider.Vertex{Project: "proj-1", Credentials: creds}, Models: []string{"gemini-2.5-flash", "gemini-2.5-flash-preview-tts"}}); err != nil { + t.Fatal(err) + } + return New(), v +} + +// wavOf is the PCM a WAV holds and its rate, or fails the test when b +// isn't a 16-bit mono PCM WAV. +func wavOf(t *testing.T, b []byte) ([]byte, int) { + t.Helper() + if len(b) < 44 || string(b[:4]) != "RIFF" || string(b[8:16]) != "WAVEfmt " || string(b[36:40]) != "data" { + t.Fatalf("not a WAV: %q", b[:min(len(b), 48)]) + } + le := binary.LittleEndian + if le.Uint16(b[20:]) != 1 || le.Uint16(b[22:]) != 1 || le.Uint16(b[34:]) != 16 || int(le.Uint32(b[4:])) != len(b)-8 || int(le.Uint32(b[40:])) != len(b)-44 { + t.Fatalf("WAV header %v", b[:44]) + } + return b[44:], int(le.Uint32(b[24:])) +} + +// A Gemini TTS model added to Vertex AI is asked on generateContent, not +// at an /audio/speech Google doesn't have: the input after the +// instructions, in the Gemini voice nearest the OpenAI one asked, audio +// alone, signed with the project's Google token. Its PCM comes back as a +// 24 kHz WAV, and the call is in the usage ledger with Gemini's counts. +func TestGeminiSpeechOnVertex(t *testing.T) { + s, v := vertexSpeaker(t) + code, h, got := postSpeech(t, s, "/v1/audio/speech", `{"model":"google-vertex/gemini-2.5-flash-preview-tts","input":"Hello from the magpie.","voice":"coral","instructions":"Say cheerfully","speed":1.25}`) + if code != 200 || h.Get("Content-Type") != "audio/wav" { + t.Fatalf("%d %q %s", code, h.Get("Content-Type"), got) + } + pcm, rate := wavOf(t, got) + if !bytes.Equal(pcm, geminiPCM) || rate != 24000 { + t.Fatalf("WAV holds %d bytes at %d Hz, want Gemini's %d at 24000", len(pcm), rate, len(geminiPCM)) + } + a := v.last(t) + if a.path != "/v1/projects/proj-1/locations/global/publishers/google/models/gemini-2.5-flash-preview-tts:generateContent" || a.auth != "Bearer ya29.vertex-test" { + t.Fatalf("asked %s with %q", a.path, a.auth) + } + b, _ := json.Marshal(a.body) + if g := gjson.GetBytes(b, "generationConfig.responseModalities").Raw; g != `["AUDIO"]` { + t.Fatalf("responseModalities %s: %s", g, b) + } + if g := gjson.GetBytes(b, "generationConfig.speechConfig.voiceConfig.prebuiltVoiceConfig.voiceName").String(); g != "Sulafat" { + t.Fatalf("voice %q: %s", g, b) + } + if g := gjson.GetBytes(b, "contents.0.parts.0.text").String(); g != "Say cheerfully: Hello from the magpie." || gjson.GetBytes(b, "contents.0.role").String() != "user" { + t.Fatalf("contents %s", b) + } + if bytes.Contains(b, []byte("speed")) || bytes.Contains(b, []byte(`"model"`)) { + t.Fatalf("an OpenAI field went to Gemini: %s", b) + } + 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].Provider != "google-vertex" || recs[0].Model != "gemini-2.5-flash-preview-tts" || recs[0].Status != 200 || recs[0].Input != 9 || recs[0].Output != 87 { + t.Fatalf("usage %+v", recs) + } +} + +// response_format pcm is Gemini's PCM as it came; a format magpie has no +// encoder for (mp3, OpenAI's default, opus…) is a WAV, said so in its +// Content-Type; one OpenAI has none of is turned away, as is a stream, +// and neither reaches Google. The voice is a Gemini one by its name in any +// case, Kore for one Gemini hasn't. +func TestGeminiSpeechFormatsAndVoices(t *testing.T) { + s, v := vertexSpeaker(t) + const m = `"model":"google-vertex/gemini-2.5-flash-preview-tts","input":"hi"` + voiceOf := func() string { + b, _ := json.Marshal(v.last(t).body) + return gjson.GetBytes(b, "generationConfig.speechConfig.voiceConfig.prebuiltVoiceConfig.voiceName").String() + } + code, h, got := postSpeech(t, s, "/v1/audio/speech", `{`+m+`,"voice":"puck","response_format":"pcm"}`) + if code != 200 || h.Get("Content-Type") != "audio/pcm" || !bytes.Equal(got, geminiPCM) || voiceOf() != "Puck" { + t.Fatalf("pcm: %d %q %d bytes, voice %s", code, h.Get("Content-Type"), len(got), voiceOf()) + } + for _, f := range []string{"mp3", "opus", "wav"} { + code, h, got = postSpeech(t, s, "/v1/audio/speech", `{`+m+`,"voice":"someone","response_format":"`+f+`"}`) + if code != 200 || h.Get("Content-Type") != "audio/wav" || voiceOf() != "Kore" { + t.Fatalf("%s: %d %q %s, voice %s", f, code, h.Get("Content-Type"), got, voiceOf()) + } + wavOf(t, got) + } + asked := v.count() + for body, want := range map[string]string{ + `{` + m + `,"response_format":"ogg"}`: "wav (the default) or pcm", + `{` + m + `,"stream_format":"sse"}`: "without stream_format sse", + `{"model":"google-vertex/gemini-2.5-flash-preview-tts","input":" "}`: "nothing to read aloud", + } { + if code, _, got := postSpeech(t, s, "/v1/audio/speech", body); code != 400 || !strings.Contains(string(got), want) { + t.Fatalf("%s: %d %s", body, code, got) + } + } + if n := v.count(); n != asked { + t.Fatalf("Google was asked %d times for requests turned away", n-asked) + } +} + +// An answer with no audio (a refusal said in text, or a block) is an +// error naming why, not an empty WAV. +func TestGeminiSpeechWithoutAudio(t *testing.T) { + s, v := vertexSpeaker(t) + v.mu.Lock() + v.reply = func(int, map[string]any) (int, string) { + return 200, `{"candidates":[{"content":{"parts":[{"text":"I can't read that."}],"role":"model"},"finishReason":"OTHER","index":0}],"usageMetadata":{"promptTokenCount":9,"totalTokenCount":9}}` + } + v.mu.Unlock() + code, _, got := postSpeech(t, s, "/v1/audio/speech", `{"model":"google-vertex/gemini-2.5-flash-preview-tts","input":"hi"}`) + if code != 502 || !strings.Contains(string(got), "Gemini gave no audio (OTHER): I can't read that.") { + t.Fatalf("%d %s", code, got) + } +} + +// The Gemini API provider (AI Studio) is asked on its own generateContent +// beside its OpenAI-compatible base, with its key in x-goog-api-key, and +// the input and instructions go out masked when secrets are kept. A +// relay's Gemini TTS model, behind an OpenAI-style API of its own, still +// goes to its /audio/speech as sent. +func TestGeminiSpeechOnAIStudio(t *testing.T) { + fresh(t) + if err := settings.Save(settings.Settings{Redact: true}); err != nil { + t.Fatal(err) + } + if err := provider.Save(provider.Provider{ID: "gg", Name: "Google", Chat: provider.AIStudioChat, Key: "AIzaSy-test", Models: []string{"gemini-2.5-pro-preview-tts"}}); err != nil { + t.Fatal(err) + } + if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Chat: "https://relay.example/v1", Gemini: "https://relay.example/v1beta", Key: "rk", Models: []string{"gemini-2.5-flash-preview-tts"}}); err != nil { + t.Fatal(err) + } + type asked struct { + url, key, auth string + body []byte + } + var mu sync.Mutex + var seen []asked + s := New() + s.client = &http.Client{Transport: countTransport(func(r *http.Request) (*http.Response, error) { + b, _ := io.ReadAll(r.Body) + mu.Lock() + seen = append(seen, asked{r.URL.String(), r.Header.Get("x-goog-api-key"), r.Header.Get("Authorization"), b}) + mu.Unlock() + switch { + case r.URL.Host == "generativelanguage.googleapis.com" && strings.HasSuffix(r.URL.Path, ":generateContent"): + return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": {"application/json; charset=UTF-8"}}, Body: io.NopCloser(strings.NewReader(geminiSpoken))}, nil + case r.URL.Host == "relay.example" && r.URL.Path == "/v1/audio/speech": + return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": {"audio/mpeg"}}, Body: io.NopCloser(bytes.NewReader(mp3))}, nil + } + return nil, fmt.Errorf("unexpected request to %s", r.URL) + })} + secret := "sk-ant-api03-" + strings.Repeat("Ab3x", 20) + body, _ := json.Marshal(map[string]any{"model": "gg/gemini-2.5-pro-preview-tts", "input": "Read this: " + secret, "instructions": "Say slowly", "voice": "Charon", "response_format": "wav"}) + code, h, got := postSpeech(t, s, "/v1/audio/speech", string(body)) + if code != 200 || h.Get("Content-Type") != "audio/wav" { + t.Fatalf("%d %q %s", code, h.Get("Content-Type"), got) + } + if pcm, _ := wavOf(t, got); !bytes.Equal(pcm, geminiPCM) { + t.Fatalf("WAV holds %d bytes", len(pcm)) + } + mu.Lock() + a := seen[len(seen)-1] + mu.Unlock() + if a.url != "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro-preview-tts:generateContent" || a.key != "AIzaSy-test" || a.auth != "" { + t.Fatalf("asked %s, key %q, auth %q", a.url, a.key, a.auth) + } + text := gjson.GetBytes(a.body, "contents.0.parts.0.text").String() + if bytes.Contains(a.body, []byte(secret)) || !strings.HasPrefix(text, "Say slowly: Read this: ") || gjson.GetBytes(a.body, "generationConfig.speechConfig.voiceConfig.prebuiltVoiceConfig.voiceName").String() != "Charon" { + t.Fatalf("Google was sent %s", a.body) + } + code, h, got = postSpeech(t, s, "/v1/audio/speech", `{"model":"relay/gemini-2.5-flash-preview-tts","input":"hi","voice":"coral"}`) + if code != 200 || h.Get("Content-Type") != "audio/mpeg" || !bytes.Equal(got, mp3) { + t.Fatalf("relay: %d %q", code, h.Get("Content-Type")) + } + mu.Lock() + a = seen[len(seen)-1] + mu.Unlock() + if a.url != "https://relay.example/v1/audio/speech" || gjson.GetBytes(a.body, "voice").String() != "coral" { + t.Fatalf("relay asked %s with %s", a.url, a.body) + } +}