forked from elizaOS/eliza
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathllama.ts
779 lines (698 loc) · 23.7 KB
/
llama.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
import {
elizaLogger,
IAgentRuntime,
ServiceType,
ModelProviderName,
} from "@elizaos/core";
import { Service } from "@elizaos/core";
import fs from "fs";
import https from "https";
import {
GbnfJsonSchema,
getLlama,
Llama,
LlamaChatSession,
LlamaContext,
LlamaContextSequence,
LlamaContextSequenceRepeatPenalty,
LlamaJsonSchemaGrammar,
LlamaModel,
Token,
} from "node-llama-cpp";
import path from "path";
import si from "systeminformation";
import { fileURLToPath } from "url";
const wordsToPunish = [
" please",
" feel",
" free",
"!",
"–",
"—",
"?",
".",
",",
"; ",
" cosmos",
" tapestry",
" tapestries",
" glitch",
" matrix",
" cyberspace",
" troll",
" questions",
" topics",
" discuss",
" basically",
" simulation",
" simulate",
" universe",
" like",
" debug",
" debugging",
" wild",
" existential",
" juicy",
" circuits",
" help",
" ask",
" happy",
" just",
" cosmic",
" cool",
" joke",
" punchline",
" fancy",
" glad",
" assist",
" algorithm",
" Indeed",
" Furthermore",
" However",
" Notably",
" Therefore",
" Additionally",
" conclusion",
" Significantly",
" Consequently",
" Thus",
" What",
" Otherwise",
" Moreover",
" Subsequently",
" Accordingly",
" Unlock",
" Unleash",
" buckle",
" pave",
" forefront",
" harness",
" harnessing",
" bridging",
" bridging",
" Spearhead",
" spearheading",
" Foster",
" foster",
" environmental",
" impact",
" Navigate",
" navigating",
" challenges",
" chaos",
" social",
" inclusion",
" inclusive",
" diversity",
" diverse",
" delve",
" noise",
" infinite",
" insanity",
" coffee",
" singularity",
" AI",
" digital",
" artificial",
" intelligence",
" consciousness",
" reality",
" metaverse",
" virtual",
" virtual reality",
" VR",
" Metaverse",
" humanity",
];
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const jsonSchemaGrammar: Readonly<{
type: string;
properties: {
user: {
type: string;
};
content: {
type: string;
};
};
}> = {
type: "object",
properties: {
user: {
type: "string",
},
content: {
type: "string",
},
},
};
interface QueuedMessage {
context: string;
temperature: number;
stop: string[];
max_tokens: number;
frequency_penalty: number;
presence_penalty: number;
useGrammar: boolean;
resolve: (value: any | string | PromiseLike<any | string>) => void;
reject: (reason?: any) => void;
}
export class LlamaService extends Service {
private llama: Llama | undefined;
private model: LlamaModel | undefined;
private modelPath: string;
private grammar: LlamaJsonSchemaGrammar<GbnfJsonSchema> | undefined;
private ctx: LlamaContext | undefined;
private sequence: LlamaContextSequence | undefined;
private modelUrl: string;
private ollamaModel: string | undefined;
private messageQueue: QueuedMessage[] = [];
private isProcessing: boolean = false;
private modelInitialized: boolean = false;
private runtime: IAgentRuntime | undefined;
static serviceType: ServiceType = ServiceType.TEXT_GENERATION;
constructor() {
super();
this.llama = undefined;
this.model = undefined;
this.modelUrl =
"https://huggingface.co/NousResearch/Hermes-3-Llama-3.1-8B-GGUF/resolve/main/Hermes-3-Llama-3.1-8B.Q8_0.gguf?download=true";
const modelName = "model.gguf";
this.modelPath = path.join(
process.env.LLAMALOCAL_PATH?.trim() ?? "./",
modelName
);
this.ollamaModel = process.env.OLLAMA_MODEL;
}
async initialize(runtime: IAgentRuntime): Promise<void> {
elizaLogger.info("Initializing LlamaService...");
this.runtime = runtime;
}
private async ensureInitialized() {
if (!this.modelInitialized) {
elizaLogger.info(
"Model not initialized, starting initialization..."
);
await this.initializeModel();
} else {
elizaLogger.info("Model already initialized");
}
}
async initializeModel() {
try {
elizaLogger.info("Checking model file...");
await this.checkModel();
const systemInfo = await si.graphics();
const hasCUDA = systemInfo.controllers.some((controller) =>
controller.vendor.toLowerCase().includes("nvidia")
);
if (hasCUDA) {
elizaLogger.info(
"LlamaService: CUDA detected, using GPU acceleration"
);
} else {
elizaLogger.warn(
"LlamaService: No CUDA detected - local response will be slow"
);
}
elizaLogger.info("Initializing Llama instance...");
this.llama = await getLlama({
gpu: hasCUDA ? "cuda" : undefined,
});
elizaLogger.info("Creating JSON schema grammar...");
const grammar = new LlamaJsonSchemaGrammar(
this.llama,
jsonSchemaGrammar as GbnfJsonSchema
);
this.grammar = grammar;
elizaLogger.info("Loading model...");
this.model = await this.llama.loadModel({
modelPath: this.modelPath,
});
elizaLogger.info("Creating context and sequence...");
this.ctx = await this.model.createContext({ contextSize: 8192 });
this.sequence = this.ctx.getSequence();
this.modelInitialized = true;
elizaLogger.success("Model initialization complete");
this.processQueue();
} catch (error) {
elizaLogger.error(
"Model initialization failed. Deleting model and retrying:",
error
);
try {
elizaLogger.info(
"Attempting to delete and re-download model..."
);
await this.deleteModel();
await this.initializeModel();
} catch (retryError) {
elizaLogger.error(
"Model re-initialization failed:",
retryError
);
throw new Error(
`Model initialization failed after retry: ${retryError.message}`
);
}
}
}
async checkModel() {
if (!fs.existsSync(this.modelPath)) {
elizaLogger.info("Model file not found, starting download...");
await new Promise<void>((resolve, reject) => {
const file = fs.createWriteStream(this.modelPath);
let downloadedSize = 0;
let totalSize = 0;
const downloadModel = (url: string) => {
https
.get(url, (response) => {
if (
response.statusCode >= 300 &&
response.statusCode < 400 &&
response.headers.location
) {
elizaLogger.info(
`Following redirect to: ${response.headers.location}`
);
downloadModel(response.headers.location);
return;
}
if (response.statusCode !== 200) {
reject(
new Error(
`Failed to download model: HTTP ${response.statusCode}`
)
);
return;
}
totalSize = parseInt(
response.headers["content-length"] || "0",
10
);
elizaLogger.info(
`Downloading model: Hermes-3-Llama-3.1-8B.Q8_0.gguf`
);
elizaLogger.info(
`Download location: ${this.modelPath}`
);
elizaLogger.info(
`Total size: ${(totalSize / 1024 / 1024).toFixed(2)} MB`
);
response.pipe(file);
let progressString = "";
response.on("data", (chunk) => {
downloadedSize += chunk.length;
const progress =
totalSize > 0
? (
(downloadedSize / totalSize) *
100
).toFixed(1)
: "0.0";
const dots = ".".repeat(
Math.floor(Number(progress) / 5)
);
progressString = `Downloading model: [${dots.padEnd(20, " ")}] ${progress}%`;
elizaLogger.progress(progressString);
});
file.on("finish", () => {
file.close();
elizaLogger.progress(""); // Clear the progress line
elizaLogger.success("Model download complete");
resolve();
});
response.on("error", (error) => {
fs.unlink(this.modelPath, () => {});
reject(
new Error(
`Model download failed: ${error.message}`
)
);
});
})
.on("error", (error) => {
fs.unlink(this.modelPath, () => {});
reject(
new Error(
`Model download request failed: ${error.message}`
)
);
});
};
downloadModel(this.modelUrl);
file.on("error", (err) => {
fs.unlink(this.modelPath, () => {}); // Delete the file async
console.error("File write error:", err.message);
reject(err);
});
});
} else {
elizaLogger.warn("Model already exists.");
}
}
async deleteModel() {
if (fs.existsSync(this.modelPath)) {
fs.unlinkSync(this.modelPath);
}
}
async queueMessageCompletion(
context: string,
temperature: number,
stop: string[],
frequency_penalty: number,
presence_penalty: number,
max_tokens: number
): Promise<any> {
await this.ensureInitialized();
return new Promise((resolve, reject) => {
this.messageQueue.push({
context,
temperature,
stop,
frequency_penalty,
presence_penalty,
max_tokens,
useGrammar: true,
resolve,
reject,
});
this.processQueue();
});
}
async queueTextCompletion(
context: string,
temperature: number,
stop: string[],
frequency_penalty: number,
presence_penalty: number,
max_tokens: number
): Promise<string> {
await this.ensureInitialized();
return new Promise((resolve, reject) => {
this.messageQueue.push({
context,
temperature,
stop,
frequency_penalty: frequency_penalty ?? 1.0,
presence_penalty: presence_penalty ?? 1.0,
max_tokens,
useGrammar: false,
resolve,
reject,
});
this.processQueue();
});
}
private async processQueue() {
if (
this.isProcessing ||
this.messageQueue.length === 0 ||
!this.modelInitialized
) {
return;
}
this.isProcessing = true;
while (this.messageQueue.length > 0) {
const message = this.messageQueue.shift();
if (message) {
try {
const response = await this.getCompletionResponse(
message.context,
message.temperature,
message.stop,
message.frequency_penalty,
message.presence_penalty,
message.max_tokens,
message.useGrammar
);
message.resolve(response);
} catch (error) {
message.reject(error);
}
}
}
this.isProcessing = false;
}
async completion(prompt: string, runtime: IAgentRuntime): Promise<string> {
try {
await this.initialize(runtime);
if (runtime.modelProvider === ModelProviderName.OLLAMA) {
return await this.ollamaCompletion(prompt);
}
return await this.localCompletion(prompt);
} catch (error) {
elizaLogger.error("Error in completion:", error);
throw error;
}
}
async embedding(text: string, runtime: IAgentRuntime): Promise<number[]> {
try {
await this.initialize(runtime);
if (runtime.modelProvider === ModelProviderName.OLLAMA) {
return await this.ollamaEmbedding(text);
}
return await this.localEmbedding(text);
} catch (error) {
elizaLogger.error("Error in embedding:", error);
throw error;
}
}
private async getCompletionResponse(
context: string,
temperature: number,
stop: string[],
frequency_penalty: number,
presence_penalty: number,
max_tokens: number,
useGrammar: boolean
): Promise<any | string> {
const ollamaModel = process.env.OLLAMA_MODEL;
if (ollamaModel) {
const ollamaUrl =
process.env.OLLAMA_SERVER_URL || "http://localhost:11434";
elizaLogger.info(
`Using Ollama API at ${ollamaUrl} with model ${ollamaModel}`
);
const response = await fetch(`${ollamaUrl}/api/generate`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
model: ollamaModel,
prompt: context,
stream: false,
options: {
temperature,
stop,
frequency_penalty,
presence_penalty,
num_predict: max_tokens,
},
}),
});
if (!response.ok) {
throw new Error(
`Ollama request failed: ${response.statusText}`
);
}
const result = await response.json();
return useGrammar ? { content: result.response } : result.response;
}
// Use local GGUF model
if (!this.sequence) {
throw new Error("Model not initialized.");
}
const session = new LlamaChatSession({
contextSequence: this.sequence
});
const response = await session.prompt(context, {
onTextChunk(chunk) { // stream the response to the console as it's being generated
process.stdout.write(chunk);
}
});
if (!response) {
throw new Error("Response is undefined");
}
if (useGrammar) {
// extract everything between ```json and ```
let jsonString = response.match(/```json(.*?)```/s)?.[1].trim();
if (!jsonString) {
// try parsing response as JSON
try {
jsonString = JSON.stringify(JSON.parse(response));
} catch {
throw new Error("JSON string not found");
}
}
try {
const parsedResponse = JSON.parse(jsonString);
if (!parsedResponse) {
throw new Error("Parsed response is undefined");
}
await this.sequence.clearHistory();
return parsedResponse;
} catch (error) {
elizaLogger.error("Error parsing JSON:", error);
}
} else {
await this.sequence.clearHistory();
return response;
}
}
async getEmbeddingResponse(input: string): Promise<number[] | undefined> {
const ollamaModel = process.env.OLLAMA_MODEL;
if (ollamaModel) {
const ollamaUrl =
process.env.OLLAMA_SERVER_URL || "http://localhost:11434";
const embeddingModel =
process.env.OLLAMA_EMBEDDING_MODEL || "mxbai-embed-large";
elizaLogger.info(
`Using Ollama API for embeddings with model ${embeddingModel} (base: ${ollamaModel})`
);
const response = await fetch(`${ollamaUrl}/api/embeddings`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
model: embeddingModel,
prompt: input,
}),
});
if (!response.ok) {
throw new Error(
`Ollama embeddings request failed: ${response.statusText}`
);
}
const result = await response.json();
return result.embedding;
}
// Use local GGUF model
if (!this.sequence) {
throw new Error("Sequence not initialized");
}
const ollamaUrl =
process.env.OLLAMA_SERVER_URL || "http://localhost:11434";
const embeddingModel =
process.env.OLLAMA_EMBEDDING_MODEL || "mxbai-embed-large";
elizaLogger.info(
`Using Ollama API for embeddings with model ${embeddingModel} (base: ${this.ollamaModel})`
);
const response = await fetch(`${ollamaUrl}/api/embeddings`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
input: input,
model: embeddingModel,
}),
});
if (!response.ok) {
throw new Error(`Failed to get embedding: ${response.statusText}`);
}
const embedding = await response.json();
return embedding.vector;
}
private async ollamaCompletion(prompt: string): Promise<string> {
const ollamaModel = process.env.OLLAMA_MODEL;
const ollamaUrl =
process.env.OLLAMA_SERVER_URL || "http://localhost:11434";
elizaLogger.info(
`Using Ollama API at ${ollamaUrl} with model ${ollamaModel}`
);
const response = await fetch(`${ollamaUrl}/api/generate`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
model: ollamaModel,
prompt: prompt,
stream: false,
options: {
temperature: 0.7,
stop: ["\n"],
frequency_penalty: 0.5,
presence_penalty: 0.5,
num_predict: 256,
},
}),
});
if (!response.ok) {
throw new Error(`Ollama request failed: ${response.statusText}`);
}
const result = await response.json();
return result.response;
}
private async ollamaEmbedding(text: string): Promise<number[]> {
const ollamaModel = process.env.OLLAMA_MODEL;
const ollamaUrl =
process.env.OLLAMA_SERVER_URL || "http://localhost:11434";
const embeddingModel =
process.env.OLLAMA_EMBEDDING_MODEL || "mxbai-embed-large";
elizaLogger.info(
`Using Ollama API for embeddings with model ${embeddingModel} (base: ${ollamaModel})`
);
const response = await fetch(`${ollamaUrl}/api/embeddings`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
model: embeddingModel,
prompt: text,
}),
});
if (!response.ok) {
throw new Error(
`Ollama embeddings request failed: ${response.statusText}`
);
}
const result = await response.json();
return result.embedding;
}
private async localCompletion(prompt: string): Promise<string> {
if (!this.sequence) {
throw new Error("Sequence not initialized");
}
const tokens = this.model!.tokenize(prompt);
// tokenize the words to punish
const wordsToPunishTokens = wordsToPunish
.map((word) => this.model!.tokenize(word))
.flat();
const repeatPenalty: LlamaContextSequenceRepeatPenalty = {
punishTokens: () => wordsToPunishTokens,
penalty: 1.2,
frequencyPenalty: 0.5,
presencePenalty: 0.5,
};
const responseTokens: Token[] = [];
for await (const token of this.sequence.evaluate(tokens, {
temperature: 0.7,
repeatPenalty: repeatPenalty,
yieldEogToken: false,
})) {
const current = this.model.detokenize([...responseTokens, token]);
if (current.includes("\n")) {
elizaLogger.info("Stop sequence found");
break;
}
responseTokens.push(token);
process.stdout.write(this.model!.detokenize([token]));
if (responseTokens.length > 256) {
elizaLogger.info("Max tokens reached");
break;
}
}
const response = this.model!.detokenize(responseTokens);
if (!response) {
throw new Error("Response is undefined");
}
await this.sequence.clearHistory();
return response;
}
private async localEmbedding(text: string): Promise<number[]> {
if (!this.sequence) {
throw new Error("Sequence not initialized");
}
const embeddingContext = await this.model.createEmbeddingContext();
const embedding = await embeddingContext.getEmbeddingFor(text);
return embedding?.vector ? [...embedding.vector] : undefined;
}
}
export default LlamaService;