К основному содержанию
скилл CX Codex

deepgram-core-workflow-b — скилл для Claude Code: расшифровка речи

Скилл deepgram-core-workflow-b для Claude Code подключает потоковую расшифровку через Deepgram WebSocket. Используется для голосовых интерфейсов, живых субтитров и приложений с голосовым ИИ.

MIT 1 установок ★ 2 935 обновлён 2026-10-29

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add jeremylongshore/tons-of-skills-marketplace --skill deepgram-core-workflow-b -a claude-code
Открыть на GitHub

Что делает deepgram-core-workflow-b

Скилл описывает работу с Deepgram WebSocket через @deepgram/sdk: подключение аудио, обработку промежуточных и финальных результатов, определение конца реплики и разделение речи по говорящим. Также в нём есть схема переподключения с задержкой и пример SSE-обработчика для браузерных клиентов.

Для работы нужны установленный @deepgram/sdk и ключ DEEPGRAM_API_KEY. Источником звука может быть микрофон, поток файла или аудио из браузера по WebSocket. Захват с микрофона использует rec из Sox, поэтому без установленного Sox этот вариант не заработает. Скилл также описывает проверку соединения и авторизации на тестовой фразе, а в журнал предлагает записывать идентификатор корреляции и смену состояний, не аудио и не ключи.

Какие задачи решает

  • подключить аудио к Deepgram через WebSocket
  • обрабатывать промежуточную и финальную расшифровку
  • разделить текст расшифровки по говорящим
  • переподключать поток после ошибки соединения
  • передавать результаты транскрипции браузеру через SSE

Примеры запросов агенту

  • Настрой потоковую расшифровку речи через Deepgram WebSocket в этом приложении.
  • Добавь захват звука с микрофона через rec и обработку финальных результатов.
  • Раздели финальную расшифровку по говорящим и добавь переподключение при обрыве.

Как установить deepgram-core-workflow-b

1Через Skills CLI (Vercel)

npx skills add jeremylongshore/tons-of-skills-marketplace --skill deepgram-core-workflow-b -a claude-code

2Вручную: положить файлы

~/.claude/skills/deepgram-core-workflow-b/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/deepgram-core-workflow-b/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о deepgram-core-workflow-b

Как установить deepgram-core-workflow-b в Claude Code?

Выполни npx skills add jeremylongshore/tons-of-skills-marketplace --skill deepgram-core-workflow-b -a claude-code. Файл скилла находится по пути ~/.claude/skills/deepgram-core-workflow-b/SKILL.md.

Что делает deepgram-core-workflow-b?

Помогает настроить потоковую расшифровку через Deepgram WebSocket: обрабатывать результаты, отмечать конец реплики и разделять речь по говорящим. Также описывает переподключение и передачу расшифровки браузеру через SSE.

Что нужно для захвата звука с микрофона?

Нужны @deepgram/sdk, настроенный DEEPGRAM_API_KEY и установленный Sox. Захват запускается через rec.

Исходный текст

SKILL.md · MIT
---
name: deepgram-core-workflow-b
description: 'Implement real-time streaming transcription with Deepgram WebSocket.

  Use when building live transcription, voice interfaces,

  real-time captioning, or voice AI applications.

  Trigger: "deepgram streaming", "real-time transcription", "live transcription",

  "websocket transcription", "voice streaming", "deepgram live".

  '
allowed-tools: Read, Write, Edit, Bash(npm:*), Bash(pip:*), Grep
version: 1.13.0
license: MIT
author: Jeremy Longshore <[email protected]>
tags:
- saas
- deepgram
- voice-ai
- transcription
- streaming
- websocket
compatibility: Designed for Claude Code
---
# Deepgram Core Workflow B: Live Streaming Transcription

## Examples

Open a development streaming session with a non-sensitive test utterance, verify connection/authentication, partial/final transcript state, timeout, and close behavior. Enforce the session's data/consent policy and log a correlation ID plus state transitions—not audio bytes, API keys, or full participant speech.

## Overview

Real-time streaming transcription using Deepgram's WebSocket API. The SDK manages the WebSocket connection via `listen.live()`. Covers microphone capture, interim/final result handling, speaker diarization, UtteranceEnd detection, auto-reconnect, and building an SSE endpoint for browser clients.

## Prerequisites

- `@deepgram/sdk` installed, `DEEPGRAM_API_KEY` configured
- Audio source: microphone (via Sox/`rec`), file stream, or WebSocket audio from browser
- For mic capture: `sox` installed (`apt install sox` / `brew install sox`)

## Instructions

### Step 1: Basic Live Transcription

```typescript
import { createClient, LiveTranscriptionEvents } from '@deepgram/sdk';

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

const connection = deepgram.listen.live({
  model: 'nova-3',
  language: 'en',
  smart_format: true,
  punctuate: true,
  interim_results: true,      // Show in-progress results
  utterance_end_ms: 1000,     // Silence threshold for utterance end
  vad_events: true,           // Voice activity detection events
  encoding: 'linear16',       // 16-bit PCM
  sample_rate: 16000,         // 16 kHz
  channels: 1,                // Mono
});

// Connection lifecycle events
connection.on(LiveTranscriptionEvents.Open, () => {
  console.log('WebSocket connected to Deepgram');
});

connection.on(LiveTranscriptionEvents.Close, () => {
  console.log('WebSocket closed');
});

connection.on(LiveTranscriptionEvents.Error, (err) => {
  console.error('Deepgram error:', err);
});

// Transcript events
connection.on(LiveTranscriptionEvents.Transcript, (data) => {
  const transcript = data.channel.alternatives[0]?.transcript;
  if (!transcript) return;

  if (data.is_final) {
    console.log(`[FINAL] ${transcript}`);
  } else {
    process.stdout.write(`\r[interim] ${transcript}`);
  }
});

// UtteranceEnd — fires when speaker pauses
connection.on(LiveTranscriptionEvents.UtteranceEnd, () => {
  console.log('\n--- utterance end ---');
});
```

### Step 2: Microphone Capture with Sox

```typescript
import { spawn } from 'child_process';

function startMicrophone(connection: any) {
  // Sox captures from default mic: 16kHz, 16-bit signed LE, mono
  const mic = spawn('rec', [
    '-q',              // Quiet (no progress)
    '-r', '16000',     // Sample rate
    '-e', 'signed',    // Encoding
    '-b', '16',        // Bit depth
    '-c', '1',         // Mono
    '-t', 'raw',       // Raw PCM output
    '-',               // Output to stdout
  ]);

  mic.stdout.on('data', (chunk: Buffer) => {
    if (connection.getReadyState() === 1) {  // WebSocket.OPEN
      connection.send(chunk);
    }
  });

  mic.on('error', (err) => {
    console.error('Microphone error:', err.message);
    console.log('Install sox: apt install sox / brew install sox');
  });

  return mic;
}

// Usage
const mic = startMicrophone(connection);

// Graceful shutdown
process.on('SIGINT', () => {
  mic.kill();
  connection.finish();  // Sends CloseStream message, waits for final results
  setTimeout(() => process.exit(0), 2000);
});
```

### Step 3: Live Diarization

```typescript
const connection = deepgram.listen.live({
  model: 'nova-3',
  smart_format: true,
  diarize: true,
  interim_results: false,  // Only final for cleaner diarization
  utterance_end_ms: 1500,
  encoding: 'linear16',
  sample_rate: 16000,
  channels: 1,
});

connection.on(LiveTranscriptionEvents.Transcript, (data) => {
  if (!data.is_final) return;

  const words = data.channel.alternatives[0]?.words ?? [];
  if (words.length === 0) return;

  // Group consecutive words by speaker
  let currentSpeaker = words[0].speaker;
  let segment = '';

  for (const word of words) {
    if (word.speaker !== currentSpeaker) {
      console.log(`Speaker ${currentSpeaker}: ${segment.trim()}`);
      currentSpeaker = word.speaker;
      segment = '';
    }
    segment += ` ${word.punctuated_word ?? word.word}`;
  }
  console.log(`Speaker ${currentSpeaker}: ${segment.trim()}`);
});
```

### Step 4: Auto-Reconnect with Backoff

```typescript
class ReconnectingLiveTranscription {
  private client: ReturnType<typeof createClient>;
  private connection: any = null;
  private reconnectAttempts = 0;
  private maxReconnectAttempts = 10;
  private baseDelay = 1000;

  constructor(apiKey: string, private options: Record<string, any>) {
    this.client = createClient(apiKey);
  }

  connect() {
    this.connection = this.client.listen.live(this.options);

    this.connection.on(LiveTranscriptionEvents.Open, () => {
      console.log('Connected');
      this.reconnectAttempts = 0;  // Reset on success
    });

    this.connection.on(LiveTranscriptionEvents.Close, () => {
      this.scheduleReconnect();
    });

    this.connection.on(LiveTranscriptionEvents.Error, (err: Error) => {
      console.error('Connection error:', err.message);
      this.scheduleReconnect();
    });

    return this.connection;
  }

  private scheduleReconnect() {
    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.error('Max reconnection attempts reached');
      return;
    }
    const delay = this.baseDelay * Math.pow(2, this.reconnectAttempts)
      + Math.random() * 1000;  // Jitter
    this.reconnectAttempts++;
    console.log(`Reconnecting in ${Math.round(delay)}ms (attempt ${this.reconnectAttempts})`);
    setTimeout(() => this.connect(), delay);
  }

  send(chunk: Buffer) {
    if (this.connection?.getReadyState() === 1) {
      this.connection.send(chunk);
    }
  }

  close() {
    this.maxReconnectAttempts = 0;  // Prevent reconnect
    this.connection?.finish();
  }
}
```

### Step 5: SSE Endpoint for Browser Clients

```typescript
import express from 'express';
import { createClient, LiveTranscriptionEvents } from '@deepgram/sdk';

const app = express();

app.get('/api/transcribe/stream', (req, res) => {
  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');

  const deepgram = createClient(process.env.DEEPGRAM_API_KEY!);
  const connection = deepgram.listen.live({
    model: 'nova-3',
    smart_format: true,
    interim_results: true,
    encoding: 'linear16',
    sample_rate: 16000,
    channels: 1,
  });

  connection.on(LiveTranscriptionEvents.Transcript, (data) => {
    const transcript = data.channel.alternatives[0]?.transcript;
    if (transcript) {
      res.write(`data: ${JSON.stringify({
        transcript,
        is_final: data.is_final,
        speech_final: data.speech_final,
      })}\n\n`);
    }
  });

  // Client provides audio via a paired WebSocket (see browser setup)
  req.on('close', () => {
    connection.finish();
  });
});
```

### Step 6: KeepAlive for Long Sessions

```typescript
// Deepgram closes idle connections after ~10s of no audio.
// Send KeepAlive messages during silence periods.
connection.on(LiveTranscriptionEvents.Open, () => {
  const keepAliveInterval = setInterval(() => {
    if (connection.getReadyState() === 1) {
      connection.keepAlive();
    }
  }, 8000);  // Every 8 seconds

  connection.on(LiveTranscriptionEvents.Close, () => {
    clearInterval(keepAliveInterval);
  });
});
```

## Output

- Live WebSocket transcription with interim/final results
- Microphone capture pipeline (Sox -> Deepgram)
- Speaker diarization in streaming mode
- Auto-reconnect with exponential backoff and jitter
- SSE endpoint for browser integration
- KeepAlive handling for long sessions

## Error Handling

| Issue | Cause | Solution |
|-------|-------|----------|
| WebSocket closes immediately | Invalid API key or bad encoding params | Check key, verify `encoding`/`sample_rate` match audio |
| No transcripts received | Audio not being sent or wrong format | Verify `connection.send(chunk)` is called with raw PCM |
| High latency | Network congestion | Use `interim_results: true` for perceived speed |
| `rec` command not found | Sox not installed | `apt install sox` or `brew install sox` |
| Connection drops after 10s | No audio + no KeepAlive | Send `connection.keepAlive()` every 8s |
| Garbled output | Sample rate mismatch | Ensure audio sample rate matches `sample_rate` option |

## Resources

- [Live Streaming Audio](https://developers.deepgram.com/docs/live-streaming-audio)
- [Streaming API Reference](https://developers.deepgram.com/reference/speech-to-text/listen-streaming)
- [End of Speech Detection](https://developers.deepgram.com/docs/understanding-end-of-speech-detection)
- [SDK LiveTranscriptionEvents](https://github.com/deepgram/deepgram-js-sdk)

## Next Steps

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

© Jeremy Longshore · MIT · jeremylongshore/tons-of-skills-marketplace

Похожие скиллы

Все скиллы по теме «ИИ и ML» →
deepgram membrane Скилл для интеграции Deepgram: управляйте проектами, API-ключами и запускайте транскрипцию аудио и видео через Membrane CLI. Нужен аккаунт Deepgram (бесплатный тариф поддерживается) и доступ в сеть. CX Codex +1 162установок deepgram-speech calesthio Скилл deepgram-speech для Claude Code настраивает транскрибацию, синтез речи Aura и голосовых агентов через Deepgram. Запускается при выборе моделей распознавания, разметке субтитров и диаризации. CX Codex +1 132установок deepgram-webhooks hookdeck Скилл deepgram-webhooks для Claude Code принимает и проверяет вебхуки Deepgram. Обрабатывает асинхронные результаты транскрипции и колбэки завершённых запросов. CX Codex +1 200установок assemblyai AssemblyAI Скилл помогает писать код для транскрибации, потокового распознавания речи, диктовки и синтеза речи через AssemblyAI. Нужен при работе с голосовыми функциями. CX Codex +1 614установок voice-ai-development sickn33 Скилл voice-ai-development для Claude Code проектирует голосовых агентов и приложения с речевым интерфейсом. Работает с транскрибацией, синтезом речи и аудио в реальном времени. CX Codex +1 972установок gemini-live-api-dev официальный google-gemini Скилл gemini-live-api-dev обучает агента собирать потоковые голосовые и видеоприложения через Gemini Live API поверх WebSockets. Помогает настроить сессии на Gemini 3.8 и перевести проект со старых версий API. CX Codex +1 11 300установок

Из того же набора139

Весь набор →
instantly-webhooks-events Скилл instantly-webhooks-events помогает развернуть надёжный приёмник вебхуков Instantly API v2 с валидацией схем, дедупликацией событий и защитой секретов. CX Codex +1 1установок windsurf-data-handling Скилл windsurf-data-handling помогает описать потоки данных, настроить исключения контекста и собрать подтверждения для проверок приватности и соответствия. CX Codex +1 1установок windsurf-flows-automation Скилл windsurf-flows-automation для Claude Code создаёт и сопровождает Windsurf Flows — автоматизированные сценарии повторяющихся задач разработки. Превращает рутину в команды. CX Codex +1 1установок lindy-core-workflow-b Скилл lindy-core-workflow-b для Claude Code описывает настройку триггеров, расписаний и связок агентов в Lindy. Задаёт сценарии сборки автономных рабочих процессов. CX Codex +1 1установок code-documentation-analyzer Автоактивируемый скилл для разбора документации кода: API-справочники, руководства пользователя, архитектурные описания. Включается по фразам вроде «code documentation analyzer» или «code analyzer». CX Codex +1 1установок retellai-policy-guardrails Скилл retellai-policy-guardrails задаёт правила и границы действий для голосовых агентов на платформе Retell AI. Он нужен при настройке телефонии, чтобы бот не выходил за рамки разрешённых операций. CX Codex +1 1установок openevidence-deploy-integration Скилл openevidence-deploy-integration помогает спланировать внедрение OpenEvidence в клинический процесс: от выбора рабочего сценария до обучения, согласований и условий отката. CX Codex +1 1установок speak-install-auth Скилл speak-install-auth для подключения Speak — платформы изучения языков с AI-наставником. Настраивает API-ключи, OpenAI Realtime для речи и готовит среду к первому уроку на одном из 14+ языков. CX Codex +1 1установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой