-
Notifications
You must be signed in to change notification settings - Fork 17
Voice Streaming #183
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Voice Streaming #183
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
142 changes: 142 additions & 0 deletions
142
examples-backend/product-roadmap-backend/src/mastra/voiceStreamHandler.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,142 @@ | ||||||||||||||
| import { Context } from 'hono'; | ||||||||||||||
| import { Readable } from 'stream'; | ||||||||||||||
| import { createSSEStream, streamJSONEvent } from '../utils/streamUtils'; | ||||||||||||||
| import { chatWorkflow } from './workflows/chatWorkflow'; | ||||||||||||||
| import { OpenAIVoice } from '@mastra/voice-openai'; | ||||||||||||||
|
|
||||||||||||||
| export const voiceProvider = new OpenAIVoice({ | ||||||||||||||
| speechModel: { apiKey: process.env.OPENAI_API_KEY!, name: 'tts-1' }, | ||||||||||||||
| listeningModel: { | ||||||||||||||
| apiKey: process.env.OPENAI_API_KEY!, | ||||||||||||||
| name: 'whisper-1', | ||||||||||||||
| }, | ||||||||||||||
| }); | ||||||||||||||
|
|
||||||||||||||
| /** | ||||||||||||||
| * Create workflow input data from the voice streaming parameters | ||||||||||||||
| */ | ||||||||||||||
| function createWorkflowInput( | ||||||||||||||
| baseInput: { | ||||||||||||||
| prompt: string; | ||||||||||||||
| additionalContext?: unknown; | ||||||||||||||
| temperature?: number; | ||||||||||||||
| maxTokens?: number; | ||||||||||||||
| systemPrompt?: string; | ||||||||||||||
| resourceId?: string; | ||||||||||||||
| threadId?: string; | ||||||||||||||
| }, | ||||||||||||||
| controller: ReadableStreamDefaultController<Uint8Array>, | ||||||||||||||
| isStreaming: boolean = true, | ||||||||||||||
| isVoice: boolean = false | ||||||||||||||
| ) { | ||||||||||||||
| return { | ||||||||||||||
| ...baseInput, | ||||||||||||||
| streamController: isStreaming ? controller : undefined, | ||||||||||||||
| isVoice, | ||||||||||||||
| }; | ||||||||||||||
| } | ||||||||||||||
|
|
||||||||||||||
| /** | ||||||||||||||
| * Handle voice streaming request | ||||||||||||||
| * Transcribes audio, then streams the LLM response back | ||||||||||||||
| */ | ||||||||||||||
| export async function handleVoiceStream(c: Context) { | ||||||||||||||
| try { | ||||||||||||||
| const form = await c.req.formData(); | ||||||||||||||
| const audioFile = form.get('audio') as File; | ||||||||||||||
| const additionalContext = form.get('context') as string | null; | ||||||||||||||
| const settings = form.get('settings') as string | null; | ||||||||||||||
|
|
||||||||||||||
| let parsedAdditionalContext: unknown = undefined; | ||||||||||||||
| let parsedSettings: { | ||||||||||||||
| temperature?: number; | ||||||||||||||
| maxTokens?: number; | ||||||||||||||
| systemPrompt?: string; | ||||||||||||||
| resourceId?: string; | ||||||||||||||
| threadId?: string; | ||||||||||||||
| } = {}; | ||||||||||||||
|
|
||||||||||||||
| // Parse additional context if provided | ||||||||||||||
| if (additionalContext) { | ||||||||||||||
| try { | ||||||||||||||
| parsedAdditionalContext = JSON.parse(additionalContext); | ||||||||||||||
| } catch { | ||||||||||||||
| // leave undefined if not valid JSON | ||||||||||||||
| } | ||||||||||||||
| } | ||||||||||||||
|
|
||||||||||||||
| // Parse voice settings if provided | ||||||||||||||
| if (settings) { | ||||||||||||||
| try { | ||||||||||||||
| parsedSettings = JSON.parse(settings); | ||||||||||||||
| } catch { | ||||||||||||||
| // use empty object if not valid JSON | ||||||||||||||
| } | ||||||||||||||
| } | ||||||||||||||
|
|
||||||||||||||
| if (!audioFile) { | ||||||||||||||
| return c.json({ error: 'audio required' }, 400); | ||||||||||||||
| } | ||||||||||||||
|
|
||||||||||||||
| // Convert audio file to buffer and then to stream | ||||||||||||||
| const buf = Buffer.from(await audioFile.arrayBuffer()); | ||||||||||||||
|
|
||||||||||||||
| // Transcribe the audio | ||||||||||||||
| const transcription = await voiceProvider.listen(Readable.from(buf), { | ||||||||||||||
| filetype: 'webm', | ||||||||||||||
| }); | ||||||||||||||
|
Comment on lines
+85
to
+87
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. style: hardcoded
Suggested change
Prompt To Fix With AIThis is a comment left during a code review.
Path: examples-backend/product-roadmap-backend/src/mastra/voiceStreamHandler.ts
Line: 85:87
Comment:
style: hardcoded `filetype: 'webm'` assumes input format - consider making dynamic
```suggestion
const transcription = await voiceProvider.listen(Readable.from(buf), {
filetype: audioFile.type.includes('webm') ? 'webm' : 'wav',
});
```
How can I resolve this? If you propose a fix, please make it concise. |
||||||||||||||
|
|
||||||||||||||
| // Create SSE stream for real-time response | ||||||||||||||
| return createSSEStream(async (controller) => { | ||||||||||||||
| // Emit the transcription in the format that Cedar OS voice streaming expects | ||||||||||||||
| console.log('Emitting voice transcription:', transcription); | ||||||||||||||
| streamJSONEvent(controller, 'transcription', { | ||||||||||||||
| type: 'transcription', | ||||||||||||||
| transcription: transcription, | ||||||||||||||
| }); | ||||||||||||||
|
|
||||||||||||||
| // Start the chat workflow with the transcription | ||||||||||||||
| const run = await chatWorkflow.createRunAsync(); | ||||||||||||||
| const result = await run.start({ | ||||||||||||||
| inputData: createWorkflowInput( | ||||||||||||||
| { | ||||||||||||||
| prompt: transcription, | ||||||||||||||
| additionalContext: parsedAdditionalContext ?? additionalContext, | ||||||||||||||
| temperature: parsedSettings.temperature, | ||||||||||||||
| maxTokens: parsedSettings.maxTokens, | ||||||||||||||
| systemPrompt: parsedSettings.systemPrompt, | ||||||||||||||
| resourceId: parsedSettings.resourceId, | ||||||||||||||
| threadId: parsedSettings.threadId, | ||||||||||||||
| }, | ||||||||||||||
| controller, | ||||||||||||||
| true, | ||||||||||||||
| true | ||||||||||||||
| ), | ||||||||||||||
| }); | ||||||||||||||
|
|
||||||||||||||
| if (result.status !== 'success') { | ||||||||||||||
| console.error('Workflow failed:', result.status); | ||||||||||||||
| streamJSONEvent(controller, 'error', { | ||||||||||||||
| type: 'error', | ||||||||||||||
| error: `Workflow failed: ${result.status}`, | ||||||||||||||
| }); | ||||||||||||||
| } | ||||||||||||||
|
|
||||||||||||||
| // Emit completion event | ||||||||||||||
| console.log('Voice stream completed successfully'); | ||||||||||||||
| streamJSONEvent(controller, 'done', { | ||||||||||||||
| type: 'done', | ||||||||||||||
| completedItems: [], | ||||||||||||||
| }); | ||||||||||||||
|
|
||||||||||||||
| // The workflow handles streaming the response through the controller | ||||||||||||||
| // No need to manually close here as the workflow will handle completion | ||||||||||||||
| }); | ||||||||||||||
| } catch (error) { | ||||||||||||||
| console.error('Voice stream error:', error); | ||||||||||||||
| return c.json( | ||||||||||||||
| { error: error instanceof Error ? error.message : 'Internal error' }, | ||||||||||||||
| 500 | ||||||||||||||
| ); | ||||||||||||||
| } | ||||||||||||||
| } | ||||||||||||||
34 changes: 34 additions & 0 deletions
34
examples-backend/product-roadmap-backend/src/mastra/voiceUtils.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| import { OpenAIVoice } from '@mastra/voice-openai'; | ||
| import { streamAudioFromText } from '../utils/streamUtils'; | ||
|
|
||
| export const voiceProvider = new OpenAIVoice({ | ||
| speechModel: { apiKey: process.env.OPENAI_API_KEY!, name: 'tts-1' }, | ||
| listeningModel: { | ||
| apiKey: process.env.OPENAI_API_KEY!, | ||
| name: 'whisper-1', | ||
| }, | ||
| }); | ||
|
|
||
| export function createSpeakFunction() { | ||
| return (t: string, options?: Record<string, unknown>) => | ||
| voiceProvider.speak( | ||
| t, | ||
| options as { speaker?: string; speed?: number } | ||
| ) as unknown as Promise<ReadableStream>; | ||
| } | ||
|
|
||
| export async function handleVoiceOutput( | ||
| streamController: ReadableStreamDefaultController<Uint8Array>, | ||
| pendingText: string, | ||
| options: { voice?: string; speed?: number; eventType?: string } = {} | ||
| ) { | ||
| if (!pendingText) return; | ||
|
|
||
| const speakFn = createSpeakFunction(); | ||
| await streamAudioFromText(streamController, speakFn, pendingText, { | ||
| voice: 'alloy', | ||
| speed: 1.0, | ||
| eventType: 'audio', | ||
| ...options, | ||
| }); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
logic: missing environment variable validation will cause runtime errors if API key is not set
Prompt To Fix With AI