mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-06 16:01:07 +00:00
feat: add console image 2.0 and full voice surfaces
Expose Console Imagine Image 2.0 aliases, TTS/STT/realtime/custom-voice gateway routes, and creative-console voice controls while keeping the existing web-image-2.0 customizations.
This commit is contained in:
1 parent
7b1a3e14a5
commit
4fe04ef623
24 files changed
+2584
-30
No files matched your search
@@ -32,11 +32,19 @@ func TestConsoleRoutesUseStableProviderNamespace(t *testing.T) {
|
||||
if seen["Console/grok-4.3"] == nil {
|
||||
t.Fatal("canonical Console/grok-4.3 route is missing")
|
||||
}
|
||||
for _, modelID := range []string{"Console/grok-imagine-image-quality", "Console/grok-imagine-image"} {
|
||||
for _, modelID := range []string{"Console/grok-imagine-image-quality-2.0", "Console/grok-imagine-image-2.0"} {
|
||||
if !seen[modelID]["image"] || !seen[modelID]["image_edit"] {
|
||||
t.Fatalf("Console image route capabilities for %s = %#v", modelID, seen[modelID])
|
||||
}
|
||||
}
|
||||
for _, modelID := range []string{"Console/grok-voice-latest", "Console/grok-voice-think-fast-2.0", "Console/grok-voice-think-fast-1.0"} {
|
||||
if !seen[modelID]["realtime"] || !seen[modelID]["tts"] {
|
||||
t.Fatalf("Console voice route capabilities for %s = %#v", modelID, seen[modelID])
|
||||
}
|
||||
}
|
||||
if !seen["Console/grok-transcribe"]["stt"] {
|
||||
t.Fatal("Console STT route is missing")
|
||||
}
|
||||
if !seen["Console/grok-imagine-video"]["video"] {
|
||||
t.Fatal("Console video route is missing")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,638 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account"
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/audit"
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/clientkey"
|
||||
modeldomain "github.com/chenyme/grok2api/backend/internal/domain/model"
|
||||
infraegress "github.com/chenyme/grok2api/backend/internal/infra/egress"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/provider"
|
||||
)
|
||||
|
||||
type TTSInput struct {
|
||||
RequestID string
|
||||
ClientKey clientkey.Key
|
||||
PublicModel string
|
||||
Text string
|
||||
VoiceID string
|
||||
Language string
|
||||
OutputFormat provider.TTSOutputFormat
|
||||
Speed float64
|
||||
OptimizeStreamingLatency int
|
||||
TextNormalization bool
|
||||
WithTimestamps bool
|
||||
}
|
||||
|
||||
type STTInput struct {
|
||||
RequestID string
|
||||
ClientKey clientkey.Key
|
||||
PublicModel string
|
||||
FileName string
|
||||
FileMIME string
|
||||
FileData []byte
|
||||
URL string
|
||||
AudioFormat string
|
||||
SampleRate string
|
||||
Language string
|
||||
Format bool
|
||||
Multichannel bool
|
||||
Channels int
|
||||
Diarize bool
|
||||
KeyTerms []string
|
||||
FillerWords bool
|
||||
VADThreshold *float64
|
||||
}
|
||||
|
||||
type RealtimeClientSecretInput struct {
|
||||
RequestID string
|
||||
ClientKey clientkey.Key
|
||||
PublicModel string
|
||||
ExpiresAfter int
|
||||
SessionJSON []byte
|
||||
}
|
||||
|
||||
type VoiceListInput struct {
|
||||
RequestID string
|
||||
ClientKey clientkey.Key
|
||||
PublicModel string
|
||||
}
|
||||
|
||||
type CustomVoiceCreateInput struct {
|
||||
RequestID string
|
||||
ClientKey clientkey.Key
|
||||
PublicModel string
|
||||
Name string
|
||||
Language string
|
||||
Gender string
|
||||
Tone string
|
||||
UseCase string
|
||||
FileName string
|
||||
FileMIME string
|
||||
FileData []byte
|
||||
}
|
||||
|
||||
type CustomVoiceUpdateInput struct {
|
||||
RequestID string
|
||||
ClientKey clientkey.Key
|
||||
PublicModel string
|
||||
VoiceID string
|
||||
Name *string
|
||||
Language *string
|
||||
Gender *string
|
||||
Tone *string
|
||||
UseCase *string
|
||||
}
|
||||
|
||||
type CustomVoiceIDInput struct {
|
||||
RequestID string
|
||||
ClientKey clientkey.Key
|
||||
PublicModel string
|
||||
VoiceID string
|
||||
}
|
||||
|
||||
type voiceProviderSupport func(accountdomain.Provider) bool
|
||||
|
||||
func (s *Service) SynthesizeSpeech(ctx context.Context, input TTSInput) (*Result, error) {
|
||||
return s.executeVoice(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationTTS, modeldomain.CapabilityTTS, func(providerValue accountdomain.Provider) bool {
|
||||
_, ok := s.providers.TTS(providerValue)
|
||||
return ok
|
||||
}, func(executionCtx context.Context, providerValue accountdomain.Provider, credential accountdomain.Credential, upstream string) (*provider.Response, error) {
|
||||
adapter, ok := s.providers.TTS(providerValue)
|
||||
if !ok {
|
||||
return nil, ErrNoAvailableAccount
|
||||
}
|
||||
result, err := adapter.SynthesizeSpeech(executionCtx, provider.TTSRequest{
|
||||
Credential: credential, Model: upstream, Text: input.Text, VoiceID: input.VoiceID, Language: input.Language,
|
||||
OutputFormat: input.OutputFormat, Speed: input.Speed, OptimizeStreamingLatency: input.OptimizeStreamingLatency,
|
||||
TextNormalization: input.TextNormalization, WithTimestamps: input.WithTimestamps,
|
||||
})
|
||||
if err != nil {
|
||||
return voiceErrorResponse(err)
|
||||
}
|
||||
if result.JSONEnvelope || input.WithTimestamps {
|
||||
payload := map[string]any{
|
||||
"audio": firstNonEmpty(result.Base64Audio, base64.StdEncoding.EncodeToString(result.Audio)),
|
||||
"content_type": firstNonEmpty(result.ContentType, "audio/mpeg"),
|
||||
"duration": result.Duration,
|
||||
}
|
||||
if result.Timestamps != nil {
|
||||
times := make([]map[string]any, 0, len(result.Timestamps.GraphTimes))
|
||||
for _, item := range result.Timestamps.GraphTimes {
|
||||
times = append(times, map[string]any{"start": item.Start, "end": item.End})
|
||||
}
|
||||
payload["audio_timestamps"] = map[string]any{"graph_chars": result.Timestamps.GraphChars, "graph_times": times}
|
||||
}
|
||||
return jsonVoiceResponse(http.StatusOK, payload), nil
|
||||
}
|
||||
header := http.Header{}
|
||||
header.Set("Content-Type", firstNonEmpty(result.ContentType, "audio/mpeg"))
|
||||
header.Set("Content-Length", fmt.Sprintf("%d", len(result.Audio)))
|
||||
return &provider.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Status: fmt.Sprintf("%d %s", http.StatusOK, http.StatusText(http.StatusOK)),
|
||||
Header: header,
|
||||
Body: io.NopCloser(bytes.NewReader(result.Audio)),
|
||||
QuotaUnits: 1,
|
||||
}, nil
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) ListTTSVoices(ctx context.Context, input VoiceListInput) (*Result, error) {
|
||||
return s.executeVoice(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationTTS, modeldomain.CapabilityTTS, func(providerValue accountdomain.Provider) bool {
|
||||
_, ok := s.providers.TTS(providerValue)
|
||||
return ok
|
||||
}, func(executionCtx context.Context, providerValue accountdomain.Provider, credential accountdomain.Credential, _ string) (*provider.Response, error) {
|
||||
adapter, ok := s.providers.TTS(providerValue)
|
||||
if !ok {
|
||||
return nil, ErrNoAvailableAccount
|
||||
}
|
||||
voices, err := adapter.ListTTSVoices(executionCtx, credential)
|
||||
if err != nil {
|
||||
return voiceErrorResponse(err)
|
||||
}
|
||||
items := make([]map[string]any, 0, len(voices))
|
||||
for _, voice := range voices {
|
||||
item := map[string]any{"voice_id": voice.VoiceID, "name": voice.Name}
|
||||
if voice.Language != "" {
|
||||
item["language"] = voice.Language
|
||||
} else {
|
||||
item["language"] = nil
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
return jsonVoiceResponse(http.StatusOK, map[string]any{"voices": items}), nil
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) GetTTSVoice(ctx context.Context, input CustomVoiceIDInput) (*Result, error) {
|
||||
return s.executeVoice(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationTTS, modeldomain.CapabilityTTS, func(providerValue accountdomain.Provider) bool {
|
||||
_, ok := s.providers.TTS(providerValue)
|
||||
return ok
|
||||
}, func(executionCtx context.Context, providerValue accountdomain.Provider, credential accountdomain.Credential, _ string) (*provider.Response, error) {
|
||||
adapter, ok := s.providers.TTS(providerValue)
|
||||
if !ok {
|
||||
return nil, ErrNoAvailableAccount
|
||||
}
|
||||
voice, err := adapter.GetTTSVoice(executionCtx, credential, input.VoiceID)
|
||||
if err != nil {
|
||||
return voiceErrorResponse(err)
|
||||
}
|
||||
payload := map[string]any{"voice_id": voice.VoiceID, "name": voice.Name}
|
||||
if voice.Language != "" {
|
||||
payload["language"] = voice.Language
|
||||
} else {
|
||||
payload["language"] = nil
|
||||
}
|
||||
return jsonVoiceResponse(http.StatusOK, payload), nil
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) TranscribeSpeech(ctx context.Context, input STTInput) (*Result, error) {
|
||||
return s.executeVoice(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationSTT, modeldomain.CapabilitySTT, func(providerValue accountdomain.Provider) bool {
|
||||
_, ok := s.providers.STT(providerValue)
|
||||
return ok
|
||||
}, func(executionCtx context.Context, providerValue accountdomain.Provider, credential accountdomain.Credential, upstream string) (*provider.Response, error) {
|
||||
adapter, ok := s.providers.STT(providerValue)
|
||||
if !ok {
|
||||
return nil, ErrNoAvailableAccount
|
||||
}
|
||||
result, err := adapter.TranscribeSpeech(executionCtx, provider.STTRequest{
|
||||
Credential: credential, Model: upstream, FileName: input.FileName, FileMIME: input.FileMIME, FileData: input.FileData,
|
||||
URL: input.URL, AudioFormat: input.AudioFormat, SampleRate: input.SampleRate, Language: input.Language, Format: input.Format,
|
||||
Multichannel: input.Multichannel, Channels: input.Channels, Diarize: input.Diarize, KeyTerms: input.KeyTerms,
|
||||
FillerWords: input.FillerWords, VADThreshold: input.VADThreshold,
|
||||
})
|
||||
if err != nil {
|
||||
return voiceErrorResponse(err)
|
||||
}
|
||||
if len(result.RawJSON) > 0 {
|
||||
header := http.Header{}
|
||||
header.Set("Content-Type", "application/json")
|
||||
header.Set("Content-Length", fmt.Sprintf("%d", len(result.RawJSON)))
|
||||
return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: header, Body: io.NopCloser(bytes.NewReader(result.RawJSON)), QuotaUnits: 1}, nil
|
||||
}
|
||||
payload := map[string]any{"text": result.Text, "language": result.Language, "duration": result.Duration}
|
||||
if len(result.Words) > 0 {
|
||||
words := make([]map[string]any, 0, len(result.Words))
|
||||
for _, word := range result.Words {
|
||||
item := map[string]any{"text": word.Text, "start": word.Start, "end": word.End}
|
||||
if word.Speaker != nil {
|
||||
item["speaker"] = *word.Speaker
|
||||
}
|
||||
words = append(words, item)
|
||||
}
|
||||
payload["words"] = words
|
||||
}
|
||||
if len(result.Channels) > 0 {
|
||||
channels := make([]map[string]any, 0, len(result.Channels))
|
||||
for _, channel := range result.Channels {
|
||||
item := map[string]any{"index": channel.Index, "text": channel.Text}
|
||||
if len(channel.Words) > 0 {
|
||||
words := make([]map[string]any, 0, len(channel.Words))
|
||||
for _, word := range channel.Words {
|
||||
wordItem := map[string]any{"text": word.Text, "start": word.Start, "end": word.End}
|
||||
if word.Speaker != nil {
|
||||
wordItem["speaker"] = *word.Speaker
|
||||
}
|
||||
words = append(words, wordItem)
|
||||
}
|
||||
item["words"] = words
|
||||
}
|
||||
channels = append(channels, item)
|
||||
}
|
||||
payload["channels"] = channels
|
||||
}
|
||||
return jsonVoiceResponse(http.StatusOK, payload), nil
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) CreateRealtimeClientSecret(ctx context.Context, input RealtimeClientSecretInput) (*Result, error) {
|
||||
return s.executeVoice(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationRealtime, modeldomain.CapabilityRealtime, func(providerValue accountdomain.Provider) bool {
|
||||
_, ok := s.providers.RealtimeVoice(providerValue)
|
||||
return ok
|
||||
}, func(executionCtx context.Context, providerValue accountdomain.Provider, credential accountdomain.Credential, upstream string) (*provider.Response, error) {
|
||||
adapter, ok := s.providers.RealtimeVoice(providerValue)
|
||||
if !ok {
|
||||
return nil, ErrNoAvailableAccount
|
||||
}
|
||||
result, err := adapter.CreateRealtimeClientSecret(executionCtx, provider.RealtimeClientSecretRequest{
|
||||
Credential: credential, Model: firstNonEmpty(upstream, input.PublicModel), ExpiresAfter: input.ExpiresAfter, SessionJSON: input.SessionJSON,
|
||||
})
|
||||
if err != nil {
|
||||
return voiceErrorResponse(err)
|
||||
}
|
||||
if len(result.RawJSON) > 0 {
|
||||
header := http.Header{}
|
||||
header.Set("Content-Type", "application/json")
|
||||
header.Set("Content-Length", fmt.Sprintf("%d", len(result.RawJSON)))
|
||||
return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: header, Body: io.NopCloser(bytes.NewReader(result.RawJSON)), QuotaUnits: 1}, nil
|
||||
}
|
||||
return jsonVoiceResponse(http.StatusOK, map[string]any{"value": result.Value, "expires_at": result.ExpiresAt}), nil
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) CreateCustomVoice(ctx context.Context, input CustomVoiceCreateInput) (*Result, error) {
|
||||
return s.executeVoice(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationVoice, modeldomain.CapabilityTTS, func(providerValue accountdomain.Provider) bool {
|
||||
_, ok := s.providers.CustomVoices(providerValue)
|
||||
return ok
|
||||
}, func(executionCtx context.Context, providerValue accountdomain.Provider, credential accountdomain.Credential, _ string) (*provider.Response, error) {
|
||||
adapter, ok := s.providers.CustomVoices(providerValue)
|
||||
if !ok {
|
||||
return nil, ErrNoAvailableAccount
|
||||
}
|
||||
result, err := adapter.CreateCustomVoice(executionCtx, provider.CustomVoiceCreateRequest{
|
||||
Credential: credential, Name: input.Name, Language: input.Language, Gender: input.Gender, Tone: input.Tone,
|
||||
UseCase: input.UseCase, FileName: input.FileName, FileMIME: input.FileMIME, FileData: input.FileData,
|
||||
})
|
||||
if err != nil {
|
||||
return voiceErrorResponse(err)
|
||||
}
|
||||
if len(result.RawJSON) > 0 {
|
||||
header := http.Header{}
|
||||
header.Set("Content-Type", "application/json")
|
||||
header.Set("Content-Length", fmt.Sprintf("%d", len(result.RawJSON)))
|
||||
return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: header, Body: io.NopCloser(bytes.NewReader(result.RawJSON)), QuotaUnits: 1}, nil
|
||||
}
|
||||
return jsonVoiceResponse(http.StatusOK, customVoicePayload(result)), nil
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) ListCustomVoices(ctx context.Context, input VoiceListInput, limit int, paginationToken string) (*Result, error) {
|
||||
return s.executeVoice(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationVoice, modeldomain.CapabilityTTS, func(providerValue accountdomain.Provider) bool {
|
||||
_, ok := s.providers.CustomVoices(providerValue)
|
||||
return ok
|
||||
}, func(executionCtx context.Context, providerValue accountdomain.Provider, credential accountdomain.Credential, _ string) (*provider.Response, error) {
|
||||
adapter, ok := s.providers.CustomVoices(providerValue)
|
||||
if !ok {
|
||||
return nil, ErrNoAvailableAccount
|
||||
}
|
||||
voices, next, err := adapter.ListCustomVoices(executionCtx, credential, limit, paginationToken)
|
||||
if err != nil {
|
||||
return voiceErrorResponse(err)
|
||||
}
|
||||
items := make([]map[string]any, 0, len(voices))
|
||||
for _, voice := range voices {
|
||||
items = append(items, customVoicePayload(voice))
|
||||
}
|
||||
payload := map[string]any{"voices": items}
|
||||
if next != "" {
|
||||
payload["pagination_token"] = next
|
||||
}
|
||||
return jsonVoiceResponse(http.StatusOK, payload), nil
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) GetCustomVoice(ctx context.Context, input CustomVoiceIDInput) (*Result, error) {
|
||||
return s.executeVoice(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationVoice, modeldomain.CapabilityTTS, func(providerValue accountdomain.Provider) bool {
|
||||
_, ok := s.providers.CustomVoices(providerValue)
|
||||
return ok
|
||||
}, func(executionCtx context.Context, providerValue accountdomain.Provider, credential accountdomain.Credential, _ string) (*provider.Response, error) {
|
||||
adapter, ok := s.providers.CustomVoices(providerValue)
|
||||
if !ok {
|
||||
return nil, ErrNoAvailableAccount
|
||||
}
|
||||
result, err := adapter.GetCustomVoice(executionCtx, credential, input.VoiceID)
|
||||
if err != nil {
|
||||
return voiceErrorResponse(err)
|
||||
}
|
||||
if len(result.RawJSON) > 0 {
|
||||
header := http.Header{}
|
||||
header.Set("Content-Type", "application/json")
|
||||
header.Set("Content-Length", fmt.Sprintf("%d", len(result.RawJSON)))
|
||||
return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: header, Body: io.NopCloser(bytes.NewReader(result.RawJSON)), QuotaUnits: 1}, nil
|
||||
}
|
||||
return jsonVoiceResponse(http.StatusOK, customVoicePayload(result)), nil
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) UpdateCustomVoice(ctx context.Context, input CustomVoiceUpdateInput) (*Result, error) {
|
||||
return s.executeVoice(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationVoice, modeldomain.CapabilityTTS, func(providerValue accountdomain.Provider) bool {
|
||||
_, ok := s.providers.CustomVoices(providerValue)
|
||||
return ok
|
||||
}, func(executionCtx context.Context, providerValue accountdomain.Provider, credential accountdomain.Credential, _ string) (*provider.Response, error) {
|
||||
adapter, ok := s.providers.CustomVoices(providerValue)
|
||||
if !ok {
|
||||
return nil, ErrNoAvailableAccount
|
||||
}
|
||||
result, err := adapter.UpdateCustomVoice(executionCtx, provider.CustomVoiceUpdateRequest{
|
||||
Credential: credential, VoiceID: input.VoiceID, Name: input.Name, Language: input.Language, Gender: input.Gender, Tone: input.Tone, UseCase: input.UseCase,
|
||||
})
|
||||
if err != nil {
|
||||
return voiceErrorResponse(err)
|
||||
}
|
||||
if len(result.RawJSON) > 0 {
|
||||
header := http.Header{}
|
||||
header.Set("Content-Type", "application/json")
|
||||
header.Set("Content-Length", fmt.Sprintf("%d", len(result.RawJSON)))
|
||||
return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: header, Body: io.NopCloser(bytes.NewReader(result.RawJSON)), QuotaUnits: 1}, nil
|
||||
}
|
||||
return jsonVoiceResponse(http.StatusOK, customVoicePayload(result)), nil
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) DeleteCustomVoice(ctx context.Context, input CustomVoiceIDInput) (*Result, error) {
|
||||
return s.executeVoice(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationVoice, modeldomain.CapabilityTTS, func(providerValue accountdomain.Provider) bool {
|
||||
_, ok := s.providers.CustomVoices(providerValue)
|
||||
return ok
|
||||
}, func(executionCtx context.Context, providerValue accountdomain.Provider, credential accountdomain.Credential, _ string) (*provider.Response, error) {
|
||||
adapter, ok := s.providers.CustomVoices(providerValue)
|
||||
if !ok {
|
||||
return nil, ErrNoAvailableAccount
|
||||
}
|
||||
if err := adapter.DeleteCustomVoice(executionCtx, credential, input.VoiceID); err != nil {
|
||||
return voiceErrorResponse(err)
|
||||
}
|
||||
return jsonVoiceResponse(http.StatusOK, map[string]any{"deleted": true, "voice_id": input.VoiceID}), nil
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) GetCustomVoiceAudio(ctx context.Context, input CustomVoiceIDInput) (*Result, error) {
|
||||
return s.executeVoice(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationVoice, modeldomain.CapabilityTTS, func(providerValue accountdomain.Provider) bool {
|
||||
_, ok := s.providers.CustomVoices(providerValue)
|
||||
return ok
|
||||
}, func(executionCtx context.Context, providerValue accountdomain.Provider, credential accountdomain.Credential, _ string) (*provider.Response, error) {
|
||||
adapter, ok := s.providers.CustomVoices(providerValue)
|
||||
if !ok {
|
||||
return nil, ErrNoAvailableAccount
|
||||
}
|
||||
data, contentType, err := adapter.GetCustomVoiceAudio(executionCtx, credential, input.VoiceID)
|
||||
if err != nil {
|
||||
return voiceErrorResponse(err)
|
||||
}
|
||||
header := http.Header{}
|
||||
header.Set("Content-Type", firstNonEmpty(contentType, "audio/mpeg"))
|
||||
header.Set("Content-Length", fmt.Sprintf("%d", len(data)))
|
||||
return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: header, Body: io.NopCloser(bytes.NewReader(data)), QuotaUnits: 1}, nil
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) executeVoice(
|
||||
ctx context.Context,
|
||||
requestID string,
|
||||
key clientkey.Key,
|
||||
publicModel string,
|
||||
operation audit.Operation,
|
||||
capability modeldomain.Capability,
|
||||
supports voiceProviderSupport,
|
||||
execute func(context.Context, accountdomain.Provider, accountdomain.Credential, string) (*provider.Response, error),
|
||||
) (*Result, error) {
|
||||
ctx, egressTrace := infraegress.WithTrace(ctx)
|
||||
startedAt := time.Now()
|
||||
eventID := newAuditEventID()
|
||||
routes, err := s.models.GetByPublicIDCandidates(ctx, publicModel)
|
||||
if err != nil {
|
||||
// Voice catalog helpers may not require a specific model when only voices are listed.
|
||||
// Fall back to any enabled route for the capability so built-in voice listing still works.
|
||||
if publicModel == "" || publicModel == "grok-voice-latest" || publicModel == "grok-transcribe" {
|
||||
return nil, ErrModelNotFound
|
||||
}
|
||||
return nil, ErrModelNotFound
|
||||
}
|
||||
route, err := s.selectMediaRoute(routes, key, capability, supports)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
externalModel := modeldomain.ExternalPublicID(route.Provider, route.PublicID)
|
||||
auditBase := audit.Record{
|
||||
EventID: eventID, RequestID: requestID, ClientKeyID: key.ID, ClientKeyName: key.Name,
|
||||
ModelRouteID: route.ID, ModelPublicID: externalModel, ModelUpstreamModel: modeldomain.DisplayUpstreamModel(route.Provider, route.UpstreamModel),
|
||||
Provider: string(route.Provider), Operation: operation, UsageSource: audit.UsageSourceNone,
|
||||
}
|
||||
if err := s.checkLedgerReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
writeFailureAudit := func(statusCode int, errorCode string, credential *accountdomain.Credential) {
|
||||
record := auditBase
|
||||
record.StatusCode = statusCode
|
||||
record.ErrorCode = errorCode
|
||||
record.DurationMS = time.Since(startedAt).Milliseconds()
|
||||
record.CreatedAt = time.Now().UTC()
|
||||
if credential != nil {
|
||||
accountID := credential.ID
|
||||
record.AccountID = &accountID
|
||||
record.AccountName = credential.Name
|
||||
}
|
||||
applyAuditEgress(&record, egressTrace, route.Provider)
|
||||
persistCtx, cancel := context.WithTimeout(context.Background(), finalizationTimeout)
|
||||
defer cancel()
|
||||
if auditErr := s.audits.Create(persistCtx, record); auditErr != nil {
|
||||
s.logger.Error("request_usage_write_failed", "event_id", record.EventID, "request_id", requestID, "error", auditErr)
|
||||
}
|
||||
}
|
||||
quotaMode := s.providers.QuotaMode(route.Provider, route.UpstreamModel)
|
||||
attemptPolicy := newRoutingAttemptPolicy(int(s.maxAttempts.Load()))
|
||||
excluded := make(map[uint64]bool)
|
||||
var selection *selectionSession
|
||||
var lease *accountLease
|
||||
var credential accountdomain.Credential
|
||||
var response *provider.Response
|
||||
var lastCredentialFailure *accountdomain.Credential
|
||||
var lastCredentialError error
|
||||
for attempt := 0; attemptPolicy.allows(attempt); attempt++ {
|
||||
if selection == nil {
|
||||
selection, err = s.selector.beginSelectionSessionForKey(ctx, route.Provider, route.ID, route.UpstreamModel, quotaMode, "", excluded, false, key.AccountScope())
|
||||
}
|
||||
if err == nil {
|
||||
lease, err = selection.Acquire(ctx, excluded, false)
|
||||
}
|
||||
if err != nil {
|
||||
errorCode := "upstream_unavailable"
|
||||
var selectionFailure *SelectionUnavailableError
|
||||
if errors.As(err, &selectionFailure) {
|
||||
errorCode = selectionFailure.Code()
|
||||
}
|
||||
writeFailureAudit(http.StatusServiceUnavailable, errorCode, lastCredentialFailure)
|
||||
return nil, fmt.Errorf("%w: %w", ErrNoAvailableAccount, err)
|
||||
}
|
||||
excluded[lease.Credential.ID] = true
|
||||
credential, err = s.accounts.EnsureCredential(ctx, lease.Credential, false)
|
||||
if err != nil {
|
||||
failedCredential := lease.Credential
|
||||
lastCredentialFailure = &failedCredential
|
||||
lastCredentialError = err
|
||||
lease.Release()
|
||||
continue
|
||||
}
|
||||
lease.markSelectorUpstreamStarted()
|
||||
response, err = execute(ctx, route.Provider, credential, route.UpstreamModel)
|
||||
if err != nil {
|
||||
if isSSOCredentialRejected(err, credential) {
|
||||
s.markSSOCredentialRejected(ctx, credential, fmt.Sprintf("%s SSO credential rejected", credential.Provider))
|
||||
failedCredential := credential
|
||||
lastCredentialFailure = &failedCredential
|
||||
lastCredentialError = provider.ErrUnauthorized
|
||||
lease.Release()
|
||||
continue
|
||||
}
|
||||
s.selector.MarkFailure(ctx, credential, 0, 0)
|
||||
lease.Release()
|
||||
writeFailureAudit(http.StatusBadGateway, "upstream_unavailable", &credential)
|
||||
return nil, err
|
||||
}
|
||||
if response.StatusCode == http.StatusUnauthorized && credential.AuthType == accountdomain.AuthTypeSSO {
|
||||
_, _ = readRetryableBody(response.Body)
|
||||
s.markSSOCredentialRejected(ctx, credential, fmt.Sprintf("%s SSO credential rejected", credential.Provider))
|
||||
failedCredential := credential
|
||||
lastCredentialFailure = &failedCredential
|
||||
lastCredentialError = provider.ErrUnauthorized
|
||||
response = nil
|
||||
lease.Release()
|
||||
continue
|
||||
}
|
||||
if s.providers.RetryForbiddenAsEgress(credential.Provider) && response.StatusCode == http.StatusForbidden && attempt == 0 && attemptPolicy.hasNext(attempt) {
|
||||
_, _ = readRetryableBody(response.Body)
|
||||
delete(excluded, credential.ID)
|
||||
if selection != nil {
|
||||
selection.RetryAccount(credential.ID)
|
||||
}
|
||||
lease.Release()
|
||||
continue
|
||||
}
|
||||
if response.StatusCode == http.StatusTooManyRequests && attemptPolicy.hasNext(attempt) {
|
||||
retryAfter := parseRetryAfter(response.Header.Get("Retry-After"), time.Now().UTC())
|
||||
body, _ := readRetryableBody(response.Body)
|
||||
s.selector.MarkFailure(ctx, credential, response.StatusCode, retryAfter)
|
||||
response.Body = io.NopCloser(bytes.NewReader(body))
|
||||
_, _ = readRetryableBody(response.Body)
|
||||
lease.Release()
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
if response == nil {
|
||||
writeFailureAudit(http.StatusServiceUnavailable, "upstream_unavailable", lastCredentialFailure)
|
||||
if lastCredentialError == nil {
|
||||
lastCredentialError = ErrNoAvailableAccount
|
||||
}
|
||||
return nil, fmt.Errorf("%w: %w", ErrNoAvailableAccount, lastCredentialError)
|
||||
}
|
||||
accountID := credential.ID
|
||||
var once sync.Once
|
||||
finalize := func(_ Usage, _ string, errorCode string) {
|
||||
once.Do(func() {
|
||||
successful := auditRequestSucceeded(response.StatusCode, errorCode)
|
||||
lease.completeSelectorObservation(successful)
|
||||
lease.Release()
|
||||
record := auditBase
|
||||
record.AccountID, record.AccountName, record.StatusCode = &accountID, credential.Name, response.StatusCode
|
||||
record.ErrorCode = errorCode
|
||||
record.DurationMS, record.CreatedAt = time.Since(startedAt).Milliseconds(), time.Now().UTC()
|
||||
applyAuditEgress(&record, egressTrace, route.Provider)
|
||||
persistCtx, cancel := context.WithTimeout(context.Background(), finalizationTimeout)
|
||||
defer cancel()
|
||||
if err := s.audits.Create(persistCtx, record); err != nil {
|
||||
s.logger.Error("request_usage_write_failed", "event_id", record.EventID, "request_id", requestID, "error", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
return &Result{StatusCode: response.StatusCode, Status: response.Status, Header: response.Header, Body: &finalizingBody{ReadCloser: response.Body, finalize: func() { finalize(Usage{}, "", "stream_closed") }}, Finalize: finalize}, nil
|
||||
}
|
||||
|
||||
func jsonVoiceResponse(status int, value any) *provider.Response {
|
||||
data, _ := json.Marshal(value)
|
||||
header := http.Header{}
|
||||
header.Set("Content-Type", "application/json")
|
||||
header.Set("Content-Length", fmt.Sprintf("%d", len(data)))
|
||||
return &provider.Response{
|
||||
StatusCode: status,
|
||||
Status: fmt.Sprintf("%d %s", status, http.StatusText(status)),
|
||||
Header: header,
|
||||
Body: io.NopCloser(bytes.NewReader(data)),
|
||||
QuotaUnits: 1,
|
||||
}
|
||||
}
|
||||
|
||||
func voiceErrorResponse(err error) (*provider.Response, error) {
|
||||
var upstream interface{ HTTPStatusCode() int; Error() string }
|
||||
if errors.As(err, &upstream) && upstream.HTTPStatusCode() > 0 {
|
||||
return jsonVoiceResponse(upstream.HTTPStatusCode(), map[string]any{"error": map[string]any{"type": "upstream_error", "message": upstream.Error()}}), nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func customVoicePayload(value provider.CustomVoice) map[string]any {
|
||||
payload := map[string]any{
|
||||
"voice_id": value.VoiceID,
|
||||
"name": value.Name,
|
||||
}
|
||||
if value.Language != "" {
|
||||
payload["language"] = value.Language
|
||||
}
|
||||
if value.Gender != "" {
|
||||
payload["gender"] = value.Gender
|
||||
}
|
||||
if value.Tone != "" {
|
||||
payload["tone"] = value.Tone
|
||||
}
|
||||
if value.UseCase != "" {
|
||||
payload["use_case"] = value.UseCase
|
||||
}
|
||||
if value.CreatedAt != "" {
|
||||
payload["created_at"] = value.CreatedAt
|
||||
}
|
||||
if value.UpdatedAt != "" {
|
||||
payload["updated_at"] = value.UpdatedAt
|
||||
}
|
||||
return payload
|
||||
}
|
||||
|
||||
func firstNonEmpty(values ...string) string {
|
||||
for _, value := range values {
|
||||
if strings.TrimSpace(value) != "" {
|
||||
return strings.TrimSpace(value)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -153,9 +153,15 @@ func endpointCapabilitiesForDefinition(routes []modeldomain.Route, definition pr
|
||||
available["image_edit"] = definition.Media.ImageEdit
|
||||
case modeldomain.CapabilityVideo:
|
||||
available["video"] = definition.Media.VideoGeneration
|
||||
case modeldomain.CapabilityTTS:
|
||||
available["tts"] = definition.Media.TTS
|
||||
case modeldomain.CapabilitySTT:
|
||||
available["stt"] = definition.Media.STT
|
||||
case modeldomain.CapabilityRealtime:
|
||||
available["realtime"] = definition.Media.Realtime
|
||||
}
|
||||
}
|
||||
order := []string{"completions", "responses", "messages", "image", "image_edit", "video"}
|
||||
order := []string{"completions", "responses", "messages", "image", "image_edit", "video", "tts", "stt", "realtime"}
|
||||
result := make([]string, 0, len(order))
|
||||
for _, capability := range order {
|
||||
if available[capability] {
|
||||
|
||||
@@ -12,6 +12,10 @@ const (
|
||||
OperationImage Operation = "image"
|
||||
OperationImageEdit Operation = "image_edit"
|
||||
OperationVideo Operation = "video"
|
||||
OperationTTS Operation = "tts"
|
||||
OperationSTT Operation = "stt"
|
||||
OperationRealtime Operation = "realtime"
|
||||
OperationVoice Operation = "voice"
|
||||
)
|
||||
|
||||
type UsageSource string
|
||||
|
||||
@@ -22,6 +22,9 @@ const (
|
||||
CapabilityImage Capability = "image"
|
||||
CapabilityImageEdit Capability = "image_edit"
|
||||
CapabilityVideo Capability = "video"
|
||||
CapabilityTTS Capability = "tts"
|
||||
CapabilitySTT Capability = "stt"
|
||||
CapabilityRealtime Capability = "realtime"
|
||||
)
|
||||
|
||||
// Capabilities returns every persisted route capability. Callers use this as
|
||||
@@ -33,6 +36,9 @@ func Capabilities() []Capability {
|
||||
CapabilityImage,
|
||||
CapabilityImageEdit,
|
||||
CapabilityVideo,
|
||||
CapabilityTTS,
|
||||
CapabilitySTT,
|
||||
CapabilityRealtime,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -747,13 +747,19 @@ func discoveredRouteDefaults(provider account.Provider, upstreamModel string) (s
|
||||
return upstreamModel, model.CapabilityResponses
|
||||
case account.ProviderConsole:
|
||||
switch upstreamModel {
|
||||
case "grok-imagine-image", "grok-imagine-image-quality":
|
||||
case "grok-imagine-image":
|
||||
// The catalog also registers image_edit for the same public model.
|
||||
// Discovery only needs one existing managed capability to remain
|
||||
// idempotent and must never synthesize a Responses route.
|
||||
return upstreamModel, model.CapabilityImage
|
||||
return "grok-imagine-image-2.0", model.CapabilityImage
|
||||
case "grok-imagine-image-quality":
|
||||
return "grok-imagine-image-quality-2.0", model.CapabilityImage
|
||||
case "grok-imagine-video", "grok-imagine-video-1.5":
|
||||
return upstreamModel, model.CapabilityVideo
|
||||
case "grok-voice-latest", "grok-voice-think-fast-2.0", "grok-voice-think-fast-1.0":
|
||||
return upstreamModel, model.CapabilityRealtime
|
||||
case "grok-transcribe":
|
||||
return upstreamModel, model.CapabilitySTT
|
||||
default:
|
||||
return upstreamModel, model.CapabilityResponses
|
||||
}
|
||||
|
||||
@@ -78,6 +78,9 @@ func (a *Adapter) QuotaMode(upstreamModel string) string {
|
||||
if ResolveMedia(upstreamModel, modeldomain.CapabilityVideo) {
|
||||
return QuotaModeVideo
|
||||
}
|
||||
if ResolveMedia(upstreamModel, modeldomain.CapabilityTTS) || ResolveMedia(upstreamModel, modeldomain.CapabilitySTT) || ResolveMedia(upstreamModel, modeldomain.CapabilityRealtime) {
|
||||
return QuotaMode
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
|
||||
@@ -35,17 +35,25 @@ var mediaCatalog = []struct {
|
||||
UpstreamModel string
|
||||
Capabilities []modeldomain.Capability
|
||||
}{
|
||||
{PublicID: "grok-imagine-image-quality", UpstreamModel: "grok-imagine-image-quality", Capabilities: []modeldomain.Capability{modeldomain.CapabilityImage, modeldomain.CapabilityImageEdit}},
|
||||
{PublicID: "grok-imagine-image", UpstreamModel: "grok-imagine-image", Capabilities: []modeldomain.Capability{modeldomain.CapabilityImage, modeldomain.CapabilityImageEdit}},
|
||||
// Console Image 2.0 uses the same upstream model IDs as the official image API.
|
||||
// Public names keep the -2.0 suffix so Console and Web stay distinguishable.
|
||||
{PublicID: "grok-imagine-image-quality-2.0", UpstreamModel: "grok-imagine-image-quality", Capabilities: []modeldomain.Capability{modeldomain.CapabilityImage, modeldomain.CapabilityImageEdit}},
|
||||
{PublicID: "grok-imagine-image-2.0", UpstreamModel: "grok-imagine-image", Capabilities: []modeldomain.Capability{modeldomain.CapabilityImage, modeldomain.CapabilityImageEdit}},
|
||||
{PublicID: "grok-imagine-video", UpstreamModel: "grok-imagine-video", Capabilities: []modeldomain.Capability{modeldomain.CapabilityVideo}},
|
||||
// Free Console accounts can use the 1.5 video model on the official Console media API.
|
||||
{PublicID: "grok-imagine-video-1.5", UpstreamModel: "grok-imagine-video-1.5", Capabilities: []modeldomain.Capability{modeldomain.CapabilityVideo}},
|
||||
{PublicID: "grok-voice-latest", UpstreamModel: "grok-voice-latest", Capabilities: []modeldomain.Capability{modeldomain.CapabilityRealtime, modeldomain.CapabilityTTS}},
|
||||
{PublicID: "grok-voice-think-fast-2.0", UpstreamModel: "grok-voice-think-fast-2.0", Capabilities: []modeldomain.Capability{modeldomain.CapabilityRealtime, modeldomain.CapabilityTTS}},
|
||||
{PublicID: "grok-voice-think-fast-1.0", UpstreamModel: "grok-voice-think-fast-1.0", Capabilities: []modeldomain.Capability{modeldomain.CapabilityRealtime, modeldomain.CapabilityTTS}},
|
||||
{PublicID: "grok-transcribe", UpstreamModel: "grok-transcribe", Capabilities: []modeldomain.Capability{modeldomain.CapabilitySTT}},
|
||||
}
|
||||
|
||||
// Effort-suffixed aliases only include levels each Provider/model combination
|
||||
// actually supports (see domain/model.SupportedReasoningEffortsForProvider).
|
||||
// No blanket none/low/medium/high/xhigh/max template.
|
||||
var aliases = []provider.ModelAlias{
|
||||
consoleAlias("grok-imagine-image", "grok-imagine-image-2.0", "grok-imagine-image", ""),
|
||||
consoleAlias("grok-imagine-image-quality", "grok-imagine-image-quality-2.0", "grok-imagine-image-quality", ""),
|
||||
consoleAlias("grok-4.3-console", "grok-4.3", "grok-4.3", ""),
|
||||
consoleAlias("grok-4.20-0309-reasoning-console", "grok-4.20-0309-reasoning", "grok-4.20-0309-reasoning", ""),
|
||||
consoleAlias("grok-4.20-0309-non-reasoning-console", "grok-4.20-0309-non-reasoning", "grok-4.20-0309-non-reasoning", ""),
|
||||
|
||||
@@ -47,12 +47,19 @@ func TestCatalogContainsAllConsoleModelsAndAliases(t *testing.T) {
|
||||
{publicID: "Console/grok-4.20-multi-agent-0309", capability: modeldomain.CapabilityResponses}: "grok-4.20-multi-agent-0309",
|
||||
{publicID: "Console/grok-4.5", capability: modeldomain.CapabilityResponses}: "grok-4.5",
|
||||
{publicID: "Console/grok-build-0.1", capability: modeldomain.CapabilityResponses}: "grok-build-0.1",
|
||||
{publicID: "Console/grok-imagine-image-quality", capability: modeldomain.CapabilityImage}: "grok-imagine-image-quality",
|
||||
{publicID: "Console/grok-imagine-image-quality", capability: modeldomain.CapabilityImageEdit}: "grok-imagine-image-quality",
|
||||
{publicID: "Console/grok-imagine-image", capability: modeldomain.CapabilityImage}: "grok-imagine-image",
|
||||
{publicID: "Console/grok-imagine-image", capability: modeldomain.CapabilityImageEdit}: "grok-imagine-image",
|
||||
{publicID: "Console/grok-imagine-video", capability: modeldomain.CapabilityVideo}: "grok-imagine-video",
|
||||
{publicID: "Console/grok-imagine-video-1.5", capability: modeldomain.CapabilityVideo}: "grok-imagine-video-1.5",
|
||||
{publicID: "Console/grok-imagine-image-quality-2.0", capability: modeldomain.CapabilityImage}: "grok-imagine-image-quality",
|
||||
{publicID: "Console/grok-imagine-image-quality-2.0", capability: modeldomain.CapabilityImageEdit}: "grok-imagine-image-quality",
|
||||
{publicID: "Console/grok-imagine-image-2.0", capability: modeldomain.CapabilityImage}: "grok-imagine-image",
|
||||
{publicID: "Console/grok-imagine-image-2.0", capability: modeldomain.CapabilityImageEdit}: "grok-imagine-image",
|
||||
{publicID: "Console/grok-imagine-video", capability: modeldomain.CapabilityVideo}: "grok-imagine-video",
|
||||
{publicID: "Console/grok-imagine-video-1.5", capability: modeldomain.CapabilityVideo}: "grok-imagine-video-1.5",
|
||||
{publicID: "Console/grok-voice-latest", capability: modeldomain.CapabilityRealtime}: "grok-voice-latest",
|
||||
{publicID: "Console/grok-voice-latest", capability: modeldomain.CapabilityTTS}: "grok-voice-latest",
|
||||
{publicID: "Console/grok-voice-think-fast-2.0", capability: modeldomain.CapabilityRealtime}: "grok-voice-think-fast-2.0",
|
||||
{publicID: "Console/grok-voice-think-fast-2.0", capability: modeldomain.CapabilityTTS}: "grok-voice-think-fast-2.0",
|
||||
{publicID: "Console/grok-voice-think-fast-1.0", capability: modeldomain.CapabilityRealtime}: "grok-voice-think-fast-1.0",
|
||||
{publicID: "Console/grok-voice-think-fast-1.0", capability: modeldomain.CapabilityTTS}: "grok-voice-think-fast-1.0",
|
||||
{publicID: "Console/grok-transcribe", capability: modeldomain.CapabilitySTT}: "grok-transcribe",
|
||||
}
|
||||
routes := Routes()
|
||||
if len(routes) != len(expected) {
|
||||
@@ -93,6 +100,7 @@ func TestCatalogContainsAllConsoleModelsAndAliases(t *testing.T) {
|
||||
for model, want := range map[string]string{
|
||||
"grok-4.5": QuotaMode, "grok-imagine-image-quality": QuotaModeImage,
|
||||
"grok-imagine-image": QuotaModeImage, "grok-imagine-video": QuotaModeVideo, "grok-imagine-video-1.5": QuotaModeVideo,
|
||||
"grok-voice-latest": QuotaMode, "grok-voice-think-fast-2.0": QuotaMode, "grok-voice-think-fast-1.0": QuotaMode, "grok-transcribe": QuotaMode,
|
||||
} {
|
||||
if got := adapter.QuotaMode(model); got != want {
|
||||
t.Fatalf("QuotaMode(%q) = %q, want %q", model, got, want)
|
||||
|
||||
@@ -18,6 +18,9 @@ func (a *Adapter) Definition() provider.Definition {
|
||||
modeldomain.CapabilityImage,
|
||||
modeldomain.CapabilityImageEdit,
|
||||
modeldomain.CapabilityVideo,
|
||||
modeldomain.CapabilityTTS,
|
||||
modeldomain.CapabilitySTT,
|
||||
modeldomain.CapabilityRealtime,
|
||||
},
|
||||
Quota: provider.QuotaRemoteWindow,
|
||||
Credential: provider.CredentialSurface{
|
||||
@@ -28,6 +31,7 @@ func (a *Adapter) Definition() provider.Definition {
|
||||
},
|
||||
Media: provider.MediaSurface{
|
||||
ImageGeneration: true, ImageEdit: true, VideoGeneration: true,
|
||||
TTS: true, STT: true, Realtime: true, CustomVoices: true,
|
||||
},
|
||||
// Console shares the browser/clearance surface with Web. A 403 is
|
||||
// therefore normally an egress challenge, not proof that the SSO
|
||||
|
||||
@@ -292,6 +292,23 @@ func (a *Adapter) doDPoPRequest(
|
||||
method, endpoint string,
|
||||
body []byte,
|
||||
accept string,
|
||||
) (*http.Response, error) {
|
||||
contentType := ""
|
||||
if len(body) > 0 {
|
||||
contentType = "application/json"
|
||||
}
|
||||
return a.doDPoPRequestWithContentType(ctx, credential, ssoToken, lease, method, endpoint, body, contentType, accept)
|
||||
}
|
||||
|
||||
func (a *Adapter) doDPoPRequestWithContentType(
|
||||
ctx context.Context,
|
||||
credential account.Credential,
|
||||
ssoToken string,
|
||||
lease *infraegress.Lease,
|
||||
method, endpoint string,
|
||||
body []byte,
|
||||
contentType string,
|
||||
accept string,
|
||||
) (*http.Response, error) {
|
||||
for attempt := 0; attempt < 2; attempt++ {
|
||||
session, cacheKey, err := a.dpop.get(ctx, a, credential, ssoToken, lease)
|
||||
@@ -308,7 +325,10 @@ func (a *Adapter) doDPoPRequest(
|
||||
}
|
||||
applyBrowserHeaders(request, ssoToken, lease)
|
||||
if len(body) > 0 {
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
if strings.TrimSpace(contentType) == "" {
|
||||
contentType = "application/json"
|
||||
}
|
||||
request.Header.Set("Content-Type", contentType)
|
||||
}
|
||||
if strings.TrimSpace(accept) != "" {
|
||||
request.Header.Set("Accept", accept)
|
||||
|
||||
@@ -0,0 +1,741 @@
|
||||
package console
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/account"
|
||||
egressdomain "github.com/chenyme/grok2api/backend/internal/domain/egress"
|
||||
modeldomain "github.com/chenyme/grok2api/backend/internal/domain/model"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/provider"
|
||||
)
|
||||
|
||||
const (
|
||||
consoleVoiceBodyLimit = 64 << 20
|
||||
consoleVoiceAudioLimit = 512 << 20
|
||||
consoleCustomVoiceLimit = 32 << 20
|
||||
)
|
||||
|
||||
func (a *Adapter) SynthesizeSpeech(ctx context.Context, request provider.TTSRequest) (provider.TTSResult, error) {
|
||||
if model := strings.TrimSpace(request.Model); model != "" && !ResolveMedia(model, modeldomain.CapabilityTTS) {
|
||||
// Official REST TTS is not strictly bound to a single model id; catalog
|
||||
// models remain preferred when callers supply one.
|
||||
}
|
||||
text := strings.TrimSpace(request.Text)
|
||||
if text == "" {
|
||||
return provider.TTSResult{}, invalidConsoleVoiceError("text 不能为空")
|
||||
}
|
||||
if utf8.RuneCountInString(text) > 15000 {
|
||||
return provider.TTSResult{}, invalidConsoleVoiceError("text 最多 15000 个字符")
|
||||
}
|
||||
language := strings.TrimSpace(request.Language)
|
||||
if language == "" {
|
||||
return provider.TTSResult{}, invalidConsoleVoiceError("language 不能为空")
|
||||
}
|
||||
payload := map[string]any{"text": text, "language": language}
|
||||
if voiceID := strings.TrimSpace(request.VoiceID); voiceID != "" {
|
||||
payload["voice_id"] = voiceID
|
||||
}
|
||||
if format := normalizeTTSOutputFormat(request.OutputFormat); format != nil {
|
||||
payload["output_format"] = format
|
||||
}
|
||||
if request.Speed > 0 {
|
||||
payload["speed"] = request.Speed
|
||||
}
|
||||
if request.OptimizeStreamingLatency > 0 {
|
||||
payload["optimize_streaming_latency"] = strconv.Itoa(request.OptimizeStreamingLatency)
|
||||
}
|
||||
if request.TextNormalization {
|
||||
payload["text_normalization"] = true
|
||||
}
|
||||
if request.WithTimestamps {
|
||||
payload["with_timestamps"] = true
|
||||
}
|
||||
response, err := a.forwardConsoleVoice(ctx, request.Credential, http.MethodPost, "/tts", payload, "application/json", "*/*")
|
||||
if err != nil {
|
||||
return provider.TTSResult{}, err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode < 200 || response.StatusCode >= 300 {
|
||||
return provider.TTSResult{}, consoleVoiceResponseError(response)
|
||||
}
|
||||
contentType := strings.ToLower(strings.TrimSpace(response.Header.Get("Content-Type")))
|
||||
data, err := io.ReadAll(io.LimitReader(response.Body, consoleVoiceAudioLimit+1))
|
||||
if err != nil {
|
||||
return provider.TTSResult{}, err
|
||||
}
|
||||
if len(data) > consoleVoiceAudioLimit {
|
||||
return provider.TTSResult{}, errors.New("Console TTS 响应超过安全上限")
|
||||
}
|
||||
if strings.Contains(contentType, "application/json") || request.WithTimestamps {
|
||||
var envelope struct {
|
||||
Audio string `json:"audio"`
|
||||
ContentType string `json:"content_type"`
|
||||
Duration float64 `json:"duration"`
|
||||
AudioTimestamps *struct {
|
||||
GraphChars []string `json:"graph_chars"`
|
||||
GraphTimes []struct {
|
||||
Start float64 `json:"start"`
|
||||
End float64 `json:"end"`
|
||||
} `json:"graph_times"`
|
||||
} `json:"audio_timestamps"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &envelope); err != nil {
|
||||
if !strings.Contains(contentType, "application/json") {
|
||||
return provider.TTSResult{Audio: data, ContentType: firstNonEmpty(contentType, "audio/mpeg")}, nil
|
||||
}
|
||||
return provider.TTSResult{}, fmt.Errorf("解析 Console TTS JSON 响应失败: %w", err)
|
||||
}
|
||||
audio, err := base64.StdEncoding.DecodeString(strings.TrimSpace(envelope.Audio))
|
||||
if err != nil {
|
||||
return provider.TTSResult{}, fmt.Errorf("解码 Console TTS audio 失败: %w", err)
|
||||
}
|
||||
result := provider.TTSResult{
|
||||
Audio: audio, ContentType: firstNonEmpty(envelope.ContentType, contentType, "audio/mpeg"),
|
||||
Duration: envelope.Duration, Base64Audio: envelope.Audio, JSONEnvelope: true,
|
||||
}
|
||||
if envelope.AudioTimestamps != nil {
|
||||
times := make([]provider.TTSTimestampSpan, 0, len(envelope.AudioTimestamps.GraphTimes))
|
||||
for _, item := range envelope.AudioTimestamps.GraphTimes {
|
||||
times = append(times, provider.TTSTimestampSpan{Start: item.Start, End: item.End})
|
||||
}
|
||||
result.Timestamps = &provider.TTSTimestamps{
|
||||
GraphChars: append([]string(nil), envelope.AudioTimestamps.GraphChars...),
|
||||
GraphTimes: times,
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
return provider.TTSResult{Audio: data, ContentType: firstNonEmpty(contentType, "audio/mpeg")}, nil
|
||||
}
|
||||
|
||||
func (a *Adapter) ListTTSVoices(ctx context.Context, credential account.Credential) ([]provider.VoiceInfo, error) {
|
||||
response, err := a.forwardConsoleVoice(ctx, credential, http.MethodGet, "/tts/voices", nil, "", "application/json")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode < 200 || response.StatusCode >= 300 {
|
||||
return nil, consoleVoiceResponseError(response)
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(response.Body, consoleVoiceBodyLimit+1))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var payload struct {
|
||||
Voices []struct {
|
||||
VoiceID string `json:"voice_id"`
|
||||
Name string `json:"name"`
|
||||
Language *string `json:"language"`
|
||||
} `json:"voices"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &payload); err != nil {
|
||||
return nil, fmt.Errorf("解析 Console TTS voices 失败: %w", err)
|
||||
}
|
||||
result := make([]provider.VoiceInfo, 0, len(payload.Voices))
|
||||
for _, item := range payload.Voices {
|
||||
language := ""
|
||||
if item.Language != nil {
|
||||
language = strings.TrimSpace(*item.Language)
|
||||
}
|
||||
result = append(result, provider.VoiceInfo{VoiceID: strings.TrimSpace(item.VoiceID), Name: strings.TrimSpace(item.Name), Language: language})
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (a *Adapter) GetTTSVoice(ctx context.Context, credential account.Credential, voiceID string) (provider.VoiceInfo, error) {
|
||||
voiceID = strings.TrimSpace(voiceID)
|
||||
if voiceID == "" {
|
||||
return provider.VoiceInfo{}, invalidConsoleVoiceError("voice_id 不能为空")
|
||||
}
|
||||
response, err := a.forwardConsoleVoice(ctx, credential, http.MethodGet, "/tts/voices/"+url.PathEscape(voiceID), nil, "", "application/json")
|
||||
if err != nil {
|
||||
return provider.VoiceInfo{}, err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode < 200 || response.StatusCode >= 300 {
|
||||
return provider.VoiceInfo{}, consoleVoiceResponseError(response)
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(response.Body, consoleVoiceBodyLimit+1))
|
||||
if err != nil {
|
||||
return provider.VoiceInfo{}, err
|
||||
}
|
||||
var payload struct {
|
||||
VoiceID string `json:"voice_id"`
|
||||
Name string `json:"name"`
|
||||
Language *string `json:"language"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &payload); err != nil {
|
||||
return provider.VoiceInfo{}, fmt.Errorf("解析 Console TTS voice 失败: %w", err)
|
||||
}
|
||||
language := ""
|
||||
if payload.Language != nil {
|
||||
language = strings.TrimSpace(*payload.Language)
|
||||
}
|
||||
return provider.VoiceInfo{VoiceID: strings.TrimSpace(payload.VoiceID), Name: strings.TrimSpace(payload.Name), Language: language}, nil
|
||||
}
|
||||
|
||||
func (a *Adapter) TranscribeSpeech(ctx context.Context, request provider.STTRequest) (provider.STTResult, error) {
|
||||
hasFile := len(request.FileData) > 0
|
||||
hasURL := strings.TrimSpace(request.URL) != ""
|
||||
if hasFile == hasURL {
|
||||
return provider.STTResult{}, invalidConsoleVoiceError("STT 必须提供 file 或 url 其中之一")
|
||||
}
|
||||
var body bytes.Buffer
|
||||
writer := multipart.NewWriter(&body)
|
||||
writeField := func(name, value string) error {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" {
|
||||
return nil
|
||||
}
|
||||
return writer.WriteField(name, value)
|
||||
}
|
||||
_ = writeField("audio_format", request.AudioFormat)
|
||||
_ = writeField("sample_rate", request.SampleRate)
|
||||
_ = writeField("language", request.Language)
|
||||
if request.Format {
|
||||
_ = writer.WriteField("format", "true")
|
||||
}
|
||||
if request.Multichannel {
|
||||
_ = writer.WriteField("multichannel", "true")
|
||||
}
|
||||
if request.Channels > 0 {
|
||||
_ = writer.WriteField("channels", strconv.Itoa(request.Channels))
|
||||
}
|
||||
if request.Diarize {
|
||||
_ = writer.WriteField("diarize", "true")
|
||||
}
|
||||
for _, term := range request.KeyTerms {
|
||||
_ = writeField("keyterm", term)
|
||||
}
|
||||
if request.FillerWords {
|
||||
_ = writer.WriteField("filler_words", "true")
|
||||
}
|
||||
if request.VADThreshold != nil {
|
||||
_ = writer.WriteField("vad_threshold", strconv.FormatFloat(*request.VADThreshold, 'f', -1, 64))
|
||||
}
|
||||
if modelName := strings.TrimSpace(request.Model); modelName != "" {
|
||||
_ = writer.WriteField("model", modelName)
|
||||
}
|
||||
if hasURL {
|
||||
_ = writer.WriteField("url", strings.TrimSpace(request.URL))
|
||||
}
|
||||
if hasFile {
|
||||
fileName := strings.TrimSpace(request.FileName)
|
||||
if fileName == "" {
|
||||
fileName = "audio.bin"
|
||||
}
|
||||
part, err := writer.CreateFormFile("file", path.Base(fileName))
|
||||
if err != nil {
|
||||
return provider.STTResult{}, err
|
||||
}
|
||||
if _, err := part.Write(request.FileData); err != nil {
|
||||
return provider.STTResult{}, err
|
||||
}
|
||||
}
|
||||
if err := writer.Close(); err != nil {
|
||||
return provider.STTResult{}, err
|
||||
}
|
||||
response, err := a.forwardConsoleVoiceBytes(ctx, request.Credential, http.MethodPost, "/stt", body.Bytes(), writer.FormDataContentType(), "application/json")
|
||||
if err != nil {
|
||||
return provider.STTResult{}, err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode < 200 || response.StatusCode >= 300 {
|
||||
return provider.STTResult{}, consoleVoiceResponseError(response)
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(response.Body, consoleVoiceBodyLimit+1))
|
||||
if err != nil {
|
||||
return provider.STTResult{}, err
|
||||
}
|
||||
result, err := parseSTTResult(data)
|
||||
if err != nil {
|
||||
return provider.STTResult{}, err
|
||||
}
|
||||
result.RawJSON = append([]byte(nil), data...)
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (a *Adapter) CreateRealtimeClientSecret(ctx context.Context, request provider.RealtimeClientSecretRequest) (provider.RealtimeClientSecretResult, error) {
|
||||
payload := map[string]any{}
|
||||
if request.ExpiresAfter > 0 {
|
||||
payload["expires_after"] = map[string]any{"seconds": request.ExpiresAfter}
|
||||
}
|
||||
if len(bytes.TrimSpace(request.SessionJSON)) > 0 {
|
||||
var session any
|
||||
if err := json.Unmarshal(request.SessionJSON, &session); err != nil {
|
||||
return provider.RealtimeClientSecretResult{}, invalidConsoleVoiceError("session 必须是合法 JSON 对象")
|
||||
}
|
||||
payload["session"] = session
|
||||
} else if modelName := strings.TrimSpace(request.Model); modelName != "" {
|
||||
payload["session"] = map[string]any{"model": modelName}
|
||||
}
|
||||
response, err := a.forwardConsoleVoice(ctx, request.Credential, http.MethodPost, "/realtime/client_secrets", payload, "application/json", "application/json")
|
||||
if err != nil {
|
||||
return provider.RealtimeClientSecretResult{}, err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode < 200 || response.StatusCode >= 300 {
|
||||
return provider.RealtimeClientSecretResult{}, consoleVoiceResponseError(response)
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(response.Body, consoleVoiceBodyLimit+1))
|
||||
if err != nil {
|
||||
return provider.RealtimeClientSecretResult{}, err
|
||||
}
|
||||
var payloadResult struct {
|
||||
Value string `json:"value"`
|
||||
ExpiresAt int64 `json:"expires_at"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &payloadResult); err != nil {
|
||||
return provider.RealtimeClientSecretResult{}, fmt.Errorf("解析 Console realtime client secret 失败: %w", err)
|
||||
}
|
||||
if strings.TrimSpace(payloadResult.Value) == "" {
|
||||
return provider.RealtimeClientSecretResult{}, errors.New("Console realtime client secret 响应缺少 value")
|
||||
}
|
||||
return provider.RealtimeClientSecretResult{Value: payloadResult.Value, ExpiresAt: payloadResult.ExpiresAt, RawJSON: append([]byte(nil), data...)}, nil
|
||||
}
|
||||
|
||||
func (a *Adapter) RealtimeWebSocketURL(modelName string, query string) (string, error) {
|
||||
base := strings.TrimRight(strings.TrimSpace(a.config().BaseURL), "/")
|
||||
if base == "" {
|
||||
return "", errors.New("Console BaseURL 未配置")
|
||||
}
|
||||
endpoint, err := url.Parse(consoleV1Endpoint(base, "/realtime"))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
switch strings.ToLower(endpoint.Scheme) {
|
||||
case "https":
|
||||
endpoint.Scheme = "wss"
|
||||
case "http":
|
||||
endpoint.Scheme = "ws"
|
||||
case "wss", "ws":
|
||||
default:
|
||||
return "", fmt.Errorf("不支持的 Console realtime scheme: %s", endpoint.Scheme)
|
||||
}
|
||||
values := endpoint.Query()
|
||||
if modelName = strings.TrimSpace(modelName); modelName != "" {
|
||||
values.Set("model", modelName)
|
||||
}
|
||||
if extra := strings.TrimSpace(query); extra != "" {
|
||||
extraValues, err := url.ParseQuery(strings.TrimPrefix(extra, "?"))
|
||||
if err != nil {
|
||||
return "", invalidConsoleVoiceError("realtime query 无效")
|
||||
}
|
||||
for key, items := range extraValues {
|
||||
for _, item := range items {
|
||||
values.Add(key, item)
|
||||
}
|
||||
}
|
||||
}
|
||||
endpoint.RawQuery = values.Encode()
|
||||
return endpoint.String(), nil
|
||||
}
|
||||
|
||||
func (a *Adapter) CreateCustomVoice(ctx context.Context, request provider.CustomVoiceCreateRequest) (provider.CustomVoice, error) {
|
||||
if strings.TrimSpace(request.Name) == "" {
|
||||
return provider.CustomVoice{}, invalidConsoleVoiceError("name 不能为空")
|
||||
}
|
||||
if len(request.FileData) == 0 {
|
||||
return provider.CustomVoice{}, invalidConsoleVoiceError("自定义音色必须提供参考音频")
|
||||
}
|
||||
if len(request.FileData) > consoleCustomVoiceLimit {
|
||||
return provider.CustomVoice{}, invalidConsoleVoiceError("参考音频不能超过 32 MiB")
|
||||
}
|
||||
var body bytes.Buffer
|
||||
writer := multipart.NewWriter(&body)
|
||||
_ = writer.WriteField("name", strings.TrimSpace(request.Name))
|
||||
for key, value := range map[string]string{"language": request.Language, "gender": request.Gender, "tone": request.Tone, "use_case": request.UseCase} {
|
||||
if strings.TrimSpace(value) != "" {
|
||||
_ = writer.WriteField(key, strings.TrimSpace(value))
|
||||
}
|
||||
}
|
||||
fileName := strings.TrimSpace(request.FileName)
|
||||
if fileName == "" {
|
||||
fileName = "reference.wav"
|
||||
}
|
||||
part, err := writer.CreateFormFile("file", path.Base(fileName))
|
||||
if err != nil {
|
||||
return provider.CustomVoice{}, err
|
||||
}
|
||||
if _, err := part.Write(request.FileData); err != nil {
|
||||
return provider.CustomVoice{}, err
|
||||
}
|
||||
if err := writer.Close(); err != nil {
|
||||
return provider.CustomVoice{}, err
|
||||
}
|
||||
response, err := a.forwardConsoleVoiceBytes(ctx, request.Credential, http.MethodPost, "/custom-voices", body.Bytes(), writer.FormDataContentType(), "application/json")
|
||||
if err != nil {
|
||||
return provider.CustomVoice{}, err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode < 200 || response.StatusCode >= 300 {
|
||||
return provider.CustomVoice{}, consoleVoiceResponseError(response)
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(response.Body, consoleVoiceBodyLimit+1))
|
||||
if err != nil {
|
||||
return provider.CustomVoice{}, err
|
||||
}
|
||||
return parseCustomVoice(data)
|
||||
}
|
||||
|
||||
func (a *Adapter) ListCustomVoices(ctx context.Context, credential account.Credential, limit int, paginationToken string) ([]provider.CustomVoice, string, error) {
|
||||
values := url.Values{}
|
||||
if limit > 0 {
|
||||
values.Set("limit", strconv.Itoa(limit))
|
||||
}
|
||||
if token := strings.TrimSpace(paginationToken); token != "" {
|
||||
values.Set("pagination_token", token)
|
||||
}
|
||||
pathValue := "/custom-voices"
|
||||
if encoded := values.Encode(); encoded != "" {
|
||||
pathValue += "?" + encoded
|
||||
}
|
||||
response, err := a.forwardConsoleVoice(ctx, credential, http.MethodGet, pathValue, nil, "", "application/json")
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode < 200 || response.StatusCode >= 300 {
|
||||
return nil, "", consoleVoiceResponseError(response)
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(response.Body, consoleVoiceBodyLimit+1))
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
var payload struct {
|
||||
Voices []json.RawMessage `json:"voices"`
|
||||
PaginationToken string `json:"pagination_token"`
|
||||
NextPaginationToken string `json:"next_pagination_token"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &payload); err != nil {
|
||||
return nil, "", fmt.Errorf("解析 Console custom voices 失败: %w", err)
|
||||
}
|
||||
result := make([]provider.CustomVoice, 0, len(payload.Voices))
|
||||
for _, raw := range payload.Voices {
|
||||
item, err := parseCustomVoice(raw)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
result = append(result, item)
|
||||
}
|
||||
next := strings.TrimSpace(payload.NextPaginationToken)
|
||||
if next == "" {
|
||||
next = strings.TrimSpace(payload.PaginationToken)
|
||||
}
|
||||
return result, next, nil
|
||||
}
|
||||
|
||||
func (a *Adapter) GetCustomVoice(ctx context.Context, credential account.Credential, voiceID string) (provider.CustomVoice, error) {
|
||||
voiceID = strings.TrimSpace(voiceID)
|
||||
if voiceID == "" {
|
||||
return provider.CustomVoice{}, invalidConsoleVoiceError("voice_id 不能为空")
|
||||
}
|
||||
response, err := a.forwardConsoleVoice(ctx, credential, http.MethodGet, "/custom-voices/"+url.PathEscape(voiceID), nil, "", "application/json")
|
||||
if err != nil {
|
||||
return provider.CustomVoice{}, err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode < 200 || response.StatusCode >= 300 {
|
||||
return provider.CustomVoice{}, consoleVoiceResponseError(response)
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(response.Body, consoleVoiceBodyLimit+1))
|
||||
if err != nil {
|
||||
return provider.CustomVoice{}, err
|
||||
}
|
||||
return parseCustomVoice(data)
|
||||
}
|
||||
|
||||
func (a *Adapter) UpdateCustomVoice(ctx context.Context, request provider.CustomVoiceUpdateRequest) (provider.CustomVoice, error) {
|
||||
voiceID := strings.TrimSpace(request.VoiceID)
|
||||
if voiceID == "" {
|
||||
return provider.CustomVoice{}, invalidConsoleVoiceError("voice_id 不能为空")
|
||||
}
|
||||
payload := map[string]any{}
|
||||
set := func(key string, value *string) {
|
||||
if value != nil {
|
||||
payload[key] = strings.TrimSpace(*value)
|
||||
}
|
||||
}
|
||||
set("name", request.Name)
|
||||
set("language", request.Language)
|
||||
set("gender", request.Gender)
|
||||
set("tone", request.Tone)
|
||||
set("use_case", request.UseCase)
|
||||
if len(payload) == 0 {
|
||||
return provider.CustomVoice{}, invalidConsoleVoiceError("至少提供一个可更新字段")
|
||||
}
|
||||
response, err := a.forwardConsoleVoice(ctx, request.Credential, http.MethodPatch, "/custom-voices/"+url.PathEscape(voiceID), payload, "application/json", "application/json")
|
||||
if err != nil {
|
||||
return provider.CustomVoice{}, err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode < 200 || response.StatusCode >= 300 {
|
||||
return provider.CustomVoice{}, consoleVoiceResponseError(response)
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(response.Body, consoleVoiceBodyLimit+1))
|
||||
if err != nil {
|
||||
return provider.CustomVoice{}, err
|
||||
}
|
||||
return parseCustomVoice(data)
|
||||
}
|
||||
|
||||
func (a *Adapter) DeleteCustomVoice(ctx context.Context, credential account.Credential, voiceID string) error {
|
||||
voiceID = strings.TrimSpace(voiceID)
|
||||
if voiceID == "" {
|
||||
return invalidConsoleVoiceError("voice_id 不能为空")
|
||||
}
|
||||
response, err := a.forwardConsoleVoice(ctx, credential, http.MethodDelete, "/custom-voices/"+url.PathEscape(voiceID), nil, "", "application/json")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode < 200 || response.StatusCode >= 300 {
|
||||
return consoleVoiceResponseError(response)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *Adapter) GetCustomVoiceAudio(ctx context.Context, credential account.Credential, voiceID string) ([]byte, string, error) {
|
||||
voiceID = strings.TrimSpace(voiceID)
|
||||
if voiceID == "" {
|
||||
return nil, "", invalidConsoleVoiceError("voice_id 不能为空")
|
||||
}
|
||||
response, err := a.forwardConsoleVoice(ctx, credential, http.MethodGet, "/custom-voices/"+url.PathEscape(voiceID)+"/audio", nil, "", "*/*")
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode < 200 || response.StatusCode >= 300 {
|
||||
return nil, "", consoleVoiceResponseError(response)
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(response.Body, consoleCustomVoiceLimit+1))
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
if len(data) > consoleCustomVoiceLimit {
|
||||
return nil, "", errors.New("Console custom voice audio 超过安全上限")
|
||||
}
|
||||
return data, firstNonEmpty(response.Header.Get("Content-Type"), "audio/mpeg"), nil
|
||||
}
|
||||
|
||||
func (a *Adapter) ProxyVoice(ctx context.Context, request provider.VoiceProxyRequest) (*provider.Response, error) {
|
||||
method := strings.ToUpper(strings.TrimSpace(request.Method))
|
||||
if method == "" {
|
||||
method = http.MethodGet
|
||||
}
|
||||
pathValue := strings.TrimSpace(request.Path)
|
||||
if pathValue == "" || strings.Contains(pathValue, "://") || strings.Contains(pathValue, "..") {
|
||||
return invalidConsoleMediaRequest("voice path 无效"), nil
|
||||
}
|
||||
if !strings.HasPrefix(pathValue, "/") {
|
||||
pathValue = "/" + pathValue
|
||||
}
|
||||
if query := strings.TrimSpace(request.Query); query != "" {
|
||||
if strings.Contains(pathValue, "?") {
|
||||
pathValue += "&" + strings.TrimPrefix(query, "?")
|
||||
} else {
|
||||
pathValue += "?" + strings.TrimPrefix(query, "?")
|
||||
}
|
||||
}
|
||||
accept := strings.TrimSpace(request.Accept)
|
||||
if accept == "" {
|
||||
accept = "*/*"
|
||||
}
|
||||
response, err := a.forwardConsoleVoiceBytes(ctx, request.Credential, method, pathValue, request.Body, request.ContentType, accept)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return responseResult(response, response.Body), nil
|
||||
}
|
||||
|
||||
func (a *Adapter) forwardConsoleVoice(ctx context.Context, credential account.Credential, method, pathValue string, payload any, contentType, accept string) (*http.Response, error) {
|
||||
var body []byte
|
||||
var err error
|
||||
if payload != nil {
|
||||
body, err = json.Marshal(payload)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if contentType == "" {
|
||||
contentType = "application/json"
|
||||
}
|
||||
}
|
||||
return a.forwardConsoleVoiceBytes(ctx, credential, method, pathValue, body, contentType, accept)
|
||||
}
|
||||
|
||||
func (a *Adapter) forwardConsoleVoiceBytes(ctx context.Context, credential account.Credential, method, pathValue string, body []byte, contentType, accept string) (*http.Response, error) {
|
||||
if strings.HasPrefix(strings.ToLower(strings.TrimSpace(contentType)), "multipart/") {
|
||||
return a.forwardConsoleVoiceMultipart(ctx, credential, method, pathValue, body, contentType, accept)
|
||||
}
|
||||
token, err := a.cipher.Decrypt(credential.EncryptedAccessToken)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg := a.config()
|
||||
requestCtx, cancel := context.WithTimeout(ctx, time.Duration(cfg.TimeoutSeconds)*time.Second)
|
||||
lease, err := a.egress.AcquireCredential(requestCtx, egressdomain.ScopeConsole, credential)
|
||||
if err != nil {
|
||||
cancel()
|
||||
return nil, err
|
||||
}
|
||||
if accept == "" {
|
||||
accept = "*/*"
|
||||
}
|
||||
response, err := a.doDPoPRequestWithContentType(requestCtx, credential, token, lease, method, consoleV1Endpoint(cfg.BaseURL, pathValue), body, contentType, accept)
|
||||
if err != nil {
|
||||
a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsole, lease.NodeID, 0, err)
|
||||
lease.Release()
|
||||
cancel()
|
||||
return nil, err
|
||||
}
|
||||
response.Body = &releaseBody{ReadCloser: response.Body, release: func() {
|
||||
a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsole, lease.NodeID, response.StatusCode, nil)
|
||||
lease.Release()
|
||||
cancel()
|
||||
}}
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func (a *Adapter) forwardConsoleVoiceMultipart(ctx context.Context, credential account.Credential, method, pathValue string, body []byte, contentType, accept string) (*http.Response, error) {
|
||||
token, err := a.cipher.Decrypt(credential.EncryptedAccessToken)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg := a.config()
|
||||
requestCtx, cancel := context.WithTimeout(ctx, time.Duration(cfg.TimeoutSeconds)*time.Second)
|
||||
lease, err := a.egress.AcquireCredential(requestCtx, egressdomain.ScopeConsole, credential)
|
||||
if err != nil {
|
||||
cancel()
|
||||
return nil, err
|
||||
}
|
||||
if accept == "" {
|
||||
accept = "*/*"
|
||||
}
|
||||
response, err := a.doDPoPRequestWithContentType(requestCtx, credential, token, lease, method, consoleV1Endpoint(cfg.BaseURL, pathValue), body, contentType, accept)
|
||||
if err != nil {
|
||||
a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsole, lease.NodeID, 0, err)
|
||||
lease.Release()
|
||||
cancel()
|
||||
return nil, err
|
||||
}
|
||||
response.Body = &releaseBody{ReadCloser: response.Body, release: func() {
|
||||
a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsole, lease.NodeID, response.StatusCode, nil)
|
||||
lease.Release()
|
||||
cancel()
|
||||
}}
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func normalizeTTSOutputFormat(format provider.TTSOutputFormat) map[string]any {
|
||||
codec := strings.ToLower(strings.TrimSpace(format.Codec))
|
||||
if codec == "" && format.SampleRate == 0 && format.BitRate == 0 {
|
||||
return nil
|
||||
}
|
||||
if codec == "" {
|
||||
codec = "mp3"
|
||||
}
|
||||
result := map[string]any{"codec": codec}
|
||||
if format.SampleRate > 0 {
|
||||
result["sample_rate"] = format.SampleRate
|
||||
}
|
||||
if format.BitRate > 0 {
|
||||
result["bit_rate"] = format.BitRate
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func parseSTTResult(data []byte) (provider.STTResult, error) {
|
||||
var payload struct {
|
||||
Text string `json:"text"`
|
||||
Language string `json:"language"`
|
||||
Duration float64 `json:"duration"`
|
||||
Words []struct {
|
||||
Text string `json:"text"`
|
||||
Start float64 `json:"start"`
|
||||
End float64 `json:"end"`
|
||||
Speaker *int `json:"speaker"`
|
||||
} `json:"words"`
|
||||
Channels []struct {
|
||||
Index int `json:"index"`
|
||||
Text string `json:"text"`
|
||||
Words []struct {
|
||||
Text string `json:"text"`
|
||||
Start float64 `json:"start"`
|
||||
End float64 `json:"end"`
|
||||
Speaker *int `json:"speaker"`
|
||||
} `json:"words"`
|
||||
} `json:"channels"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &payload); err != nil {
|
||||
return provider.STTResult{}, fmt.Errorf("解析 Console STT 响应失败: %w", err)
|
||||
}
|
||||
result := provider.STTResult{Text: payload.Text, Language: payload.Language, Duration: payload.Duration}
|
||||
for _, word := range payload.Words {
|
||||
result.Words = append(result.Words, provider.STTWord{Text: word.Text, Start: word.Start, End: word.End, Speaker: word.Speaker})
|
||||
}
|
||||
for _, channel := range payload.Channels {
|
||||
item := provider.STTChannel{Index: channel.Index, Text: channel.Text}
|
||||
for _, word := range channel.Words {
|
||||
item.Words = append(item.Words, provider.STTWord{Text: word.Text, Start: word.Start, End: word.End, Speaker: word.Speaker})
|
||||
}
|
||||
result.Channels = append(result.Channels, item)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func parseCustomVoice(data []byte) (provider.CustomVoice, error) {
|
||||
var payload struct {
|
||||
VoiceID string `json:"voice_id"`
|
||||
Name string `json:"name"`
|
||||
Language string `json:"language"`
|
||||
Gender string `json:"gender"`
|
||||
Tone string `json:"tone"`
|
||||
UseCase string `json:"use_case"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &payload); err != nil {
|
||||
return provider.CustomVoice{}, fmt.Errorf("解析 Console custom voice 失败: %w", err)
|
||||
}
|
||||
if strings.TrimSpace(payload.VoiceID) == "" {
|
||||
return provider.CustomVoice{}, errors.New("Console custom voice 响应缺少 voice_id")
|
||||
}
|
||||
return provider.CustomVoice{
|
||||
VoiceID: strings.TrimSpace(payload.VoiceID), Name: strings.TrimSpace(payload.Name), Language: strings.TrimSpace(payload.Language),
|
||||
Gender: strings.TrimSpace(payload.Gender), Tone: strings.TrimSpace(payload.Tone), UseCase: strings.TrimSpace(payload.UseCase),
|
||||
CreatedAt: strings.TrimSpace(payload.CreatedAt), UpdatedAt: strings.TrimSpace(payload.UpdatedAt), RawJSON: append([]byte(nil), data...),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func consoleVoiceResponseError(response *http.Response) error {
|
||||
data, _, err := provider.ReadDiagnosticBody(response.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
summary := strings.TrimSpace(string(data))
|
||||
if summary == "" {
|
||||
summary = http.StatusText(response.StatusCode)
|
||||
}
|
||||
if len(summary) > 2048 {
|
||||
summary = summary[:2048]
|
||||
}
|
||||
return &consoleMediaUpstreamError{status: response.StatusCode, summary: summary}
|
||||
}
|
||||
|
||||
func invalidConsoleVoiceError(message string) error {
|
||||
return &consoleMediaUpstreamError{status: http.StatusBadRequest, summary: message}
|
||||
}
|
||||
@@ -55,6 +55,10 @@ type MediaSurface struct {
|
||||
ImageGeneration bool
|
||||
ImageEdit bool
|
||||
VideoGeneration bool
|
||||
TTS bool
|
||||
STT bool
|
||||
Realtime bool
|
||||
CustomVoices bool
|
||||
}
|
||||
|
||||
// CredentialSurface 描述号池凭据的接入和维护方式。
|
||||
@@ -131,7 +135,7 @@ func (d Definition) Validate() error {
|
||||
capabilities := make(map[modeldomain.Capability]struct{}, len(d.ModelCapabilities))
|
||||
for _, capability := range d.ModelCapabilities {
|
||||
switch capability {
|
||||
case modeldomain.CapabilityResponses, modeldomain.CapabilityChat, modeldomain.CapabilityImage, modeldomain.CapabilityImageEdit, modeldomain.CapabilityVideo:
|
||||
case modeldomain.CapabilityResponses, modeldomain.CapabilityChat, modeldomain.CapabilityImage, modeldomain.CapabilityImageEdit, modeldomain.CapabilityVideo, modeldomain.CapabilityTTS, modeldomain.CapabilitySTT, modeldomain.CapabilityRealtime:
|
||||
default:
|
||||
return fmt.Errorf("Provider %s 声明了无效模型能力 %q", d.Provider, capability)
|
||||
}
|
||||
@@ -163,6 +167,9 @@ func (d Definition) Validate() error {
|
||||
{enabled: d.Media.ImageGeneration, capability: modeldomain.CapabilityImage, name: "图像生成"},
|
||||
{enabled: d.Media.ImageEdit, capability: modeldomain.CapabilityImageEdit, name: "图像编辑"},
|
||||
{enabled: d.Media.VideoGeneration, capability: modeldomain.CapabilityVideo, name: "视频生成"},
|
||||
{enabled: d.Media.TTS, capability: modeldomain.CapabilityTTS, name: "语音合成"},
|
||||
{enabled: d.Media.STT, capability: modeldomain.CapabilitySTT, name: "语音识别"},
|
||||
{enabled: d.Media.Realtime, capability: modeldomain.CapabilityRealtime, name: "实时语音"},
|
||||
}
|
||||
for _, item := range mediaCapabilities {
|
||||
_, declared := capabilities[item.capability]
|
||||
|
||||
@@ -62,10 +62,10 @@ func TestProductionProviderDefinitionsMatchImplementedCapabilities(t *testing.T)
|
||||
},
|
||||
{
|
||||
provider: account.ProviderConsole, catalog: provider.ModelCatalogStatic, quota: provider.QuotaRemoteWindow,
|
||||
capabilities: []modeldomain.Capability{modeldomain.CapabilityResponses, modeldomain.CapabilityImage, modeldomain.CapabilityImageEdit, modeldomain.CapabilityVideo},
|
||||
capabilities: []modeldomain.Capability{modeldomain.CapabilityResponses, modeldomain.CapabilityImage, modeldomain.CapabilityImageEdit, modeldomain.CapabilityVideo, modeldomain.CapabilityTTS, modeldomain.CapabilitySTT, modeldomain.CapabilityRealtime},
|
||||
credential: provider.CredentialSurface{AuthType: account.AuthTypeSSO, Import: true},
|
||||
conversation: provider.ConversationSurface{Responses: true, ChatCompletions: true, Messages: true},
|
||||
media: provider.MediaSurface{ImageGeneration: true, ImageEdit: true, VideoGeneration: true},
|
||||
media: provider.MediaSurface{ImageGeneration: true, ImageEdit: true, VideoGeneration: true, TTS: true, STT: true, Realtime: true, CustomVoices: true},
|
||||
inference: provider.InferencePolicy{Usage: provider.UsageUpstream, RetryForbiddenAsEgress: true},
|
||||
},
|
||||
}
|
||||
|
||||
@@ -296,6 +296,148 @@ type VideoResult struct {
|
||||
AssetID string
|
||||
}
|
||||
|
||||
type TTSOutputFormat struct {
|
||||
Codec string
|
||||
SampleRate int
|
||||
BitRate int
|
||||
}
|
||||
|
||||
type TTSRequest struct {
|
||||
Credential account.Credential
|
||||
Model string
|
||||
Text string
|
||||
VoiceID string
|
||||
Language string
|
||||
OutputFormat TTSOutputFormat
|
||||
Speed float64
|
||||
OptimizeStreamingLatency int
|
||||
TextNormalization bool
|
||||
WithTimestamps bool
|
||||
}
|
||||
|
||||
type TTSTimestampSpan struct {
|
||||
Start float64
|
||||
End float64
|
||||
}
|
||||
|
||||
type TTSTimestamps struct {
|
||||
GraphChars []string
|
||||
GraphTimes []TTSTimestampSpan
|
||||
}
|
||||
|
||||
type TTSResult struct {
|
||||
Audio []byte
|
||||
ContentType string
|
||||
Duration float64
|
||||
Base64Audio string
|
||||
Timestamps *TTSTimestamps
|
||||
JSONEnvelope bool
|
||||
}
|
||||
|
||||
type STTRequest struct {
|
||||
Credential account.Credential
|
||||
Model string
|
||||
FileName string
|
||||
FileMIME string
|
||||
FileData []byte
|
||||
URL string
|
||||
AudioFormat string
|
||||
SampleRate string
|
||||
Language string
|
||||
Format bool
|
||||
Multichannel bool
|
||||
Channels int
|
||||
Diarize bool
|
||||
KeyTerms []string
|
||||
FillerWords bool
|
||||
VADThreshold *float64
|
||||
}
|
||||
|
||||
type STTWord struct {
|
||||
Text string
|
||||
Start float64
|
||||
End float64
|
||||
Speaker *int
|
||||
}
|
||||
|
||||
type STTChannel struct {
|
||||
Index int
|
||||
Text string
|
||||
Words []STTWord
|
||||
}
|
||||
|
||||
type STTResult struct {
|
||||
Text string
|
||||
Language string
|
||||
Duration float64
|
||||
Words []STTWord
|
||||
Channels []STTChannel
|
||||
RawJSON []byte
|
||||
}
|
||||
|
||||
type VoiceInfo struct {
|
||||
VoiceID string
|
||||
Name string
|
||||
Language string
|
||||
}
|
||||
|
||||
type CustomVoice struct {
|
||||
VoiceID string
|
||||
Name string
|
||||
Language string
|
||||
Gender string
|
||||
Tone string
|
||||
UseCase string
|
||||
CreatedAt string
|
||||
UpdatedAt string
|
||||
RawJSON []byte
|
||||
}
|
||||
|
||||
type CustomVoiceCreateRequest struct {
|
||||
Credential account.Credential
|
||||
Name string
|
||||
Language string
|
||||
Gender string
|
||||
Tone string
|
||||
UseCase string
|
||||
FileName string
|
||||
FileMIME string
|
||||
FileData []byte
|
||||
}
|
||||
|
||||
type CustomVoiceUpdateRequest struct {
|
||||
Credential account.Credential
|
||||
VoiceID string
|
||||
Name *string
|
||||
Language *string
|
||||
Gender *string
|
||||
Tone *string
|
||||
UseCase *string
|
||||
}
|
||||
|
||||
type RealtimeClientSecretRequest struct {
|
||||
Credential account.Credential
|
||||
Model string
|
||||
ExpiresAfter int
|
||||
SessionJSON []byte
|
||||
}
|
||||
|
||||
type RealtimeClientSecretResult struct {
|
||||
Value string
|
||||
ExpiresAt int64
|
||||
RawJSON []byte
|
||||
}
|
||||
|
||||
type VoiceProxyRequest struct {
|
||||
Credential account.Credential
|
||||
Method string
|
||||
Path string
|
||||
Query string
|
||||
Body []byte
|
||||
ContentType string
|
||||
Accept string
|
||||
}
|
||||
|
||||
// RefreshedCredential represents rotated credentials returned by an OAuth refresh.
|
||||
type RefreshedCredential struct {
|
||||
EncryptedAccessToken string
|
||||
@@ -428,6 +570,44 @@ type VideoContentDownloader interface {
|
||||
DownloadVideo(ctx context.Context, credential account.Credential, rawURL string) (io.ReadCloser, string, int64, error)
|
||||
}
|
||||
|
||||
// TTSAdapter synthesizes speech audio for text prompts.
|
||||
type TTSAdapter interface {
|
||||
Adapter
|
||||
SynthesizeSpeech(ctx context.Context, request TTSRequest) (TTSResult, error)
|
||||
ListTTSVoices(ctx context.Context, credential account.Credential) ([]VoiceInfo, error)
|
||||
GetTTSVoice(ctx context.Context, credential account.Credential, voiceID string) (VoiceInfo, error)
|
||||
}
|
||||
|
||||
// STTAdapter transcribes audio into text.
|
||||
type STTAdapter interface {
|
||||
Adapter
|
||||
TranscribeSpeech(ctx context.Context, request STTRequest) (STTResult, error)
|
||||
}
|
||||
|
||||
// RealtimeVoiceAdapter issues ephemeral secrets and can proxy websocket sessions.
|
||||
type RealtimeVoiceAdapter interface {
|
||||
Adapter
|
||||
CreateRealtimeClientSecret(ctx context.Context, request RealtimeClientSecretRequest) (RealtimeClientSecretResult, error)
|
||||
RealtimeWebSocketURL(model string, query string) (string, error)
|
||||
}
|
||||
|
||||
// CustomVoiceAdapter manages team-scoped cloned voices.
|
||||
type CustomVoiceAdapter interface {
|
||||
Adapter
|
||||
CreateCustomVoice(ctx context.Context, request CustomVoiceCreateRequest) (CustomVoice, error)
|
||||
ListCustomVoices(ctx context.Context, credential account.Credential, limit int, paginationToken string) ([]CustomVoice, string, error)
|
||||
GetCustomVoice(ctx context.Context, credential account.Credential, voiceID string) (CustomVoice, error)
|
||||
UpdateCustomVoice(ctx context.Context, request CustomVoiceUpdateRequest) (CustomVoice, error)
|
||||
DeleteCustomVoice(ctx context.Context, credential account.Credential, voiceID string) error
|
||||
GetCustomVoiceAudio(ctx context.Context, credential account.Credential, voiceID string) ([]byte, string, error)
|
||||
}
|
||||
|
||||
// VoiceProxyAdapter forwards arbitrary official voice REST resources with account auth.
|
||||
type VoiceProxyAdapter interface {
|
||||
Adapter
|
||||
ProxyVoice(ctx context.Context, request VoiceProxyRequest) (*Response, error)
|
||||
}
|
||||
|
||||
type RoutingMetadataAdapter interface {
|
||||
Adapter
|
||||
QuotaMode(upstreamModel string) string
|
||||
@@ -609,6 +789,26 @@ func (r *Registry) Validate() error {
|
||||
return fmt.Errorf("Provider %s 声明视频能力但未实现适配器", value)
|
||||
}
|
||||
}
|
||||
if definition.Media.TTS {
|
||||
if _, ok := adapter.(TTSAdapter); !ok {
|
||||
return fmt.Errorf("Provider %s 声明语音合成能力但未实现适配器", value)
|
||||
}
|
||||
}
|
||||
if definition.Media.STT {
|
||||
if _, ok := adapter.(STTAdapter); !ok {
|
||||
return fmt.Errorf("Provider %s 声明语音识别能力但未实现适配器", value)
|
||||
}
|
||||
}
|
||||
if definition.Media.Realtime {
|
||||
if _, ok := adapter.(RealtimeVoiceAdapter); !ok {
|
||||
return fmt.Errorf("Provider %s 声明实时语音能力但未实现适配器", value)
|
||||
}
|
||||
}
|
||||
if definition.Media.CustomVoices {
|
||||
if _, ok := adapter.(CustomVoiceAdapter); !ok {
|
||||
return fmt.Errorf("Provider %s 声明自定义音色能力但未实现适配器", value)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -829,6 +1029,51 @@ func (r *Registry) Videos(value account.Provider) (VideoAdapter, bool) {
|
||||
return result, ok
|
||||
}
|
||||
|
||||
func (r *Registry) TTS(value account.Provider) (TTSAdapter, bool) {
|
||||
adapter, ok := r.Get(value)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
result, ok := adapter.(TTSAdapter)
|
||||
return result, ok
|
||||
}
|
||||
|
||||
func (r *Registry) STT(value account.Provider) (STTAdapter, bool) {
|
||||
adapter, ok := r.Get(value)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
result, ok := adapter.(STTAdapter)
|
||||
return result, ok
|
||||
}
|
||||
|
||||
func (r *Registry) RealtimeVoice(value account.Provider) (RealtimeVoiceAdapter, bool) {
|
||||
adapter, ok := r.Get(value)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
result, ok := adapter.(RealtimeVoiceAdapter)
|
||||
return result, ok
|
||||
}
|
||||
|
||||
func (r *Registry) CustomVoices(value account.Provider) (CustomVoiceAdapter, bool) {
|
||||
adapter, ok := r.Get(value)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
result, ok := adapter.(CustomVoiceAdapter)
|
||||
return result, ok
|
||||
}
|
||||
|
||||
func (r *Registry) VoiceProxy(value account.Provider) (VoiceProxyAdapter, bool) {
|
||||
adapter, ok := r.Get(value)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
result, ok := adapter.(VoiceProxyAdapter)
|
||||
return result, ok
|
||||
}
|
||||
|
||||
// CredentialRejection 表示上游响应或错误是否构成「凭据被拒」的稳定判定。
|
||||
// 与网关 UpstreamFailure 的 CredentialRejected / PermanentAccountDenial / SpendingLimitBlocked 分类保持一致,
|
||||
// 供 account.Service 等非网关路径复用同一套失效收敛语义。
|
||||
|
||||
@@ -90,6 +90,17 @@ func (h *Handler) Register(router *gin.RouterGroup) {
|
||||
router.POST("/videos/generations", h.generateVideo)
|
||||
router.GET("/videos/:requestId", h.getVideo)
|
||||
router.GET("/videos/:requestId/content", h.getVideoContent)
|
||||
router.POST("/tts", h.synthesizeSpeech)
|
||||
router.GET("/tts/voices", h.listTTSVoices)
|
||||
router.GET("/tts/voices/:voiceId", h.getTTSVoice)
|
||||
router.POST("/stt", h.transcribeSpeech)
|
||||
router.POST("/realtime/client_secrets", h.createRealtimeClientSecret)
|
||||
router.POST("/custom-voices", h.createCustomVoice)
|
||||
router.GET("/custom-voices", h.listCustomVoices)
|
||||
router.GET("/custom-voices/:voiceId", h.getCustomVoice)
|
||||
router.PATCH("/custom-voices/:voiceId", h.updateCustomVoice)
|
||||
router.DELETE("/custom-voices/:voiceId", h.deleteCustomVoice)
|
||||
router.GET("/custom-voices/:voiceId/audio", h.getCustomVoiceAudio)
|
||||
router.POST("/responses/compact", h.compactResponse)
|
||||
router.GET("/responses/:responseId", h.getResponse)
|
||||
router.DELETE("/responses/:responseId", h.deleteResponse)
|
||||
|
||||
@@ -0,0 +1,522 @@
|
||||
package inference
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/chenyme/grok2api/backend/internal/application/gateway"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/provider"
|
||||
"github.com/chenyme/grok2api/backend/internal/transport/http/middleware"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type ttsRequest struct {
|
||||
Model string `json:"model"`
|
||||
Text string `json:"text"`
|
||||
VoiceID string `json:"voice_id"`
|
||||
Language string `json:"language"`
|
||||
OutputFormat json.RawMessage `json:"output_format"`
|
||||
Speed *float64 `json:"speed"`
|
||||
OptimizeStreamingLatency json.RawMessage `json:"optimize_streaming_latency"`
|
||||
TextNormalization *bool `json:"text_normalization"`
|
||||
WithTimestamps *bool `json:"with_timestamps"`
|
||||
}
|
||||
|
||||
type realtimeClientSecretRequest struct {
|
||||
Model string `json:"model"`
|
||||
ExpiresAfter json.RawMessage `json:"expires_after"`
|
||||
Session json.RawMessage `json:"session"`
|
||||
}
|
||||
|
||||
func (h *Handler) synthesizeSpeech(c *gin.Context) {
|
||||
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, h.maxBodyBytes)
|
||||
if !isJSONRequest(c) {
|
||||
writeOpenAIError(c, http.StatusUnsupportedMediaType, "invalid_request", "TTS 仅支持 application/json")
|
||||
return
|
||||
}
|
||||
var request ttsRequest
|
||||
if err := decodeSingleJSON(c.Request.Body, &request, false); err != nil {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "TTS 请求无效")
|
||||
return
|
||||
}
|
||||
text := strings.TrimSpace(request.Text)
|
||||
language := strings.TrimSpace(request.Language)
|
||||
if text == "" || language == "" {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "TTS 缺少有效 text 或 language")
|
||||
return
|
||||
}
|
||||
model := strings.TrimSpace(request.Model)
|
||||
if model == "" {
|
||||
model = "grok-voice-latest"
|
||||
}
|
||||
format := provider.TTSOutputFormat{}
|
||||
if len(bytesTrim(request.OutputFormat)) > 0 {
|
||||
var raw struct {
|
||||
Codec string `json:"codec"`
|
||||
SampleRate *int `json:"sample_rate"`
|
||||
BitRate *int `json:"bit_rate"`
|
||||
}
|
||||
if err := json.Unmarshal(request.OutputFormat, &raw); err != nil {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "output_format 无效")
|
||||
return
|
||||
}
|
||||
format.Codec = strings.TrimSpace(raw.Codec)
|
||||
if raw.SampleRate != nil {
|
||||
format.SampleRate = *raw.SampleRate
|
||||
}
|
||||
if raw.BitRate != nil {
|
||||
format.BitRate = *raw.BitRate
|
||||
}
|
||||
}
|
||||
speed := 0.0
|
||||
if request.Speed != nil {
|
||||
speed = *request.Speed
|
||||
}
|
||||
optimize := 0
|
||||
if len(bytesTrim(request.OptimizeStreamingLatency)) > 0 {
|
||||
var asString string
|
||||
var asNumber float64
|
||||
if json.Unmarshal(request.OptimizeStreamingLatency, &asString) == nil {
|
||||
optimize, _ = strconv.Atoi(strings.TrimSpace(asString))
|
||||
} else if json.Unmarshal(request.OptimizeStreamingLatency, &asNumber) == nil {
|
||||
optimize = int(asNumber)
|
||||
}
|
||||
}
|
||||
clientKey, requestID, ok := requestIdentity(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
input := gateway.TTSInput{
|
||||
RequestID: requestID, ClientKey: clientKey, PublicModel: model, Text: text, VoiceID: strings.TrimSpace(request.VoiceID),
|
||||
Language: language, OutputFormat: format, Speed: speed, OptimizeStreamingLatency: optimize,
|
||||
}
|
||||
if request.TextNormalization != nil {
|
||||
input.TextNormalization = *request.TextNormalization
|
||||
}
|
||||
if request.WithTimestamps != nil {
|
||||
input.WithTimestamps = *request.WithTimestamps
|
||||
}
|
||||
result, err := h.gateway.SynthesizeSpeech(c.Request.Context(), input)
|
||||
if err != nil {
|
||||
writeGatewayError(c, err)
|
||||
return
|
||||
}
|
||||
h.writeMediaResult(c, result)
|
||||
}
|
||||
|
||||
func (h *Handler) listTTSVoices(c *gin.Context) {
|
||||
clientKey, requestID, ok := requestIdentity(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
model := strings.TrimSpace(c.Query("model"))
|
||||
if model == "" {
|
||||
model = "grok-voice-latest"
|
||||
}
|
||||
result, err := h.gateway.ListTTSVoices(c.Request.Context(), gateway.VoiceListInput{RequestID: requestID, ClientKey: clientKey, PublicModel: model})
|
||||
if err != nil {
|
||||
writeGatewayError(c, err)
|
||||
return
|
||||
}
|
||||
h.writeMediaResult(c, result)
|
||||
}
|
||||
|
||||
func (h *Handler) getTTSVoice(c *gin.Context) {
|
||||
clientKey, requestID, ok := requestIdentity(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
model := strings.TrimSpace(c.Query("model"))
|
||||
if model == "" {
|
||||
model = "grok-voice-latest"
|
||||
}
|
||||
result, err := h.gateway.GetTTSVoice(c.Request.Context(), gateway.CustomVoiceIDInput{
|
||||
RequestID: requestID, ClientKey: clientKey, PublicModel: model, VoiceID: c.Param("voiceId"),
|
||||
})
|
||||
if err != nil {
|
||||
writeGatewayError(c, err)
|
||||
return
|
||||
}
|
||||
h.writeMediaResult(c, result)
|
||||
}
|
||||
|
||||
func (h *Handler) transcribeSpeech(c *gin.Context) {
|
||||
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, h.maxBodyBytes)
|
||||
clientKey, requestID, ok := requestIdentity(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
contentType := strings.ToLower(strings.TrimSpace(c.GetHeader("Content-Type")))
|
||||
input := gateway.STTInput{RequestID: requestID, ClientKey: clientKey, PublicModel: "grok-transcribe"}
|
||||
if strings.HasPrefix(contentType, "multipart/form-data") {
|
||||
if err := c.Request.ParseMultipartForm(h.maxBodyBytes); err != nil {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "STT multipart 请求无效")
|
||||
return
|
||||
}
|
||||
form := c.Request.MultipartForm
|
||||
get := func(name string) string {
|
||||
if form == nil {
|
||||
return ""
|
||||
}
|
||||
values := form.Value[name]
|
||||
if len(values) == 0 {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(values[0])
|
||||
}
|
||||
if model := get("model"); model != "" {
|
||||
input.PublicModel = model
|
||||
}
|
||||
input.URL = get("url")
|
||||
input.AudioFormat = get("audio_format")
|
||||
input.SampleRate = firstNonEmpty(get("sample_rate"), get("sample_rate_hertz"))
|
||||
input.Language = get("language")
|
||||
input.Format = parseTruthy(get("format"))
|
||||
input.Multichannel = parseTruthy(get("multichannel"))
|
||||
if channels := get("channels"); channels != "" {
|
||||
if value, err := strconv.Atoi(channels); err == nil {
|
||||
input.Channels = value
|
||||
}
|
||||
}
|
||||
input.Diarize = parseTruthy(get("diarize"))
|
||||
input.FillerWords = parseTruthy(get("filler_words"))
|
||||
if form != nil {
|
||||
input.KeyTerms = append([]string(nil), form.Value["keyterm"]...)
|
||||
}
|
||||
if threshold := get("vad_threshold"); threshold != "" {
|
||||
if value, err := strconv.ParseFloat(threshold, 64); err == nil {
|
||||
input.VADThreshold = &value
|
||||
}
|
||||
}
|
||||
file, header, err := c.Request.FormFile("file")
|
||||
if err == nil {
|
||||
defer file.Close()
|
||||
data, readErr := io.ReadAll(io.LimitReader(file, h.maxBodyBytes+1))
|
||||
if readErr != nil {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "读取音频文件失败")
|
||||
return
|
||||
}
|
||||
if int64(len(data)) > h.maxBodyBytes {
|
||||
writeOpenAIError(c, http.StatusRequestEntityTooLarge, "request_too_large", "音频文件超过限制")
|
||||
return
|
||||
}
|
||||
input.FileData = data
|
||||
if header != nil {
|
||||
input.FileName = header.Filename
|
||||
input.FileMIME = header.Header.Get("Content-Type")
|
||||
}
|
||||
}
|
||||
} else if isJSONRequest(c) {
|
||||
var payload struct {
|
||||
Model string `json:"model"`
|
||||
URL string `json:"url"`
|
||||
AudioFormat string `json:"audio_format"`
|
||||
SampleRate any `json:"sample_rate"`
|
||||
Language string `json:"language"`
|
||||
Format any `json:"format"`
|
||||
Multichannel any `json:"multichannel"`
|
||||
Channels any `json:"channels"`
|
||||
Diarize any `json:"diarize"`
|
||||
KeyTerms []string `json:"keyterm"`
|
||||
FillerWords any `json:"filler_words"`
|
||||
VADThreshold *float64 `json:"vad_threshold"`
|
||||
}
|
||||
if err := decodeSingleJSON(c.Request.Body, &payload, false); err != nil {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "STT JSON 请求无效")
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(payload.Model) != "" {
|
||||
input.PublicModel = strings.TrimSpace(payload.Model)
|
||||
}
|
||||
input.URL = strings.TrimSpace(payload.URL)
|
||||
input.AudioFormat = strings.TrimSpace(payload.AudioFormat)
|
||||
input.SampleRate = anyString(payload.SampleRate)
|
||||
input.Language = strings.TrimSpace(payload.Language)
|
||||
input.Format = anyTruthy(payload.Format)
|
||||
input.Multichannel = anyTruthy(payload.Multichannel)
|
||||
if channels := anyString(payload.Channels); channels != "" {
|
||||
if value, err := strconv.Atoi(channels); err == nil {
|
||||
input.Channels = value
|
||||
}
|
||||
}
|
||||
input.Diarize = anyTruthy(payload.Diarize)
|
||||
input.KeyTerms = payload.KeyTerms
|
||||
input.FillerWords = anyTruthy(payload.FillerWords)
|
||||
input.VADThreshold = payload.VADThreshold
|
||||
} else {
|
||||
writeOpenAIError(c, http.StatusUnsupportedMediaType, "invalid_request", "STT 支持 multipart/form-data 或 application/json")
|
||||
return
|
||||
}
|
||||
if len(input.FileData) == 0 && strings.TrimSpace(input.URL) == "" {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "STT 必须提供 file 或 url")
|
||||
return
|
||||
}
|
||||
result, err := h.gateway.TranscribeSpeech(c.Request.Context(), input)
|
||||
if err != nil {
|
||||
writeGatewayError(c, err)
|
||||
return
|
||||
}
|
||||
h.writeMediaResult(c, result)
|
||||
}
|
||||
|
||||
func (h *Handler) createRealtimeClientSecret(c *gin.Context) {
|
||||
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, h.maxBodyBytes)
|
||||
if !isJSONRequest(c) {
|
||||
writeOpenAIError(c, http.StatusUnsupportedMediaType, "invalid_request", "realtime client secret 仅支持 application/json")
|
||||
return
|
||||
}
|
||||
var request realtimeClientSecretRequest
|
||||
if err := decodeSingleJSON(c.Request.Body, &request, false); err != nil {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "realtime client secret 请求无效")
|
||||
return
|
||||
}
|
||||
model := strings.TrimSpace(request.Model)
|
||||
if model == "" {
|
||||
model = "grok-voice-latest"
|
||||
}
|
||||
expiresAfter := 0
|
||||
if len(bytesTrim(request.ExpiresAfter)) > 0 {
|
||||
var wrapper struct {
|
||||
Seconds int `json:"seconds"`
|
||||
}
|
||||
if err := json.Unmarshal(request.ExpiresAfter, &wrapper); err == nil {
|
||||
expiresAfter = wrapper.Seconds
|
||||
}
|
||||
}
|
||||
clientKey, requestID, ok := requestIdentity(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
result, err := h.gateway.CreateRealtimeClientSecret(c.Request.Context(), gateway.RealtimeClientSecretInput{
|
||||
RequestID: requestID, ClientKey: clientKey, PublicModel: model, ExpiresAfter: expiresAfter, SessionJSON: request.Session,
|
||||
})
|
||||
if err != nil {
|
||||
writeGatewayError(c, err)
|
||||
return
|
||||
}
|
||||
h.writeMediaResult(c, result)
|
||||
}
|
||||
|
||||
func (h *Handler) createCustomVoice(c *gin.Context) {
|
||||
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, h.maxBodyBytes)
|
||||
clientKey, requestID, ok := requestIdentity(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := c.Request.ParseMultipartForm(h.maxBodyBytes); err != nil {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "custom voice 请求无效")
|
||||
return
|
||||
}
|
||||
name := strings.TrimSpace(c.PostForm("name"))
|
||||
if name == "" {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "name 不能为空")
|
||||
return
|
||||
}
|
||||
file, header, err := c.Request.FormFile("file")
|
||||
if err != nil {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "必须提供参考音频 file")
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
data, err := io.ReadAll(io.LimitReader(file, h.maxBodyBytes+1))
|
||||
if err != nil || int64(len(data)) > h.maxBodyBytes {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "读取参考音频失败")
|
||||
return
|
||||
}
|
||||
model := strings.TrimSpace(c.PostForm("model"))
|
||||
if model == "" {
|
||||
model = "grok-voice-latest"
|
||||
}
|
||||
input := gateway.CustomVoiceCreateInput{
|
||||
RequestID: requestID, ClientKey: clientKey, PublicModel: model, Name: name,
|
||||
Language: c.PostForm("language"), Gender: c.PostForm("gender"), Tone: c.PostForm("tone"), UseCase: c.PostForm("use_case"),
|
||||
FileData: data,
|
||||
}
|
||||
if header != nil {
|
||||
input.FileName = header.Filename
|
||||
input.FileMIME = header.Header.Get("Content-Type")
|
||||
}
|
||||
result, err := h.gateway.CreateCustomVoice(c.Request.Context(), input)
|
||||
if err != nil {
|
||||
writeGatewayError(c, err)
|
||||
return
|
||||
}
|
||||
h.writeMediaResult(c, result)
|
||||
}
|
||||
|
||||
func (h *Handler) listCustomVoices(c *gin.Context) {
|
||||
clientKey, requestID, ok := requestIdentity(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
model := strings.TrimSpace(c.Query("model"))
|
||||
if model == "" {
|
||||
model = "grok-voice-latest"
|
||||
}
|
||||
limit := 0
|
||||
if raw := strings.TrimSpace(c.Query("limit")); raw != "" {
|
||||
if value, err := strconv.Atoi(raw); err == nil {
|
||||
limit = value
|
||||
}
|
||||
}
|
||||
result, err := h.gateway.ListCustomVoices(c.Request.Context(), gateway.VoiceListInput{RequestID: requestID, ClientKey: clientKey, PublicModel: model}, limit, c.Query("pagination_token"))
|
||||
if err != nil {
|
||||
writeGatewayError(c, err)
|
||||
return
|
||||
}
|
||||
h.writeMediaResult(c, result)
|
||||
}
|
||||
|
||||
func (h *Handler) getCustomVoice(c *gin.Context) {
|
||||
clientKey, requestID, ok := requestIdentity(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
model := strings.TrimSpace(c.Query("model"))
|
||||
if model == "" {
|
||||
model = "grok-voice-latest"
|
||||
}
|
||||
result, err := h.gateway.GetCustomVoice(c.Request.Context(), gateway.CustomVoiceIDInput{RequestID: requestID, ClientKey: clientKey, PublicModel: model, VoiceID: c.Param("voiceId")})
|
||||
if err != nil {
|
||||
writeGatewayError(c, err)
|
||||
return
|
||||
}
|
||||
h.writeMediaResult(c, result)
|
||||
}
|
||||
|
||||
func (h *Handler) updateCustomVoice(c *gin.Context) {
|
||||
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, h.maxBodyBytes)
|
||||
if !isJSONRequest(c) {
|
||||
writeOpenAIError(c, http.StatusUnsupportedMediaType, "invalid_request", "custom voice 更新仅支持 application/json")
|
||||
return
|
||||
}
|
||||
var payload struct {
|
||||
Model string `json:"model"`
|
||||
Name *string `json:"name"`
|
||||
Language *string `json:"language"`
|
||||
Gender *string `json:"gender"`
|
||||
Tone *string `json:"tone"`
|
||||
UseCase *string `json:"use_case"`
|
||||
}
|
||||
if err := decodeSingleJSON(c.Request.Body, &payload, false); err != nil {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "custom voice 更新请求无效")
|
||||
return
|
||||
}
|
||||
model := strings.TrimSpace(payload.Model)
|
||||
if model == "" {
|
||||
model = "grok-voice-latest"
|
||||
}
|
||||
clientKey, requestID, ok := requestIdentity(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
result, err := h.gateway.UpdateCustomVoice(c.Request.Context(), gateway.CustomVoiceUpdateInput{
|
||||
RequestID: requestID, ClientKey: clientKey, PublicModel: model, VoiceID: c.Param("voiceId"),
|
||||
Name: payload.Name, Language: payload.Language, Gender: payload.Gender, Tone: payload.Tone, UseCase: payload.UseCase,
|
||||
})
|
||||
if err != nil {
|
||||
writeGatewayError(c, err)
|
||||
return
|
||||
}
|
||||
h.writeMediaResult(c, result)
|
||||
}
|
||||
|
||||
func (h *Handler) deleteCustomVoice(c *gin.Context) {
|
||||
clientKey, requestID, ok := requestIdentity(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
model := strings.TrimSpace(c.Query("model"))
|
||||
if model == "" {
|
||||
model = "grok-voice-latest"
|
||||
}
|
||||
result, err := h.gateway.DeleteCustomVoice(c.Request.Context(), gateway.CustomVoiceIDInput{RequestID: requestID, ClientKey: clientKey, PublicModel: model, VoiceID: c.Param("voiceId")})
|
||||
if err != nil {
|
||||
writeGatewayError(c, err)
|
||||
return
|
||||
}
|
||||
h.writeMediaResult(c, result)
|
||||
}
|
||||
|
||||
func (h *Handler) getCustomVoiceAudio(c *gin.Context) {
|
||||
clientKey, requestID, ok := requestIdentity(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
model := strings.TrimSpace(c.Query("model"))
|
||||
if model == "" {
|
||||
model = "grok-voice-latest"
|
||||
}
|
||||
result, err := h.gateway.GetCustomVoiceAudio(c.Request.Context(), gateway.CustomVoiceIDInput{RequestID: requestID, ClientKey: clientKey, PublicModel: model, VoiceID: c.Param("voiceId")})
|
||||
if err != nil {
|
||||
writeGatewayError(c, err)
|
||||
return
|
||||
}
|
||||
h.writeMediaResult(c, result)
|
||||
}
|
||||
|
||||
func bytesTrim(value json.RawMessage) []byte {
|
||||
return []byte(strings.TrimSpace(string(value)))
|
||||
}
|
||||
|
||||
func parseTruthy(value string) bool {
|
||||
switch strings.ToLower(strings.TrimSpace(value)) {
|
||||
case "1", "true", "yes", "on":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func anyTruthy(value any) bool {
|
||||
switch typed := value.(type) {
|
||||
case nil:
|
||||
return false
|
||||
case bool:
|
||||
return typed
|
||||
case string:
|
||||
return parseTruthy(typed)
|
||||
case float64:
|
||||
return typed != 0
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func anyString(value any) string {
|
||||
switch typed := value.(type) {
|
||||
case nil:
|
||||
return ""
|
||||
case string:
|
||||
return strings.TrimSpace(typed)
|
||||
case float64:
|
||||
return strconv.FormatInt(int64(typed), 10)
|
||||
case json.Number:
|
||||
return typed.String()
|
||||
default:
|
||||
return strings.TrimSpace(stringify(value))
|
||||
}
|
||||
}
|
||||
|
||||
func stringify(value any) string {
|
||||
data, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return strings.Trim(string(data), `"`)
|
||||
}
|
||||
|
||||
func firstNonEmpty(values ...string) string {
|
||||
for _, value := range values {
|
||||
if strings.TrimSpace(value) != "" {
|
||||
return strings.TrimSpace(value)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// keep middleware import used for request identity compatibility in package docs.
|
||||
var _ = middleware.ClientKey
|
||||
@@ -94,6 +94,14 @@ func inferenceBodyOperation(path string) string {
|
||||
return "image_generation"
|
||||
case "/v1/images/edits":
|
||||
return "image_edit"
|
||||
case "/v1/tts":
|
||||
return "tts"
|
||||
case "/v1/stt":
|
||||
return "stt"
|
||||
case "/v1/realtime/client_secrets":
|
||||
return "realtime_client_secret"
|
||||
case "/v1/custom-voices":
|
||||
return "custom_voices"
|
||||
case "/v1/videos/generations":
|
||||
return "video_generation"
|
||||
default:
|
||||
|
||||
@@ -21,7 +21,7 @@ const modelRouteValidator = hasShape({
|
||||
publicId: isString,
|
||||
provider: isOneOf("grok_build", "grok_web", "grok_console"),
|
||||
upstreamModel: isString,
|
||||
capability: isOneOf("responses", "chat", "image", "image_edit", "video"),
|
||||
capability: isOneOf("responses", "chat", "image", "image_edit", "video", "tts", "stt", "realtime"),
|
||||
origin: isOneOf("catalog", "discovered", "manual"),
|
||||
enabled: isBoolean,
|
||||
accountIds: isArrayOf(isString),
|
||||
@@ -35,7 +35,7 @@ const modelRouteValidator = hasShape({
|
||||
});
|
||||
const decodeModelRoute = createObjectDecoder<ModelRouteDTO>("model route", {
|
||||
id: isString, publicId: isString, provider: isOneOf("grok_build", "grok_web", "grok_console"), upstreamModel: isString,
|
||||
capability: isOneOf("responses", "chat", "image", "image_edit", "video"), origin: isOneOf("catalog", "discovered", "manual"),
|
||||
capability: isOneOf("responses", "chat", "image", "image_edit", "video", "tts", "stt", "realtime"), origin: isOneOf("catalog", "discovered", "manual"),
|
||||
enabled: isBoolean, accountIds: isArrayOf(isString), bindingMode: isBoolean, supportedAccounts: isNumber,
|
||||
syncedAccounts: isNumber, totalAccounts: isNumber, capabilityKnown: isBoolean, available: isBoolean, lastSyncedAt: isOptional(isString),
|
||||
});
|
||||
@@ -43,7 +43,7 @@ const decodeModelPage = createPaginatedDecoder<ModelRouteDTO>(modelRouteValidato
|
||||
const modelRouteGroupValidator = hasShape({
|
||||
key: isString,
|
||||
routes: (value) => Array.isArray(value) && value.length > 0 && value.every(modelRouteValidator),
|
||||
endpointCapabilities: isArrayOf(isOneOf("completions", "responses", "messages", "image", "image_edit", "video")),
|
||||
endpointCapabilities: isArrayOf(isOneOf("completions", "responses", "messages", "image", "image_edit", "video", "tts", "stt", "realtime")),
|
||||
});
|
||||
const decodeModelGroupPage = createPaginatedDecoder<ModelRouteGroupDTO>(modelRouteGroupValidator);
|
||||
const modelAccountValidator = hasShape({ id: isString, name: isString });
|
||||
|
||||
@@ -3,7 +3,7 @@ export type ModelRouteDTO = {
|
||||
publicId: string;
|
||||
provider: "grok_build" | "grok_web" | "grok_console";
|
||||
upstreamModel: string;
|
||||
capability: "responses" | "chat" | "image" | "image_edit" | "video";
|
||||
capability: "responses" | "chat" | "image" | "image_edit" | "video" | "tts" | "stt" | "realtime";
|
||||
origin: "catalog" | "discovered" | "manual";
|
||||
enabled: boolean;
|
||||
accountIds: string[];
|
||||
@@ -16,7 +16,7 @@ export type ModelRouteDTO = {
|
||||
lastSyncedAt?: string;
|
||||
};
|
||||
|
||||
export type ModelEndpointCapability = "completions" | "responses" | "messages" | "image" | "image_edit" | "video";
|
||||
export type ModelEndpointCapability = "completions" | "responses" | "messages" | "image" | "image_edit" | "video" | "tts" | "stt" | "realtime";
|
||||
|
||||
export type ModelRouteGroupDTO = {
|
||||
key: string;
|
||||
|
||||
@@ -157,6 +157,143 @@ export async function getVideo(input: {
|
||||
return status.video ? { ...status, video: { ...status.video, url: resolveMediaURL(status.video.url) } } : status;
|
||||
}
|
||||
|
||||
|
||||
export type VoiceInfo = {
|
||||
voiceId: string;
|
||||
name: string;
|
||||
language?: string;
|
||||
};
|
||||
|
||||
export type TTSResult = {
|
||||
url: string;
|
||||
contentType: string;
|
||||
duration?: number;
|
||||
};
|
||||
|
||||
export type STTResult = {
|
||||
text: string;
|
||||
language?: string;
|
||||
duration?: number;
|
||||
words?: Array<{ text: string; start: number; end: number; speaker?: number }>;
|
||||
};
|
||||
|
||||
export async function listVoices(input: {
|
||||
apiKey: string;
|
||||
model?: string;
|
||||
signal?: AbortSignal;
|
||||
}): Promise<VoiceInfo[]> {
|
||||
const query = input.model ? `?model=${encodeURIComponent(input.model)}` : "";
|
||||
const payload = await publicApiRequest(input.apiKey, `/tts/voices${query}`, { method: "GET", signal: input.signal });
|
||||
if (!isRecord(payload) || !Array.isArray(payload.voices)) {
|
||||
throw new CreativeApiError(200, "The voice list response was invalid", "invalid_response");
|
||||
}
|
||||
return payload.voices.map((item) => {
|
||||
if (!isRecord(item) || typeof item.voice_id !== "string") {
|
||||
throw new CreativeApiError(200, "The voice list response was invalid", "invalid_response");
|
||||
}
|
||||
return {
|
||||
voiceId: item.voice_id,
|
||||
name: typeof item.name === "string" ? item.name : item.voice_id,
|
||||
language: typeof item.language === "string" ? item.language : undefined,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export async function synthesizeSpeech(input: {
|
||||
apiKey: string;
|
||||
model: string;
|
||||
text: string;
|
||||
voiceId: string;
|
||||
language: string;
|
||||
signal?: AbortSignal;
|
||||
}): Promise<TTSResult> {
|
||||
const response = await fetch("/v1/tts", {
|
||||
method: "POST",
|
||||
headers: new Headers({
|
||||
Accept: "application/json, audio/*",
|
||||
Authorization: `Bearer ${input.apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
}),
|
||||
body: JSON.stringify({
|
||||
model: input.model,
|
||||
text: input.text,
|
||||
voice_id: input.voiceId,
|
||||
language: input.language,
|
||||
}),
|
||||
signal: input.signal,
|
||||
});
|
||||
const contentType = response.headers.get("content-type") || "";
|
||||
if (!response.ok) {
|
||||
const responseText = await response.text();
|
||||
const payload = parseJSON(responseText);
|
||||
const error = readError(payload);
|
||||
throw new CreativeApiError(response.status, error.message ?? (responseText.trim() || response.statusText || `HTTP ${response.status}`), error.code);
|
||||
}
|
||||
if (contentType.includes("application/json")) {
|
||||
const payload = await response.json();
|
||||
if (!isRecord(payload) || typeof payload.audio !== "string") {
|
||||
throw new CreativeApiError(200, "The TTS response was invalid", "invalid_response");
|
||||
}
|
||||
const mime = typeof payload.content_type === "string" ? payload.content_type : "audio/mpeg";
|
||||
const url = `data:${mime};base64,${payload.audio}`;
|
||||
return {
|
||||
url,
|
||||
contentType: mime,
|
||||
duration: typeof payload.duration === "number" ? payload.duration : undefined,
|
||||
};
|
||||
}
|
||||
const buffer = await response.arrayBuffer();
|
||||
const mime = contentType || "audio/mpeg";
|
||||
const blob = new Blob([buffer], { type: mime });
|
||||
return { url: URL.createObjectURL(blob), contentType: mime };
|
||||
}
|
||||
|
||||
export async function transcribeSpeech(input: {
|
||||
apiKey: string;
|
||||
model: string;
|
||||
file: File;
|
||||
language?: string;
|
||||
signal?: AbortSignal;
|
||||
}): Promise<STTResult> {
|
||||
const form = new FormData();
|
||||
form.append("model", input.model);
|
||||
if (input.language) form.append("language", input.language);
|
||||
form.append("format", "true");
|
||||
form.append("file", input.file, input.file.name);
|
||||
const response = await fetch("/v1/stt", {
|
||||
method: "POST",
|
||||
headers: new Headers({ Accept: "application/json", Authorization: `Bearer ${input.apiKey}` }),
|
||||
body: form,
|
||||
signal: input.signal,
|
||||
});
|
||||
const responseText = await response.text();
|
||||
const payload = parseJSON(responseText);
|
||||
if (!response.ok) {
|
||||
const error = readError(payload);
|
||||
throw new CreativeApiError(response.status, error.message ?? (responseText.trim() || response.statusText || `HTTP ${response.status}`), error.code);
|
||||
}
|
||||
if (!isRecord(payload) || typeof payload.text !== "string") {
|
||||
throw new CreativeApiError(200, "The STT response was invalid", "invalid_response");
|
||||
}
|
||||
const words = Array.isArray(payload.words)
|
||||
? payload.words.flatMap((item) => {
|
||||
if (!isRecord(item) || typeof item.text !== "string") return [];
|
||||
return [{
|
||||
text: item.text,
|
||||
start: typeof item.start === "number" ? item.start : 0,
|
||||
end: typeof item.end === "number" ? item.end : 0,
|
||||
speaker: typeof item.speaker === "number" ? item.speaker : undefined,
|
||||
}];
|
||||
})
|
||||
: undefined;
|
||||
return {
|
||||
text: payload.text,
|
||||
language: typeof payload.language === "string" ? payload.language : undefined,
|
||||
duration: typeof payload.duration === "number" ? payload.duration : undefined,
|
||||
words,
|
||||
};
|
||||
}
|
||||
|
||||
async function publicApiRequest(apiKey: string, path: string, options: RequestOptions): Promise<unknown> {
|
||||
const headers = new Headers({ Accept: "application/json", Authorization: `Bearer ${apiKey}` });
|
||||
let body: string | undefined;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||
import { ArrowUp, BrainCircuit, Check, CheckCircle2, Clock3, ExternalLink, Globe, History, ImageIcon, ImagePlus, ImageUpscale, Images, Loader2, MessageSquareText, Pencil, RefreshCw, Sparkle, Square, SquarePen, Trash2, TriangleAlert, TvMinimal, Upload, Video, Wrench, X } from "lucide-react";
|
||||
import { ArrowUp, AudioLines, BrainCircuit, Check, CheckCircle2, Clock3, ExternalLink, Globe, History, ImageIcon, ImagePlus, ImageUpscale, Images, Loader2, MessageSquareText, Mic, Pencil, RefreshCw, Sparkle, Square, SquarePen, Trash2, TriangleAlert, TvMinimal, Upload, Video, Wrench, X } from "lucide-react";
|
||||
import { marked } from "marked";
|
||||
import { useEffect, useMemo, useRef, useState, type FormEvent, type KeyboardEvent, type ReactNode } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
@@ -24,19 +24,25 @@ import {
|
||||
createVideo,
|
||||
generateImage,
|
||||
getVideo,
|
||||
listVoices,
|
||||
synthesizeSpeech,
|
||||
transcribeSpeech,
|
||||
type ChatMessage,
|
||||
type ChatStreamSnapshot,
|
||||
type ChatToolActivity,
|
||||
type ImageResult,
|
||||
type ReasoningEffort,
|
||||
type STTResult,
|
||||
type TTSResult,
|
||||
type VideoStatus,
|
||||
type VoiceInfo,
|
||||
} from "@/features/creative-console/creative-console-api";
|
||||
import { getClientKeySecret, listClientKeys, type ClientKeyDTO } from "@/features/client-keys/client-keys-api";
|
||||
import { importVideoInputFromURL, uploadVideoInput } from "@/features/media/media-api";
|
||||
import { PageHeader } from "@/shared/components/page-header";
|
||||
import { cn } from "@/shared/lib/cn";
|
||||
|
||||
type CreativeMode = "chat" | "image" | "video";
|
||||
type CreativeMode = "chat" | "image" | "video" | "voice";
|
||||
type ConversationMessage = ChatMessage & {
|
||||
id: string;
|
||||
reasoning?: string;
|
||||
@@ -94,7 +100,7 @@ export function CreativeConsolePage() {
|
||||
const [selectedKeyId, setSelectedKeyId] = useState("");
|
||||
const [secretState, setSecretState] = useState<SecretState | null>(null);
|
||||
const [keyError, setKeyError] = useState("");
|
||||
const [selectedModels, setSelectedModels] = useState<Record<CreativeMode, string>>({ chat: "", image: "", video: "" });
|
||||
const [selectedModels, setSelectedModels] = useState<Record<CreativeMode, string>>({ chat: "", image: "", video: "", voice: "" });
|
||||
const [chatToolbarElement, setChatToolbarElement] = useState<HTMLDivElement | null>(null);
|
||||
const requestedSecretKeyRef = useRef("");
|
||||
|
||||
@@ -124,11 +130,13 @@ export function CreativeConsolePage() {
|
||||
chat: uniqueModelsByPublicID(permittedModels.filter((model) => model.capability === "chat" || model.capability === "responses")),
|
||||
image: uniqueModelsByPublicID(permittedModels.filter((model) => model.capability === "image")),
|
||||
video: uniqueModelsByPublicID(permittedModels.filter((model) => model.capability === "video")),
|
||||
voice: uniqueModelsByPublicID(permittedModels.filter((model) => model.capability === "tts" || model.capability === "stt" || model.capability === "realtime")),
|
||||
}), [permittedModels]);
|
||||
const effectiveModels = useMemo<Record<CreativeMode, string>>(() => ({
|
||||
chat: modelGroups.chat.some((model) => model.publicId === selectedModels.chat) ? selectedModels.chat : modelGroups.chat[0]?.publicId ?? "",
|
||||
image: modelGroups.image.some((model) => model.publicId === selectedModels.image) ? selectedModels.image : modelGroups.image[0]?.publicId ?? "",
|
||||
video: modelGroups.video.some((model) => model.publicId === selectedModels.video) ? selectedModels.video : modelGroups.video[0]?.publicId ?? "",
|
||||
voice: modelGroups.voice.some((model) => model.publicId === selectedModels.voice) ? selectedModels.voice : modelGroups.voice[0]?.publicId ?? "",
|
||||
}), [modelGroups, selectedModels]);
|
||||
|
||||
const secretMutation = useMutation({
|
||||
@@ -193,6 +201,7 @@ export function CreativeConsolePage() {
|
||||
<TabsTrigger className="flex-1 gap-1.5 rounded-full px-3 lg:min-w-20 [&_svg]:size-3.5" value="chat"><MessageSquareText />{t("creativeConsole.modes.chat")}</TabsTrigger>
|
||||
<TabsTrigger className="flex-1 gap-1.5 rounded-full px-3 lg:min-w-20 [&_svg]:size-3.5" value="image"><ImageIcon />{t("creativeConsole.modes.image")}</TabsTrigger>
|
||||
<TabsTrigger className="flex-1 gap-1.5 rounded-full px-3 lg:min-w-20 [&_svg]:size-3.5" value="video"><Video />{t("creativeConsole.modes.video")}</TabsTrigger>
|
||||
<TabsTrigger className="flex-1 gap-1.5 rounded-full px-3 lg:min-w-20 [&_svg]:size-3.5" value="voice"><AudioLines />{t("creativeConsole.modes.voice")}</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
|
||||
@@ -220,6 +229,7 @@ export function CreativeConsolePage() {
|
||||
<div className="h-full" hidden={mode !== "chat"}><ChatPanel key={effectiveKeyId || "default"} storageScope={effectiveKeyId || "default"} toolbarElement={chatToolbarElement} {...panelProps("chat")} /></div>
|
||||
<div className="h-full" hidden={mode !== "image"}><ImagePanel {...panelProps("image")} /></div>
|
||||
<div className="h-full" hidden={mode !== "video"}><VideoPanel {...panelProps("video")} /></div>
|
||||
<div className="h-full" hidden={mode !== "voice"}><VoicePanel {...panelProps("voice")} /></div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
@@ -1071,6 +1081,132 @@ function VideoResult({ requestId, status, loading, error, onRetry }: { requestId
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
function VoicePanel({ apiKey, model, modelOptions, onModelChange }: CreativePanelProps) {
|
||||
const { t } = useTranslation();
|
||||
const [subMode, setSubMode] = useState<"tts" | "stt">("tts");
|
||||
const [prompt, setPrompt] = useState("");
|
||||
const [language, setLanguage] = useState("zh");
|
||||
const [voiceId, setVoiceId] = useState("eve");
|
||||
const [audioFile, setAudioFile] = useState<File | null>(null);
|
||||
const [ttsResult, setTtsResult] = useState<TTSResult | null>(null);
|
||||
const [sttResult, setSttResult] = useState<STTResult | null>(null);
|
||||
const fileInputRef = useRef<HTMLInputElement | null>(null);
|
||||
|
||||
const voicesQuery = useQuery({
|
||||
queryKey: ["creative-console", "voices", apiKey, model],
|
||||
queryFn: ({ signal }) => listVoices({ apiKey, model: model || "grok-voice-latest", signal }),
|
||||
enabled: Boolean(apiKey),
|
||||
staleTime: 60_000,
|
||||
});
|
||||
const voices = voicesQuery.data ?? [];
|
||||
useEffect(() => {
|
||||
if (voices.length === 0) return;
|
||||
if (!voices.some((voice) => voice.voiceId === voiceId)) {
|
||||
setVoiceId(voices[0].voiceId);
|
||||
}
|
||||
}, [voiceId, voices]);
|
||||
|
||||
const ttsMutation = useMutation({
|
||||
mutationFn: () => synthesizeSpeech({ apiKey, model: model || "grok-voice-latest", text: prompt.trim(), voiceId, language }),
|
||||
onSuccess: (result) => {
|
||||
setTtsResult(result);
|
||||
setSttResult(null);
|
||||
},
|
||||
});
|
||||
const sttMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
if (!audioFile) throw new Error(t("creativeConsole.errors.noAudio"));
|
||||
return transcribeSpeech({ apiKey, model: model || "grok-transcribe", file: audioFile, language });
|
||||
},
|
||||
onSuccess: (result) => {
|
||||
setSttResult(result);
|
||||
setTtsResult(null);
|
||||
},
|
||||
});
|
||||
|
||||
function submit(event: FormEvent) {
|
||||
event.preventDefault();
|
||||
if (!apiKey || !model) return;
|
||||
if (subMode === "tts") {
|
||||
if (!prompt.trim() || ttsMutation.isPending) return;
|
||||
ttsMutation.reset();
|
||||
ttsMutation.mutate();
|
||||
return;
|
||||
}
|
||||
if (!audioFile || sttMutation.isPending) return;
|
||||
sttMutation.reset();
|
||||
sttMutation.mutate();
|
||||
}
|
||||
|
||||
const busy = ttsMutation.isPending || sttMutation.isPending;
|
||||
const languageOptions = ["auto", "zh", "en", "ja", "ko", "fr", "de", "es"] as const;
|
||||
|
||||
return (
|
||||
<div className="flex h-full min-h-0 flex-col">
|
||||
<div className="min-h-0 flex-1 overflow-y-auto px-1 py-4">
|
||||
{!ttsResult && !sttResult && !busy ? <WelcomeState title={t("creativeConsole.welcomeVoice")} /> : null}
|
||||
{busy ? <LoadingResult text={subMode === "tts" ? t("creativeConsole.synthesizing") : t("creativeConsole.transcribing")} /> : null}
|
||||
{ttsResult ? (
|
||||
<div className="mx-auto flex w-full max-w-3xl flex-col gap-3 rounded-2xl bg-secondary/40 p-4">
|
||||
<audio controls src={ttsResult.url} className="w-full" />
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 text-xs text-muted-foreground">
|
||||
<span>{ttsResult.contentType}{typeof ttsResult.duration === "number" ? ` · ${ttsResult.duration.toFixed(2)}s` : ""}</span>
|
||||
<Button variant="secondary" size="sm" asChild><a href={ttsResult.url} download="speech.mp3"><ExternalLink />{t("creativeConsole.open")}</a></Button>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
{sttResult ? (
|
||||
<div className="mx-auto w-full max-w-3xl space-y-3 rounded-2xl bg-secondary/40 p-4">
|
||||
<p className="whitespace-pre-wrap text-sm leading-6">{sttResult.text}</p>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{[sttResult.language, typeof sttResult.duration === "number" ? `${sttResult.duration.toFixed(2)}s` : ""].filter(Boolean).join(" · ")}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
{ttsMutation.isError ? <div className="px-2 text-[11px] text-destructive">{ttsMutation.error.message}</div> : null}
|
||||
{sttMutation.isError ? <div className="px-2 text-[11px] text-destructive">{sttMutation.error.message}</div> : null}
|
||||
</div>
|
||||
<form onSubmit={submit} className={composerClassName}>
|
||||
<div className="flex items-center gap-2 px-3 pt-3">
|
||||
<Button type="button" size="sm" variant={subMode === "tts" ? "secondary" : "ghost"} className="h-8 gap-1.5" onClick={() => setSubMode("tts")}><AudioLines />{t("creativeConsole.synthesize")}</Button>
|
||||
<Button type="button" size="sm" variant={subMode === "stt" ? "secondary" : "ghost"} className="h-8 gap-1.5" onClick={() => setSubMode("stt")}><Mic />{t("creativeConsole.transcribe")}</Button>
|
||||
</div>
|
||||
{subMode === "tts" ? (
|
||||
<Textarea id="voice-prompt" value={prompt} onChange={(event) => setPrompt(event.target.value)} placeholder={t("creativeConsole.voicePlaceholder")} className="min-h-24 resize-none border-0 bg-transparent px-4 py-3 text-sm focus-visible:ring-0" />
|
||||
) : (
|
||||
<div className="flex items-center gap-2 px-4 py-3">
|
||||
<input ref={fileInputRef} type="file" accept="audio/*,.mp3,.wav,.m4a,.ogg,.flac" className="hidden" onChange={(event) => setAudioFile(event.target.files?.[0] ?? null)} />
|
||||
<Button type="button" variant="secondary" size="sm" onClick={() => fileInputRef.current?.click()}><Upload />{audioFile ? audioFile.name : t("creativeConsole.uploadAudio")}</Button>
|
||||
{audioFile ? <Button type="button" variant="ghost" size="icon" aria-label={t("creativeConsole.clearAudio")} onClick={() => setAudioFile(null)}><X /></Button> : null}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center justify-between gap-2 px-3 pb-3">
|
||||
<div className="flex min-w-0 flex-wrap items-center gap-1">
|
||||
<CompactModelSelect value={model} models={modelOptions} onChange={onModelChange} />
|
||||
<CompactSelect value={language} options={languageOptions} onChange={setLanguage} ariaLabel={t("creativeConsole.voiceLanguage")} />
|
||||
{subMode === "tts" ? (
|
||||
<Select value={voiceId} onValueChange={setVoiceId} disabled={voices.length === 0 && voicesQuery.isPending}>
|
||||
<SelectTrigger className="h-8 w-auto max-w-40 gap-1 border-0 bg-transparent px-2 shadow-none hover:bg-secondary/70 focus:ring-0" aria-label={t("creativeConsole.voiceId")}>
|
||||
<SelectValue placeholder={t("creativeConsole.voiceId")} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{(voices.length > 0 ? voices : [{ voiceId: "eve", name: "eve" } as VoiceInfo]).map((voice) => (
|
||||
<SelectItem key={voice.voiceId} value={voice.voiceId}>{voice.name || voice.voiceId}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
) : null}
|
||||
</div>
|
||||
<Button type="submit" size="icon" aria-label={subMode === "tts" ? t("creativeConsole.synthesize") : t("creativeConsole.transcribe")} disabled={!apiKey || !model || busy || (subMode === "tts" ? !prompt.trim() : !audioFile)}>
|
||||
{busy ? <Loader2 className="animate-spin" /> : <ArrowUp />}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function WelcomeState({ title }: { title: string }) {
|
||||
return (
|
||||
<div className="flex min-h-[20rem] items-center justify-center px-6 text-center">
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import type { TFunction } from "i18next";
|
||||
import { Clapperboard, Image as ImageIcon, MessagesSquare, MessageSquareText, MoreHorizontal, Paintbrush, Pencil, Plus, RefreshCw, Search, SquareTerminal, Trash2 } from "lucide-react";
|
||||
import { AudioLines, Clapperboard, Image as ImageIcon, MessagesSquare, MessageSquareText, Mic, MoreHorizontal, Paintbrush, Pencil, Plus, Radio, RefreshCw, Search, SquareTerminal, Trash2 } from "lucide-react";
|
||||
import { useMemo, useState } from "react";
|
||||
import { useForm, useWatch } from "react-hook-form";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -53,7 +53,7 @@ export function ModelsPage() {
|
||||
publicId: z.string().min(1, t("errors.required")),
|
||||
provider: z.enum(["grok_build", "grok_web", "grok_console"]),
|
||||
upstreamModel: z.string().min(1, t("errors.required")),
|
||||
capability: z.enum(["responses", "chat", "image", "image_edit", "video"]),
|
||||
capability: z.enum(["responses", "chat", "image", "image_edit", "video", "tts", "stt", "realtime"]),
|
||||
enabled: z.boolean(),
|
||||
bindingMode: z.boolean(),
|
||||
accountIds: z.array(z.string()),
|
||||
@@ -473,6 +473,9 @@ const endpointCapabilityMetadata = {
|
||||
image: { icon: ImageIcon, method: "POST", path: "/v1/images/generations", color: "text-emerald-600 dark:text-emerald-400" },
|
||||
image_edit: { icon: Paintbrush, method: "POST", path: "/v1/images/edits", color: "text-amber-700 dark:text-amber-400" },
|
||||
video: { icon: Clapperboard, method: "POST", path: "/v1/videos/generations", color: "text-rose-600 dark:text-rose-400" },
|
||||
tts: { icon: AudioLines, method: "POST", path: "/v1/tts", color: "text-cyan-700 dark:text-cyan-400" },
|
||||
stt: { icon: Mic, method: "POST", path: "/v1/stt", color: "text-teal-700 dark:text-teal-400" },
|
||||
realtime: { icon: Radio, method: "POST", path: "/v1/realtime/client_secrets", color: "text-sky-700 dark:text-sky-400" },
|
||||
} as const;
|
||||
|
||||
type ModelRouteGroup = {
|
||||
@@ -533,5 +536,8 @@ function displayCapabilityLabel(capability: ModelDisplayCapability, t: TFunction
|
||||
image: t("models.capabilityImage"),
|
||||
image_edit: t("models.capabilityImageEdit"),
|
||||
video: t("models.capabilityVideo"),
|
||||
tts: t("models.capabilityTTS"),
|
||||
stt: t("models.capabilitySTT"),
|
||||
realtime: t("models.capabilityRealtime"),
|
||||
}[capability];
|
||||
}
|
||||
@@ -182,12 +182,12 @@ const resources = {
|
||||
},
|
||||
creativeConsole: {
|
||||
title: "创作控制台",
|
||||
description: "使用已创建的客户端密钥直接测试聊天、图片和视频生成。",
|
||||
description: "使用已创建的客户端密钥直接测试聊天、图片、视频和语音。",
|
||||
promotion: "想要更完整的 AI 创作体验?试试我开发的另一个项目 {{product}}:开箱即用的轻量 Web Chat,支持多模型对话与图片生成,静态运行时仅约 34 MB。",
|
||||
promotionAction: "了解 DEEIX Chat",
|
||||
clientKey: "客户端密钥",
|
||||
selectKey: "选择客户端密钥",
|
||||
modes: { chat: "聊天", image: "图片", video: "视频" },
|
||||
modes: { chat: "聊天", image: "图片", video: "视频", voice: "语音" },
|
||||
welcome: "今天想创作什么?",
|
||||
welcomeImage: "描述你的想法,生成一幅图片",
|
||||
welcomeVideo: "描述你的想法,生成一段视频",
|
||||
@@ -210,6 +210,18 @@ const resources = {
|
||||
chatPlaceholder: "输入要发送给模型的内容。",
|
||||
imagePlaceholder: "描述要生成的画面、主体、风格和细节。",
|
||||
videoPlaceholder: "描述视频画面、动作、镜头和节奏。",
|
||||
voicePlaceholder: "输入要合成的文本,或上传音频进行识别。",
|
||||
welcomeVoice: "选择音色并开始语音创作",
|
||||
synthesizing: "正在合成语音…",
|
||||
transcribing: "正在识别语音…",
|
||||
uploadAudio: "上传音频",
|
||||
clearAudio: "清除音频",
|
||||
|
||||
synthesize: "合成语音",
|
||||
transcribe: "识别语音",
|
||||
voiceLanguage: "语言",
|
||||
voiceId: "音色",
|
||||
|
||||
send: "发送",
|
||||
messageList: "对话消息",
|
||||
scrollToLatest: "滚动到最新消息",
|
||||
@@ -260,6 +272,7 @@ const resources = {
|
||||
noKeys: "没有可用的已启用客户端密钥,请先创建或启用密钥。",
|
||||
noModels: "当前模式没有可用模型,请确认模型已启用且账号池可服务。",
|
||||
videoFailed: "视频生成失败",
|
||||
noAudio: "请先选择音频文件",
|
||||
},
|
||||
},
|
||||
media: {
|
||||
@@ -1252,12 +1265,12 @@ const resources = {
|
||||
nav: { dashboard: "Dashboard", accounts: "Accounts", models: "Models", clientKeys: "Client keys", creativeConsole: "Creative console", gallery: "Gallery", videoGallery: "Video Gallery", audits: "Request audits", qualityGuard: "Quality guard", docs: "Documentation", settings: "Settings" },
|
||||
creativeConsole: {
|
||||
title: "Creative console",
|
||||
description: "Use an existing client key to test chat, image, and video generation directly.",
|
||||
description: "Use an existing client key to test chat, image, video, and voice directly.",
|
||||
promotion: "Looking for a more complete AI creation experience? Try another project I built, {{product}}: a lightweight, ready-to-deploy Web Chat for multi-model conversations and image generation with a static runtime footprint of about 34 MB.",
|
||||
promotionAction: "Explore DEEIX Chat",
|
||||
clientKey: "Client key",
|
||||
selectKey: "Select a client key",
|
||||
modes: { chat: "Chat", image: "Image", video: "Video" },
|
||||
modes: { chat: "Chat", image: "Image", video: "Video", voice: "Voice" },
|
||||
welcome: "What would you like to create today?",
|
||||
welcomeImage: "Describe an idea and create an image",
|
||||
welcomeVideo: "Describe an idea and create a video",
|
||||
@@ -1280,6 +1293,16 @@ const resources = {
|
||||
chatPlaceholder: "Enter the message to send to the model.",
|
||||
imagePlaceholder: "Describe the scene, subject, style, and details to generate.",
|
||||
videoPlaceholder: "Describe the video scene, motion, camera, and pacing.",
|
||||
voicePlaceholder: "Enter text to synthesize, or upload audio for transcription.",
|
||||
welcomeVoice: "Choose a voice and start creating audio",
|
||||
synthesizing: "Synthesizing speech…",
|
||||
transcribing: "Transcribing speech…",
|
||||
uploadAudio: "Upload audio",
|
||||
clearAudio: "Clear audio",
|
||||
synthesize: "Synthesize",
|
||||
transcribe: "Transcribe",
|
||||
voiceLanguage: "Language",
|
||||
voiceId: "Voice",
|
||||
send: "Send",
|
||||
messageList: "Conversation messages",
|
||||
scrollToLatest: "Scroll to latest message",
|
||||
@@ -1330,6 +1353,7 @@ const resources = {
|
||||
noKeys: "No enabled client keys are available. Create or enable a key first.",
|
||||
noModels: "No model is available for this mode. Confirm that models are enabled and the account pool can serve them.",
|
||||
videoFailed: "Video generation failed",
|
||||
noAudio: "Choose an audio file first",
|
||||
},
|
||||
},
|
||||
media: { images: { title: "Gallery", description: "Browse generated image assets", search: "Search ID, type, or hash", empty: "No images", noMatches: "No matching images", totalImages: "Total images", totalBytes: "Storage", pageSummary: "Showing {{count}} / {{total}}", openImage: "Open image {{id}}", deleteTitle: "Delete {{count}} selected images?", deleteDescription: "The image files and gallery records will be permanently removed, and existing image links will stop working. This cannot be undone.", deleted: "Deleted {{count}} images" }, videos: { title: "Video Gallery", description: "View video generation job records", search: "Search prompt or ID", empty: "No video jobs", statusFilter: "Status filter", totalJobs: "Total jobs", queued: "Queued", inProgress: "In progress", completed: "Completed", failed: "Failed", prompt: "Prompt", model: "Model", status: "Status", progress: "Progress", statusProgress: "Status / progress", spec: "Spec", owner: "Owner", createdAt: "Created", completedAt: "Completed", time: "Time", createdShort: "Created", completedShort: "Done", preview: "Preview video", previewTitle: "Video preview", previewUnavailable: "Local video unavailable", deleteTitle: "Delete {{count}} video records?", deleteDescription: "The task records and their local videos will be permanently removed, and existing video links will stop working. This cannot be undone.", deleted: "Deleted {{count}} video records", seconds: "{{count}} sec", pageSummary: "Showing {{count}} / {{total}}" }, videoStatus: { queued: "Queued", in_progress: "In progress", completed: "Completed", failed: "Failed" } },
|
||||
@@ -1696,6 +1720,9 @@ Object.assign(resources["zh-CN"].translation.models as unknown as Record<string,
|
||||
capabilityImage: "Image",
|
||||
capabilityImageEdit: "Image Edit",
|
||||
capabilityVideo: "Video",
|
||||
capabilityTTS: "TTS",
|
||||
capabilitySTT: "STT",
|
||||
capabilityRealtime: "Realtime",
|
||||
automaticAccounts: "自动账号池",
|
||||
mixedAccounts: "混合账号池",
|
||||
partiallyEnabled: "部分启用",
|
||||
@@ -1712,6 +1739,9 @@ Object.assign(resources.en.translation.models as unknown as Record<string, strin
|
||||
capabilityImage: "Image",
|
||||
capabilityImageEdit: "Image Edit",
|
||||
capabilityVideo: "Video",
|
||||
capabilityTTS: "TTS",
|
||||
capabilitySTT: "STT",
|
||||
capabilityRealtime: "Realtime",
|
||||
automaticAccounts: "Automatic pool",
|
||||
mixedAccounts: "Mixed account pools",
|
||||
partiallyEnabled: "Partially enabled",
|
||||
|
||||
Reference in new issue
Block a user