@ depgram/ 反应
反应提供者和钩子 Deepgram 语音代理 API。管理连接生命周期、麦克风、音频播放、对话状态和模式跟踪.
关于预建的UI组件,见 @deepgram/ui。 。 。 .
安装
npm install @deepgram/react @deepgram/agents
快速启动
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>
);
}
代理代理商
将您的组件树与代理状态管理相包。 创建和管理一个 AgentSession, (中文(简体) ), AgentMicrophone,以及 AgentPlayer 内部.
<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和初始数据 autoStart 价值确定提供者一生的资源。 改变这些道具不会重建或自动重启会话. 使用 updateListen, (中文(简体) ), updateThink, (中文(简体) ), updateSpeak,以及 updatePrompt 用于支持的会话中间变化; 当需要新的会话配置或玩家样本率时, 重新挂载提供者.
onListenUpdated, (中文(简体) ), onPromptUpdated, (中文(简体) ), onSpeakUpdated,以及 onThinkUpdated 获取服务器对匹配运行时间更新方法的确认.
模式跟踪
提供者跟踪四种代理模式: "idle", (中文(简体) ), "listening", (中文(简体) ), "thinking",以及 "speaking"。 。 。 .
"thinking" 仅在服务器发送时设置 AgentThinking; 文本输入的转弯可能不会发送该事件. "speaking" 当服务器发送时设置 AgentStartedSpeaking 以及,何时 tts={true},如果该事件缺席,则从收到的代理音频推断出。 与 tts={false},在进行推断时需要服务器事件。 说话到听觉的过渡是回放意识:当服务器起火时 AgentAudioDone,供应商等待到 AgentPlayer.getRemainingPlaybackTime() 切换到零前达到零 "listening"。这可以防止音频仍在播放时过早改变模式.
钩子
使用代理状态
连接状态和生命周期控制 .
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();
使用代理模式
发言/收听/思考模式.
const {
mode, // "idle" | "listening" | "thinking" | "speaking"
isSpeaking, // boolean
isListening, // boolean
isThinking, // boolean
} = useAgentMode();
代理连接
谈话记录和短信.
const {
conversation, // ConversationEntry[] -- { id, role, content, timestamp }
clearConversation, // () => void
sendUserMessage, // (text: string) => void
sendAgentMessage, // (message: string, behavior?: "default" | "queue" | "interrupt") => void
} = useAgentConversation();
使用自动麦克风
麦克风状态 哑声控制 和输入量.
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();
使用代理服务器
音频回放状态,哑声控制,和输出量.
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();
使用代理控制
生命周期、消息、运行时间设置和哑弹动作组合在一个钩子中。 像其他有重点的钩子一样,会消耗 AgentContext,因此,当提供者值变化时,消费者仍然重新屈服.
const {
start,
stop,
sendUserMessage,
sendAgentMessage,
updateListen,
updateThink,
updateSpeak,
updatePrompt,
clearConversation,
setMicMuted,
setOutputMuted,
} = useAgentControls();
使用代理客户端工具
注册客户端函数调用处理器,范围设定为组件的生命周期. 自动卸载.
function WeatherPanel() {
useAgentClientTool("getWeather", async (fn) => {
const { city } = JSON.parse(fn.arguments);
const data = await fetchWeather(city);
return JSON.stringify(data);
});
return <div>...</div>;
}
动态客户端工具在 onFunctionCall 倒置道具打开 AgentProvider。 。 。 .
代理会议
直接接触基础 AgentSession 实例(逃出舱口).
const session = useAgentSession();
session.on("warning", (msg) => console.warn(msg));
使用代理连接
原始上下文值( 逃出舱口) 。 返回全部内容 AgentContextValue. 偏好为较小的,目的特定的API表面提供有重点的钩.
使用深方程式代理( 独立)
不需要的自带钩 AgentProvider。创建和管理自己的会话、麦克风和播放器。 用于简单的集成或者在不需要提供者/文本模式时有用.
初始数据 config 财务报告和审定财务报表 playerSampleRate 类似地适用于钩子的生平. 使用返回的更新方法来更改所支持的运行时间设置 .
start() 开始新会话并清除 conversation。 。 。 .
独立的钩子接受相同的通知回调 与 AgentProvider,包括: onListenUpdated, (中文(简体) ), onPromptUpdated, (中文(简体) ), onSpeakUpdated,以及 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),
});
出口
所有钩子、提供者、上下文类型和常见的SDK类型(从 @deepgram/agents 为方便起见:
// 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,
};
移徙
见 0.1至0.2 移徙指南 当升级现有集成时.
许可证
麻省理工学院