@deepslate-labs/core

中文文档
0.1.23发布于 2026/10/16TypeScriptES Module近 30 天下载 4105

Shared core library for Deepslate SDK integrations (TypeScript)

原始使用文档
文档目录18 节
  1. What's Inside
  2. Installation
  3. Requirements
  4. Dependencies
  5. Usage
  6. Credentials
  7. Model Selection
  8. TTS Configuration
  9. Experiments
  10. DeepslateSession
  11. API Reference
  12. DeepslateSession.create(options, opts?)
  13. DeepslateSession — send methods
  14. DeepslateSession — events
  15. DeepslateOptions
  16. VadConfig
  17. Documentation
  18. License

@deepslate-labs/core

License Documentation Node

Shared core library for Deepslate's realtime voice AI SDKs (TypeScript).

You probably don't need to install this directly.

Install @deepslate-labs/livekit instead — it pulls in @deepslate-labs/core automatically. This package is for developers building custom Deepslate integrations outside of LiveKit.

DeepslateSession is a typed EventEmitter — you subscribe to server events with session.on(event, …).


What's Inside

@deepslate-labs/core provides everything needed to connect to the Deepslate Realtime API from any Node application:

  • DeepslateSession — High-level session that manages the full WebSocket lifecycle, protobuf framing, session initialization, reconnection, and event dispatch. A typed EventEmitter. The primary building block for custom integrations.
  • DeepslateOptions / DeepslateModel — API credentials, model selection and connection configuration, with resolveOptions() / optionsFromEnv() normalizers.
  • VadConfig — Server-side Voice Activity Detection parameters.
  • HostedTtsConfig / HostedTtsMode — Deepslate-hosted (cloned) voice TTS configuration.
  • ElevenLabsTtsConfig / ElevenLabsLocation — ElevenLabs TTS configuration (elevenLabsConfigFromEnv() loads from env).
  • BaseDeepslateClient — Low-level WebSocket client with exponential-backoff reconnection (used internally by DeepslateSession).
  • Protobuf bindings — re-exported via @deepslate-labs/proto for the Deepslate realtime wire protocol.

Installation

npm install @deepslate-labs/core

Requirements

  • Node.js 18 or higher

Dependencies

  • ws — WebSocket client
  • @deepslate-labs/proto — generated protobuf bindings (protobuf-es v2)

Usage

This section is for custom integration authors. For standard usage see the LiveKit package.

Credentials

import { optionsFromEnv, resolveOptions } from "@deepslate-labs/core";

// Load from environment variables (recommended)
const opts = optionsFromEnv();

// Or configure manually
const opts = resolveOptions({
  vendorId: "your_vendor_id",
  organizationId: "your_org_id",
  apiKey: "your_api_key",
  systemPrompt: "You are a helpful assistant.",
});

Required environment variables:

DEEPSLATE_VENDOR_ID=your_vendor_id
DEEPSLATE_ORGANIZATION_ID=your_organization_id
DEEPSLATE_API_KEY=your_api_key

Model Selection

import { DeepslateModel, optionsFromEnv } from "@deepslate-labs/core";

const opts = optionsFromEnv({ model: DeepslateModel.OPAL_V2_1 });

If model is not set, the platform default is used.

See docs.deepslate.eu/opal#available-models for the complete list of models.

TTS Configuration

Two TTS providers are supported. Pass either config as ttsConfig to DeepslateSession.create().

Deepslate-hosted (cloned) voice — no external provider credentials required:

import { HostedTtsMode, type HostedTtsConfig } from "@deepslate-labs/core";

const tts: HostedTtsConfig = {
  provider: "hosted",
  voiceId: "c3dfa73f-a1ab-4aad-b48a-0e9b9fe4a69f",
  mode: HostedTtsMode.HIGH_QUALITY, // or HostedTtsMode.LOW_LATENCY
};

ElevenLabs:

import { elevenLabsConfigFromEnv, ElevenLabsLocation } from "@deepslate-labs/core";

// Load from environment variables
const tts = elevenLabsConfigFromEnv();

// Or configure manually
const tts = {
  provider: "eleven_labs" as const,
  apiKey: "your_elevenlabs_key",
  voiceId: "21m00Tcm4TlvDq8ikWAM",
  modelId: "eleven_turbo_v2",
  location: ElevenLabsLocation.US, // US (default), EU, or INDIA
};

Experiments

No stability guarantees. Experiments may change or disappear without a version bump or warning.

Deepslate can enable server-side experiments for a session. Pass them as a plain map of experiment name to parameter value. Names are opaque strings; an experiment that takes no parameters is enabled with null:

import { DeepslateSession } from "@deepslate-labs/core";

const session = DeepslateSession.create({
  vendorId, organizationId, apiKey,
  experiments: { "example-experiment:1": null },
});

Each experiment defines its own value, so what a value means, and whether one is needed at all, depends on the experiment. Values may be any JSON value: null, booleans, numbers, strings, arrays, or nested objects, and a parameter object may be filled in partially:

const session = DeepslateSession.create({
  vendorId, organizationId, apiKey,
  experiments: {
    "example-experiment:1": { someSetting: "value", anotherSetting: 3 },
  },
});

The SDK holds no catalogue of experiments: it sends whatever you pass, and the server ignores names it does not know. Ask your Deepslate contact which experiments are available and what values they accept.

DeepslateSession

DeepslateSession is the recommended entry point for custom integrations. It handles the full protocol lifecycle — session initialization, protobuf serialization, reconnection, and server-event routing — emitting strongly-typed events so your code only deals with application logic.

Use DeepslateSession.create() when your code owns the connection: it creates its own BaseDeepslateClient and closes it automatically when close() is called.

import { DeepslateSession, optionsFromEnv, elevenLabsConfigFromEnv } from "@deepslate-labs/core";

const session = DeepslateSession.create(
  optionsFromEnv({ systemPrompt: "You are a helpful assistant." }),
  { ttsConfig: elevenLabsConfigFromEnv(), userAgent: "MyApp/1.0" },
);

session.on("sessionInitialized", () => {
  // Session is ready — safe to send the first message
  void session.sendText("What is the capital of France?");
});

session.on("textFragment", (text) => process.stdout.write(text));

session.on("audioChunk", (pcm, sampleRate, channels, transcript) => {
  // Forward PCM audio to your output device / transport
});

session.on("toolCall", async (callId, name, params) => {
  const result = await dispatchTool(name, params);
  await session.sendToolResponse(callId, result);
});

session.on("error", (category, message, traceId) => {
  console.error(`[${category}] ${message}`);
});

session.start();

// Initialize for text-only interaction (audio sessions initialize automatically).
// "sessionInitialized" fires once the session is ready.
await session.initialize(24000, 1);

// ... later
await session.close();

Sending audio

Audio sessions initialize automatically on the first sendAudio() call. The session also reconfigures transparently if the audio format changes mid-session:

// pcm: raw signed 16-bit PCM (Uint8Array)
await session.sendAudio(pcm, 16000, 1);

Updating tools at runtime

await session.updateTools([
  {
    type: "function",
    function: {
      name: "get_weather",
      description: "Get the weather for a city.",
      parameters: {
        type: "object",
        properties: { city: { type: "string" } },
        required: ["city"],
      },
    },
  },
]);

Tool definitions are re-synced automatically after every reconnect.

Reconnection

start() drives BaseDeepslateClient.runWithRetry() internally. On a dropped connection the session resets its state, re-sends the initialize request, re-syncs tool definitions, and resumes — all without any action required from your code. Call close() to stop the retry loop permanently.

A handshake the server permanently rejects (HTTP 4xx other than 408/429 — e.g. a bad API key, an unknown vendor/organization, or a model the organization has no access to) is not retried: fatalError fires immediately with a HandshakeRejectedError whose status and model describe the rejection and whose message says what to check.


API Reference

DeepslateSession.create(options, opts?)

Factory that creates a session together with its own BaseDeepslateClient. The session owns the client and closes it when close() is called.

ParameterTypeDefaultDescription
optionsDeepslateOptionsrequiredAPI credentials and settings
opts.vadConfigVadConfigdefaultsVAD settings
opts.ttsConfigTtsConfigundefinedEnables server-side TTS audio output
opts.userAgentstringbuildUserAgent()User-Agent header sent on connect

DeepslateSession — send methods

MethodDescription
session.sendAudio(pcm, sr, ch)Send PCM audio; auto-initializes and auto-reconfigures on format change
session.sendText(text, trigger?)Send a text UserInput (default trigger: IMMEDIATE)
session.initialize(sr?, ch?)Explicitly initialize (for text-only sessions)
session.triggerInference(instructions?)Manually trigger a model reply
session.sendToolResponse(callId, result)Return a tool result to the server
session.updateTools(tools)Sync tool definitions (persisted across reconnects)
session.reconfigure(systemPrompt?, temperature?)Live-update inference settings
session.sendDirectSpeech(text, includeInHistory?, uninterruptable?)Speak text directly via TTS, bypassing the LLM
session.exportChatHistory(awaitPending?, excludeAudio?)Request a history export; result via the chatHistory event
session.sendConversationQuery(queryId, prompt?, instructions?)Side-channel inference; result via the conversationQueryResult event

DeepslateSession — events

Subscribe with session.on(event, listener). Event payloads are strongly typed via DeepslateSessionEvents.

EventListener signatureEmitted when
sessionInitialized()Session is fully initialized and ready to accept messages
textFragment(text: string, turnId: number | null)Model streams a text token (faster than realtime, see note below)
audioChunk(pcm: Uint8Array, sampleRate: number, channels: number, transcript: string | null)Model streams a TTS audio chunk
toolCall(callId: string, name: string, params: Record<string, unknown>)Model requests a tool invocation
responseBegin()Model response starts
responseEnd()Model response ends

textFragment is not a transcript of what was heard. Fragments arrive faster than realtime, ahead of TTS synthesis, so they carry the model's intended output. When a turn is interrupted, the server has already sent text that never reached the speaker. Do not use it as a record of what the caller actually heard, and never sync it straight into a conversation history. | userTranscription | (text: string, language: string \| null, turnId: number) | User speech transcription arrives | | playbackBufferClear | () | Server cleared its audio playback buffer | | chatHistory | (messages: ChatMessage[]) | Chat history export received | | conversationQueryResult | (queryId: string, text: string) | Side-channel query result received | | error | (category: string, message: string, traceId: string \| null) | Server sent an error notification | | fatalError | (err: Error) | All reconnect retries exhausted, or the handshake was rejected (HandshakeRejectedError) | | socketError | (err: Error) | Background WebSocket error (logging/observability only; does not affect the run loop) |

DeepslateOptions

FieldTypeDefaultDescription
vendorIdstringenv: DEEPSLATE_VENDOR_IDDeepslate vendor ID
organizationIdstringenv: DEEPSLATE_ORGANIZATION_IDDeepslate organization ID
apiKeystringenv: DEEPSLATE_API_KEYDeepslate API key
modelDeepslateModelIdenv: DEEPSLATE_MODEL, else undefined (platform default)Realtime model
baseUrlstring"https://app.deepslate.eu"Base URL for Deepslate API
systemPromptstring"You are a helpful assistant."Default system prompt
temperaturenumber0.3Sampling temperature (0.0–2.0)
wsUrlstringundefinedDirect WebSocket URL (overrides baseUrl; for local dev)
maxRetriesnumber3Maximum reconnection attempts before giving up
generateReplyTimeoutnumber30.0Timeout in seconds for reply generation (0 = no timeout)
experimentsExperimentsundefinedServer-side experiments to enable

VadConfig

FieldTypeDefaultDescription
confidenceThresholdnumber0.4Minimum confidence to classify audio as speech (0–1)
minVolumenumber0.0Minimum volume to classify audio as speech (0–1)
startDurationMsnumber150Duration of speech required to trigger start event
stopDurationMsnumber390Duration of silence required to trigger stop event
backbufferDurationMsnumber1000Audio buffer captured before speech detection triggers

Documentation


License

Apache License 2.0 — see LICENSE for details.

版本与发布记录

@deepslate-labs/core 共发布 10 个版本,首次发布于 2026/06/28;过去 12 个月发布了 10 个版本。

版本发布日期距今
0.1.23latest2026/10/1626 天前
0.1.222026/10/1330 天前
0.1.212026/10/041 个月前
0.1.202026/09/291 个月前
0.1.192026/09/151 个月前
0.1.182026/09/042 个月前

关于 @deepslate-labs/core 的常见问题

@deepslate-labs/core 是什么?

Shared core library for Deepslate SDK integrations (TypeScript)

如何安装 @deepslate-labs/core?

在项目目录运行 npm install @deepslate-labs/core,或使用 pnpm add / yarn add / bun add。

@deepslate-labs/core 支持 TypeScript 吗?

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

@deepslate-labs/core 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@deepslate-labs/core 可以商用吗?

@deepslate-labs/core 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@deepslate-labs/core 的下载量有多少?

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

@deepslate-labs/core 还在维护吗?

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