@push.rocks/smartai 0.0.14 → 0.0.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,158 @@
1
1
  import * as plugins from './plugins.js';
2
+ import * as paths from './paths.js';
3
+ import { MultiModalModel } from './abstract.classes.multimodal.js';
4
+ import type { ChatOptions, ChatResponse, ChatMessage } from './abstract.classes.multimodal.js';
2
5
 
3
- export class PerplexityProvider {}
6
+ export interface IPerplexityProviderOptions {
7
+ perplexityToken: string;
8
+ }
9
+
10
+ export class PerplexityProvider extends MultiModalModel {
11
+ private options: IPerplexityProviderOptions;
12
+
13
+ constructor(optionsArg: IPerplexityProviderOptions) {
14
+ super();
15
+ this.options = optionsArg;
16
+ }
17
+
18
+ async start() {
19
+ // Initialize any necessary clients or resources
20
+ }
21
+
22
+ async stop() {}
23
+
24
+ public async chatStream(input: ReadableStream<Uint8Array>): Promise<ReadableStream<string>> {
25
+ // Create a TextDecoder to handle incoming chunks
26
+ const decoder = new TextDecoder();
27
+ let buffer = '';
28
+ let currentMessage: { role: string; content: string; } | null = null;
29
+
30
+ // Create a TransformStream to process the input
31
+ const transform = new TransformStream<Uint8Array, string>({
32
+ async transform(chunk, controller) {
33
+ buffer += decoder.decode(chunk, { stream: true });
34
+
35
+ // Try to parse complete JSON messages from the buffer
36
+ while (true) {
37
+ const newlineIndex = buffer.indexOf('\n');
38
+ if (newlineIndex === -1) break;
39
+
40
+ const line = buffer.slice(0, newlineIndex);
41
+ buffer = buffer.slice(newlineIndex + 1);
42
+
43
+ if (line.trim()) {
44
+ try {
45
+ const message = JSON.parse(line);
46
+ currentMessage = {
47
+ role: message.role || 'user',
48
+ content: message.content || '',
49
+ };
50
+ } catch (e) {
51
+ console.error('Failed to parse message:', e);
52
+ }
53
+ }
54
+ }
55
+
56
+ // If we have a complete message, send it to Perplexity
57
+ if (currentMessage) {
58
+ const response = await fetch('https://api.perplexity.ai/chat/completions', {
59
+ method: 'POST',
60
+ headers: {
61
+ 'Authorization': `Bearer ${this.options.perplexityToken}`,
62
+ 'Content-Type': 'application/json',
63
+ },
64
+ body: JSON.stringify({
65
+ model: 'mixtral-8x7b-instruct',
66
+ messages: [{ role: currentMessage.role, content: currentMessage.content }],
67
+ stream: true,
68
+ }),
69
+ });
70
+
71
+ // Process each chunk from Perplexity
72
+ const reader = response.body?.getReader();
73
+ if (reader) {
74
+ try {
75
+ while (true) {
76
+ const { done, value } = await reader.read();
77
+ if (done) break;
78
+
79
+ const chunk = new TextDecoder().decode(value);
80
+ const lines = chunk.split('\n');
81
+
82
+ for (const line of lines) {
83
+ if (line.startsWith('data: ')) {
84
+ const data = line.slice(6);
85
+ if (data === '[DONE]') break;
86
+
87
+ try {
88
+ const parsed = JSON.parse(data);
89
+ const content = parsed.choices[0]?.delta?.content;
90
+ if (content) {
91
+ controller.enqueue(content);
92
+ }
93
+ } catch (e) {
94
+ console.error('Failed to parse SSE data:', e);
95
+ }
96
+ }
97
+ }
98
+ }
99
+ } finally {
100
+ reader.releaseLock();
101
+ }
102
+ }
103
+
104
+ currentMessage = null;
105
+ }
106
+ },
107
+
108
+ flush(controller) {
109
+ if (buffer) {
110
+ try {
111
+ const message = JSON.parse(buffer);
112
+ controller.enqueue(message.content || '');
113
+ } catch (e) {
114
+ console.error('Failed to parse remaining buffer:', e);
115
+ }
116
+ }
117
+ }
118
+ });
119
+
120
+ // Connect the input to our transform stream
121
+ return input.pipeThrough(transform);
122
+ }
123
+
124
+ // Implementing the synchronous chat interaction
125
+ public async chat(optionsArg: ChatOptions): Promise<ChatResponse> {
126
+ // Make API call to Perplexity
127
+ const response = await fetch('https://api.perplexity.ai/chat/completions', {
128
+ method: 'POST',
129
+ headers: {
130
+ 'Authorization': `Bearer ${this.options.perplexityToken}`,
131
+ 'Content-Type': 'application/json',
132
+ },
133
+ body: JSON.stringify({
134
+ model: 'mixtral-8x7b-instruct', // Using Mixtral model
135
+ messages: [
136
+ { role: 'system', content: optionsArg.systemMessage },
137
+ ...optionsArg.messageHistory,
138
+ { role: 'user', content: optionsArg.userMessage }
139
+ ],
140
+ }),
141
+ });
142
+
143
+ if (!response.ok) {
144
+ throw new Error(`Perplexity API error: ${response.statusText}`);
145
+ }
146
+
147
+ const result = await response.json();
148
+
149
+ return {
150
+ role: 'assistant' as const,
151
+ message: result.choices[0].message.content,
152
+ };
153
+ }
154
+
155
+ public async audio(optionsArg: { message: string }): Promise<NodeJS.ReadableStream> {
156
+ throw new Error('Audio generation is not supported by Perplexity.');
157
+ }
158
+ }