forked from envoyproxy/ai-gateway
-
Notifications
You must be signed in to change notification settings - Fork 0
feat(speech): expose DashScope voice-enrollment (voice cloning) API #9
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,86 @@ | ||
| // Copyright Envoy AI Gateway Authors | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
| // The full text of the Apache license is available in the LICENSE file at | ||
| // the root of the repo. | ||
|
|
||
| package translator | ||
|
|
||
| import ( | ||
| "io" | ||
| "strconv" | ||
|
|
||
| "github.com/envoyproxy/ai-gateway/internal/apischema/dashscope" | ||
| "github.com/envoyproxy/ai-gateway/internal/internalapi" | ||
| "github.com/envoyproxy/ai-gateway/internal/metrics" | ||
| "github.com/envoyproxy/ai-gateway/internal/tracing/tracingapi" | ||
| ) | ||
|
|
||
| // dashScopeVoiceEnrollmentPath is DashScope's native voice-cloning endpoint. A single URL | ||
| // hosts every action (create_voice / list_voice / query_voice / update_voice / delete_voice); | ||
| // the action is chosen in the request body. | ||
| // | ||
| // https://www.alibabacloud.com/help/en/model-studio/voice-clone-design-http-api | ||
| const dashScopeVoiceEnrollmentPath = "/api/v1/services/audio/tts/customization" | ||
|
|
||
| // DashScopeVoiceEnrollmentSpan is a zero-value span for voice-enrollment. There is no | ||
| // per-request response object to record — the endpoint returns short JSON envelopes | ||
| // (voice_id, status, page_index, …) that we forward untouched. | ||
| type DashScopeVoiceEnrollmentSpan = tracingapi.Span[struct{}, struct{}] | ||
|
|
||
| // DashScopeVoiceEnrollmentTranslator translates DashScope voice-enrollment requests as a | ||
| // pass-through. It exists so the gateway can attach auth/logging/RBAC to the DashScope | ||
| // management surface without reshaping the payload. | ||
| type DashScopeVoiceEnrollmentTranslator = Translator[dashscope.VoiceEnrollmentRequest, DashScopeVoiceEnrollmentSpan] | ||
|
|
||
| // dashScopeVoiceEnrollmentTranslator forwards voice-enrollment CRUD calls to DashScope | ||
| // unchanged. The body varies per action (create takes `url`+`prefix`, delete takes only | ||
| // `voice_id`, list is paginated, etc.) so any translator-side reshaping would just add | ||
| // friction; we forward the caller's payload verbatim and only rewrite `:path`. | ||
| type dashScopeVoiceEnrollmentTranslator struct{} | ||
|
|
||
| // NewDashScopeVoiceEnrollmentTranslator creates a pass-through translator for voice-enrollment. | ||
| func NewDashScopeVoiceEnrollmentTranslator() DashScopeVoiceEnrollmentTranslator { | ||
| return &dashScopeVoiceEnrollmentTranslator{} | ||
| } | ||
|
|
||
| // RequestBody implements [DashScopeVoiceEnrollmentTranslator.RequestBody]. | ||
| // | ||
| // Body flows through untouched — DashScope owns the schema per action, and modelling every | ||
| // variant here would just track upstream drift. The router already parsed body.model / | ||
| // body.input.action for logging + routing, so nothing else is required. We only need to | ||
| // re-emit the original bytes when Envoy's upstream stage forces a body replacement (retry / | ||
| // streaming), and to rewrite `:path` to the DashScope native URL because Envoy is otherwise | ||
| // still sitting on the client's inbound path. | ||
| func (dashScopeVoiceEnrollmentTranslator) RequestBody(original []byte, _ *dashscope.VoiceEnrollmentRequest, forceBodyMutation bool) ( | ||
| newHeaders []internalapi.Header, newBody []byte, err error, | ||
| ) { | ||
| newHeaders = []internalapi.Header{{pathHeaderName, dashScopeVoiceEnrollmentPath}} | ||
| if forceBodyMutation && len(original) > 0 { | ||
| newBody = original | ||
| newHeaders = append(newHeaders, internalapi.Header{contentLengthHeaderName, strconv.Itoa(len(newBody))}) | ||
| } | ||
| return | ||
| } | ||
|
|
||
| // ResponseHeaders implements [DashScopeVoiceEnrollmentTranslator.ResponseHeaders]. | ||
| // DashScope returns application/json envelopes and the caller expects that shape, so we do | ||
| // not touch response headers. | ||
| func (dashScopeVoiceEnrollmentTranslator) ResponseHeaders(_ map[string]string) (newHeaders []internalapi.Header, err error) { | ||
| return nil, nil | ||
| } | ||
|
|
||
| // ResponseBody implements [DashScopeVoiceEnrollmentTranslator.ResponseBody]. Passes DashScope's | ||
| // JSON response through unchanged; the action-specific envelope (`voice_id`, `voice_list`, | ||
| // resource_link, status, …) is the caller's contract, not the gateway's to reshape. | ||
| func (dashScopeVoiceEnrollmentTranslator) ResponseBody(_ map[string]string, _ io.Reader, _ bool, _ DashScopeVoiceEnrollmentSpan) ( | ||
| newHeaders []internalapi.Header, newBody []byte, tokenUsage metrics.TokenUsage, responseModel internalapi.ResponseModel, err error, | ||
| ) { | ||
| return nil, nil, metrics.TokenUsage{}, "voice-enrollment", nil | ||
| } | ||
|
|
||
| // ResponseError implements [DashScopeVoiceEnrollmentTranslator.ResponseError]. DashScope's | ||
| // error envelope (`code`, `message`) is passed through as-is — no OpenAI-shaped rewriting is | ||
| // meaningful for a fork-only native endpoint. | ||
| func (dashScopeVoiceEnrollmentTranslator) ResponseError(_ map[string]string, _ io.Reader) (newHeaders []internalapi.Header, newBody []byte, err error) { | ||
| return nil, nil, nil | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| // Copyright Envoy AI Gateway Authors | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
| // The full text of the Apache license is available in the LICENSE file at | ||
| // the root of the repo. | ||
|
|
||
| package translator | ||
|
|
||
| import ( | ||
| "strings" | ||
| "testing" | ||
|
|
||
| "github.com/stretchr/testify/require" | ||
|
|
||
| "github.com/envoyproxy/ai-gateway/internal/apischema/dashscope" | ||
| ) | ||
|
|
||
| func TestDashScopeVoiceEnrollment_RequestBody(t *testing.T) { | ||
| tr := NewDashScopeVoiceEnrollmentTranslator() | ||
| req := &dashscope.VoiceEnrollmentRequest{ | ||
| Model: "voice-enrollment", | ||
| Input: dashscope.VoiceEnrollmentInput{Action: "create_voice"}, | ||
| } | ||
| original := []byte(`{"model":"voice-enrollment","input":{"action":"create_voice","target_model":"qwen3-tts-flash","prefix":"pk","url":"https://example.com/a.wav"}}`) | ||
|
|
||
| t.Run("path is rewritten, body is not replayed by default", func(t *testing.T) { | ||
| hm, body, err := tr.RequestBody(original, req, false) | ||
| require.NoError(t, err) | ||
| require.Empty(t, body, "no forced mutation → translator should not carry the body itself") | ||
|
|
||
| var pathVal string | ||
| for _, h := range hm { | ||
| if h.Key() == ":path" { | ||
| pathVal = h.Value() | ||
| } | ||
| } | ||
| require.Equal(t, dashScopeVoiceEnrollmentPath, pathVal) | ||
| }) | ||
|
|
||
| t.Run("forceBodyMutation replays the original body verbatim", func(t *testing.T) { | ||
| hm, body, err := tr.RequestBody(original, req, true) | ||
| require.NoError(t, err) | ||
| require.Equal(t, original, body, "forced replay must preserve caller's payload byte-for-byte") | ||
|
|
||
| var cl string | ||
| for _, h := range hm { | ||
| if h.Key() == "content-length" { | ||
| cl = h.Value() | ||
| } | ||
| } | ||
| require.NotEmpty(t, cl) | ||
| }) | ||
| } | ||
|
|
||
| func TestDashScopeVoiceEnrollment_ResponseHeaders(t *testing.T) { | ||
| tr := NewDashScopeVoiceEnrollmentTranslator() | ||
| hm, err := tr.ResponseHeaders(nil) | ||
| require.NoError(t, err) | ||
| require.Empty(t, hm, "response headers pass through untouched") | ||
| } | ||
|
|
||
| func TestDashScopeVoiceEnrollment_ResponseBody(t *testing.T) { | ||
| tr := NewDashScopeVoiceEnrollmentTranslator() | ||
| envelope := `{"request_id":"rid","output":{"voice_id":"custom-abc"},"usage":{"count":1}}` | ||
| hm, body, tokens, respModel, err := tr.ResponseBody(nil, strings.NewReader(envelope), true, nil) | ||
| require.NoError(t, err) | ||
| require.Empty(t, hm) | ||
| require.Empty(t, body, "pass-through: envoy delivers upstream body directly, no mutation") | ||
| require.Equal(t, "voice-enrollment", respModel) | ||
| _, set := tokens.OutputTokens() | ||
| require.False(t, set, "voice-enrollment carries no token accounting") | ||
| } | ||
|
|
||
| func TestDashScopeVoiceEnrollment_ResponseError(t *testing.T) { | ||
| tr := NewDashScopeVoiceEnrollmentTranslator() | ||
| hm, body, err := tr.ResponseError(nil, strings.NewReader(`{"code":"InvalidParameter","message":"missing url"}`)) | ||
| require.NoError(t, err) | ||
| require.Empty(t, hm) | ||
| require.Empty(t, body, "error envelope passes through unchanged") | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🔒 Security & Privacy | 🟠 Major | ⚡ Quick win
model을voice-enrollment으로 검증해야 합니다.주석과 테스트는 이 엔드포인트의 모델이 항상
voice-enrollment이라고 정의하지만, 현재 구현은 임의의req.Model을 그대로 라우팅에 반환합니다. 이 값이x-ai-eg-model및 모델별 라우팅/RBAC 선택에 사용되므로, 불일치하거나 빈 model은ErrMalformedRequest로 거부하고 고정값만 허용해야 합니다.제안 수정
if len(body) > 0 { if err := json.Unmarshal(body, &req); err != nil { return "", nil, false, nil, fmt.Errorf("%w: failed to parse JSON for voice enrollment: %w", internalapi.ErrMalformedRequest, err) } } + if req.Model != "voice-enrollment" { + return "", nil, false, nil, fmt.Errorf("%w: model must be voice-enrollment", internalapi.ErrMalformedRequest) + } // voice-enrollment is never streamed.📝 Committable suggestion
🤖 Prompt for AI Agents