|
| 1 | +package openai |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + |
| 6 | + . "github.com/onsi/ginkgo/v2" |
| 7 | + . "github.com/onsi/gomega" |
| 8 | + |
| 9 | + "github.com/mudler/LocalAI/core/config" |
| 10 | + "github.com/mudler/LocalAI/core/http/endpoints/openai/types" |
| 11 | + "github.com/mudler/LocalAI/pkg/reasoning" |
| 12 | +) |
| 13 | + |
| 14 | +// speechStreamer consumes streamed LLM tokens: it strips reasoning, emits a |
| 15 | +// transcript delta per content fragment, and sentence-pipes content into TTS so |
| 16 | +// audio starts before the full reply is generated. |
| 17 | +var _ = Describe("speechStreamer", func() { |
| 18 | + It("emits a transcript delta per token and speaks each completed sentence", func() { |
| 19 | + on := true |
| 20 | + m := &fakeModel{ttsStreamChunks: [][]byte{{7}}, ttsStreamRate: 24000} |
| 21 | + session := &Session{ |
| 22 | + OutputSampleRate: 24000, |
| 23 | + ModelInterface: m, |
| 24 | + ModelConfig: &config.ModelConfig{ |
| 25 | + Pipeline: config.Pipeline{Streaming: config.PipelineStreaming{TTS: &on}}, |
| 26 | + }, |
| 27 | + } |
| 28 | + t := &fakeTransport{} |
| 29 | + s := newSpeechStreamer(context.Background(), t, session, "resp1", "item1", "", reasoning.Config{}) |
| 30 | + |
| 31 | + for _, tok := range []string{"Hello", " world.", " Bye"} { |
| 32 | + s.onToken(tok) |
| 33 | + } |
| 34 | + content, audio, err := s.finish() |
| 35 | + |
| 36 | + Expect(err).ToNot(HaveOccurred()) |
| 37 | + Expect(content).To(Equal("Hello world. Bye")) |
| 38 | + // One transcript delta per (non-empty) token. |
| 39 | + Expect(t.countEvents(types.ServerEventTypeResponseOutputAudioTranscriptDelta)).To(Equal(3)) |
| 40 | + // Two sentences spoken: "Hello world." mid-stream + "Bye" on flush; one |
| 41 | + // chunk each. |
| 42 | + Expect(t.countEvents(types.ServerEventTypeResponseOutputAudioDelta)).To(Equal(2)) |
| 43 | + Expect(audio).To(Equal([]byte{7, 7})) |
| 44 | + }) |
| 45 | + |
| 46 | + It("does not synthesize audio when TTS streaming is disabled", func() { |
| 47 | + m := &fakeModel{ttsStreamChunks: [][]byte{{7}}, ttsStreamRate: 24000} |
| 48 | + session := &Session{ |
| 49 | + OutputSampleRate: 24000, |
| 50 | + ModelInterface: m, |
| 51 | + ModelConfig: &config.ModelConfig{}, // streaming.tts off |
| 52 | + } |
| 53 | + t := &fakeTransport{} |
| 54 | + s := newSpeechStreamer(context.Background(), t, session, "resp1", "item1", "", reasoning.Config{}) |
| 55 | + |
| 56 | + s.onToken("Hello world.") |
| 57 | + content, audio, err := s.finish() |
| 58 | + |
| 59 | + Expect(err).ToNot(HaveOccurred()) |
| 60 | + Expect(content).To(Equal("Hello world.")) |
| 61 | + Expect(t.countEvents(types.ServerEventTypeResponseOutputAudioTranscriptDelta)).To(Equal(1)) |
| 62 | + Expect(t.countEvents(types.ServerEventTypeResponseOutputAudioDelta)).To(Equal(0)) |
| 63 | + Expect(audio).To(BeEmpty()) |
| 64 | + }) |
| 65 | +}) |
0 commit comments