-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathindex.ts
More file actions
190 lines (173 loc) · 6.28 KB
/
Copy pathindex.ts
File metadata and controls
190 lines (173 loc) · 6.28 KB
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
import { PromptProvider } from '@onlook/ai/src/prompt/provider';
import { listFilesTool, readFileTool } from '@onlook/ai/src/tools';
import { CLAUDE_MODELS, LLMProvider, MCP_MODELS } from '@onlook/models';
import {
ChatSuggestionSchema,
StreamRequestType,
type ChatSuggestion,
type StreamResponse,
type UsageCheckResult,
} from '@onlook/models/chat';
import { MainChannels } from '@onlook/models/constants';
import {
generateObject,
streamText,
type CoreMessage,
type CoreSystemMessage,
type LanguageModelV1,
} from 'ai';
import { mainWindow } from '..';
import { PersistentStorage } from '../storage';
import { initModel } from './llmProvider';
class LlmManager {
private static instance: LlmManager;
private abortController: AbortController | null = null;
private useAnalytics: boolean = true;
private promptProvider: PromptProvider;
private constructor() {
this.restoreSettings();
this.promptProvider = new PromptProvider();
}
private restoreSettings() {
const settings = PersistentStorage.USER_SETTINGS.read() || {};
const enable = settings.enableAnalytics !== undefined ? settings.enableAnalytics : true;
if (enable) {
this.useAnalytics = true;
} else {
this.useAnalytics = false;
}
}
public toggleAnalytics(enable: boolean) {
this.useAnalytics = enable;
}
public static getInstance(): LlmManager {
if (!LlmManager.instance) {
LlmManager.instance = new LlmManager();
}
return LlmManager.instance;
}
public async stream(
messages: CoreMessage[],
requestType: StreamRequestType,
options?: {
abortController?: AbortController;
skipSystemPrompt?: boolean;
},
): Promise<StreamResponse> {
const { abortController, skipSystemPrompt } = options || {};
this.abortController = abortController || new AbortController();
try {
if (!skipSystemPrompt) {
const systemMessage = {
role: 'system',
content: this.promptProvider.getSystemPrompt(process.platform),
experimental_providerMetadata: {
anthropic: { cacheControl: { type: 'ephemeral' } },
},
} as CoreSystemMessage;
messages = [systemMessage, ...messages];
}
const model = await this.getModel(requestType);
const { textStream } = await streamText({
model,
messages,
abortSignal: this.abortController?.signal,
onError: (error) => {
throw error;
},
maxSteps: 10,
tools: {
listAllFiles: listFilesTool,
readFile: readFileTool,
},
maxTokens: 64000,
});
let fullText = '';
for await (const partialText of textStream) {
fullText += partialText;
this.emitPartialMessage(fullText);
}
return { content: fullText, status: 'full' };
} catch (error: any) {
try {
console.error('Error', error);
if (error?.error?.statusCode) {
if (error?.error?.statusCode === 403) {
const rateLimitError = JSON.parse(
error.error.responseBody,
) as UsageCheckResult;
return {
status: 'rate-limited',
content: 'You have reached your daily limit.',
rateLimitResult: rateLimitError,
};
} else {
return {
status: 'error',
content: error.error.responseBody,
};
}
}
const errorMessage = this.getErrorMessage(error);
return { content: errorMessage, status: 'error' };
} catch (error) {
console.error('Error parsing error', error);
return { content: 'An unknown error occurred', status: 'error' };
} finally {
this.abortController = null;
}
}
}
public abortStream(): boolean {
if (this.abortController) {
this.abortController.abort();
return true;
}
return false;
}
private emitPartialMessage(content: string) {
const res: StreamResponse = {
status: 'partial',
content,
};
mainWindow?.webContents.send(MainChannels.CHAT_STREAM_PARTIAL, res);
}
private getErrorMessage(error: unknown): string {
if (error instanceof Error) {
return error.message;
}
if (typeof error === 'string') {
return error;
}
if (error instanceof Response) {
return error.statusText;
}
if (error && typeof error === 'object' && 'message' in error) {
return String(error.message);
}
return 'An unknown error occurred';
}
private async getModel(requestType: StreamRequestType): Promise<LanguageModelV1> {
// Get the provider and model from settings or use defaults
const settings = PersistentStorage.USER_SETTINGS.read() || {};
const provider = settings.llmProvider || LLMProvider.ANTHROPIC;
const modelName = settings.llmModel || CLAUDE_MODELS.SONNET;
return await initModel(provider, modelName, { requestType });
}
public async generateSuggestions(messages: CoreMessage[]): Promise<ChatSuggestion[]> {
try {
const model = await this.getModel(StreamRequestType.SUGGESTIONS);
const { object } = await generateObject({
model,
output: 'array',
schema: ChatSuggestionSchema,
messages,
});
return object as ChatSuggestion[];
} catch (error) {
console.error(error);
return [];
}
}
}
export default LlmManager.getInstance();