DE

deepgram-sdk-patterns

Provides idiomatic code patterns for Deepgram SDKs to ensure stable, maintainable, and efficient API usage.

Install

mkdir -p .claude/skills/deepgram-sdk-patterns && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/5334" && unzip -o skill.zip -d .claude/skills/deepgram-sdk-patterns && rm skill.zip

Installs to .claude/skills/deepgram-sdk-patterns

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Apply production-ready Deepgram SDK patterns for TypeScript and Python.
71 charsno explicit “when” trigger
Intermediate

Key capabilities

  • Implement singleton client wrappers
  • Develop text-to-speech pipelines with Aura voices
  • Build audio intelligence pipelines for summary and sentiment
  • Standardize error handling for SDK calls
  • Migrate between SDK versions

How it works

It provides production-ready code patterns for client instantiation, stream handling, and feature-rich API requests using the Deepgram SDK.

Inputs & outputs

You give it
Audio or text data
You get back
Transcribed text, audio files, or intelligence metadata

When to use deepgram-sdk-patterns

  • Implement singleton client wrapper for Deepgram
  • Standardize error handling for API calls
  • Build maintainable TTS pipelines with Aura
  • Apply team-wide coding standards for SDK usage

About this skill

Deepgram SDK Patterns

Overview

Production patterns for @deepgram/sdk (TypeScript) and deepgram-sdk (Python). Covers singleton client, typed wrappers, text-to-speech with Aura, audio intelligence pipeline, error handling, and SDK v5 migration path.

Prerequisites

  • npm install @deepgram/sdk or pip install deepgram-sdk
  • DEEPGRAM_API_KEY environment variable configured

Instructions

Step 1: Singleton Client (TypeScript)

import { createClient, DeepgramClient } from '@deepgram/sdk';

class DeepgramService {
  private static instance: DeepgramService;
  private client: DeepgramClient;

  private constructor() {
    const apiKey = process.env.DEEPGRAM_API_KEY;
    if (!apiKey) throw new Error('DEEPGRAM_API_KEY is required');
    this.client = createClient(apiKey);
  }

  static getInstance(): DeepgramService {
    if (!this.instance) this.instance = new DeepgramService();
    return this.instance;
  }

  getClient(): DeepgramClient { return this.client; }
}

export const deepgram = DeepgramService.getInstance().getClient();

Step 2: Text-to-Speech with Aura

import { createClient } from '@deepgram/sdk';
import { writeFileSync } from 'fs';

const deepgram = createClient(process.env.DEEPGRAM_API_KEY!);

async function textToSpeech(text: string, outputPath: string) {
  const response = await deepgram.speak.request(
    { text },
    {
      model: 'aura-2-thalia-en',  // Female English voice
      encoding: 'linear16',
      container: 'wav',
      sample_rate: 24000,
    }
  );

  const stream = await response.getStream();
  if (!stream) throw new Error('No audio stream returned');

  // Collect stream into buffer
  const reader = stream.getReader();
  const chunks: Uint8Array[] = [];
  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    chunks.push(value);
  }

  const buffer = Buffer.concat(chunks);
  writeFileSync(outputPath, buffer);
  console.log(`Audio saved: ${outputPath} (${buffer.length} bytes)`);
  return buffer;
}

// Aura-2 voice options:
// aura-2-thalia-en    — Female, warm
// aura-2-asteria-en   — Female, default
// aura-2-orion-en     — Male, deep
// aura-2-luna-en      — Female, soft
// aura-2-helios-en    — Male, authoritative
// aura-asteria-en     — Aura v1 fallback

Step 3: Audio Intelligence Pipeline

async function analyzeConversation(audioUrl: string) {
  const { result, error } = await deepgram.listen.prerecorded.transcribeUrl(
    { url: audioUrl },
    {
      model: 'nova-3',
      smart_format: true,
      diarize: true,
      utterances: true,
      // Audio Intelligence features
      summarize: 'v2',       // Generates a short summary
      detect_topics: true,   // Identifies key topics
      sentiment: true,       // Per-segment sentiment analysis
      intents: true,         // Identifies speaker intents
    }
  );
  if (error) throw error;

  return {
    transcript: result.results.channels[0].alternatives[0].transcript,
    summary: result.results.summary?.short,
    topics: result.results.topics?.segments?.map((s: any) => ({
      text: s.text,
      topics: s.topics.map((t: any) => t.topic),
    })),
    sentiments: result.results.sentiments?.segments?.map((s: any) => ({
      text: s.text,
      sentiment: s.sentiment,
      confidence: s.sentiment_score,
    })),
    intents: result.results.intents?.segments?.map((s: any) => ({
      text: s.text,
      intent: s.intents[0]?.intent,
      confidence: s.intents[0]?.confidence_score,
    })),
  };
}

Step 4: Python Production Patterns

from deepgram import DeepgramClient, PrerecordedOptions, LiveOptions, SpeakOptions
import os

class DeepgramService:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance.client = DeepgramClient(os.environ["DEEPGRAM_API_KEY"])
        return cls._instance

    def transcribe_url(self, url: str, **kwargs):
        options = PrerecordedOptions(
            model=kwargs.get("model", "nova-3"),
            smart_format=True,
            diarize=kwargs.get("diarize", False),
            summarize=kwargs.get("summarize", False),
        )
        source = {"url": url}
        return self.client.listen.rest.v("1").transcribe_url(source, options)

    def transcribe_file(self, path: str, **kwargs):
        with open(path, "rb") as f:
            source = {"buffer": f.read(), "mimetype": self._mimetype(path)}
        options = PrerecordedOptions(
            model=kwargs.get("model", "nova-3"),
            smart_format=True,
            diarize=kwargs.get("diarize", False),
        )
        return self.client.listen.rest.v("1").transcribe_file(source, options)

    def text_to_speech(self, text: str, output_path: str):
        options = SpeakOptions(model="aura-2-thalia-en", encoding="linear16")
        response = self.client.speak.rest.v("1").save(output_path, {"text": text}, options)
        return response

    @staticmethod
    def _mimetype(path: str) -> str:
        ext = path.rsplit(".", 1)[-1].lower()
        return {"wav": "audio/wav", "mp3": "audio/mpeg", "flac": "audio/flac",
                "ogg": "audio/ogg", "m4a": "audio/mp4"}.get(ext, "audio/wav")

Step 5: Typed Response Helpers

// Extract clean types from Deepgram responses
interface TranscriptWord {
  word: string;
  start: number;
  end: number;
  confidence: number;
  speaker?: number;
  punctuated_word?: string;
}

interface TranscriptResult {
  transcript: string;
  confidence: number;
  words: TranscriptWord[];
  duration: number;
  requestId: string;
}

function parseResult(result: any): TranscriptResult {
  const alt = result.results.channels[0].alternatives[0];
  return {
    transcript: alt.transcript,
    confidence: alt.confidence,
    words: alt.words ?? [],
    duration: result.metadata.duration,
    requestId: result.metadata.request_id,
  };
}

Step 6: SDK v5 Migration Notes

// v3/v4 (current stable):
import { createClient } from '@deepgram/sdk';
const dg = createClient(apiKey);
await dg.listen.prerecorded.transcribeUrl(source, options);
await dg.listen.live(options);
await dg.speak.request({ text }, options);

// v5 (auto-generated, Fern-based):
import { DeepgramClient } from '@deepgram/sdk';
const dg = new DeepgramClient({ apiKey });
await dg.listen.v1.media.transcribeUrl(source, options);
await dg.listen.v1.connect(options);  // async
await dg.speak.v1.audio.generate({ text }, options);

Output

  • Singleton client pattern with environment validation
  • Text-to-speech (Aura-2) with stream-to-file
  • Audio intelligence pipeline (summary, topics, sentiment, intents)
  • Python production service class
  • Typed response helpers
  • v5 migration reference

Error Handling

ErrorCauseSolution
401 UnauthorizedInvalid API keyCheck DEEPGRAM_API_KEY value
400 Unsupported formatBad audio codecConvert to WAV/MP3/FLAC
speak.request is not a functionSDK version mismatchCheck import, v5 uses speak.v1.audio.generate
Empty TTS responseEmpty text inputValidate text is non-empty before calling
summarize returns nullFeature not enabledPass summarize: 'v2' (string, not boolean)

Resources

Next Steps

Proceed to deepgram-data-handling for transcript storage and processing patterns.

When not to use it

  • When simple script-based usage is sufficient
  • When complex audio intelligence features are not required

Prerequisites

Deepgram SDKDEEPGRAM_API_KEY

Limitations

  • Requires SDK-specific versioning knowledge
  • Audio intelligence features require specific API parameters

How it compares

It establishes team-wide coding standards and reusable service classes instead of ad-hoc SDK implementation.

Compared to similar skills

deepgram-sdk-patterns side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
deepgram-sdk-patterns (this skill)127dReviewIntermediate
exa-upgrade-migration127dReviewIntermediate
instantly-sdk-patterns127dCautionIntermediate
perplexity-known-pitfalls027dReviewIntermediate

Try saying

Example prompts that trigger this skill in your AI assistant.

More by jeremylongshore

View all by jeremylongshore

analyzing-logs

jeremylongshore

Analyze application logs to detect performance issues, identify error patterns, and improve stability by extracting key insights.

14123

ollama-setup

jeremylongshore

Configure auto-configure Ollama when user needs local LLM deployment, free AI alternatives, or wants to eliminate hosted API costs. Trigger phrases: "install ollama", "local AI", "free LLM", "self-hosted AI", "replace OpenAI", "no API costs". Use when appropriate context detected. Trigger with relevant phrases based on skill purpose.

1167

backtesting-trading-strategies

jeremylongshore

Backtest crypto and traditional trading strategies against historical data. Calculates performance metrics (Sharpe, Sortino, max drawdown), generates equity curves, and optimizes strategy parameters. Use when user wants to test a trading strategy, validate signals, or compare approaches. Trigger with phrases like "backtest strategy", "test trading strategy", "historical performance", "simulate trades", "optimize parameters", or "validate signals".

1071

generating-database-seed-data

jeremylongshore

Process this skill enables AI assistant to generate realistic test data and database seed scripts for development and testing environments. it uses faker libraries to create realistic data, maintains relational integrity, and allows configurable data volumes. u... Use when working with databases or data models. Trigger with phrases like 'database', 'query', or 'schema'.

1033

cursor-codebase-indexing

jeremylongshore

Execute set up and optimize Cursor codebase indexing. Triggers on "cursor index setup", "codebase indexing", "index codebase", "cursor semantic search". Use when working with cursor codebase indexing functionality. Trigger with phrases like "cursor codebase indexing", "cursor indexing", "cursor".

885

testing-mobile-apps

jeremylongshore

Execute mobile app testing on iOS and Android devices/simulators. Use when performing specialized testing. Trigger with phrases like "test mobile app", "run iOS tests", or "validate Android functionality".

810

You might also like

exa-upgrade-migration

jeremylongshore

Analyze, plan, and execute Exa SDK upgrades with breaking change detection. Use when upgrading Exa SDK versions, detecting deprecations, or migrating to new API versions. Trigger with phrases like "upgrade exa", "exa migration", "exa breaking changes", "update exa SDK", "analyze exa version".

14

instantly-sdk-patterns

jeremylongshore

Apply production-ready Instantly SDK patterns for TypeScript and Python. Use when implementing Instantly integrations, refactoring SDK usage, or establishing team coding standards for Instantly. Trigger with phrases like "instantly SDK patterns", "instantly best practices", "instantly code patterns", "idiomatic instantly".

12

perplexity-known-pitfalls

jeremylongshore

Identify and avoid Perplexity anti-patterns and common integration mistakes. Use when reviewing Perplexity code for issues, onboarding new developers, or auditing existing Perplexity integrations for best practices violations. Trigger with phrases like "perplexity mistakes", "perplexity anti-patterns", "perplexity pitfalls", "perplexity what not to do", "perplexity code review".

01

speak-sdk-patterns

jeremylongshore

Apply production-ready Speak SDK patterns for TypeScript and Python. Use when implementing Speak integrations, refactoring SDK usage, or establishing team coding standards for language learning features. Trigger with phrases like "speak SDK patterns", "speak best practices", "speak code patterns", "idiomatic speak".

01

mcp-builder

anthropics

Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).

136215

stripe-integration

wshobson

Implement Stripe payment processing for robust, PCI-compliant payment flows including checkout, subscriptions, and webhooks. Use when integrating Stripe payments, building subscription systems, or implementing secure checkout flows.

48165

Search skills

Search the agent skills registry