Skip to content
Docs
Reference

Agents SDK reference

VoiceAgent, providers and plugin interfaces of @dtelecom/agents-js.

Use @dtelecom/agents-js 0.10.0 with Node.js 22 or newer. It requires @dtelecom/server-sdk-node 0.4.0 or newer and @dtelecom/server-sdk-js 4.4.0 or newer. Voice-agent guide

npm install @dtelecom/agents-js @dtelecom/server-sdk-js @dtelecom/server-sdk-node
import { VoiceAgent } from '@dtelecom/agents-js';
import type { LLMPlugin, STTPlugin, TTSPlugin } from '@dtelecom/agents-js';
function build(stt: STTPlugin, llm: LLMPlugin, tts: TTSPlugin) {
return new VoiceAgent({ stt, llm, tts, instructions: 'Be helpful and concise.' });
}
Option Type Default Description
stt STTPlugin required Speech-to-Text provider.
llm LLMPlugin required Language model provider.
tts TTSPlugin none Text-to-Speech provider. Text-only when omitted.
instructions string required System prompt.
respondMode 'always' or 'addressed' 'always' When to answer.
agentName string 'assistant' Name for 'addressed' mode.
nameVariants string[] [] Extra names the agent answers to.
onDataMessage function none (payload, participantIdentity, topic) for data messages.
tools Tool[] none Tools the LLM can call, see Tool calling.
memory { enabled, dbPath?, scope? } none Persistent memory across sessions, see Memory.
maxContextTokens number 5000 Context size before older turns are summarised.
Method Description
start({ room, identity?, name?, cloud, ttl? }) Joins the room and starts listening. The agent creates its own token and extends it by ttl before it expires: 10 minutes before, or at half of the lifetime for short tokens. A failed extension is retried every 15 seconds and reported as an error event. ttl defaults to 6 hours, 24 at most. Instead of cloud you can pass apiKey and apiSecret, or a ready token and wsUrl with optional fallbackUrls from the issuer.
stop() Leaves the room and closes speech sessions. The agent also stops by itself when the last other participant leaves.
say(text) Speaks text without calling the LLM. Can be interrupted.
saySSML(ssml, displayText) Speaks one SSML document.
setSTTLanguage(language, { forceWhisper? }) Changes the recognition language on all active streams.
running true while the agent is in a room.
room The underlying Room from @dtelecom/server-sdk-node.
Event Payload
connected -
disconnected reason: agent_stopped after stop(), or the reason from the node: participant_removed, duplicate_identity, room_deleted, server_shutdown, server_initiated
transcription { text, isFinal, speaker, utteranceId? }
transcription_partial { text, utteranceId, revision, windowStartSeconds, speaker }
partial_end { utteranceId, reason, speaker }
stt_ready { clientId?, language?, smartTurn?, speaker }
response string
sentence text, raw: one sentence has been played
toolCall { id, name, arguments }: the LLM called a tool; arguments is a JSON string. Emitted before a handler runs
metrics TurnMetrics: latency of a completed turn, see Latency metrics
agentState 'idle' | 'listening' | 'thinking' | 'speaking'
error Error: provider and pipeline errors, and a failed token extension

Import from @dtelecom/agents-js/providers.

Option Default Description
cloud - CloudClient. Each stream gets its own Speech-to-Text session.
language 'auto' Language code, or 'auto' to detect.
forceWhisper false Always use Whisper.
partials off Provisional transcripts.
smartTurn off Semantic end-of-turn detection.
cloudSession { minutes: 10, extendWhenMinutesLeft: 2 } Reservation size and when to extend.

A session key works for one connection. After a disconnect the provider opens a new session, with a pause of 1 to 30 seconds, and keeps up to 5 seconds of audio meanwhile. Call setWebRTCSessionId(sessionId) to link sessions to a room participant; VoiceAgent does it for you.

Option Default Description
cloud - CloudClient. Opens and extends one Text-to-Speech session.
voices required Voice per language: { en: { voice: 'af_heart', langCode: 'a' } }.
defaultLanguage the first language in voices Language for untagged text.
speed 1.0 Speaking rate.
watermark false Audio watermark.
cloudSession { characters: 2000, extendWhenCharactersLeft: 500 } Reservation size and when to extend.

After a disconnect the provider opens a new session on the next text. Methods: synthesize(text, signal?) and synthesizeSSML(ssml, signal?) yield PCM16 mono 48 kHz buffers; warmup() connects in advance; close() ends the session.

Both providers work outside a voice agent, as plain streaming clients for Speech-to-Text and Text-to-Speech.

With the x402 gateway instead of Cloud, pass serverUrl and sessionKey, and getSessionKey to supply a new key after a disconnect.

Class Options
OpenAILLM apiKey, model, maxTokens (512), temperature (0.7), responseFormat
OpenRouterLLM apiKey, model, maxTokens, temperature, reasoningEffort, providerRouting

DeepgramSTT, DeepgramTTS and CartesiaTTS are included for teams that already use those services. They need their own API keys and are billed by those vendors.

Implement these to connect any model or service.

import type { LLMChatOptions, LLMChunk, Message } from '@dtelecom/agents-js';
interface MyLLM {
chat(messages: Message[], signal?: AbortSignal, options?: LLMChatOptions): AsyncGenerator<LLMChunk>;
warmup?(systemPrompt: string): Promise<void>;
}
interface MyTTS {
synthesize(text: string, signal?: AbortSignal): AsyncGenerator<Buffer>;
warmup?(): Promise<void>;
}
  • LLMPlugin.chat yields the answer as it is generated. Honour signal: it fires when the user interrupts. The third parameter, options, carries { tools, toolChoice, plainText }: this is how your own LLM receives the tool definitions. toolChoice: 'none' asks for a text answer. Tool rounds come back in messages in the OpenAI chat format: an assistant message with tool_calls, then one role: 'tool' message per call.
  • TTSPlugin.synthesize yields PCM16 mono 48 kHz audio.
  • STTPlugin.createStream returns a stream with sendAudio(pcm16), a transcription event and close(). Extend BaseSTTStream to get the event plumbing.

Give a tool a handler and the agent runs it: the LLM gets the result and the agent speaks its answer. What the LLM says before the call, such as “Let me check”, is spoken while the tool runs.

import type { AgentTool } from '@dtelecom/agents-js';
declare function getOrderStatus(orderNumber: string, signal: AbortSignal): Promise<{ status: string }>;
const tools: AgentTool[] = [
{
definition: {
type: 'function',
function: {
name: 'get_order_status',
description: 'Look up the status of an order by its number.',
parameters: {
type: 'object',
properties: { orderNumber: { type: 'string' } },
required: ['orderNumber'],
},
},
},
handler: async ({ orderNumber }, { signal }) => getOrderStatus(orderNumber, signal),
timeoutMs: 10_000, // default 30 seconds
},
];
  • The handler gets the parsed arguments and { signal, call }. signal fires when the user interrupts, when the agent stops, or at the timeout.
  • A string result goes to the LLM as is, anything else as JSON, up to 16,000 characters. An error, invalid arguments or a timeout go back as {"error": "..."}, so the LLM can tell the user.
  • Several calls in one answer run one after another. After three rounds of tool calls in one turn the LLM is asked to answer without tools.
  • The call and its result stay in the conversation context together, so later turns can refer to them.

A tool without a handler (a plain ToolDefinition) only emits toolCall and ends the turn. Your app runs the function and answers with agent.say(text):

import type { ToolDefinition, VoiceAgent } from '@dtelecom/agents-js';
declare const definition: ToolDefinition;
declare function getOrderStatus(orderNumber: string): Promise<string>;
function handleTools(agent: VoiceAgent) {
agent.on('toolCall', async (call) => {
if (call.name !== definition.function.name) return;
const { orderNumber } = JSON.parse(call.arguments);
const status = await getOrderStatus(orderNumber);
await agent.say(`Your order ${orderNumber} is ${status}.`);
});
}

After each completed answer the agent emits metrics with the latency of the turn in milliseconds, null for a stage that did not happen:

Field Meaning
sttMs Speech recognition processing time reported by the server.
queueMs Waiting for a previous turn to finish.
prepareMs Warmup, summarising and memory search before the LLM request.
ttftMs LLM request to its first token.
llmMs LLM request to its first complete sentence. Includes tool time when the first sentence comes after a tool call.
ttsMs First sentence to its first audio.
overallMs The sum of the above: from the end of speech (not counting end-of-speech detection) to the first audio.
toolMs, toolCalls Time spent in tool handlers, and the number of tool calls.
speaker Whose turn it was.

Interrupted turns and say() emit none. To show them on a page, send them to the room:

import type { VoiceAgent } from '@dtelecom/agents-js';
function shareMetrics(agent: VoiceAgent) {
agent.on('metrics', (m) => {
const data = new TextEncoder().encode(JSON.stringify({ type: 'metrics', ...m }));
agent.room?.localParticipant.publishData(data, { topic: 'agent' });
});
}

memory: { enabled: true } keeps what the agent learned between sessions. At the end of a session the LLM writes a short summary of the conversation.

  • The database is a local file, ./data/memory.db by default (dbPath). Create the folder yourself.
  • It needs three more packages: better-sqlite3, sqlite-vec and @huggingface/transformers. Embeddings are computed in the agent’s process.
import { setLogLevel } from '@dtelecom/agents-js';
setLogLevel('info');

At info level the agent logs the latency of each phase of a turn. See Latency tips.