mirror of
https://github.com/bitbaum/loki.git
synced 2026-12-05 10:08:06 +01:00
Loki's tool loop was pinned to a single vendor, and its only degradation was a
step-down to a SMALLER MODEL AT THAT SAME VENDOR. Once the vendor's daily
budget was spent, every link in the "fallback" drew on the same exhausted pool,
so they all died together. On a free tier that is not a rare edge: Groq grants
100k tokens/day org-wide, shared with the dispatch strategist, form-assist and
autopilot, and one chat turn costs roughly 10k.
The vision half of this repo already learned this, the hard way. vision-models.ts
carries the lesson after four pinned free models rotted: "A CHAIN, not a model.
Free-tier models disappear and rate-limit; a single pin is a scheduled outage."
The chat half never got it. This applies the same shape, so the repo has ONE
answer to this problem instead of two.
- config/chat-models.ts: CHAT_CHAIN, the SSOT, mirroring VISION_CHAIN. Every
provider speaks the OpenAI chat-completions shape, so adding a vendor is a
row in a table rather than a new client.
- llm.ts walks the chain, and what it does next follows from WHY a link
refused: `size` continues (another vendor's window may be far larger, and
the size error is only surfaced once EVERY link refuses, since that is what
loop.ts sheds facts on); `daily` skips that vendor's remaining models
wholesale; `capacity` advances. A whole chain refusing on capacity alone is
the one case where waiting is right, so it waits once, bounded.
- probe-models.ts probes the whole chain via callModelLinkOnce, NOT the
walker: a walk reports whoever answered, so probing "is gemma usable?"
through it would happily return another link's success and pin a dead model.
Every entry was PROBED LIVE before being pinned, not taken from docs. The free
catalogue was enumerated by filtering OpenRouter's /api/v1/models for
pricing.prompt == "0" and supported_parameters containing "tools", then each
candidate was sent a real tool call. Nine links answer; two are excluded on
evidence (gemma-4-31b returned a provider error, nemotron-nano-12b-vl returns
200 with EMPTY content, which a naive client reads as a successful empty
answer).
FIVE of the nine answer only via the TEXT protocol. A native-only loop would
have silently lost most of this chain — the concrete payoff of llm.ts always
parsing both.
Model lists are read from env AT CALL TIME (LOKI_GROQ_MODELS /
LOKI_OPENROUTER_MODELS), so routing around the next rotted model is an env
change on the box rather than a redeploy. A value frozen at import would have
needed the very delay the override exists to avoid.
agent-name-lookup.ts asserted the old SMALL_MODEL constant. Its INTENT was "a
rate limit must step down, not abandon the tools" — which the chain serves
better — so the assertion is rewritten to that intent and gains a guard that
the chain spans 2+ vendors, the property that makes it worth having.
Co-authored-by: t <t@t.t>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
152 lines
6.5 KiB
TypeScript
152 lines
6.5 KiB
TypeScript
/**
|
|
* Live model probe — is every model this app depends on actually alive?
|
|
*
|
|
* Run: npx tsx scripts/probe-models.ts [chat-model ...] (npm run probe:models)
|
|
* (defaults to a spread from frontier-ish down to tiny)
|
|
*
|
|
* Why this exists as a committed script rather than a one-off: Loki is meant to
|
|
* keep working as the model underneath it changes, and the thing that actually
|
|
* breaks when you swap models is not reasoning quality — it is whether the model
|
|
* emits a tool call the loop can parse. That is cheap to measure and impossible
|
|
* to guess, so measure it before switching, not after.
|
|
*
|
|
* Covers BOTH halves, because both have bitten:
|
|
* CHAT — can the model emit a tool call the loop can parse?
|
|
* VISION — does any model in the chain actually read an image?
|
|
*
|
|
* The vision half exists because a pinned free model (Groq's llama-4-scout) was
|
|
* decommissioned and every attached screenshot 404'd, silently, until someone
|
|
* tried one. That was the fourth pinned-free-model rot in this fleet, so the
|
|
* class gets a command instead of another one-off fix: run this before swapping
|
|
* a model, and on any "images stopped working" report.
|
|
*
|
|
* NOT part of `npm run verify`: it costs real tokens and needs live keys.
|
|
* The env-independent coverage of the same parser lives in
|
|
* scripts/test/agent-tool-loop.ts.
|
|
*
|
|
* Reads: does the model produce a call at all, via which protocol, with correct
|
|
* arguments. A model that scores `calls=0` cannot drive the loop; one that
|
|
* answers via `text` proves the fallback protocol is earning its place.
|
|
*/
|
|
import { config } from "dotenv";
|
|
config({ path: ".env.local" });
|
|
|
|
import { callModelLinkOnce } from "../src/lib/agent/llm";
|
|
import { analyzeImages } from "../src/lib/vision";
|
|
import { usableVisionChain } from "../src/config/vision-models";
|
|
import { usableChatChain, CHAT_CHAIN, type ChatLink } from "../src/config/chat-models";
|
|
|
|
const TOOLS = [
|
|
{
|
|
type: "function",
|
|
function: {
|
|
name: "search_people",
|
|
description: "Look up the operator's contacts by name.",
|
|
parameters: { type: "object", properties: { query: { type: "string" } }, required: ["query"] },
|
|
},
|
|
},
|
|
];
|
|
|
|
// Mirrors the real system prompt's tool section — including the copyable example,
|
|
// which is the part that carries small models.
|
|
const SYSTEM = [
|
|
"You are Loki. You answer ONLY from tools; you know nothing about the operator otherwise.",
|
|
"",
|
|
"Call a tool by writing these two lines in your reply, exactly like this:",
|
|
"",
|
|
"TOOL: search_people",
|
|
'ARGS: {"query": "Elena"}',
|
|
"",
|
|
"Write nothing else in a reply that calls a tool.",
|
|
].join("\n");
|
|
|
|
/**
|
|
* Resolve what to probe. No args → the whole configured chain, which is the
|
|
* question that actually matters ("is every fallback I ship real?"). Explicit
|
|
* model ids → those, matched against the chain so they carry their provider,
|
|
* falling back to the first keyed provider for an id nobody advertises yet.
|
|
*/
|
|
function linksToProbe(): ChatLink[] {
|
|
const chain = usableChatChain();
|
|
const wanted = process.argv.slice(2);
|
|
if (wanted.length === 0) return chain;
|
|
const host = chain[0]?.provider ?? CHAT_CHAIN[0];
|
|
return wanted.map((model) => chain.find((l) => l.model === model) ?? { provider: host, model });
|
|
}
|
|
|
|
async function main() {
|
|
const links = linksToProbe();
|
|
if (links.length === 0) {
|
|
console.error("No chat provider configured — set GROQ_API_KEY or OPENROUTER_API_KEY in .env.local.");
|
|
process.exit(2);
|
|
}
|
|
let usable = 0;
|
|
|
|
console.log(`Chat chain (${links.length} link(s)) — can each one actually drive the loop?\n`);
|
|
for (const link of links) {
|
|
const label = `${link.provider.id}/${link.model}`;
|
|
try {
|
|
// callModelLinkOnce, NOT the chain walker: a walk reports whoever
|
|
// answered, which would credit this model with another link's success.
|
|
const turn = await callModelLinkOnce(link, {
|
|
messages: [
|
|
{ role: "system", content: SYSTEM },
|
|
{ role: "user", content: "Who is Ilya in my contacts?" },
|
|
],
|
|
tools: TOOLS,
|
|
validToolNames: ["search_people"],
|
|
maxTokens: 300,
|
|
});
|
|
const call = turn.toolCalls[0];
|
|
const protocol = call ? (call.id.startsWith("text_") ? "text" : "native") : "-";
|
|
const ok = call?.name === "search_people" && typeof call.args.query === "string";
|
|
if (ok) usable++;
|
|
console.log(
|
|
`${ok ? "✓" : "✗"} ${label.padEnd(48)} calls=${turn.toolCalls.length} via=${protocol.padEnd(6)} args=${JSON.stringify(call?.args ?? {})}`,
|
|
);
|
|
} catch (e) {
|
|
console.log(`✗ ${label.padEnd(48)} ERROR ${e instanceof Error ? e.message.slice(0, 90) : String(e)}`);
|
|
}
|
|
}
|
|
|
|
console.log(`\n${usable}/${links.length} chat link(s) can drive the loop.`);
|
|
if (usable === 0) console.log(" ✗ NO chat model answered — Loki's tool loop is DOWN, not degraded.");
|
|
|
|
// ── Vision chain ───────────────────────────────────────────────────────────
|
|
// A 2x2 solid-red PNG. Tiny, but it proves the model actually READ the image
|
|
// rather than merely accepting the request — a provider that returns 200 with
|
|
// empty content passes a "did it error" check and fails this one.
|
|
const RED_2X2 =
|
|
"iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAAFElEQVR4nGP8z8Dwn4GKgImahgEAG1kDCf0X4o8AAAAASUVORK5CYII=";
|
|
|
|
const chain = usableVisionChain();
|
|
console.log(`\nVision chain (${chain.length} usable link(s)):`);
|
|
if (chain.length === 0) {
|
|
console.log(" ✗ none — no OPENROUTER_API_KEY and no GROQ_VISION_MODEL. Image attachments WILL fail.");
|
|
}
|
|
let visionOk = 0;
|
|
for (const { provider, model } of chain) {
|
|
try {
|
|
const r = await analyzeImages({
|
|
prompt: "What colour fills this image? Answer with one word.",
|
|
images: [{ mimeType: "image/png", dataBase64: RED_2X2 }],
|
|
maxTokens: 30,
|
|
timeoutMs: 90_000,
|
|
});
|
|
// analyzeImages walks the whole chain itself, so this reports the link
|
|
// that actually answered rather than the one we asked about.
|
|
console.log(` ✓ ${provider.id}/${model} → answered via ${r.model}: ${r.text.slice(0, 40)}`);
|
|
visionOk++;
|
|
break;
|
|
} catch (e) {
|
|
console.log(` ✗ ${provider.id}/${model} — ${e instanceof Error ? e.message.slice(0, 90) : e}`);
|
|
}
|
|
}
|
|
if (visionOk === 0 && chain.length > 0) console.log(" ✗ NO vision model answered — image attachments are broken.");
|
|
}
|
|
|
|
main().catch((e) => {
|
|
console.error(e);
|
|
process.exit(1);
|
|
});
|