Files
moloapp/example/assets/ai_openrouter.js
T

74 lines
3.0 KiB
JavaScript
Raw Normal View History

// OpenRouter page: thin client over /ai/openrouter/* (all limits server side).
(function () {
"use strict";
var $ = function (id) { return document.getElementById(id); };
var out = $("or-out"), err = $("or-error");
function post(path, body) {
err.textContent = "";
out.textContent = "...";
return fetch(path, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body)
}).then(function (res) {
return res.text().then(function (t) {
var j;
try { j = JSON.parse(t); } catch (e) { j = { message: t }; }
if (!res.ok) {
err.textContent = j.message || ("HTTP " + res.status);
out.textContent = "";
} else {
out.textContent = JSON.stringify(j, null, 2);
}
});
}).catch(function (e) { err.textContent = String(e); out.textContent = ""; });
}
function json(id) {
var v = $(id).value.trim();
if (!v) return {};
try { return JSON.parse(v); } catch (e) { err.textContent = "Not valid JSON: " + id; return null; }
}
function confirmed() { return $("or-confirm").checked; }
fetch("/ai/openrouter/status").then(function (r) { return r.json(); }).then(function (s) {
$("or-config").textContent = s.configured
? "API key found" + (s.management_configured ? " and management key found." : "; no management key.")
: "No " + s.api_key_env + ": calls answer 503 until one is configured.";
});
fetch("/ai/openrouter/calls").then(function (r) { return r.json(); }).then(function (c) {
var sel = $("or-call");
c.calls.forEach(function (x) {
var o = document.createElement("option");
o.value = x.call;
o.textContent = x.http + " " + x.path + (x.key === "mgmt" ? " (management key)" : "");
sel.appendChild(o);
});
});
function callBody(confirm) {
var args = json("or-args"), query = json("or-query"), body = json("or-body");
if (args === null || query === null || body === null) return null;
var b = { call: $("or-call").value, args: args, query: query, confirm: confirm };
if ($("or-body").value.trim()) b.body = body;
return b;
}
$("or-chat").onclick = function () {
var p = json("or-provider");
if (p === null) return;
var b = { model: $("or-model").value.trim(), prompt: $("or-prompt").value, confirm: confirmed() };
if (Object.keys(p).length) b.provider = p;
post("/ai/openrouter/chat", b);
};
function read(call, query) {
post("/ai/openrouter/call", { call: call, query: query || {} });
}
$("or-models").onclick = function () { read("getModels", { limit: 20, sort: "newest" }); };
$("or-providers").onclick = function () { read("listProviders"); };
$("or-key").onclick = function () { read("getCurrentKey"); };
$("or-credits").onclick = function () { read("getCredits"); };
$("or-plan").onclick = function () { var b = callBody(false); if (b) post("/ai/openrouter/plan", b); };
$("or-send").onclick = function () { var b = callBody(confirmed()); if (b) post("/ai/openrouter/call", b); };
})();