deepgram-sdk-patterns
DeepgramのSDKをTypeScriptとPythonで実装するときに、本番環境対応のパターンを適用できます。Deepgramの統合実装、SDKの使用方法の見直し、またはチーム内のコーディング標準の策定に活用してください。「deepgram SDKパターン」「deepgramベストプラクティス」「deepgramコードパターン」「idiomatic deepgram」「deepgram typescript」といったキーワードで呼び出せます。
description の原文を見る
Apply production-ready Deepgram SDK patterns for TypeScript and Python. Use when implementing Deepgram integrations, refactoring SDK usage, or establishing team coding standards for Deepgram. Trigger with phrases like "deepgram SDK patterns", "deepgram best practices", "deepgram code patterns", "idiomatic deepgram", "deepgram typescript".
SKILL.md 本文
Deepgram SDK パターン
概要
適切なエラーハンドリング、型定義、構造を備えた Deepgram SDK 統合用の本番環境対応パターン。
前提条件
deepgram-install-authセットアップ完了- async/await パターンの理解
- エラーハンドリングのベストプラクティスの理解
手順
ステップ 1: 型安全なクライアントシングルトンの作成
Deepgram クライアント用のシングルトンパターンを実装します。
ステップ 2: 堅牢なエラーハンドリングの追加
すべての API 呼び出しに適切なエラーハンドリングとログ記録を追加します。
ステップ 3: レスポンス検証の実装
API レスポンスを処理前に検証します。
ステップ 4: リトライロジックの追加
一時的な障害に対して指数バックオフを実装します。
出力
- 型安全なクライアントシングルトン
- 構造化ログ付きの堅牢なエラーハンドリング
- 指数バックオフを使用した自動リトライ
- API レスポンスのランタイム検証
エラーハンドリング
| エラー | 原因 | 解決方法 |
|---|---|---|
| 型の不一致 | 不正なレスポンス形式 | ランタイム検証を追加 |
| クライアント未定義 | シングルトンが初期化されていない | 使用前に init() を呼び出し |
| メモリリーク | 複数のクライアントインスタンス | シングルトンパターンを使用 |
| タイムアウト | 大きなオーディオファイル | タイムアウト設定を増加 |
例
TypeScript クライアントシングルトン
// lib/deepgram.ts
import { createClient, DeepgramClient } from '@deepgram/sdk';
let client: DeepgramClient | null = null;
export function getDeepgramClient(): DeepgramClient {
if (!client) {
const apiKey = process.env.DEEPGRAM_API_KEY;
if (!apiKey) {
throw new Error('DEEPGRAM_API_KEY environment variable not set');
}
client = createClient(apiKey);
}
return client;
}
export function resetClient(): void {
client = null;
}
型定義されたトランスクリプションレスポンス
// types/deepgram.ts
export interface TranscriptWord {
word: string;
start: number;
end: number;
confidence: number;
punctuated_word?: string;
}
export interface TranscriptAlternative {
transcript: string;
confidence: number;
words: TranscriptWord[];
}
export interface TranscriptChannel {
alternatives: TranscriptAlternative[];
}
export interface TranscriptResult {
results: {
channels: TranscriptChannel[];
utterances?: Array<{
start: number;
end: number;
transcript: string;
speaker: number;
}>;
};
metadata: {
request_id: string;
model_uuid: string;
model_info: Record<string, unknown>;
};
}
エラーハンドリングラッパー
// lib/transcribe.ts
import { getDeepgramClient } from './deepgram';
import { TranscriptResult } from '../types/deepgram';
export class TranscriptionError extends Error {
constructor(
message: string,
public readonly code: string,
public readonly requestId?: string
) {
super(message);
this.name = 'TranscriptionError';
}
}
export async function transcribeUrl(
url: string,
options: { model?: string; language?: string } = {}
): Promise<TranscriptResult> {
const client = getDeepgramClient();
try {
const { result, error } = await client.listen.prerecorded.transcribeUrl(
{ url },
{
model: options.model || 'nova-2',
language: options.language || 'en',
smart_format: true,
punctuate: true,
}
);
if (error) {
throw new TranscriptionError(
error.message || 'Transcription failed',
error.code || 'UNKNOWN_ERROR'
);
}
return result as TranscriptResult;
} catch (err) {
if (err instanceof TranscriptionError) throw err;
throw new TranscriptionError(
err instanceof Error ? err.message : 'Unknown error',
'NETWORK_ERROR'
);
}
}
指数バックオフを使用したリトライ
// lib/retry.ts
interface RetryOptions {
maxRetries?: number;
baseDelay?: number;
maxDelay?: number;
}
export async function withRetry<T>(
fn: () => Promise<T>,
options: RetryOptions = {}
): Promise<T> {
const { maxRetries = 3, baseDelay = 1000, maxDelay = 10000 } = options;
let lastError: Error | undefined;
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
return await fn();
} catch (error) {
lastError = error instanceof Error ? error : new Error(String(error));
// Don't retry on auth errors
if (lastError.message.includes('401') ||
lastError.message.includes('403')) {
throw lastError;
}
if (attempt < maxRetries) {
const delay = Math.min(baseDelay * Math.pow(2, attempt), maxDelay);
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}
throw lastError;
}
// Usage
const result = await withRetry(() => transcribeUrl(audioUrl));
Python パターン
# lib/deepgram_client.py
from deepgram import DeepgramClient, PrerecordedOptions
from functools import lru_cache
import os
@lru_cache(maxsize=1)
def get_deepgram_client() -> DeepgramClient:
"""Get or create Deepgram client singleton."""
api_key = os.environ.get('DEEPGRAM_API_KEY')
if not api_key:
raise ValueError('DEEPGRAM_API_KEY environment variable not set')
return DeepgramClient(api_key)
def transcribe_url(url: str, model: str = 'nova-2') -> dict:
"""Transcribe audio from URL with error handling."""
client = get_deepgram_client()
options = PrerecordedOptions(
model=model,
smart_format=True,
punctuate=True,
)
try:
response = client.listen.rest.v("1").transcribe_url(
{"url": url},
options
)
return response.to_dict()
except Exception as e:
raise TranscriptionError(str(e)) from e
リソース
次のステップ
deepgram-core-workflow-a に進み、音声テキスト変換ワークフロー実装を行います。
ライセンス: MIT(寛容ライセンスのため全文を引用しています) · 原本リポジトリ
詳細情報
- 作者
- Brmbobo
- リポジトリ
- Brmbobo/Web2podcast
- ライセンス
- MIT
- 最終更新
- 2026/1/26
Source: https://github.com/Brmbobo/Web2podcast / ライセンス: MIT
関連スキル
doubt-driven-development
重要な判断はすべて、本番環境への展開前に新しい視点から対抗的レビューを実施します。速度より正確性が重要な場合、不慣れなコードを扱う場合、本番環境・セキュリティに関わるロジック・取り消し不可の操作など影響度が高い場合、または後でバグを修正するよりも今検証する方が効率的な場合に活用してください。
apprun-skills
TypeScriptを使用したAppRunアプリケーションのMVU設計に関する総合的なガイダンスが得られます。コンポーネントパターン、イベントハンドリング、状態管理(非同期ジェネレータを含む)、パラメータと保護機能を備えたルーティング・ナビゲーション、vistestを使用したテストに対応しています。AppRunコンポーネントの設計・レビュー、ルートの配線、状態フローの管理、AppRunテストの作成時に活用してください。
desloppify
コードベースのヘルスチェックと技術負債の追跡ツールです。コード品質、技術負債、デッドコード、大規模ファイル、ゴッドクラス、重複関数、コードスメル、命名規則の問題、インポートサイクル、結合度の問題についてユーザーが質問した場合に使用してください。また、ヘルススコアの確認、次の改善項目の提案、クリーンアップ計画の作成をリクエストされた際にも対応します。29言語に対応しています。
debugging-and-error-recovery
テストが失敗したり、ビルドが壊れたり、動作が期待と異なったり、予期しないエラーが発生したりした場合に、体系的な根本原因デバッグをガイドします。推測ではなく、根本原因を見つけて修正するための体系的なアプローチが必要な場合に使用してください。
test-driven-development
テスト駆動開発により実装を進めます。ロジックの実装、バグの修正、動作の変更など、あらゆる場面で活用できます。コードが正常に動作することを証明する必要がある場合、バグ報告を受けた場合、既存機能を修正する予定がある場合に使用してください。
incremental-implementation
変更を段階的に実施します。複数のファイルに影響する機能や変更を実装する場合に使用してください。大量のコードを一度に書こうとしている場合や、タスクが一度では完結できないほど大きい場合に活用します。