Skip to content

chore: add elevenlabs example #373

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

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open

chore: add elevenlabs example #373

wants to merge 4 commits into from

Conversation

naomi-lgbt
Copy link
Contributor

@naomi-lgbt naomi-lgbt commented May 14, 2025

Proposed changes

Types of changes

What types of changes does your code introduce to the community .NET SDK?
Put an x in the boxes that apply

  • Bugfix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update or tests (if none of the other choices apply)

Checklist

Put an x in the boxes that apply. You can also fill these out after creating the PR. If you're unsure about any of them, don't hesitate to ask. We're here to help! This is simply a reminder of what we are going to look for before merging your code.

  • I have read the CONTRIBUTING doc
  • I have lint'ed all of my code using repo standards
  • I have added tests that prove my fix is effective or that my feature works
  • I have added necessary documentation (if appropriate)

Further comments

Summary by CodeRabbit

  • New Features

    • Added a sample application demonstrating Deepgram Agent WebSocket integration with Eleven Labs text-to-speech, including event handling and audio streaming.
    • Introduced a new .NET 8.0 project for the sample application.
  • Chores

    • Updated .gitignore to exclude .wav files from version control.
  • Refactor

    • Removed the Header record previously used for WebSocket headers.

Copy link
Contributor

coderabbitai bot commented May 14, 2025

"""

Walkthrough

The changes include updating the .gitignore file to ignore .wav files, removing the Header record definition from the Deepgram Agent WebSocket model, and adding a new example C# project demonstrating Deepgram Agent WebSocket integration with Eleven Labs TTS. The example handles audio streaming, event subscriptions, and file output.

Changes

File(s) Change Summary
.gitignore Added pattern to ignore all .wav files.
Deepgram/Models/Agent/v2/WebSocket/Header.cs Deleted the Header record, which defined key-value pairs for WebSocket headers with JSON serialization and a custom ToString() method.
examples/agent/websocket/11_labs/Program.cs Added a new example program demonstrating Deepgram Agent WebSocket client usage with Eleven Labs TTS, including event handling, audio file streaming, and writing audio responses to sequential .wav files.
examples/agent/websocket/11_labs/no_mic.csproj Added new C# project file targeting .NET 8.0, referencing the Deepgram project, and enabling global using directives and nullable reference types.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Program
    participant DeepgramAgentClient
    participant ElevenLabs
    participant AudioFile

    User->>Program: Start application
    Program->>DeepgramAgentClient: Initialize and connect with settings
    DeepgramAgentClient->>Program: Emit event subscriptions
    Program->>AudioFile: Fetch audio from URL
    loop For each audio chunk
        Program->>DeepgramAgentClient: Send audio chunk
    end
    DeepgramAgentClient->>Program: Emit AudioResponse (with audio data)
    Program->>FileSystem: Write/append audio data to .wav file
    User->>Program: Press key to stop
    Program->>DeepgramAgentClient: Stop connection
    Program->>Deepgram: Terminate library
Loading

Suggested reviewers

  • jpvajda
    """

Tip

⚡️ Free AI Code Reviews for VS Code, Cursor, Windsurf
  • CodeRabbit now supports VS Code, Cursor and Windsurf. This brings free AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback. Learn more

[!ANNOUNCEMENT]

⚡️ Faster reviews with caching
  • CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.

Enjoy the performance boost—your workflow just got faster.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1ccdc0c and 14df8df.

📒 Files selected for processing (1)
  • examples/agent/websocket/11_labs/Program.cs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • examples/agent/websocket/11_labs/Program.cs
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (3)
.gitignore (1)

252-254: Redundant ignore pattern – log.txt is already covered by *.log

Line 66 already ignores any file with a .log suffix. Adding a dedicated log.txt pattern does not hurt, but it is unnecessary noise that may lead future contributors to wonder if log.txt needs special treatment.

If you want to keep it explicit, consider adding a short comment; otherwise feel free to remove the line.

examples/agent/websocket/11_labs/no_mic.csproj (1)

4-8: Consider enabling warnings-as-errors for example projects

Enabling TreatWarningsAsErrors helps catch nullable-reference violations and other issues early, even in sample code.

   <PropertyGroup>
     <OutputType>Exe</OutputType>
     <TargetFramework>net8.0</TargetFramework>
     <ImplicitUsings>enable</ImplicitUsings>
     <Nullable>enable</Nullable>
+    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
   </PropertyGroup>

This is optional for examples, but it reinforces good habits and prevents demos from drifting into problematic territory.

examples/agent/websocket/11_labs/Program.cs (1)

67-77: Subscription boiler-plate can be reduced

Every subscription follows the same pattern:

subscribeResult = await agentClient.Subscribe(new EventHandler<OpenResponse>((s,e)=>{}));
if (!subscribeResult) { Console.WriteLine("Failed …"); return; }

Wrapping this into a helper drastically shortens the example and highlights the event handlers themselves:

async Task SubscribeAsync<T>(EventHandler<T> handler, string name)
{
    if (!await agentClient.Subscribe(handler))
        throw new InvalidOperationException($"Failed to subscribe to {name}");
}

await SubscribeAsync<OpenResponse>((s,e)=>Console.WriteLine($"-->{e.Type}"), nameof(OpenResponse));

This keeps the sample readable while still demonstrating the API.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fd43104 and 1ccdc0c.

⛔ Files ignored due to path filters (1)
  • output_0.wav is excluded by !**/*.wav, !**/*.wav
📒 Files selected for processing (4)
  • .gitignore (1 hunks)
  • Deepgram/Models/Agent/v2/WebSocket/Header.cs (0 hunks)
  • examples/agent/websocket/11_labs/Program.cs (1 hunks)
  • examples/agent/websocket/11_labs/no_mic.csproj (1 hunks)
💤 Files with no reviewable changes (1)
  • Deepgram/Models/Agent/v2/WebSocket/Header.cs
🧰 Additional context used
🧠 Learnings (2)
examples/agent/websocket/11_labs/no_mic.csproj (1)
Learnt from: OoLunar
PR: deepgram/deepgram-dotnet-sdk#352
File: examples/Deepgram.Examples.Manage.Members/Deepgram.Examples.Manage.Members.csproj:4-4
Timestamp: 2024-11-05T22:01:40.632Z
Learning: In the Deepgram .NET SDK, when the main library targets stable .NET versions, it's acceptable for example projects to target newer .NET versions (e.g., .NET 9.0), as newer .NET applications can consume dependencies from older versions.
examples/agent/websocket/11_labs/Program.cs (1)
Learnt from: dvonthenen
PR: deepgram/deepgram-dotnet-sdk#343
File: examples/text-to-speech/websocket/simple/Program.cs:47-108
Timestamp: 2024-10-23T17:23:51.386Z
Learning: Example code in `examples/text-to-speech/websocket/simple/Program.cs` is intended to be simple and does not need to be fully optimized or perfect.
🔇 Additional comments (1)
examples/agent/websocket/11_labs/Program.cs (1)

318-324: No throttling when streaming audio to the websocket

SendBinaryImmediately is awaited, but if the server’s receive window is smaller than the 8 KB buffer or network latency spikes, the tight loop can still overwhelm the socket and increase memory usage.

Consider inserting a minimal delay or reusing the DeepgramWsClientOptions.SendDelay (if available) to pace the upload, or reduce the buffer size to the SDK’s recommended chunk duration (e.g. 20 ms of audio).

Comment on lines +78 to +162
subscribeResult = await agentClient.Subscribe(new EventHandler<AudioResponse>((sender, e) =>
{
Console.WriteLine($"----> {e.Type} received");

// if the last audio response is more than 5 seconds ago, add a wav header
if (DateTime.Now.Subtract(lastAudioTime).TotalSeconds > 7)
{
audioFileCount = audioFileCount + 1; // increment the audio file count

// delete the file if it exists
if (File.Exists($"output_{audioFileCount}.wav"))
{
File.Delete($"output_{audioFileCount}.wav");
}

using (BinaryWriter writer = new BinaryWriter(File.Open($"output_{audioFileCount}.wav", FileMode.Append)))
{
Console.WriteLine("Adding WAV header to output.wav");
byte[] wavHeader = new byte[44];
int sampleRate = 24000;
short bitsPerSample = 16;
short channels = 1;
int byteRate = sampleRate * channels * (bitsPerSample / 8);
short blockAlign = (short)(channels * (bitsPerSample / 8));

wavHeader[0] = 0x52; // R
wavHeader[1] = 0x49; // I
wavHeader[2] = 0x46; // F
wavHeader[3] = 0x46; // F
wavHeader[4] = 0x00; // Placeholder for file size (will be updated later)
wavHeader[5] = 0x00; // Placeholder for file size (will be updated later)
wavHeader[6] = 0x00; // Placeholder for file size (will be updated later)
wavHeader[7] = 0x00; // Placeholder for file size (will be updated later)
wavHeader[8] = 0x57; // W
wavHeader[9] = 0x41; // A
wavHeader[10] = 0x56; // V
wavHeader[11] = 0x45; // E
wavHeader[12] = 0x66; // f
wavHeader[13] = 0x6D; // m
wavHeader[14] = 0x74; // t
wavHeader[15] = 0x20; // Space
wavHeader[16] = 0x10; // Subchunk1Size (16 for PCM)
wavHeader[17] = 0x00; // Subchunk1Size
wavHeader[18] = 0x00; // Subchunk1Size
wavHeader[19] = 0x00; // Subchunk1Size
wavHeader[20] = 0x01; // AudioFormat (1 for PCM)
wavHeader[21] = 0x00; // AudioFormat
wavHeader[22] = (byte)channels; // NumChannels
wavHeader[23] = 0x00; // NumChannels
wavHeader[24] = (byte)(sampleRate & 0xFF); // SampleRate
wavHeader[25] = (byte)((sampleRate >> 8) & 0xFF); // SampleRate
wavHeader[26] = (byte)((sampleRate >> 16) & 0xFF); // SampleRate
wavHeader[27] = (byte)((sampleRate >> 24) & 0xFF); // SampleRate
wavHeader[28] = (byte)(byteRate & 0xFF); // ByteRate
wavHeader[29] = (byte)((byteRate >> 8) & 0xFF); // ByteRate
wavHeader[30] = (byte)((byteRate >> 16) & 0xFF); // ByteRate
wavHeader[31] = (byte)((byteRate >> 24) & 0xFF); // ByteRate
wavHeader[32] = (byte)blockAlign; // BlockAlign
wavHeader[33] = 0x00; // BlockAlign
wavHeader[34] = (byte)bitsPerSample; // BitsPerSample
wavHeader[35] = 0x00; // BitsPerSample
wavHeader[36] = 0x64; // d
wavHeader[37] = 0x61; // t
wavHeader[38] = 0x74; // t
wavHeader[39] = 0x61; // a
wavHeader[40] = 0x00; // Placeholder for data chunk size (will be updated later)
wavHeader[41] = 0x00; // Placeholder for data chunk size (will be updated later)
wavHeader[42] = 0x00; // Placeholder for data chunk size (will be updated later)
wavHeader[43] = 0x00; // Placeholder for data chunk size (will be updated later)

writer.Write(wavHeader);
}
}

if (e.Stream != null)
{
using (BinaryWriter writer = new BinaryWriter(File.Open($"output_{audioFileCount}.wav", FileMode.Append)))
{
writer.Write(e.Stream.ToArray());
}
}

// record the last audio time
lastAudioTime = DateTime.Now;
}));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

⚠️ Potential issue

First audio chunk is written without a WAV header

audioFileCount starts at 0, and a header is only added when more than seven seconds have elapsed since the previous chunk.
If the very first chunk arrives within seven seconds of lastAudioTime (which is virtually guaranteed), output_0.wav will begin with raw PCM data and be unplayable.

A minimal fix is to create a new file (and therefore write the header) whenever the target file does not yet exist:

- // if the last audio response is more than 5 seconds ago, add a wav header
- if (DateTime.Now.Subtract(lastAudioTime).TotalSeconds > 7)
+ // Start a new file if it's the first chunk or if >7 s have passed since the
+ // previous chunk.  This guarantees that every file begins with a valid header.
+ var needNewFile = !File.Exists($"output_{audioFileCount}.wav") ||
+                   DateTime.Now.Subtract(lastAudioTime).TotalSeconds > 7;
+ if (needNewFile)
 {
-     audioFileCount = audioFileCount + 1; // increment the audio file count
+     audioFileCount++;                    // move to the next file

You may also want to update the RIFF/Data chunk sizes once the file is closed, or use a helper such as WaveFileWriter from NAudio to avoid manual header management altogether.

🤖 Prompt for AI Agents (early access)
In examples/agent/websocket/11_labs/Program.cs between lines 78 and 162, the
first audio chunk may be written to output_0.wav without a WAV header because
the header is only added if more than seven seconds have passed since the last
audio time. To fix this, modify the condition to also create a new file and
write the WAV header if the target file does not exist yet, ensuring the header
is always present at the start of a new file. Additionally, consider updating
the RIFF and data chunk sizes after writing is complete or use a library like
NAudio's WaveFileWriter to handle WAV headers automatically.

🛠️ Refactor suggestion

Possible race condition when multiple audio events arrive concurrently

The lastAudioTime and audioFileCount variables are shared across event invocations, but no synchronisation is applied.
If two AudioResponse callbacks overlap (e.g. on a thread pool), they can:

  1. Attempt to create/delete the same file simultaneously.
  2. Increment audioFileCount twice, skipping a number.
  3. Corrupt the header / interleave writes.

Synchronise access with a simple lock object:

+private static readonly object _fileLock = new();

...

subscribeResult = await agentClient.Subscribe(new EventHandler<AudioResponse>((sender, e) =>
{
-    // existing code …
+    lock (_fileLock)
+    {
+        // existing file-handling code …
+    }
}));
🤖 Prompt for AI Agents (early access)
In examples/agent/websocket/11_labs/Program.cs between lines 78 and 162, the
shared variables lastAudioTime and audioFileCount are accessed concurrently in
the AudioResponse event handler without synchronization, causing potential race
conditions such as simultaneous file access, incorrect increments, and corrupted
writes. To fix this, introduce a private lock object and wrap all accesses and
modifications to lastAudioTime, audioFileCount, and file operations inside a
lock statement using this object to ensure thread-safe execution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant