| |
| |
| |
| |
| |
| export class CloudService { |
| constructor({apiKey, model} = {}) { |
| this.apiKey = apiKey; |
| this.model = model; |
| } |
|
|
|
|
| |
| |
| |
| |
| |
| |
| updateConfig({apiKey, model}) { |
| if (apiKey) this.apiKey = apiKey; |
| if (model) this.model = model; |
| } |
|
|
|
|
| |
| |
| |
| |
| |
| |
| async infer(prompt) { |
| if (!this.apiKey) throw new Error('No API key set for CloudService'); |
|
|
| |
| const payload = { |
| model: this.model, |
| max_tokens: 50, |
| messages: [{role: 'user', content: prompt}] |
| }; |
|
|
| |
| const resp = await fetch('https://openrouter.ai/api/v1/chat/completions', { |
| method: 'POST', |
| headers: { |
| 'Content-Type': 'application/json', |
| 'Authorization': `Bearer ${this.apiKey}` |
| }, |
| body: JSON.stringify(payload) |
| }); |
|
|
| |
| if (!resp.ok) { |
| const text = await resp.text(); |
| throw new Error(`Cloud inference failed: ${resp.status} ${text}`); |
| } |
|
|
| const json = await resp.json(); |
|
|
| |
| let text = ''; |
| try { |
| if (json.choices && json.choices[0]) { |
| text = json.choices[0].message?.content || json.choices[0].text || ''; |
| } else if (json.output) { |
| text = Array.isArray(json.output) ? json.output.join('\n') : json.output; |
| } |
| } catch (e) { |
| text = JSON.stringify(json).slice(0, 200); |
| } |
|
|
| return { |
| answer: text, |
| stats: { |
| input_tokens: json.usage?.prompt_tokens || 0, |
| output_tokens: json.usage?.completion_tokens || 0 |
| } |
| }; |
| } |
|
|
| |
| |
| |
| |
| |
| getModelName(){ |
| return this.model; |
| } |
| } |