Skip to content

Commit c3db06d

Browse files
authored
feat(xsAI): add xsAI voice provider (#98)
* feat(xsAI): add xsAI voice provider * feat(xsAI): add xsAI voice provider * feat(xsAI): add xsAI voice provider * feat(xsAI): add xsAI voice provider
1 parent f7de864 commit c3db06d

13 files changed

Lines changed: 439 additions & 26 deletions

File tree

.changeset/xsai-voice-provider.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
---
2+
"@voltagent/voice": minor
3+
---
4+
5+
feat(xsAI): add xsAI voice provider
6+
7+
This adds support for the xsAI voice provider, including:
8+
9+
- Core provider implementation support
10+
- Support for API key authentication and custom headers
11+
- Base URL configuration for API endpoints
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
node_modules
2+
dist
3+
.DS_Store
4+
.env

examples/with-voice-xsai/README.md

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
<div align="center">
2+
<a href="https://voltagent.dev/">
3+
<img width="1800" alt="435380213-b6253409-8741-462b-a346-834cd18565a9" src="https://github.com/user-attachments/assets/452a03e7-eeda-4394-9ee7-0ffbcf37245c" />
4+
</a>
5+
6+
<br/>
7+
<br/>
8+
9+
<div align="center">
10+
<a href="https://voltagent.dev">Home Page</a> |
11+
<a href="https://voltagent.dev/docs/">Documentation</a> |
12+
<a href="https://github.com/voltagent/voltagent/tree/main/examples">Examples</a> |
13+
<a href="https://s.voltagent.dev/discord">Discord</a> |
14+
<a href="https://voltagent.dev/blog/">Blog</a>
15+
</div>
16+
</div>
17+
18+
<br/>
19+
20+
<div align="center">
21+
<strong>VoltAgent is an open source TypeScript framework for building and orchestrating AI agents.</strong><br>
22+
Escape the limitations of no-code builders and the complexity of starting from scratch.
23+
<br />
24+
<br />
25+
</div>
26+
27+
<div align="center">
28+
29+
[![npm version](https://img.shields.io/npm/v/@voltagent/core.svg)](https://www.npmjs.com/package/@voltagent/core)
30+
[![Contributor Covenant](https://img.shields.io/badge/Contributor%20Covenant-2.0-4baaaa.svg)](CODE_OF_CONDUCT.md)
31+
[![Discord](https://img.shields.io/discord/1361559153780195478.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2)](https://s.voltagent.dev/discord)
32+
[![Twitter Follow](https://img.shields.io/twitter/follow/voltagent_dev?style=social)](https://twitter.com/voltagent_dev)
33+
34+
</div>
35+
36+
<br/>
37+
38+
<div align="center">
39+
<a href="https://voltagent.dev/">
40+
<img width="896" alt="VoltAgent Schema" src="https://github.com/user-attachments/assets/f0627868-6153-4f63-ba7f-bdfcc5dd603d" />
41+
</a>
42+
43+
</div>
44+
45+
## VoltAgent: Build AI Agents Fast and Flexibly
46+
47+
VoltAgent is an open-source TypeScript framework for creating and managing AI agents. It provides modular components to build, customize, and scale agents with ease. From connecting to APIs and memory management to supporting multiple LLMs, VoltAgent simplifies the process of creating sophisticated AI systems. It enables fast development, maintains clean code, and offers flexibility to switch between models and tools without vendor lock-in.
48+
49+
## Try Example
50+
51+
```bash
52+
npm create voltagent-app@latest -- --example with-voice-xsai
53+
```
73.6 KB
Binary file not shown.
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
{
2+
"name": "voltagent-example-with-voice-xsai",
3+
"private": true,
4+
"keywords": [
5+
"voltagent",
6+
"ai",
7+
"agent",
8+
"voice",
9+
"xsai"
10+
],
11+
"license": "MIT",
12+
"author": "",
13+
"type": "module",
14+
"scripts": {
15+
"build": "tsc",
16+
"dev": "tsx watch --env-file=.env ./src ",
17+
"start": "node dist/index.js",
18+
"volt": "volt"
19+
},
20+
"dependencies": {
21+
"@ai-sdk/openai": "^1.3.10",
22+
"@voltagent/cli": "^0.1.4",
23+
"@voltagent/core": "^0.1.12",
24+
"@voltagent/vercel-ai": "^0.1.5",
25+
"@voltagent/voice": "^0.1.4",
26+
"dotenv": "^16.4.5",
27+
"openai": "^4.91.0",
28+
"zod": "^3.24.2"
29+
},
30+
"devDependencies": {
31+
"@types/node": "^22.13.5",
32+
"tsx": "^4.19.3",
33+
"typescript": "^5.8.2"
34+
}
35+
}
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import { join } from "path";
2+
import { createReadStream, createWriteStream } from "fs";
3+
import { VercelAIProvider } from "@voltagent/vercel-ai";
4+
import { VoltAgent, Agent } from "@voltagent/core";
5+
import { XsAIVoiceProvider } from "@voltagent/voice";
6+
import { openai } from "@ai-sdk/openai";
7+
8+
const voiceProvider = new XsAIVoiceProvider({
9+
apiKey: process.env.OPENAI_API_KEY!,
10+
});
11+
12+
const agent = new Agent({
13+
name: "Voice Assistant",
14+
description: "Speaks & listens via xsAI",
15+
llm: new VercelAIProvider(),
16+
model: openai("gpt-4o-mini"),
17+
voice: voiceProvider,
18+
});
19+
20+
// Create the VoltAgent with our voice-enabled agent
21+
new VoltAgent({
22+
agents: {
23+
agent,
24+
},
25+
});
26+
27+
(async () => {
28+
const voices = await agent.voice?.getVoices();
29+
console.log("Available voices:", voices);
30+
31+
const audioStream = await agent.voice?.speak(
32+
"Hello, VoltAgent is best framework for building voice agents! Yeah!",
33+
{
34+
speed: 1.0,
35+
},
36+
);
37+
38+
console.log("audioStream", audioStream);
39+
40+
// Save the audio stream to a file (for demonstration)
41+
const outputPath = join(process.cwd(), "output.mp3");
42+
const writeStream = createWriteStream(outputPath);
43+
audioStream?.pipe(writeStream);
44+
console.log("Audio saved to:", outputPath);
45+
46+
const audioFile = createReadStream(outputPath);
47+
const transcribedText = await agent.voice?.listen(audioFile, {
48+
language: "en",
49+
stream: false,
50+
});
51+
console.log("Transcribed text:", transcribedText);
52+
})();
53+
54+
// Event listeners for voice interactions
55+
voiceProvider.on("speaking", (event: { text: string }) => {
56+
console.log(`Speaking: ${event.text.substring(0, 50)}...`);
57+
});
58+
59+
voiceProvider.on("listening", () => {
60+
console.log("Listening to audio input...");
61+
});
62+
63+
voiceProvider.on("error", (error: { message: string }) => {
64+
console.error("Voice error:", error.message);
65+
});
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
{
2+
"compilerOptions": {
3+
"target": "ES2022",
4+
"module": "NodeNext",
5+
"moduleResolution": "NodeNext",
6+
"esModuleInterop": true,
7+
"forceConsistentCasingInFileNames": true,
8+
"strict": true,
9+
"outDir": "dist",
10+
"skipLibCheck": true
11+
},
12+
"include": ["src"],
13+
"exclude": ["node_modules", "dist"]
14+
}

packages/voice/package.json

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@
2424
},
2525
"dependencies": {
2626
"@voltagent/core": "^0.1.8",
27+
"@xsai/generate-speech": "^0.2.0",
28+
"@xsai/generate-transcription": "^0.2.0",
2729
"elevenlabs": "^1.55.0",
2830
"openai": "^4.91.0"
2931
},

packages/voice/src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,4 @@ export * from "./types";
22
export * from "./providers/base";
33
export * from "./providers/openai";
44
export * from "./providers/elevenlabs";
5+
export * from "./providers/xsai";
Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
import { PassThrough } from "node:stream";
2+
import type { VoiceMetadata, ReadableStreamType } from "@voltagent/core";
3+
import { BaseVoiceProvider } from "../base";
4+
import { XsaiVoiceOptions, XsaiSpeakOptions, XsaiListenOptions } from "./types";
5+
import { generateSpeech, GenerateSpeechOptions } from "@xsai/generate-speech";
6+
import { generateTranscription, GenerateTranscriptionOptions } from "@xsai/generate-transcription";
7+
8+
/* ------------------------------------------------------------------ */
9+
/* Helper: bufferise a Node stream */
10+
/* ------------------------------------------------------------------ */
11+
async function collectChunks(stream: NodeJS.ReadableStream): Promise<Buffer> {
12+
const chunks: Buffer[] = [];
13+
for await (const c of stream) {
14+
chunks.push(typeof c === "string" ? Buffer.from(c) : c);
15+
}
16+
return Buffer.concat(chunks);
17+
}
18+
19+
/* ------------------------------------------------------------------ */
20+
/* xsAI provider */
21+
/* ------------------------------------------------------------------ */
22+
export class XsAIVoiceProvider extends BaseVoiceProvider {
23+
private readonly apiKey: string;
24+
private readonly baseURL: string;
25+
private readonly ttsModel: string;
26+
private readonly speechModel: string;
27+
private readonly voice: string;
28+
private readonly headers?: Record<string, string>;
29+
30+
constructor(options: XsaiVoiceOptions) {
31+
super(options);
32+
33+
this.apiKey = options.apiKey;
34+
this.baseURL = options.baseURL ?? "https://api.openai.com/v1";
35+
this.ttsModel = options.ttsModel ?? "tts-1";
36+
this.speechModel = options.speechModel ?? "whisper-1";
37+
this.voice = options.voice ?? "alloy";
38+
this.headers = options.options?.headers;
39+
}
40+
41+
/* ------------------------------------------------------------------ */
42+
/* TEXT ➜ SPEECH */
43+
/* ------------------------------------------------------------------ */
44+
async speak(
45+
input: string | NodeJS.ReadableStream,
46+
opts: XsaiSpeakOptions = {},
47+
): Promise<NodeJS.ReadableStream> {
48+
try {
49+
const text =
50+
typeof input === "string" ? input : (await collectChunks(input)).toString("utf8");
51+
52+
if (!text.trim()) throw new Error("Input text is empty");
53+
this.emit("speaking", { text });
54+
55+
// Dynamically import the module
56+
57+
const generateSpeechOptions: GenerateSpeechOptions = {
58+
input: text,
59+
voice: opts.voice ?? this.voice ?? "default",
60+
responseFormat: opts.format ?? "mp3",
61+
speed: opts.speed ?? 1.0,
62+
/* CommonRequestOptions */
63+
apiKey: this.apiKey,
64+
baseURL: this.baseURL,
65+
model: this.ttsModel,
66+
headers: this.headers,
67+
};
68+
69+
const arrayBuf = await generateSpeech(generateSpeechOptions);
70+
71+
const stream = new PassThrough();
72+
stream.end(Buffer.from(arrayBuf));
73+
return stream;
74+
} catch (err) {
75+
this.emit("error", {
76+
message: err instanceof Error ? err.message : "Unknown error",
77+
code: "SPEAK_ERROR",
78+
details: err,
79+
});
80+
throw err;
81+
}
82+
}
83+
84+
/* ------------------------------------------------------------------ */
85+
/* SPEECH ➜ TEXT */
86+
/* ------------------------------------------------------------------ */
87+
async listen(
88+
audio: NodeJS.ReadableStream,
89+
opts: XsaiListenOptions = {},
90+
): Promise<string | ReadableStreamType> {
91+
try {
92+
this.emit("listening", { audio });
93+
const buf = await collectChunks(audio);
94+
95+
const blob = new Blob([buf]);
96+
97+
const generateTranscriptionOptions: GenerateTranscriptionOptions = {
98+
file: blob,
99+
fileName: opts.fileName ?? "audio.wav",
100+
language: opts.language,
101+
prompt: opts.prompt,
102+
temperature: opts.temperature,
103+
/* CommonRequestOptions */
104+
apiKey: this.apiKey,
105+
baseURL: this.baseURL,
106+
model: this.speechModel,
107+
headers: this.headers,
108+
};
109+
110+
const { text } = await generateTranscription(generateTranscriptionOptions);
111+
112+
return text;
113+
} catch (err) {
114+
this.emit("error", {
115+
message: err instanceof Error ? err.message : "Unknown error",
116+
code: "LISTEN_ERROR",
117+
details: err,
118+
});
119+
throw err;
120+
}
121+
}
122+
123+
/* ------------------------------------------------------------------ */
124+
/* Real‑time streaming not yet available */
125+
/* ------------------------------------------------------------------ */
126+
async connect(): Promise<void> {
127+
throw new Error("Real‑time streaming not supported by xsAI");
128+
}
129+
disconnect(): void {
130+
/* noop */
131+
}
132+
async send(): Promise<void> {
133+
throw new Error("Real‑time streaming not supported by xsAI");
134+
}
135+
136+
/* ------------------------------------------------------------------ */
137+
/* xsAI hasn't published a voice list API – stub with default */
138+
/* ------------------------------------------------------------------ */
139+
async getVoices(): Promise<VoiceMetadata[]> {
140+
return [
141+
{
142+
id: this.voice ?? "default",
143+
name: "xsAI default",
144+
language: "en",
145+
gender: "neutral",
146+
},
147+
];
148+
}
149+
}

0 commit comments

Comments
 (0)