diff --git a/acceleration/internal/routing/call.go b/acceleration/internal/routing/call.go index 2b6b6650c6..7fdcd49eeb 100644 --- a/acceleration/internal/routing/call.go +++ b/acceleration/internal/routing/call.go @@ -56,6 +56,11 @@ type Meter struct { // longer, such as a picture a queued provider takes minutes over, holds it for as long as // it may run, or concurrent work could spend past a limit once the hold lapsed. ReserveFor time.Duration + // Recorded, when set, is told how a Call ended once its row is recorded: the stat the row + // was made of and what the row costs, priced as Record prices it (free work and a quoted + // cost included), for a line logged beside the row. It is told of a failure and a panic + // too, and not of work Omit leaves out. Nil tells nobody. + Recorded func(stat Stat, costMicros int64) } // ReserveTTL is how long what a unit of request-and-answer work may cost is set aside before @@ -130,6 +135,10 @@ func Call[R pricing.Metered](ctx context.Context, meter Meter, ask func(context. if reserved != uuid.Nil && (omitted || stat.UsageID != reserved) { meter.Recorder.Release(reserved) } + // Last, so a hook that panics leaves the row queued and the reservation let go. + if !omitted && meter.Recorded != nil { + meter.Recorded(stat, meter.cost(stat)) + } }() result, err := ask(ctx) @@ -222,6 +231,15 @@ func (m Meter) record(stat Stat) { } } +// cost is what the stat's row costs, priced as Record prices it. Zero with no recorder. +func (m Meter) cost(stat Stat) int64 { + if m.Recorder == nil { + return 0 + } + request, _ := m.Recorder.price(m.Config, stat) + return request.CostMicros +} + func (m Meter) code(err error) string { if m.Code == nil { return "provider_error" diff --git a/acceleration/internal/routing/call_integration_test.go b/acceleration/internal/routing/call_integration_test.go index a60f92f073..ceadf5712f 100644 --- a/acceleration/internal/routing/call_integration_test.go +++ b/acceleration/internal/routing/call_integration_test.go @@ -13,6 +13,7 @@ import ( "time" "github.com/google/uuid" + "github.com/prometheus/client_golang/prometheus/testutil" "github.com/stretchr/testify/suite" "github.com/GetStream/Vision-Agents/acceleration/internal/alerts" @@ -325,3 +326,49 @@ func (s *CallSuite) TestAMeterNamesTheRowsAttributes() { s.Equal(map[string]string{"parent_session": "session-1"}, s.only(meter).Attributes) } + +// The row of free work costs nothing, and the row of a quoted fee costs the fee resold: +// neither is what its quantities would cost from the price list (Recorder.QuoteStat), 2,000 +// and nothing. +func (s *CallSuite) TestARecordedHookIsToldWhatTheStoredRowCosts() { + free := s.meter(priced) + free.Free = true + quoted := s.meter(number) + quoted.CostMicros = 1_150_000 + for name, meter := range map[string]Meter{"priced": s.meter(priced), "free": free, "quoted": quoted} { + var costs []int64 + meter.Recorded = func(_ Stat, costMicros int64) { costs = append(costs, costMicros) } + + _, err := Call(s.ctx, meter, func(context.Context) (used, error) { return used{pricing.InputTokens: 1_000}, nil }) + s.Require().NoError(err, name) + + row := s.only(meter) + s.Equal([]int64{row.CostMicros}, costs, "%s: the line says what the row costs", name) + switch name { + case "priced": + s.EqualValues(2_000, row.CostMicros) + case "free": + s.Zero(row.CostMicros) + case "quoted": + s.Positive(row.CostMicros) + } + } +} + +// A refused user id is counted once for the row: the line's pricing must not count it again. +func (s *CallSuite) TestARecordedHookCountsARefusedUserIDOncePerRow() { + for id, reason := range refusedUsers { + meter := s.meter(priced) + meter.Owner.UserID = id + told := 0 + meter.Recorded = func(Stat, int64) { told++ } + before := testutil.ToFloat64(usageUserIDDropped.WithLabelValues(reason)) + + _, err := Call(s.ctx, meter, func(context.Context) (used, error) { return used{"input_tokens": 1_000}, nil }) + + s.Require().NoError(err) + s.Equal(1, told) + s.Empty(s.only(meter).UserID) + s.Equal(1.0, testutil.ToFloat64(usageUserIDDropped.WithLabelValues(reason))-before, reason) + } +} diff --git a/acceleration/internal/routing/call_test.go b/acceleration/internal/routing/call_test.go index 3768808b24..0bc290a899 100644 --- a/acceleration/internal/routing/call_test.go +++ b/acceleration/internal/routing/call_test.go @@ -1,10 +1,14 @@ package routing import ( + "bytes" "context" + "errors" + "log/slog" "testing" "github.com/stretchr/testify/require" + "github.com/stretchr/testify/suite" "github.com/GetStream/Vision-Agents/acceleration/internal/pricing" ) @@ -36,3 +40,132 @@ func TestAStatTakesWhatTheWorkUsedIntoItsColumnsAndMeters(t *testing.T) { require.Equal(t, Usage{InputTokens: 2_400, CachedInputTokens: 11, OutputTokens: 22, Requests: 1}, stat.Usage) require.Equal(t, pricing.Quantities{pricing.CacheWriteInputTokens: 2_386, pricing.OutputAudioTokens: 40}, stat.Meters) } + +// hooked is every call a Meter.Recorded hook was told of: the stat and what its row costs. +type hooked struct { + stats []Stat + costs []int64 +} + +func (t *hooked) hook(stat Stat, costMicros int64) { + t.stats, t.costs = append(t.stats, stat), append(t.costs, costMicros) +} + +// inputTokens is work that read n input tokens. +type inputTokens int64 + +func (n inputTokens) Used() pricing.Quantities { + return pricing.Quantities{pricing.InputTokens: int64(n)} +} + +// CallHookSuite calls vendors through Call with a Meter.Recorded hook that keeps what it is told, +// on a meter of a model priced at 2 US dollars a million input tokens, whose recorder writes +// nothing. +type CallHookSuite struct { + suite.Suite + meter Meter + hook *hooked +} + +func TestCallHookSuite(t *testing.T) { + suite.Run(t, new(CallHookSuite)) +} + +func (s *CallHookSuite) SetupTest() { + config := ProviderConfig{Provider: "vendor", Model: "told", Price: Price{PerMillionInputTokens: 2}} + logger := slog.New(slog.DiscardHandler) + prices, err := Prices(Config{LLM: {Providers: []ProviderConfig{config}}}, logger) + s.Require().NoError(err) + recorder := NewRecorder(LLM, nil, nil, prices, logger) + s.T().Cleanup(recorder.Close) + s.hook = &hooked{} + s.meter = Meter{Recorder: recorder, Config: config, Owner: Owner{CustomerID: "acme", CallID: "default:c1"}, + Code: func(error) string { return "vendor_refused" }, Recorded: s.hook.hook} +} + +func (s *CallHookSuite) TestARecordedHookIsToldWhatTheCallUsedAndWhatItsRowCosts() { + meter, hook := s.meter, s.hook + + _, err := Call(context.Background(), meter, func(context.Context) (inputTokens, error) { return 1_000, nil }) + + s.Require().NoError(err) + s.Len(hook.stats, 1, "one call is told once") + stat := hook.stats[0] + s.True(stat.Success) + s.Empty(stat.ErrorCode) + s.EqualValues(1_000, stat.InputTokens) + s.Equal("default:c1", stat.CallID) + s.Equal([]int64{2_000}, hook.costs, "a thousand tokens at 2 US dollars a million") +} + +func (s *CallHookSuite) TestARecordedHookIsToldOfAFailureWithItsCodeAndNoCost() { + meter, hook := s.meter, s.hook + + _, err := Call(context.Background(), meter, func(context.Context) (inputTokens, error) { + return 1_000, errors.New("vendor said no") + }) + + s.Require().Error(err) + s.Len(hook.stats, 1) + s.False(hook.stats[0].Success) + s.Equal("vendor_refused", hook.stats[0].ErrorCode) + s.Equal("vendor said no", hook.stats[0].ErrorMessage) + s.Zero(hook.stats[0].InputTokens, "a failure is recorded without quantities") + s.Equal([]int64{0}, hook.costs) +} + +func (s *CallHookSuite) TestARecordedHookIsToldOfAPanicBeforeItCarriesOn() { + meter, hook := s.meter, s.hook + + s.PanicsWithValue("vendor fell over", func() { + _, _ = Call(context.Background(), meter, func(context.Context) (inputTokens, error) { panic("vendor fell over") }) + }) + + s.Len(hook.stats, 1) + s.Equal("panic", hook.stats[0].ErrorCode) +} + +func (s *CallHookSuite) TestARecordedHookIsNotToldOfWorkTheMeterOmits() { + meter, hook := s.meter, s.hook + meter.Omit = func(used pricing.Quantities) bool { return used[pricing.InputTokens] == 0 } + + _, err := Call(context.Background(), meter, func(context.Context) (inputTokens, error) { return 0, nil }) + s.Require().NoError(err) + _, err = Call(context.Background(), meter, func(context.Context) (inputTokens, error) { return 5, nil }) + s.Require().NoError(err) + + s.Len(hook.stats, 1, "only the work with a row is told") + s.EqualValues(5, hook.stats[0].InputTokens) +} + +func (s *CallHookSuite) TestARecordedHookOfAMeterWithNoRecorderIsToldItCostsNothing() { + hook := &hooked{} + + _, err := Call(context.Background(), Meter{Recorded: hook.hook}, func(context.Context) (inputTokens, error) { return 1_000, nil }) + + s.Require().NoError(err) + s.Len(hook.stats, 1, "a router built without a recorder still logs its line") + s.Equal([]int64{0}, hook.costs) +} + +func (s *CallHookSuite) TestACallWithNoRecordedHookLogsNothing() { + var logs bytes.Buffer + logger := slog.New(slog.NewJSONHandler(&logs, nil)) + previous := slog.Default() + slog.SetDefault(logger) + s.T().Cleanup(func() { slog.SetDefault(previous) }) + meter := s.meter + meter.Recorded = nil + recorder := NewRecorder(LLM, nil, nil, meter.Recorder.pricer, logger) + s.T().Cleanup(recorder.Close) + meter.Recorder = recorder + + _, err := Call(context.Background(), meter, func(context.Context) (inputTokens, error) { return 1_000, nil }) + s.Require().NoError(err) + _, err = Call(context.Background(), meter, func(context.Context) (inputTokens, error) { + return 0, errors.New("vendor said no") + }) + s.Require().Error(err) + + s.Empty(logs.String(), "the other callers of Call log no line of their own") +} diff --git a/acceleration/internal/routing/reserve_integration_test.go b/acceleration/internal/routing/reserve_integration_test.go index 94c35e98c0..25dd9ec60c 100644 --- a/acceleration/internal/routing/reserve_integration_test.go +++ b/acceleration/internal/routing/reserve_integration_test.go @@ -215,6 +215,39 @@ func (s *ReserveSuite) TestAFailedCallReleasesItsReservation() { s.False(s.rows(1)[0].Success) } +func (s *ReserveSuite) TestARecordedHookIsToldOnlyOnceTheReservationIsReleased() { + s.credit(2_000_000) + meter := s.meter() + meter.Estimate = pricing.Quantities{pricing.InputTokens: 1_000_000} + var held error + told := false + meter.Recorded = func(routing.Stat, int64) { held, told = s.spend(), true } + + _, err := routing.Call(s.ctx, meter, func(context.Context) (worked, error) { + return nil, errors.New("vendor down") + }) + + s.Require().Error(err) + s.True(told) + s.NoError(held, "the hook runs after the reservation is let go, so work it does holds no money") +} + +func (s *ReserveSuite) TestAPanickingRecordedHookStillReleasesTheReservation() { + s.credit(2_000_000) + meter := s.meter() + meter.Estimate = pricing.Quantities{pricing.InputTokens: 1_000_000} + meter.Recorded = func(routing.Stat, int64) { panic("hook fell over") } + + s.PanicsWithValue("hook fell over", func() { + _, _ = routing.Call(s.ctx, meter, func(context.Context) (worked, error) { + return nil, errors.New("vendor down") + }) + }) + + s.NoError(s.spend(), "a failed call holds nothing, though its hook panicked") + s.False(s.rows(1)[0].Success, "and the row was queued before the hook ran") +} + func (s *ReserveSuite) TestWorkThatNamesItsOwnIDReleasesTheReservation() { s.credit(2_000_000) meter := s.meter() diff --git a/acceleration/internal/routing/stats.go b/acceleration/internal/routing/stats.go index 28104d29ae..8b590de4c7 100644 --- a/acceleration/internal/routing/stats.go +++ b/acceleration/internal/routing/stats.go @@ -436,8 +436,15 @@ func (r *Recorder) lose(config ProviderConfig, entry Stat, cause error) { // priced is the stat's row priced, and the quote of its quantities. It builds each row Record // writes or lose loses once, so a user id left off is counted once per row. func (r *Recorder) priced(config ProviderConfig, entry Stat) (store.Request, pricing.Quote) { - request := row(r.modality, config, entry) + request, priced := r.price(config, entry) request.UserID = userOnRow(entry.CustomerID, entry.UserID) + return request, priced +} + +// price is what priced builds, its user id unchecked, for a caller that only reads what the +// row costs: a user id left off is counted by the row Record writes, not again here. +func (r *Recorder) price(config ProviderConfig, entry Stat) (store.Request, pricing.Quote) { + request := row(r.modality, config, entry) pricedBy := quote if entry.CostMicros != 0 { pricedBy = quoteBesideQuoted diff --git a/acceleration/internal/sttrouter/recordings.go b/acceleration/internal/sttrouter/recordings.go index 6460749622..d33e8ae1f0 100644 --- a/acceleration/internal/sttrouter/recordings.go +++ b/acceleration/internal/sttrouter/recordings.go @@ -2,9 +2,11 @@ package sttrouter import ( "context" + "log/slog" "github.com/GetStream/Vision-Agents/acceleration/internal/options" "github.com/GetStream/Vision-Agents/acceleration/internal/routing" + "github.com/GetStream/Vision-Agents/acceleration/internal/store" "github.com/GetStream/Vision-Agents/acceleration/internal/stt" "github.com/GetStream/Vision-Agents/acceleration/internal/stt/deepgram" ) @@ -130,7 +132,8 @@ func (r *Recordings) Transcribe( transcription, err := routing.Call(ctx, routing.Meter{ Recorder: r.Recorder(), Config: config, Owner: request.Owner(), - Code: func(error) string { return "transcribe_failed" }, + Code: func(error) string { return "transcribe_failed" }, + Recorded: func(stat routing.Stat, costMicros int64) { logRecordingTiming(config, stat, costMicros) }, }, func(ctx context.Context) (stt.Transcription, error) { return provider.Transcribe(ctx, recording.Source) }) @@ -139,3 +142,16 @@ func (r *Recordings) Transcribe( } return transcription, config, nil } + +// logRecordingTiming writes the "speech transcription timing" line of a whole recording, for +// the row its transcription recorded. batch tells it from a session's line, its duration is +// the request's, and with one answer for the whole file it has no first transcript to time. +func logRecordingTiming(config routing.ProviderConfig, stat routing.Stat, costMicros int64) { + logged := append(routing.LoggedCall(stat.CallID, stat.Owner, config), "batch", true, + "audio_ms", stat.AudioMs, "duration_ms", stat.LatencyMs, "cost_micros", costMicros, + "success", stat.Success, "error_code", stat.ErrorCode) + if stat.ErrorMessage != "" { + logged = append(logged, "error", store.SafeLogText(stat.ErrorMessage)) + } + slog.Info("speech transcription timing", logged...) +} diff --git a/acceleration/internal/sttrouter/recordings_timing_test.go b/acceleration/internal/sttrouter/recordings_timing_test.go new file mode 100644 index 0000000000..7b94db8729 --- /dev/null +++ b/acceleration/internal/sttrouter/recordings_timing_test.go @@ -0,0 +1,101 @@ +package sttrouter + +import ( + "bytes" + "context" + "crypto/rand" + "encoding/json" + "errors" + "log/slog" + "testing" + "testing/synctest" + "time" + + "github.com/GetStream/Vision-Agents/acceleration/internal/options" + "github.com/GetStream/Vision-Agents/acceleration/internal/routing" + "github.com/GetStream/Vision-Agents/acceleration/internal/stt" +) + +// timedTranscriber takes a quarter of a second over a recording, then answers a second and a +// half of audio, or fails with failure when it is set. +type timedTranscriber struct{ failure error } + +func (t timedTranscriber) Transcribe(context.Context, stt.Recording) (stt.Transcription, error) { + time.Sleep(250 * time.Millisecond) + if t.failure != nil { + return stt.Transcription{}, t.failure + } + return stt.Transcription{Text: "hello there", AudioDurationMs: 1_500}, nil +} +func (timedTranscriber) Start(context.Context) error { return nil } +func (timedTranscriber) Close() error { return nil } +func (timedTranscriber) Provider() string { return "batchy" } +func (timedTranscriber) Model() string { return "whole" } + +// transcribeLogged transcribes one recording with a timedTranscriber priced at 3.60 US dollars +// an audio hour (a millisecond of audio costs one micro-dollar), on a fake clock so the times +// logged are exact, and answers the "speech transcription timing" lines of its app. +func (s *RecordingsSuite) transcribeLogged(transcriber timedTranscriber, recording Recording) []map[string]any { + var logs bytes.Buffer + outer := s.T() + synctest.Test(outer, func(t *testing.T) { + s.SetT(t) + defer s.SetT(outer) + previous := slog.Default() + slog.SetDefault(slog.New(slog.NewJSONHandler(&logs, nil))) + defer slog.SetDefault(previous) + transcribers := NewTranscriberRegistry() + transcribers.Register("batchy", func(routing.Spec) (stt.Transcriber, error) { return transcriber, nil }) + config := routing.ModalityConfig{Providers: []routing.ProviderConfig{{Provider: "batchy", Model: "whole", + Languages: []string{"en"}, Region: "us", Price: routing.Price{PerAudioHour: 3.6}}}} + recordings, err := NewRecordings(Options{Config: config, Transcribers: transcribers}) + s.Require().NoError(err) + defer recordings.Close() + + recording.Options = options.STT{Target: "batchy/whole"} + _, _, _ = recordings.Transcribe(context.Background(), recording) + }) + var lines []map[string]any + for decoder := json.NewDecoder(&logs); decoder.More(); { + var line map[string]any + s.Require().NoError(decoder.Decode(&line)) + if line["msg"] == "speech transcription timing" && line["app_id"] == recording.CustomerID { + delete(line, "time") + lines = append(lines, line) + } + } + return lines +} + +func (s *RecordingsSuite) TestATranscribedRecordingLogsOneBatchLineWithWhatItCost() { + app := "acme-" + rand.Text() + + lines := s.transcribeLogged(timedTranscriber{}, Recording{CustomerID: app, AgentID: "concierge", CallID: "default:c1"}) + + s.Equal([]map[string]any{{ + "level": "INFO", "msg": "speech transcription timing", + "call": "default:c1", "app_id": app, "agent_id": "concierge", "provider": "batchy", "model": "whole", "region": "us", + "batch": true, "audio_ms": 1_500.0, "duration_ms": 250.0, "cost_micros": 1_500.0, + "success": true, "error_code": "", + }}, lines, "no ttfb_ms: one answer for the whole file has no first transcript to time") +} + +func (s *RecordingsSuite) TestAFailedTranscriptionLogsItsCodeAndItsErrorWithNoCredential() { + app := "acme-" + rand.Text() + failure := errors.New("deepgram: 401 for api_key=sk-live-0123456789abcdef") + + lines := s.transcribeLogged(timedTranscriber{failure: failure}, Recording{CustomerID: app}) + + s.Require().Len(lines, 1) + line := lines[0] + s.Require().IsType("", line["error"]) + s.Contains(line["error"], "deepgram: 401 for") + s.NotContains(line["error"], "sk-live-0123456789abcdef") + delete(line, "error") + s.Equal(map[string]any{ + "level": "INFO", "msg": "speech transcription timing", + "call": "", "app_id": app, "provider": "batchy", "model": "whole", "region": "us", + "batch": true, "audio_ms": 0.0, "duration_ms": 250.0, "cost_micros": 0.0, + "success": false, "error_code": "transcribe_failed", + }, line, "a recording outside a call names no agent and an empty call") +} diff --git a/acceleration/internal/ttsrouter/recordings.go b/acceleration/internal/ttsrouter/recordings.go index 5f37233c0a..4aa4210e16 100644 --- a/acceleration/internal/ttsrouter/recordings.go +++ b/acceleration/internal/ttsrouter/recordings.go @@ -9,6 +9,7 @@ import ( "github.com/GetStream/Vision-Agents/acceleration/internal/options" "github.com/GetStream/Vision-Agents/acceleration/internal/routing" "github.com/GetStream/Vision-Agents/acceleration/internal/stack" + "github.com/GetStream/Vision-Agents/acceleration/internal/store" "github.com/GetStream/Vision-Agents/acceleration/internal/tts" "github.com/GetStream/Vision-Agents/acceleration/internal/tts/cartesia" "github.com/GetStream/Vision-Agents/acceleration/internal/tts/elevenlabs" @@ -282,7 +283,8 @@ func (r *Recordings) speak( } recorded, err := routing.Call(ctx, routing.Meter{ Recorder: r.Recorder(), Config: config, Owner: owner, - Code: func(error) string { return "record_failed" }, + Code: func(error) string { return "record_failed" }, + Recorded: func(stat routing.Stat, costMicros int64) { r.logTiming(config, stat, costMicros) }, }, func(ctx context.Context) (tts.Recorded, error) { return provider.Record(ctx, asked) }) @@ -297,6 +299,20 @@ func (r *Recordings) speak( return recorded, nil } +// logTiming writes the "speech synthesis timing" line of a whole recording, for the row one +// candidate's recording recorded, so each voice asked has its own line. batch tells it from a +// session's line, its duration is the request's, and with one answer for the whole text it has +// no first audio to time. +func (r *Recordings) logTiming(config routing.ProviderConfig, stat routing.Stat, costMicros int64) { + logged := append(routing.LoggedCall(stat.CallID, stat.Owner, config), "batch", true, + "characters", stat.Characters, "audio_ms", stat.AudioMs, "duration_ms", stat.LatencyMs, + "cost_micros", costMicros, "success", stat.Success, "error_code", stat.ErrorCode) + if stat.ErrorMessage != "" { + logged = append(logged, "error", store.SafeLogText(stat.ErrorMessage)) + } + r.Logger().Info("speech synthesis timing", logged...) +} + // maxTriedError is how much of one candidate's error a failed recording reports. Ours, not // a vendor's: enough for the model, the status and the start of the vendor's reason, whose // body is passed on whole and has no bound of its own. diff --git a/acceleration/internal/ttsrouter/recordings_timing_test.go b/acceleration/internal/ttsrouter/recordings_timing_test.go new file mode 100644 index 0000000000..86442cd761 --- /dev/null +++ b/acceleration/internal/ttsrouter/recordings_timing_test.go @@ -0,0 +1,114 @@ +package ttsrouter + +import ( + "bytes" + "context" + "crypto/rand" + "encoding/json" + "errors" + "log/slog" + "testing" + "testing/synctest" + "time" + + "github.com/GetStream/Vision-Agents/acceleration/internal/options" + "github.com/GetStream/Vision-Agents/acceleration/internal/routing" + "github.com/GetStream/Vision-Agents/acceleration/internal/tts" +) + +// timedRecorder takes took over a text, then answers its characters and 800 ms of audio, or +// fails with failure when it is set. +type timedRecorder struct { + took time.Duration + failure error +} + +func (t timedRecorder) Record(_ context.Context, recording tts.Recording) (tts.Recorded, error) { + time.Sleep(t.took) + if t.failure != nil { + return tts.Recorded{}, t.failure + } + return tts.Recorded{Audio: []byte("audio"), Characters: int64(len(recording.Text)), AudioDurationMs: 800}, nil +} +func (timedRecorder) Start(context.Context) error { return nil } +func (timedRecorder) Close() error { return nil } +func (timedRecorder) Provider() string { return "voicy" } +func (timedRecorder) Model() string { return "whole" } + +// recordLogged speaks "hello" through a priority list of two voices, voicy speaking with first +// and spoken with next, each priced at 30 US dollars a million characters (30 micro-dollars a +// character), on a fake clock so the times logged are exact, and answers the "speech +// synthesis timing" lines of its app. +func (s *RecordingsSuite) recordLogged(app string, first, next timedRecorder) []map[string]any { + var logs bytes.Buffer + outer := s.T() + synctest.Test(outer, func(t *testing.T) { + s.SetT(t) + defer s.SetT(outer) + registry := NewRecorderRegistry() + registry.Register("voicy", func(routing.Spec) (tts.Recorder, error) { return first, nil }) + registry.Register("spoken", func(routing.Spec) (tts.Recorder, error) { return next, nil }) + price := routing.Price{PerMillionChars: 30} + config := routing.ModalityConfig{Providers: []routing.ProviderConfig{ + {Provider: "voicy", Model: "whole", Languages: []string{"en"}, Region: "us", Price: price}, + {Provider: "spoken", Model: "whole", Languages: []string{"en"}, Price: price}, + }} + recordings, err := NewRecordings(Options{Config: config, Recorders: registry, + Logger: slog.New(slog.NewJSONHandler(&logs, nil))}) + s.Require().NoError(err) + defer recordings.Close() + + _, _, _ = recordings.Record(context.Background(), Recording{CustomerID: app, + Options: options.TTS{Providers: []string{"voicy/whole", "spoken/whole"}}, Text: "hello"}) + }) + var lines []map[string]any + for decoder := json.NewDecoder(&logs); decoder.More(); { + var line map[string]any + s.Require().NoError(decoder.Decode(&line)) + if line["msg"] == "speech synthesis timing" && line["app_id"] == app { + delete(line, "time") + lines = append(lines, line) + } + } + return lines +} + +func (s *RecordingsSuite) TestASpokenRecordingLogsOneBatchLineWithWhatItCost() { + app := "acme-" + rand.Text() + + lines := s.recordLogged(app, timedRecorder{took: 300 * time.Millisecond}, timedRecorder{}) + + s.Equal([]map[string]any{{ + "level": "INFO", "msg": "speech synthesis timing", + "call": "", "app_id": app, "provider": "voicy", "model": "whole", "region": "us", + "batch": true, "characters": 5.0, "audio_ms": 800.0, "duration_ms": 300.0, "cost_micros": 150.0, + "success": true, "error_code": "", + }}, lines, "no ttfb_ms: one answer for the whole text has no first audio to time") +} + +func (s *RecordingsSuite) TestEachCandidateARecordingFallsBackFromLogsItsOwnLine() { + app := "acme-" + rand.Text() + failure := errors.New("voicy: 500 for api_key=sk-live-0123456789abcdef") + + lines := s.recordLogged(app, timedRecorder{took: 120 * time.Millisecond, failure: failure}, + timedRecorder{took: 300 * time.Millisecond}) + + s.Require().Len(lines, 2, "the voice that failed and the one that spoke") + failed := lines[0] + s.Require().IsType("", failed["error"]) + s.Contains(failed["error"], "voicy: 500 for") + s.NotContains(failed["error"], "sk-live-0123456789abcdef") + delete(failed, "error") + s.Equal(map[string]any{ + "level": "INFO", "msg": "speech synthesis timing", + "call": "", "app_id": app, "provider": "voicy", "model": "whole", "region": "us", + "batch": true, "characters": 0.0, "audio_ms": 0.0, "duration_ms": 120.0, "cost_micros": 0.0, + "success": false, "error_code": "record_failed", + }, failed) + s.Equal(map[string]any{ + "level": "INFO", "msg": "speech synthesis timing", + "call": "", "app_id": app, "provider": "spoken", "model": "whole", + "batch": true, "characters": 5.0, "audio_ms": 800.0, "duration_ms": 300.0, "cost_micros": 150.0, + "success": true, "error_code": "", + }, lines[1]) +}