ShtukbaseStandard
archivo del paquete→ .shtukbase/packages/llm-provider/llm.js

llm.js

93 líneas, 4.0 KB.

El archivo tal como está en el paquete: el código y sus comentarios no se traducen.

  1. // llm.js: a tiny OpenAI-compatible chat client for lenses (no dependencies).
  2. // window.shtukLLM.chat(settings, messages, tools, onDelta, signal) streams one completion (SSE)
  3. // and resolves to the assistant message { role, content, tool_calls }.
  4. // Prototype: settings (with the key) live in this browser's localStorage; see README.
  5. (function () {
  6. 'use strict';
  7. var KEY = 'shtuk-llm';
  8. var DEFAULTS = { baseUrl: 'https://openrouter.ai/api/v1', model: 'openai/gpt-4o-mini', apiKey: '' };
  9. function loadSettings() {
  10. var s = {};
  11. try { s = JSON.parse(localStorage.getItem(KEY) || '{}') || {}; } catch (e) { s = {}; }
  12. return {
  13. baseUrl: s.baseUrl || DEFAULTS.baseUrl,
  14. model: s.model || DEFAULTS.model,
  15. apiKey: s.apiKey || ''
  16. };
  17. }
  18. function saveSettings(s) {
  19. try { localStorage.setItem(KEY, JSON.stringify(s)); } catch (e) { /* storage blocked */ }
  20. }
  21. // MCP-style tools ({name, description, inputSchema}) -> OpenAI function tools.
  22. function toOpenAI(tools) {
  23. return (tools || []).map(function (t) {
  24. return { type: 'function', function: { name: t.name, description: t.description, parameters: t.inputSchema || { type: 'object', properties: {} } } };
  25. });
  26. }
  27. async function chat(settings, messages, tools, onDelta, signal) {
  28. var body = { model: settings.model, messages: messages, stream: true };
  29. if (tools && tools.length) body.tools = toOpenAI(tools);
  30. var res = await fetch(settings.baseUrl.replace(/\/$/, '') + '/chat/completions', {
  31. method: 'POST',
  32. signal: signal,
  33. headers: {
  34. 'content-type': 'application/json',
  35. authorization: 'Bearer ' + settings.apiKey,
  36. 'x-title': 'Shtukbase'
  37. },
  38. body: JSON.stringify(body)
  39. });
  40. if (!res.ok) {
  41. var text = '';
  42. try { text = await res.text(); } catch (e) { /* ignore */ }
  43. var msg = text;
  44. try { var j = JSON.parse(text); msg = (j.error && (j.error.message || j.error)) || text; } catch (e) { /* not json */ }
  45. throw new Error('HTTP ' + res.status + (msg ? ': ' + String(msg).slice(0, 300) : ''));
  46. }
  47. var out = { role: 'assistant', content: '', tool_calls: [] };
  48. var reader = res.body.getReader();
  49. var decoder = new TextDecoder();
  50. var buf = '';
  51. var done = false;
  52. function handle(data) {
  53. if (data === '[DONE]') { done = true; return; }
  54. var chunk;
  55. try { chunk = JSON.parse(data); } catch (e) { return; }
  56. if (chunk.error) throw new Error(chunk.error.message || String(chunk.error));
  57. var choice = chunk.choices && chunk.choices[0];
  58. var d = choice && choice.delta;
  59. if (!d) return;
  60. if (d.content) { out.content += d.content; if (onDelta) onDelta({ text: d.content }); }
  61. (d.tool_calls || []).forEach(function (tc) {
  62. var i = tc.index != null ? tc.index : out.tool_calls.length;
  63. var slot = out.tool_calls[i] || (out.tool_calls[i] = { id: '', type: 'function', function: { name: '', arguments: '' } });
  64. if (tc.id) slot.id = tc.id;
  65. if (tc.function && tc.function.name) slot.function.name += tc.function.name;
  66. if (tc.function && tc.function.arguments) slot.function.arguments += tc.function.arguments;
  67. if (onDelta) onDelta({ toolCall: i });
  68. });
  69. }
  70. while (!done) {
  71. var r = await reader.read();
  72. if (r.done) break;
  73. buf += decoder.decode(r.value, { stream: true });
  74. var lines = buf.split(/\r?\n/);
  75. buf = lines.pop();
  76. for (var k = 0; k < lines.length && !done; k++) {
  77. var line = lines[k];
  78. if (line.indexOf('data:') === 0) handle(line.slice(5).trim());
  79. }
  80. }
  81. if (!done && buf.indexOf('data:') === 0) handle(buf.slice(5).trim());
  82. try { reader.cancel(); } catch (e) { /* ignore */ }
  83. out.tool_calls = out.tool_calls.filter(Boolean);
  84. out.tool_calls.forEach(function (tc, i) { if (!tc.id) tc.id = 'call_' + i + '_' + Date.now(); });
  85. if (!out.tool_calls.length) delete out.tool_calls;
  86. return out;
  87. }
  88. window.shtukLLM = { chat: chat, loadSettings: loadSettings, saveSettings: saveSettings, defaults: DEFAULTS };
  89. })();