包文件→ .shtukbase/packages/llm-provider/llm.js
llm.js
93 行, 4.0 KB.
文件按包中的原样显示:代码及其注释不做翻译。
- // llm.js: a tiny OpenAI-compatible chat client for lenses (no dependencies).
- // window.shtukLLM.chat(settings, messages, tools, onDelta, signal) streams one completion (SSE)
- // and resolves to the assistant message { role, content, tool_calls }.
- // Prototype: settings (with the key) live in this browser's localStorage; see README.
- (function () {
- 'use strict';
- var KEY = 'shtuk-llm';
- var DEFAULTS = { baseUrl: 'https://openrouter.ai/api/v1', model: 'openai/gpt-4o-mini', apiKey: '' };
- function loadSettings() {
- var s = {};
- try { s = JSON.parse(localStorage.getItem(KEY) || '{}') || {}; } catch (e) { s = {}; }
- return {
- baseUrl: s.baseUrl || DEFAULTS.baseUrl,
- model: s.model || DEFAULTS.model,
- apiKey: s.apiKey || ''
- };
- }
- function saveSettings(s) {
- try { localStorage.setItem(KEY, JSON.stringify(s)); } catch (e) { /* storage blocked */ }
- }
- // MCP-style tools ({name, description, inputSchema}) -> OpenAI function tools.
- function toOpenAI(tools) {
- return (tools || []).map(function (t) {
- return { type: 'function', function: { name: t.name, description: t.description, parameters: t.inputSchema || { type: 'object', properties: {} } } };
- });
- }
- async function chat(settings, messages, tools, onDelta, signal) {
- var body = { model: settings.model, messages: messages, stream: true };
- if (tools && tools.length) body.tools = toOpenAI(tools);
- var res = await fetch(settings.baseUrl.replace(/\/$/, '') + '/chat/completions', {
- method: 'POST',
- signal: signal,
- headers: {
- 'content-type': 'application/json',
- authorization: 'Bearer ' + settings.apiKey,
- 'x-title': 'Shtukbase'
- },
- body: JSON.stringify(body)
- });
- if (!res.ok) {
- var text = '';
- try { text = await res.text(); } catch (e) { /* ignore */ }
- var msg = text;
- try { var j = JSON.parse(text); msg = (j.error && (j.error.message || j.error)) || text; } catch (e) { /* not json */ }
- throw new Error('HTTP ' + res.status + (msg ? ': ' + String(msg).slice(0, 300) : ''));
- }
- var out = { role: 'assistant', content: '', tool_calls: [] };
- var reader = res.body.getReader();
- var decoder = new TextDecoder();
- var buf = '';
- var done = false;
- function handle(data) {
- if (data === '[DONE]') { done = true; return; }
- var chunk;
- try { chunk = JSON.parse(data); } catch (e) { return; }
- if (chunk.error) throw new Error(chunk.error.message || String(chunk.error));
- var choice = chunk.choices && chunk.choices[0];
- var d = choice && choice.delta;
- if (!d) return;
- if (d.content) { out.content += d.content; if (onDelta) onDelta({ text: d.content }); }
- (d.tool_calls || []).forEach(function (tc) {
- var i = tc.index != null ? tc.index : out.tool_calls.length;
- var slot = out.tool_calls[i] || (out.tool_calls[i] = { id: '', type: 'function', function: { name: '', arguments: '' } });
- if (tc.id) slot.id = tc.id;
- if (tc.function && tc.function.name) slot.function.name += tc.function.name;
- if (tc.function && tc.function.arguments) slot.function.arguments += tc.function.arguments;
- if (onDelta) onDelta({ toolCall: i });
- });
- }
- while (!done) {
- var r = await reader.read();
- if (r.done) break;
- buf += decoder.decode(r.value, { stream: true });
- var lines = buf.split(/\r?\n/);
- buf = lines.pop();
- for (var k = 0; k < lines.length && !done; k++) {
- var line = lines[k];
- if (line.indexOf('data:') === 0) handle(line.slice(5).trim());
- }
- }
- if (!done && buf.indexOf('data:') === 0) handle(buf.slice(5).trim());
- try { reader.cancel(); } catch (e) { /* ignore */ }
- out.tool_calls = out.tool_calls.filter(Boolean);
- out.tool_calls.forEach(function (tc, i) { if (!tc.id) tc.id = 'call_' + i + '_' + Date.now(); });
- if (!out.tool_calls.length) delete out.tool_calls;
- return out;
- }
- window.shtukLLM = { chat: chat, loadSettings: loadSettings, saveSettings: saveSettings, defaults: DEFAULTS };
- })();