Skip to content

Commit 6e30c41

Browse files
authored
Merge pull request #1797 from elizaOS/fix/lint_errors
chore: remove unused import and var
2 parents 3fec0bd + 9a6e380 commit 6e30c41

File tree

2 files changed

+78
-72
lines changed

2 files changed

+78
-72
lines changed

packages/client-discord/src/actions/chat_with_attachments.ts

-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import { composeContext } from "@elizaos/core";
22
import { generateText, trimTokens } from "@elizaos/core";
3-
import type { TiktokenModel } from "js-tiktoken";
43
import { models } from "@elizaos/core";
54
import { parseJSONObjectFromText } from "@elizaos/core";
65
import {

packages/client-twitter/src/plugins/SttTtsSpacesPlugin.ts

+78-71
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
// src/plugins/SttTtsPlugin.ts
22

3-
import { spawn } from 'child_process';
4-
import { ITranscriptionService } from '@elizaos/core';
5-
import { Space, JanusClient, AudioDataWithUser } from 'agent-twitter-client';
3+
import { spawn } from "child_process";
4+
import { ITranscriptionService } from "@elizaos/core";
5+
import { Space, JanusClient, AudioDataWithUser } from "agent-twitter-client";
66

77
interface PluginConfig {
88
openAiApiKey?: string; // for STT & ChatGPT
@@ -14,7 +14,7 @@ interface PluginConfig {
1414
elevenLabsModel?: string; // e.g. "eleven_monolingual_v1"
1515
systemPrompt?: string; // ex. "You are a helpful AI assistant"
1616
chatContext?: Array<{
17-
role: 'system' | 'user' | 'assistant';
17+
role: "system" | "user" | "assistant";
1818
content: string;
1919
}>;
2020
transcriptionService: ITranscriptionService;
@@ -33,12 +33,12 @@ export class SttTtsPlugin implements Plugin {
3333
private openAiApiKey?: string;
3434
private elevenLabsApiKey?: string;
3535

36-
private gptModel = 'gpt-3.5-turbo';
37-
private voiceId = '21m00Tcm4TlvDq8ikWAM';
38-
private elevenLabsModel = 'eleven_monolingual_v1';
39-
private systemPrompt = 'You are a helpful AI assistant.';
36+
private gptModel = "gpt-3.5-turbo";
37+
private voiceId = "21m00Tcm4TlvDq8ikWAM";
38+
private elevenLabsModel = "eleven_monolingual_v1";
39+
private systemPrompt = "You are a helpful AI assistant.";
4040
private chatContext: Array<{
41-
role: 'system' | 'user' | 'assistant';
41+
role: "system" | "user" | "assistant";
4242
content: string;
4343
}> = [];
4444

@@ -63,24 +63,26 @@ export class SttTtsPlugin implements Plugin {
6363
private ttsQueue: string[] = [];
6464
private isSpeaking = false;
6565

66-
onAttach(space: Space) {
67-
console.log('[SttTtsPlugin] onAttach => space was attached');
66+
onAttach(_space: Space) {
67+
console.log("[SttTtsPlugin] onAttach => space was attached");
6868
}
6969

7070
init(params: { space: Space; pluginConfig?: Record<string, any> }): void {
7171
console.log(
72-
'[SttTtsPlugin] init => Space fully ready. Subscribing to events.',
72+
"[SttTtsPlugin] init => Space fully ready. Subscribing to events."
7373
);
7474

7575
this.space = params.space;
76-
this.janus = (this.space as any)?.janusClient as JanusClient | undefined;
76+
this.janus = (this.space as any)?.janusClient as
77+
| JanusClient
78+
| undefined;
7779

7880
const config = params.pluginConfig as PluginConfig;
7981
this.openAiApiKey = config?.openAiApiKey;
8082
this.elevenLabsApiKey = config?.elevenLabsApiKey;
8183
this.transcriptionService = config.transcriptionService;
8284
if (config?.gptModel) this.gptModel = config.gptModel;
83-
if (typeof config?.silenceThreshold === 'number') {
85+
if (typeof config?.silenceThreshold === "number") {
8486
this.silenceThreshold = config.silenceThreshold;
8587
}
8688
if (config?.voiceId) {
@@ -95,24 +97,24 @@ export class SttTtsPlugin implements Plugin {
9597
if (config?.chatContext) {
9698
this.chatContext = config.chatContext;
9799
}
98-
console.log('[SttTtsPlugin] Plugin config =>', config);
100+
console.log("[SttTtsPlugin] Plugin config =>", config);
99101

100102
// Listen for mute events
101103
this.space.on(
102-
'muteStateChanged',
104+
"muteStateChanged",
103105
(evt: { userId: string; muted: boolean }) => {
104-
console.log('[SttTtsPlugin] Speaker muteStateChanged =>', evt);
106+
console.log("[SttTtsPlugin] Speaker muteStateChanged =>", evt);
105107
if (evt.muted) {
106108
this.handleMute(evt.userId).catch((err) =>
107-
console.error('[SttTtsPlugin] handleMute error =>', err),
109+
console.error("[SttTtsPlugin] handleMute error =>", err)
108110
);
109111
} else {
110112
this.speakerUnmuted.set(evt.userId, true);
111113
if (!this.pcmBuffers.has(evt.userId)) {
112114
this.pcmBuffers.set(evt.userId, []);
113115
}
114116
}
115-
},
117+
}
116118
);
117119
}
118120

@@ -157,22 +159,22 @@ export class SttTtsPlugin implements Plugin {
157159
const view = new DataView(buffer);
158160

159161
// RIFF chunk descriptor
160-
this.writeString(view, 0, 'RIFF');
162+
this.writeString(view, 0, "RIFF");
161163
view.setUint32(4, 36 + dataSize, true); // file size - 8
162-
this.writeString(view, 8, 'WAVE');
164+
this.writeString(view, 8, "WAVE");
163165

164166
// fmt sub-chunk
165-
this.writeString(view, 12, 'fmt ');
166-
view.setUint32(16, 16, true); // Subchunk1Size (16 for PCM)
167-
view.setUint16(20, 1, true); // AudioFormat (1 = PCM)
167+
this.writeString(view, 12, "fmt ");
168+
view.setUint32(16, 16, true); // Subchunk1Size (16 for PCM)
169+
view.setUint16(20, 1, true); // AudioFormat (1 = PCM)
168170
view.setUint16(22, numChannels, true); // NumChannels
169-
view.setUint32(24, sampleRate, true); // SampleRate
170-
view.setUint32(28, byteRate, true); // ByteRate
171-
view.setUint16(32, blockAlign, true); // BlockAlign
172-
view.setUint16(34, 16, true); // BitsPerSample (16)
171+
view.setUint32(24, sampleRate, true); // SampleRate
172+
view.setUint32(28, byteRate, true); // ByteRate
173+
view.setUint16(32, blockAlign, true); // BlockAlign
174+
view.setUint16(34, 16, true); // BitsPerSample (16)
173175

174176
// data sub-chunk
175-
this.writeString(view, 36, 'data');
177+
this.writeString(view, 36, "data");
176178
view.setUint32(40, dataSize, true);
177179

178180
// Write PCM samples
@@ -199,11 +201,11 @@ export class SttTtsPlugin implements Plugin {
199201
this.pcmBuffers.set(userId, []);
200202

201203
if (!chunks.length) {
202-
console.log('[SttTtsPlugin] No audio chunks for user =>', userId);
204+
console.log("[SttTtsPlugin] No audio chunks for user =>", userId);
203205
return;
204206
}
205207
console.log(
206-
`[SttTtsPlugin] Flushing STT buffer for user=${userId}, chunks=${chunks.length}`,
208+
`[SttTtsPlugin] Flushing STT buffer for user=${userId}, chunks=${chunks.length}`
207209
);
208210

209211
const totalLen = chunks.reduce((acc, c) => acc + c.length, 0);
@@ -221,14 +223,19 @@ export class SttTtsPlugin implements Plugin {
221223
const sttText = await this.transcriptionService.transcribe(wavBuffer);
222224

223225
if (!sttText || !sttText.trim()) {
224-
console.log('[SttTtsPlugin] No speech recognized for user =>', userId);
226+
console.log(
227+
"[SttTtsPlugin] No speech recognized for user =>",
228+
userId
229+
);
225230
return;
226231
}
227232
console.log(`[SttTtsPlugin] STT => user=${userId}, text="${sttText}"`);
228233

229234
// GPT answer
230235
const replyText = await this.askChatGPT(sttText);
231-
console.log(`[SttTtsPlugin] GPT => user=${userId}, reply="${replyText}"`);
236+
console.log(
237+
`[SttTtsPlugin] GPT => user=${userId}, reply="${replyText}"`
238+
);
232239

233240
// Use the standard speak method with queue
234241
await this.speakText(replyText);
@@ -242,7 +249,7 @@ export class SttTtsPlugin implements Plugin {
242249
if (!this.isSpeaking) {
243250
this.isSpeaking = true;
244251
this.processTtsQueue().catch((err) => {
245-
console.error('[SttTtsPlugin] processTtsQueue error =>', err);
252+
console.error("[SttTtsPlugin] processTtsQueue error =>", err);
246253
});
247254
}
248255
}
@@ -260,7 +267,7 @@ export class SttTtsPlugin implements Plugin {
260267
const pcm = await this.convertMp3ToPcm(ttsAudio, 48000);
261268
await this.streamToJanus(pcm, 48000);
262269
} catch (err) {
263-
console.error('[SttTtsPlugin] TTS streaming error =>', err);
270+
console.error("[SttTtsPlugin] TTS streaming error =>", err);
264271
}
265272
}
266273
this.isSpeaking = false;
@@ -271,20 +278,20 @@ export class SttTtsPlugin implements Plugin {
271278
*/
272279
private async askChatGPT(userText: string): Promise<string> {
273280
if (!this.openAiApiKey) {
274-
throw new Error('[SttTtsPlugin] No OpenAI API key for ChatGPT');
281+
throw new Error("[SttTtsPlugin] No OpenAI API key for ChatGPT");
275282
}
276-
const url = 'https://api.openai.com/v1/chat/completions';
283+
const url = "https://api.openai.com/v1/chat/completions";
277284
const messages = [
278-
{ role: 'system', content: this.systemPrompt },
285+
{ role: "system", content: this.systemPrompt },
279286
...this.chatContext,
280-
{ role: 'user', content: userText },
287+
{ role: "user", content: userText },
281288
];
282289

283290
const resp = await fetch(url, {
284-
method: 'POST',
291+
method: "POST",
285292
headers: {
286293
Authorization: `Bearer ${this.openAiApiKey}`,
287-
'Content-Type': 'application/json',
294+
"Content-Type": "application/json",
288295
},
289296
body: JSON.stringify({
290297
model: this.gptModel,
@@ -295,14 +302,14 @@ export class SttTtsPlugin implements Plugin {
295302
if (!resp.ok) {
296303
const errText = await resp.text();
297304
throw new Error(
298-
`[SttTtsPlugin] ChatGPT error => ${resp.status} ${errText}`,
305+
`[SttTtsPlugin] ChatGPT error => ${resp.status} ${errText}`
299306
);
300307
}
301308

302309
const json = await resp.json();
303-
const reply = json.choices?.[0]?.message?.content || '';
304-
this.chatContext.push({ role: 'user', content: userText });
305-
this.chatContext.push({ role: 'assistant', content: reply });
310+
const reply = json.choices?.[0]?.message?.content || "";
311+
this.chatContext.push({ role: "user", content: userText });
312+
this.chatContext.push({ role: "assistant", content: reply });
306313
return reply.trim();
307314
}
308315

@@ -311,14 +318,14 @@ export class SttTtsPlugin implements Plugin {
311318
*/
312319
private async elevenLabsTts(text: string): Promise<Buffer> {
313320
if (!this.elevenLabsApiKey) {
314-
throw new Error('[SttTtsPlugin] No ElevenLabs API key');
321+
throw new Error("[SttTtsPlugin] No ElevenLabs API key");
315322
}
316323
const url = `https://api.elevenlabs.io/v1/text-to-speech/${this.voiceId}`;
317324
const resp = await fetch(url, {
318-
method: 'POST',
325+
method: "POST",
319326
headers: {
320-
'Content-Type': 'application/json',
321-
'xi-api-key': this.elevenLabsApiKey,
327+
"Content-Type": "application/json",
328+
"xi-api-key": this.elevenLabsApiKey,
322329
},
323330
body: JSON.stringify({
324331
text,
@@ -329,7 +336,7 @@ export class SttTtsPlugin implements Plugin {
329336
if (!resp.ok) {
330337
const errText = await resp.text();
331338
throw new Error(
332-
`[SttTtsPlugin] ElevenLabs TTS error => ${resp.status} ${errText}`,
339+
`[SttTtsPlugin] ElevenLabs TTS error => ${resp.status} ${errText}`
333340
);
334341
}
335342
const arrayBuf = await resp.arrayBuffer();
@@ -341,37 +348,37 @@ export class SttTtsPlugin implements Plugin {
341348
*/
342349
private convertMp3ToPcm(
343350
mp3Buf: Buffer,
344-
outRate: number,
351+
outRate: number
345352
): Promise<Int16Array> {
346353
return new Promise((resolve, reject) => {
347-
const ff = spawn('ffmpeg', [
348-
'-i',
349-
'pipe:0',
350-
'-f',
351-
's16le',
352-
'-ar',
354+
const ff = spawn("ffmpeg", [
355+
"-i",
356+
"pipe:0",
357+
"-f",
358+
"s16le",
359+
"-ar",
353360
outRate.toString(),
354-
'-ac',
355-
'1',
356-
'pipe:1',
361+
"-ac",
362+
"1",
363+
"pipe:1",
357364
]);
358365
let raw = Buffer.alloc(0);
359366

360-
ff.stdout.on('data', (chunk: Buffer) => {
367+
ff.stdout.on("data", (chunk: Buffer) => {
361368
raw = Buffer.concat([raw, chunk]);
362369
});
363-
ff.stderr.on('data', () => {
370+
ff.stderr.on("data", () => {
364371
// ignoring ffmpeg logs
365372
});
366-
ff.on('close', (code) => {
373+
ff.on("close", (code) => {
367374
if (code !== 0) {
368375
reject(new Error(`ffmpeg error code=${code}`));
369376
return;
370377
}
371378
const samples = new Int16Array(
372379
raw.buffer,
373380
raw.byteOffset,
374-
raw.byteLength / 2,
381+
raw.byteLength / 2
375382
);
376383
resolve(samples);
377384
});
@@ -387,7 +394,7 @@ export class SttTtsPlugin implements Plugin {
387394
*/
388395
private async streamToJanus(
389396
samples: Int16Array,
390-
sampleRate: number,
397+
sampleRate: number
391398
): Promise<void> {
392399
// TODO: Check if better than 480 fixed
393400
const FRAME_SIZE = Math.floor(sampleRate * 0.01); // 10ms frames => 480 @48kHz
@@ -408,25 +415,25 @@ export class SttTtsPlugin implements Plugin {
408415

409416
public setSystemPrompt(prompt: string) {
410417
this.systemPrompt = prompt;
411-
console.log('[SttTtsPlugin] setSystemPrompt =>', prompt);
418+
console.log("[SttTtsPlugin] setSystemPrompt =>", prompt);
412419
}
413420

414421
/**
415422
* Change the GPT model at runtime (e.g. "gpt-4", "gpt-3.5-turbo", etc.).
416423
*/
417424
public setGptModel(model: string) {
418425
this.gptModel = model;
419-
console.log('[SttTtsPlugin] setGptModel =>', model);
426+
console.log("[SttTtsPlugin] setGptModel =>", model);
420427
}
421428

422429
/**
423430
* Add a message (system, user or assistant) to the chat context.
424431
* E.g. to store conversation history or inject a persona.
425432
*/
426-
public addMessage(role: 'system' | 'user' | 'assistant', content: string) {
433+
public addMessage(role: "system" | "user" | "assistant", content: string) {
427434
this.chatContext.push({ role, content });
428435
console.log(
429-
`[SttTtsPlugin] addMessage => role=${role}, content=${content}`,
436+
`[SttTtsPlugin] addMessage => role=${role}, content=${content}`
430437
);
431438
}
432439

@@ -435,11 +442,11 @@ export class SttTtsPlugin implements Plugin {
435442
*/
436443
public clearChatContext() {
437444
this.chatContext = [];
438-
console.log('[SttTtsPlugin] clearChatContext => done');
445+
console.log("[SttTtsPlugin] clearChatContext => done");
439446
}
440447

441448
cleanup(): void {
442-
console.log('[SttTtsPlugin] cleanup => releasing resources');
449+
console.log("[SttTtsPlugin] cleanup => releasing resources");
443450
this.pcmBuffers.clear();
444451
this.speakerUnmuted.clear();
445452
this.ttsQueue = [];

0 commit comments

Comments
 (0)