@deepgram/react

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

React hooks and components for @deepgram/agents

原始使用文档
文档目录18 节
  1. Install
  2. Quick Start
  3. AgentProvider
  4. Mode Tracking
  5. Hooks
  6. useAgentState
  7. useAgentMode
  8. useAgentConversation
  9. useAgentMicrophone
  10. useAgentPlayer
  11. useAgentControls
  12. useAgentClientTool
  13. useAgentSession
  14. useAgentContext
  15. useDeepgramAgent (standalone)
  16. Exports
  17. Migration
  18. License

@deepgram/react

React provider and hooks for the Deepgram Voice Agent API. Manages connection lifecycle, microphone, audio playback, conversation state, and mode tracking.

For pre-built UI components, see @deepgram/ui.

Install

npm install @deepgram/react @deepgram/agents

Quick Start

import { AgentProvider, useAgentState, useAgentConversation } from "@deepgram/react";

function App() {
  return (
    <AgentProvider
      config={{
        auth: { tokenFactory: () => fetch('/api/deepgram-token').then(r => r.text()) },
        agent: { think: { provider: { type: 'open_ai', model: 'gpt-4o-mini' } } },
      }}
    >
      <VoiceAgent />
    </AgentProvider>
  );
}

function VoiceAgent() {
  const { state, start, stop } = useAgentState();
  const { conversation, sendUserMessage } = useAgentConversation();
  const handleStart = async () => {
    try {
      await start();
    } catch (error) {
      console.error("Failed to start voice agent", error);
    }
  };

  return (
    <div>
      <button onClick={state === "idle" ? handleStart : stop}>
        {state === "idle" ? "Start" : "Stop"}
      </button>
      {conversation.map((entry) => (
        <p key={entry.id}><b>{entry.role}:</b> {entry.content}</p>
      ))}
    </div>
  );
}

AgentProvider

Wraps your component tree with agent state management. Creates and manages an AgentSession, AgentMicrophone, and AgentPlayer internally.

<AgentProvider
  config={agentSessionConfig}   // Required: AgentSessionConfig
  microphone={true}             // Enable microphone capture (default: true)
  microphoneOptions={{          // MicrophoneOptions
    sampleRate: 16_000,
    echoCancellation: true,
    noiseSuppression: true,
    autoGainControl: true,
  }}
  tts={true}                    // Enable audio playback (default: true)
  playerSampleRate={24_000}     // Agent audio sample rate (default: 24_000)
  autoStart={false}             // Auto-connect on mount (default: false)
  onFunctionCall={handler}      // Fallback function call handler
  onError={handleError}         // Protocol Error notification
  onSdkError={handleSdkError}   // SDK transport or automatic-start failure
  onWarning={handleWarning}     // Protocol Warning notification
  onLatencyReport={handleLatency}
  onInjectionRefused={handleRefusal}
  onListenUpdated={handleListenUpdate}
  onPromptUpdated={handlePromptUpdate}
  onSpeakUpdated={handleSpeakUpdate}
  onThinkUpdated={handleThinkUpdate}
  onHistory={handleHistory}
>
  {children}
</AgentProvider>

config, playerSampleRate, and the initial autoStart value establish resources for the provider's lifetime. Changing those props does not reconstruct or automatically restart the session. Use updateListen, updateThink, updateSpeak, and updatePrompt for supported mid-session changes; remount the provider when a new session config or player sample rate is required.

onListenUpdated, onPromptUpdated, onSpeakUpdated, and onThinkUpdated receive the server confirmations for their matching runtime update methods.

Mode Tracking

The provider tracks four agent modes: "idle", "listening", "thinking", and "speaking".

"thinking" is set only when the server sends AgentThinking; text-injected turns may not send that event. "speaking" is set when the server sends AgentStartedSpeaking and, when tts={true}, inferred from incoming agent audio if that event is absent. With tts={false}, speaking inference requires the server event. The speaking-to-listening transition is playback-aware: when the server fires AgentAudioDone, the provider waits until AgentPlayer.getRemainingPlaybackTime() reaches zero before switching to "listening". This prevents premature mode changes while audio is still playing.

Hooks

useAgentState

Connection state and lifecycle controls.

const {
  state,          // "idle" | "connecting" | "connected" | "reconnecting" | "disconnected"
  isIdle,         // boolean
  isConnecting,   // boolean
  isConnected,    // boolean
  isReconnecting, // boolean
  isDisconnected, // boolean
  isActive,       // true when connected, connecting, or reconnecting
  start,          // () => Promise<void>; rejects on failure and does not call onSdkError
  stop,           // () => void
} = useAgentState();

useAgentMode

Speaking/listening/thinking mode.

const {
   mode,        // "idle" | "listening" | "thinking" | "speaking"
   isSpeaking,  // boolean
   isListening, // boolean
   isThinking,  // boolean
} = useAgentMode();

useAgentConversation

Conversation transcript and text messaging.

const {
  conversation,       // ConversationEntry[] -- { id, role, content, timestamp }
  clearConversation,  // () => void
  sendUserMessage,    // (text: string) => void
  sendAgentMessage,   // (message: string, behavior?: "default" | "queue" | "interrupt") => void
} = useAgentConversation();

useAgentMicrophone

Microphone state, mute controls, and input volume.

const {
  micActive,       // boolean -- hardware is open
  micMuted,        // boolean -- muted (open but not sending)
  setMicMuted,     // (muted: boolean) => void
  toggle,          // () => void -- toggles mute
  enabled,         // boolean -- false when microphone={false} on provider
  getInputVolume,  // () => number -- 0-1, call per animation frame
} = useAgentMicrophone();

useAgentPlayer

Audio playback state, mute controls, and output volume.

const {
  outputMuted,      // boolean
  setOutputMuted,   // (muted: boolean) => void
  toggle,           // () => void
  enabled,          // boolean -- false when tts={false} on provider
  getOutputVolume,  // () => number -- 0-1, call per animation frame
} = useAgentPlayer();

useAgentControls

Lifecycle, messaging, runtime settings, and mute actions grouped in one hook. Like the other focused hooks, it consumes AgentContext, so consumers still re-render when the provider value changes.

const {
  start,
  stop,
  sendUserMessage,
  sendAgentMessage,
  updateListen,
  updateThink,
  updateSpeak,
  updatePrompt,
  clearConversation,
  setMicMuted,
  setOutputMuted,
} = useAgentControls();

useAgentClientTool

Register a client-side function call handler scoped to the component's lifecycle. Automatically unregisters on unmount.

function WeatherPanel() {
  useAgentClientTool("getWeather", async (fn) => {
    const { city } = JSON.parse(fn.arguments);
    const data = await fetchWeather(city);
    return JSON.stringify(data);
  });

  return <div>...</div>;
}

Dynamic client tools are checked before the onFunctionCall fallback prop on AgentProvider.

useAgentSession

Direct access to the underlying AgentSession instance (escape hatch).

const session = useAgentSession();
session.on("warning", (msg) => console.warn(msg));

useAgentContext

Raw context value (escape hatch). Returns the full AgentContextValue. Prefer focused hooks for a smaller, purpose-specific API surface.

useDeepgramAgent (standalone)

Self-contained hook that does not require AgentProvider. Creates and manages its own session, microphone, and player. Useful for simple integrations or when you don't need the provider/context pattern.

The initial config and playerSampleRate similarly apply for the hook's lifetime. Use the returned update methods for supported runtime settings changes.

start() begins a fresh session and clears conversation.

The standalone hook accepts the same notification callbacks as AgentProvider, including onListenUpdated, onPromptUpdated, onSpeakUpdated, and onThinkUpdated.

const {
  state, mode, micActive, micMuted, outputMuted, conversation,
  start, stop, setMicMuted, setOutputMuted,
  sendUserMessage, sendAgentMessage,
  updateListen, updateThink, updateSpeak, updatePrompt,
  clearConversation, interrupt,
} = useDeepgramAgent({
  config: {
    auth: { tokenFactory: () => fetch('/api/token').then(r => r.text()) },
    agent: { think: { provider: { type: 'open_ai', model: 'gpt-4o-mini' } } },
  },
  onWarning: (message) => console.warn(message),
  onLatencyReport: (report) => console.debug(report),
});

Exports

All hooks, the provider, context types, and common SDK types (re-exported from @deepgram/agents for convenience):

// Provider
export { AgentProvider };
export type { AgentNotificationCallbacks, AgentProviderProps };

// Hooks
export {
  useAgentState, useAgentMode, useAgentConversation,
  useAgentMicrophone, useAgentPlayer, useAgentControls,
  useAgentClientTool, useAgentSession, useAgentContext,
  useDeepgramAgent,
};

// Hook result types
export type {
  UseAgentStateResult, UseAgentConversationResult,
  UseAgentMicrophoneResult, UseAgentPlayerResult,
  UseAgentModeResult, UseAgentControlsResult,
  UseDeepgramAgentResult, UseDeepgramAgentOptions,
};

// Context types
export type { AgentContextValue, ConversationEntry, AgentMode };

// SDK types (re-exported from @deepgram/agents)
export type {
  AgentSessionConfig, AuthConfig, TokenFactory,
  AgentSettingsObject, AgentMessageBehavior, ListenSettings,
  ThinkSettings, SpeakSettings, MicrophoneOptions,
  AgentThinkingMessage, ListenUpdatedMessage, PromptUpdatedMessage,
  SpeakUpdatedMessage, ThinkUpdatedMessage, LatencyReportMessage,
  HistoryMessage, InjectionRefusedMessage,
  AgentErrorMessage, AgentWarningMessage,
};

Migration

See the 0.1 to 0.2 migration guide when upgrading an existing integration.

License

MIT

版本与发布记录

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

版本发布日期距今
0.2.0latest2026/09/102 个月前
0.1.02026/05/016 个月前

关于 @deepgram/react 的常见问题

@deepgram/react 是什么?

React hooks and components for @deepgram/agents

如何安装 @deepgram/react?

在项目目录运行 npm install @deepgram/react,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(>=18.0.0)、react-dom(>=18.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@deepgram/react 支持 TypeScript 吗?

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

@deepgram/react 支持 ESM 还是 CommonJS?

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

@deepgram/react 可以商用吗?

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

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

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

@deepgram/react 还在维护吗?

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