@deepgram/sdk

中文文档
5.18.0发布于 2026/11/04MITTypeScriptESM + CJS构建来源已验证近 30 天下载 490.7万
中文使用文档
文档目录33 节
  1. 文档
  2. 从旧版本移入
  3. 安装
  4. 参考文献
  5. 正在流出 WebSocket API
  6. 使用量
  7. 快速启动
  8. 认证
  9. API 密钥认证
  10. 访问托肯认证
  11. 环境变量
  12. 获取 API 密钥
  13. 浏览器使用
  14. WebSocket 特性( 完全支持)
  15. REST API 特性( 必需的)
  16. 设置选项
  17. 例外处理
  18. 请求和响应类型
  19. 高级特性
  20. 请求配置
  21. 正在取消 WebSocket 连接( AbortSignal)
  22. 访问原始响应数据
  23. 自定义获取客户端
  24. WebSocket 代理服务器 / 自定义 HTTP 探员
  25. 日志
  26. 运行时间相容性
  27. 捐款
  28. 开发设置
  29. 贡献准则
  30. 后向兼容性
  31. 获取帮助
  32. 社区行为守则
  33. 许可证

深格拉姆 JavaScript SDK

Built with Fern npm version Node.js 18+ MIT License

官方JavaScript/TypeScript SDK用于Deepgram的自动语音识别,文本对语音,语言理解API. 用世界一流的语音和语言AI模型为您的应用程序提供动力.

文档

API 综合文献和指南可在 开发者. diepgram.com。 。 。 .

从旧版本移入

安装

使用 npm 安装 Deepgram JavaScript SDK :

npm install @deepgram/sdk

参考文献

正在流出 WebSocket API

每个流出客户端都会曝光 connect() 财务报告和审定财务报表 createConnection()。它们是返回起始关闭套接字的别名: 寄存器,调用套接字的 connect(),然后等待时 waitForOpen() 在发送数据之前.

所有套接字都显示 on("open" | "message" | "close" | "error", callback), (中文(简体) ), off(event, callback), (中文(简体) ), connect(), (中文(简体) ), waitForOpen(), (中文(简体) ), close(), (中文(简体) ), readyState级别 socket 属性。 登记 on() 对于同一事件,再次替换先前的回调。 偏好下面输入的发送方法而不是调用 socket.send() 直接说.

过 shouldReconnect: (event) => boolean 当连接需要自定义关闭策略时。 本地流听 V2 自动处理服务器的无状态( L)1005关闭于 sendCloseStream() 作为终端; 其他本地套接字关闭保留默认重试行为 。 自定义运输默认会禁用包装重试; 与 reconnect: true页:1 1005 关闭后 CloseStream 或 TTS 数据 Close 是终端,除非 shouldReconnect 超过它.

服务创建套接字输入的发送方法
语音代理 v1client.agent.v1.connect() 或者说 .createConnection()sendSettings, (中文(简体) ), sendUpdateListen, (中文(简体) ), sendUpdateThink, (中文(简体) ), sendUpdateThinkLive, (中文(简体) ), sendUpdateSpeak, (中文(简体) ), sendInjectUserMessage, (中文(简体) ), sendInjectAgentMessage, (中文(简体) ), sendInjectDynamicAgentMessage, (中文(简体) ), sendFunctionCallResponse, (中文(简体) ), sendKeepAlive, (中文(简体) ), sendUpdatePrompt, (中文(简体) ), sendForceEndTurn, (中文(简体) ), sendCustomToThinkProvider (经验;需要习惯) wss:// 想想终点, sendMedia。思考生命方法需要 agent.think_live 内 sendSettings;没有它,API返回一个错误.
语音对文本 v1client.listen.v1.connect(args) 或者说 .createConnection(args)sendMedia, (中文(简体) ), sendFinalize, (中文(简体) ), sendCloseStream, (中文(简体) ), sendKeepAlive, (中文(简体) ), sendConfigure
Flux STT v2( 对话)client.listen.v2.connect(args) 或者说 .createConnection(args)sendMedia, (中文(简体) ), sendCloseStream, (中文(简体) ), sendForceEndTurn, (中文(简体) ), sendConfigure
文本对语音v1client.speak.v1.connect(args) 或者说 .createConnection(args)sendText, (中文(简体) ), sendFlush, (中文(简体) ), sendClear, (中文(简体) ), sendClose
流量 TTS v2client.speak.v2.connect(args) 或者说 .createConnection(args)sendSpeak, (中文(简体) ), sendFlush, (中文(简体) ), sendInterrupt, (中文(简体) ), sendConfigure, (中文(简体) ), sendClose

Nova-3 多语种 听 V1, 设定 language: "multi" 并可选择通过一个或多个 language_hint 数值。 暗示语言检测对所列语言有偏差;语言检测不限制语言记录,而是与其他语言一样被忽视 language。结果包括检测 languages 已规范 languages_hinted (没有发送提示时为空数组). A 类 sendConfigure(...) 收到更新 ConfigureSuccess 或者说 ConfigureFailure; 保留遗产 Error 处理旧服务器框架.

公共连接参数类型和 Depgram 特定包装行为定义于 src/CustomClient.ts。使用链接的套接字类进行精确的信息和事件类型.

对于语音代理函数呼叫,不发送 FunctionCallResponse 身份证明 FunctionCallCancelled 活动。 设定 defer_until_eot: true 一个 agent.think.functions 当其动作无法被撤销时输入:代理等待用户转弯确认,如果转弯恢复,则丢弃被推迟的呼叫.

使用量

快速启动

Deepgram SDK为所有主要使用案例提供客户端:

实时语音识别( 听 v1)

连接到我们的 WebSocket 并转录实时流媒体音频 :

import { DeepgramClient } from "@deepgram/sdk";

const client = new DeepgramClient();

const connection = await client.listen.v1.connect({
  model: "nova-3",
  language: "en",
  punctuate: "true",
  interim_results: "true",
});

connection.on("open", () => console.log("Connection opened"));

connection.on("message", (data) => {
  if (data.type === "Results") {
    console.log(data);
  }
});

connection.connect();
await connection.waitForOpen();

// Send audio data
connection.sendMedia(audioData);

通过一个 abortSignal 以停止连接尝试或活动会话,并禁用自动重联。 如果你等着 waitForOpen(),使该等离子显示 正在取消 WebSocket 连接( AbortSignal)。 。 。 .

每条相通的连接也是可同步的,所以可以和 for await 而不是召回:

const connection = await client.listen.v1.connect({ model: "nova-3", interim_results: "true" });

connection.connect();
await connection.waitForOpen();

for await (const message of connection) {
  if (message.type === "Results" && message.is_final) {
    console.log(message.channel.alternatives[0].transcript);
  }
}

当连接关闭时, 迭接结束, 如果错误则丢出, 并且 break 关闭 连接。 正在运行的循环正文中发送到的消息 相当缓冲 而不是掉下来,和 on("message", ...) 如果两者兼而有之,就继续合作. 每个连接都支持一个活跃的传动器. 其排队量为1000个消息或16个米B; 溢出会扔出并关闭连接,而不是在内存中保留未绑定的音频. 这个有用 listen.v1, (中文(简体) ), listen.v2, (中文(简体) ), agent.v1, (中文(简体) ), speak.v1 财务报告和审定财务报表 speak.v2; 在套接字上 带有音频,二进制帧作为 Blob。 。 。 .

文件译名

转录预先录制的音频文件(API 参考:

import { createReadStream } from "fs";
import { DeepgramClient } from "@deepgram/sdk";

const client = new DeepgramClient();

const response = await client.listen.v1.media.transcribeFile(
  createReadStream("audio.wav"),
  { model: "nova-3" }
);
console.log(response.results.channels[0].alternatives[0].transcript);

文字对语言

从文本中生成自然声音的语音( E)API 参考:

import { DeepgramClient } from "@deepgram/sdk";

const client = new DeepgramClient();

const response = await client.speak.v1.audio.generate({
  text: "Hello, this is a sample text to speech conversion.",
  model: "aura-2-thalia-en",
  encoding: "linear16",
  container: "wav",
});

// Save the audio file
const stream = response.stream();

文本分析

分析情绪、主题和意图的文本(API 参考:

import { DeepgramClient } from "@deepgram/sdk";

const client = new DeepgramClient();

const response = await client.read.v1.text.analyze({
  text: "Hello, world!",
  language: "en",
});

语音代理( Conversational AI)

构建交互式语音代理 :

import { DeepgramClient } from "@deepgram/sdk";

const client = new DeepgramClient();

const connection = await client.agent.v1.connect();

connection.on("open", () => console.log("Connection opened"));

connection.on("message", (data) => {
  if (data.type === "ConversationText") {
    console.log(data);
  }
});

connection.connect();
await connection.waitForOpen();

connection.sendSettings({
  type: "Settings",
  audio: {
    input: { encoding: "linear16", sample_rate: 24000 },
    output: { encoding: "linear16", sample_rate: 16000, container: "wav" },
  },
  agent: {
    language: "en",
    listen: {
      provider: { type: "deepgram", version: "v1", model: "nova-3" },
    },
    think: {
      provider: { type: "open_ai", model: "gpt-4o-mini" },
      prompt: "You are a friendly AI assistant.",
    },
    speak: {
      provider: { type: "deepgram", model: "aura-2-thalia-en" },
    },
  },
});

认证

Deepgram SDK支持两种认证方法:

API 密钥认证

将您的 Deepgram API 密钥用于服务器侧应用 :

import { DeepgramClient } from "@deepgram/sdk";

// Explicit API key
const client = new DeepgramClient({ apiKey: "YOUR_API_KEY" });

// Or via environment variable DEEPGRAM_API_KEY
const client = new DeepgramClient();

访问托肯认证

使用访问符进行临时或范围访问(推荐给客户端应用程序):

import { DeepgramClient } from "@deepgram/sdk";

// Explicit access token
const client = new DeepgramClient({ accessToken: "YOUR_ACCESS_TOKEN" });

// Or via environment variable DEEPGRAM_ACCESS_TOKEN
const client = new DeepgramClient();

// Generate access tokens using your API key
const authClient = new DeepgramClient({ apiKey: "YOUR_API_KEY" });
const tokenResponse = await authClient.auth.v1.tokens.grant();
const tokenClient = new DeepgramClient({ accessToken: tokenResponse.access_token });

环境变量

SDK从这些环境变量中自动发现资质 :

  • DEEPGRAM_ACCESS_TOKEN - 您的登录标志(优先)
  • DEEPGRAM_API_KEY - 您的 Deepgram API 键

优先发言: 明确参数 > 环境变量

获取 API 密钥

要访问 Deepgram API 您需要一个 免费 Deepgram API 密钥。 。 。 .

浏览器使用

SDK在现代浏览器中工作,有一些考虑:

WebSocket 特性( 完全支持)

  • 实时译名: 直接连接 wss://api.deepgram.com
  • 语音代理: 直接连接 wss://agent.deepgram.com
  • 实时文字对语音: 直接连接 wss://api.deepgram.com

REST API 特性( 必需的)

由于 Depgram API 中的 CORS 标题限制, 您在从浏览器中调用 REST API 时必须使用代理服务器 。 过 "proxy" 作为您的 API 键和点 baseUrl 到您的代理服务器 :

import { DeepgramClient } from "@deepgram/sdk";

const client = new DeepgramClient({
  apiKey: "proxy",
  baseUrl: "http://localhost:8080",
});

您的代理必须设置 Authorization: token DEEPGRAM_API_KEY 标题并转发请求到 Deepgram 的 API 。 见我们的例子 深格拉姆节点代理。 。 。 .

设置选项

<!-- CDN (UMD) -->
<script src="https://cdn.jsdelivr.net/npm/@deepgram/sdk"></script>
<script>
  const { DeepgramClient } = deepgram;
</script>

<!-- CDN (ESM) -->
<script type="module">
  import { DeepgramClient } from "https://cdn.jsdelivr.net/npm/@deepgram/sdk/+esm";
</script>

例外处理

API 返回非成功状态代码( 4xx 或 5xx), a DeepgramError 丢出 :

import { DeepgramClient, DeepgramError } from "@deepgram/sdk";

const client = new DeepgramClient();

try {
  await client.listen.v1.media.transcribeFile(audioData, { model: "nova-3" });
} catch (err) {
  if (err instanceof DeepgramError) {
    console.log(err.statusCode);
    console.log(err.message);
    console.log(err.body);
  }
}

请求和响应类型

SDK 导出所有请求和响应类型为 TypeScript 接口 :

// Direct import (recommended)
import { ListenV1Response, SpeakV1Response } from "@deepgram/sdk";

// Or via namespace
import { Deepgram } from "@deepgram/sdk";
type Response = Deepgram.ListenV1Response;

高级特性

请求配置

配置超时、重试和其他请求选项 :

const response = await client.listen.v1.media.transcribeFile(audioData, {
  model: "nova-3",
  timeoutInSeconds: 60,
  maxRetries: 3,
});

正在取消 WebSocket 连接( AbortSignal)

所有实时 connect() 方法 - listen.v1.connect(), (中文(简体) ), listen.v2.connect(), (中文(简体) ), agent.v1.connect(), (中文(简体) ), speak.v1.connect(),以及 speak.v2.connect() 接受 abortSignal。当取消必须控制在连接所有者之外时使用它, 例如在快速开始和停止会话的应用程序中.

当信号中断时, SDK 停止了等待的或主动的传输并自动禁用 复相通达. 注册 close 回调可以作为取消的一部分运行. 中止符号 无法在 connection.on(),以及 waitForOpen() 不观察 信号直接。 如果打开时可以取消连接, 请让等待中止 - 意识 :

import { DeepgramClient } from "@deepgram/sdk";

const client = new DeepgramClient();
const controller = new AbortController();

function waitForOpenOrAbort(
  connection: { waitForOpen(): Promise<unknown> },
  signal: AbortSignal,
): Promise<void> {
  return new Promise((resolve, reject) => {
    const cleanup = () => signal.removeEventListener("abort", onAbort);
    const onAbort = () => {
      cleanup();
      reject(signal.reason ?? new Error("Connection aborted"));
    };

    if (signal.aborted) {
      onAbort();
      return;
    }

    signal.addEventListener("abort", onAbort, { once: true });
    connection.waitForOpen().then(
      () => {
        cleanup();
        resolve();
      },
      (error) => {
        cleanup();
        reject(error);
      },
    );
  });
}

const connection = await client.listen.v1.connect({
  model: "nova-3",
  language: "en",
  abortSignal: controller.signal,
});

connection.on("open", () => console.log("Connection opened"));
connection.on("message", (data) => console.log(data));

connection.connect();
await waitForOpenOrAbort(connection, controller.signal);

// Cancel the session later. If this happens before open, the helper above rejects.
controller.abort();

中止的信号是连接的终端。 要开始新会话, 请创建新会话 AbortController 和连接。 中止符号不提供 removeAllListeners(); 管理 在旧连接上单独注册的召回周期.

访问原始响应数据

const { data, rawResponse } = await client.listen.v1.media
  .transcribeFile(audioData, { model: "nova-3" })
  .withRawResponse();

console.log(rawResponse.headers["X-My-Header"]);

自定义获取客户端

对不支持的环境使用自定义获取执行 :

import { DeepgramClient } from "@deepgram/sdk";

const client = new DeepgramClient({
  apiKey: "YOUR_API_KEY",
  fetcher: yourCustomFetchImplementation,
});

WebSocket 代理服务器 / 自定义 HTTP 探员

在Node.js中,您可以路由流式WebSocket连接(listen, (中文(简体) ), speak, (中文(简体) ), agent(中文(简体) ) 通过任何相容的自定义 http.Agent 执行。 例如,安装一个 18相容的节点版本 https-proxy-agent数字 :

npm install https-proxy-agent@8

然后创建一个 HttpsProxyAgent 通过公司HTTP/HTTPS的线路流量 egress代理服务器. 设定 agent 在客户端上应用到每一个连接,或者通过它 每个连接以覆盖客户端默认值 :

import { DeepgramClient } from "@deepgram/sdk";
import { HttpsProxyAgent } from "https-proxy-agent";

const agent = new HttpsProxyAgent(process.env.HTTPS_PROXY!);

// Applies to every streaming connection from this client.
const client = new DeepgramClient({ apiKey: "YOUR_API_KEY", agent });

// ...or per connection (overrides the client-level agent).
const socket = await client.listen.v1.createConnection({ model: "nova-3", agent });

这个 agent 选项是仅节点;它在浏览器和网络工人运行时被忽略, 使用当地人 WebSocket 无法接受自定义代理.

日志

import { DeepgramClient, logging } from "@deepgram/sdk";

const client = new DeepgramClient({
  apiKey: "YOUR_API_KEY",
  logging: {
    level: logging.LogLevel.Debug,
    logger: new logging.ConsoleLogger(),
    silent: false,
  },
});

运行时间相容性

SDK工作时间如下:

  • 节点.js 18+
  • 维塞尔
  • 云花岗工人
  • 德诺v1.25+
  • 1.0+号舱
  • 原生反应

捐款

我们欢迎为改进SDK做出贡献! 然而,请注意,这个图书馆主要来自我们的API规格.

开发设置

  1. 安装依赖关系数字 :

    pnpm install
    
  2. 构建数字 :

    make build
    
  3. 运行测试数字 :

    make test
    

贡献准则

看我们的 捐款 向导.

后向兼容性

旧的 SDK 版本将只获得优先 1 (P1) 错误支持 。 我们的守则和依赖性都迅速处理了安全问题。 缺乏明确工作余地的重大错误也得到优先注意.

获取帮助

我们很想听到你的消息 所以,如果你有问题,评论 或者在项目中找到一个错误,让我们知道!

社区行为守则

请看我们的社区 行为守则 (b) 在对这一项目作出贡献之前.

许可证

这个项目根据麻省理工学院许可证颁发——见 自由主义 详细文件.

版本与发布记录

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

版本发布日期距今
5.18.0latest2026/11/047 天前
5.17.02026/10/2814 天前
5.16.02026/10/2319 天前
5.15.02026/10/1230 天前
5.14.02026/10/021 个月前
5.13.02026/09/281 个月前

其他发布通道:alpha → 5.0.0-alpha.3,beta → 5.0.0-beta.4。

关于 @deepgram/sdk 的常见问题

@deepgram/sdk 是什么?

[! [节点.js 18+] (https://img.shields.io/badge/node-18+-b 页面存档备份,存于互联网档案馆

如何安装 @deepgram/sdk?

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

@deepgram/sdk 支持 TypeScript 吗?

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

@deepgram/sdk 支持 ESM 还是 CommonJS?

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

@deepgram/sdk 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=18.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@deepgram/sdk 可以商用吗?

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

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

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

@deepgram/sdk 还在维护吗?

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