@deepgram/agents

中文文档
0.2.0发布于 2026/10/21MITTypeScriptESM + CJS构建来源已验证近 30 天下载 3万

Deepgram Voice Agent SDK — browser/Node WebSocket client with microphone and audio playback

原始使用文档
文档目录20 节
  1. Status
  2. Install
  3. Quick Start
  4. Authentication
  5. AgentSession
  6. Constructor
  7. Config
  8. Methods
  9. Events
  10. State
  11. Reconnect
  12. AgentMicrophone
  13. Usage
  14. Volume and Frequency Data
  15. Events
  16. AgentPlayer
  17. Usage
  18. Volume and Frequency Data
  19. Exports
  20. License

@deepgram/agents

Core SDK for the Deepgram Voice Agent API. Manages the WebSocket session, microphone capture, and audio playback with volume/frequency analysis.

Status

This package is pre-1.0. Interfaces may change between minor versions.

Install

npm install @deepgram/agents

or with Bun:

bun add @deepgram/agents

Quick Start

import { AgentSession, AgentMicrophone, AgentPlayer } from "@deepgram/agents";

const session = new AgentSession({
  auth: { tokenFactory: () => fetch('/api/deepgram-token').then(r => r.text()) },
  agent: {
    listen: { provider: { type: 'deepgram', version: 'v1', model: 'nova-3' } },
    think: { provider: { type: 'open_ai', model: 'gpt-4o-mini' } },
    speak: { provider: { type: 'deepgram', model: 'aura-2-thalia-en' } },
  },
  audio: { output: { encoding: 'linear16', sampleRate: 24_000 } },
});

const player = new AgentPlayer();
session.on("audio", (chunk) => player.queue(chunk));
session.on("conversation-text", (msg) => {
  console.log(`${msg.role}: ${msg.content}`);
});

const mic = new AgentMicrophone((data) => session.sendAudio(data));

await session.connect();
await mic.start();

// Later:
// mic.stop();
// session.disconnect();
// player.dispose();

Authentication

Two auth modes via AgentSessionConfig.auth:

// Server-side: raw API key
{ apiKey: "your-deepgram-api-key" }

// Browser-safe: token factory (recommended)
{ tokenFactory: () => fetch('/api/token').then(r => r.text()) }

The token factory is called before every connection and reconnection attempt. Tokens are cached until invalidated by a reconnect, so the factory is not called on every audio frame.

The SDK authenticates using the Sec-WebSocket-Protocol header trick -- the browser WebSocket constructor doesn't support custom headers, so the token is passed as a subprotocol value. This is handled internally.

AgentSession

Core WebSocket session. Wraps @deepgram/sdk's agent connection with:

  • Token factory auth (fresh credentials on every reconnect)
  • Typed EventEmitter events
  • Exponential-backoff reconnect with jitter
  • Automatic KeepAlive pings
  • Audio buffering until SettingsApplied
  • Ordered normalization of SDK binary Blob messages to ArrayBuffer

@deepgram/agents depends directly on @deepgram/sdk. It disables the underlying socket's retries and owns application-level reconnect so each attempt can refresh authentication and restore Settings. Accumulated conversation context is restored for inline agent configurations only; the protocol cannot attach inline context to an agent UUID. Consumers continue to receive the documented ArrayBuffer from the audio event even though the underlying SDK delivers binary messages to its callback as Blob.

Constructor

const session = new AgentSession(config: AgentSessionConfig);

Config

interface AgentSessionConfig {
  auth: { apiKey: string } | { tokenFactory: () => Promise<string> };
  agent: AgentSettingsObject | string;  // inline config or pre-built agent UUID
  audio?: {
    input?: { encoding?: AudioEncoding; sampleRate?: number };   // default: linear16 @ 16kHz
    output?: { encoding?: OutputEncoding; sampleRate?: number }; // default: linear16 @ 24kHz
  };
  keepAliveInterval?: number;  // default: 10_000ms
  reconnect?: ReconnectConfig;
  experimental?: boolean;
  tags?: string[];
}

Methods

MethodDescription
connect()Open WebSocket connection
disconnect()Close connection (no reconnect)
clearConversationHistory()Clear context accumulated for future inline-agent reconnects
sendAudio(data: ArrayBuffer)Send PCM audio frame (queued until SettingsApplied)
injectUserMessage(content)Send a text message as the user
injectAgentMessage(message, behavior?)Inject text as the agent with optional default, queue, or interrupt behavior
updateListen(listen)Update listening settings mid-session
updateSpeak(speak)Update TTS settings mid-session
updateThink(think)Update LLM settings mid-session
updatePrompt(prompt)Update system prompt mid-session
sendFunctionCallResponse(id, name, content)Respond to a function call request
getId()Returns the request ID from Welcome

Events

session.on("welcome", (msg) => {});
session.on("settings-applied", (msg) => {});
session.on("conversation-text", (msg) => {});
session.on("user-started-speaking", (msg) => {});
session.on("agent-thinking", (msg) => {});
session.on("agent-started-speaking", (msg) => {});
session.on("agent-audio-done", (msg) => {});
session.on("function-call-request", (msg) => {});
session.on("function-call-response", (msg) => {});
session.on("prompt-updated", (msg) => {});
session.on("speak-updated", (msg) => {});
session.on("think-updated", (msg) => {});
session.on("listen-updated", (msg) => {});
session.on("latency-report", (msg) => {});
session.on("history", (msg) => {});
session.on("injection-refused", (msg) => {});
session.on("error", (msg) => {});
session.on("warning", (msg) => {});

// Binary audio from the agent
session.on("audio", (chunk: ArrayBuffer) => {});

// SDK lifecycle
session.on("connecting", () => {});
session.on("connected", () => {});
session.on("reconnecting", (attempt, delayMs) => {});
session.on("disconnected", (reason) => {});
session.on("sdk-error", (err) => {});

State

session.state; // "idle" | "connecting" | "connected" | "reconnecting" | "disconnected"

Reconnect

Auto-reconnect is enabled by default with exponential backoff + jitter. After SettingsApplied, the latest value of each runtime setting (prompt, listen, speak, think) is replayed, ordered by when each setting was last updated, before audio queued during reconnect is flushed. Accumulated text and completed function-call context is restored for inline agent configurations only. Audio sent after an unexpected close or error stays queued across attempts and resumes only after the replacement connection receives SettingsApplied. The consecutive-attempt counter also resets at SettingsApplied, not merely when the transport opens. Configure via reconnect:

{
  enabled: true,       // default
  maxAttempts: 8,      // default
  baseDelay: 500,      // ms, default
  maxDelay: 30_000,    // ms, default
  jitter: true,        // default: +/-20%
}

AgentMicrophone

Captures PCM audio from the user's microphone via AudioWorklet.

Usage

const mic = new AgentMicrophone(
  (data: ArrayBuffer) => session.sendAudio(data),
  {
    sampleRate: 16_000,         // default
    echoCancellation: true,     // default
    noiseSuppression: true,     // default
    autoGainControl: true,      // default
  },
);

await mic.start();
mic.mute();
mic.unmute();
mic.stop();

Volume and Frequency Data

mic.getInputVolume();            // 0-1, RMS-based
mic.getInputByteFrequencyData(); // Uint8Array of frequency bin magnitudes (0-255)

Events

mic.on("audio-frame", (data: ArrayBuffer) => {});
mic.on("error", (err: Error) => {});

AgentPlayer

Decodes and plays raw PCM Int16 (linear16) audio from the agent. Provides volume/frequency analysis for visualizations and supports barge-in via interrupt(). AgentPlayer does not decode compressed output; use linear16 output or provide a separate decoder/player.

Usage

const player = new AgentPlayer({ sampleRate: 24_000 }); // default

// Queue audio from the session
session.on("audio", (chunk) => player.queue(chunk));

// Barge-in: interrupt when the user starts speaking
session.on("user-started-speaking", () => player.interrupt());

// Volume control
player.setVolume(0.8);
player.mute();
player.unmute();

// Cleanup
player.dispose();

Volume and Frequency Data

player.getOutputVolume();            // 0-1, RMS-based
player.getOutputByteFrequencyData(); // Uint8Array of frequency bin magnitudes (0-255)
player.getRemainingPlaybackTime();   // seconds of queued audio remaining

Exports

// Classes
export { AgentSession, AgentMicrophone, AgentPlayer };

// Types
export type {
  AgentState,
  AgentSessionConfig, AuthConfig, TokenFactory, ReconnectConfig,
  AgentSessionEvents,
  MicrophoneOptions,
  PlayerOptions,
  AgentSettingsObject, ListenSettings, ThinkSettings, SpeakSettings,
  AgentMessageBehavior,
  // Server messages
  WelcomeMessage, SettingsAppliedMessage, ConversationTextMessage,
  UserStartedSpeakingMessage, AgentThinkingMessage,
  FunctionCallRequestMessage, FunctionCallResponseMessage, FunctionCallItem,
  AgentStartedSpeakingMessage, AgentAudioDoneMessage,
  PromptUpdatedMessage, SpeakUpdatedMessage, ThinkUpdatedMessage,
  ListenUpdatedMessage, LatencyReportMessage, HistoryMessage,
  AgentErrorMessage, AgentWarningMessage,
  InjectionRefusedMessage, ServerMessage,
};

License

MIT

版本与发布记录

@deepgram/agents 共发布 3 个版本,首次发布于 2026/05/01;过去 12 个月发布了 3 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.2.0latest2026/10/2121 天前
0.1.22026/09/042 个月前
0.1.12026/05/016 个月前

关于 @deepgram/agents 的常见问题

@deepgram/agents 是什么?

Deepgram Voice Agent SDK — browser/Node WebSocket client with microphone and audio playback

如何安装 @deepgram/agents?

在项目目录运行 npm install @deepgram/agents,或使用 pnpm add / yarn add / bun add。

@deepgram/agents 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@deepgram/agents 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@deepgram/agents 可以商用吗?

@deepgram/agents 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@deepgram/agents 的下载量有多少?

根据 npm 官方下载统计,@deepgram/agents 在 2026/10/12 – 2026/11/10 这 30 天内被下载 30,091 次,日均约 1,003 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@deepgram/agents 还在维护吗?

最新版本 0.2.0 发布于 2026/10/21(21 天前);至今共发布 3 个版本,其中过去 12 个月发布了 3 个;首次发布于 2026/05/01。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。