File size: 7,120 Bytes
0110dee | 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 | import { useSettingsStore } from '../../stores/settings.store';
export interface ChatMessage {
role: 'user' | 'assistant' | 'system';
content: string;
}
export interface ChatCompletionOptions {
messages: ChatMessage[];
temperature?: number;
maxTokens?: number;
stream?: boolean;
onChunk?: (chunk: string) => void;
}
export interface ChatCompletionResponse {
content: string;
finishReason: string;
}
/**
* Universal AI client that supports WebLLM, OpenRouter, and Ollama
*/
export class AIClient {
private webllmWorker: Worker | null = null;
/**
* Initialize the AI client based on current settings
*/
async initialize(): Promise<void> {
const { aiProvider } = useSettingsStore.getState();
if (aiProvider === 'webllm') {
await this.initializeWebLLM();
}
// OpenRouter and Ollama don't need initialization
}
/**
* Initialize WebLLM worker
*/
private async initializeWebLLM(): Promise<void> {
if (this.webllmWorker) return;
// WebLLM worker will be created in Phase 3
console.log('WebLLM initialization placeholder');
}
/**
* Send chat completion request
*/
async chatCompletion(options: ChatCompletionOptions): Promise<ChatCompletionResponse> {
const { aiProvider } = useSettingsStore.getState();
switch (aiProvider) {
case 'webllm':
return this.webllmCompletion(options);
case 'openrouter':
return this.openRouterCompletion(options);
case 'ollama':
return this.ollamaCompletion(options);
default:
throw new Error(`Unknown AI provider: ${aiProvider}`);
}
}
/**
* WebLLM completion (browser-native)
*/
private async webllmCompletion(options: ChatCompletionOptions): Promise<ChatCompletionResponse> {
// Placeholder - will be implemented in Phase 3
console.log('WebLLM completion:', options);
return {
content: 'WebLLM response (placeholder)',
finishReason: 'stop',
};
}
/**
* OpenRouter completion (cloud API)
*/
private async openRouterCompletion(options: ChatCompletionOptions): Promise<ChatCompletionResponse> {
const { openRouterApiKey, openRouterModel } = useSettingsStore.getState();
if (!openRouterApiKey) {
throw new Error('OpenRouter API key not configured. Please add it in Settings.');
}
const response = await fetch('https://openrouter.ai/api/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${openRouterApiKey}`,
'Content-Type': 'application/json',
'HTTP-Referer': window.location.origin,
'X-Title': 'BOB IDE',
},
body: JSON.stringify({
model: openRouterModel,
messages: options.messages,
temperature: options.temperature ?? 0.7,
max_tokens: options.maxTokens ?? 2048,
stream: options.stream ?? false,
}),
});
if (!response.ok) {
const error = await response.text();
throw new Error(`OpenRouter API error: ${error}`);
}
if (options.stream && options.onChunk) {
return this.handleOpenRouterStream(response, options.onChunk);
}
const data = await response.json();
return {
content: data.choices[0].message.content,
finishReason: data.choices[0].finish_reason,
};
}
/**
* Handle OpenRouter streaming response
*/
private async handleOpenRouterStream(
response: Response,
onChunk: (chunk: string) => void
): Promise<ChatCompletionResponse> {
const reader = response.body?.getReader();
if (!reader) throw new Error('No response body');
const decoder = new TextDecoder();
let fullContent = '';
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
const lines = chunk.split('\n').filter(line => line.trim().startsWith('data: '));
for (const line of lines) {
const data = line.replace('data: ', '');
if (data === '[DONE]') continue;
try {
const parsed = JSON.parse(data);
const content = parsed.choices[0]?.delta?.content;
if (content) {
fullContent += content;
onChunk(content);
}
} catch (e) {
// Skip invalid JSON
}
}
}
} finally {
reader.releaseLock();
}
return {
content: fullContent,
finishReason: 'stop',
};
}
/**
* Ollama completion (local API)
*/
private async ollamaCompletion(options: ChatCompletionOptions): Promise<ChatCompletionResponse> {
const { ollamaBaseUrl, ollamaModel } = useSettingsStore.getState();
const response = await fetch(`${ollamaBaseUrl}/api/chat`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: ollamaModel,
messages: options.messages,
stream: options.stream ?? false,
options: {
temperature: options.temperature ?? 0.7,
num_predict: options.maxTokens ?? 2048,
},
}),
});
if (!response.ok) {
const error = await response.text();
throw new Error(`Ollama API error: ${error}`);
}
if (options.stream && options.onChunk) {
return this.handleOllamaStream(response, options.onChunk);
}
const data = await response.json();
return {
content: data.message.content,
finishReason: 'stop',
};
}
/**
* Handle Ollama streaming response
*/
private async handleOllamaStream(
response: Response,
onChunk: (chunk: string) => void
): Promise<ChatCompletionResponse> {
const reader = response.body?.getReader();
if (!reader) throw new Error('No response body');
const decoder = new TextDecoder();
let fullContent = '';
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
const lines = chunk.split('\n').filter(line => line.trim());
for (const line of lines) {
try {
const parsed = JSON.parse(line);
const content = parsed.message?.content;
if (content) {
fullContent += content;
onChunk(content);
}
} catch (e) {
// Skip invalid JSON
}
}
}
} finally {
reader.releaseLock();
}
return {
content: fullContent,
finishReason: 'stop',
};
}
/**
* Clean up resources
*/
dispose(): void {
if (this.webllmWorker) {
this.webllmWorker.terminate();
this.webllmWorker = null;
}
}
}
// Singleton instance
export const aiClient = new AIClient();
// Made with Bob
|