@konneal/engine 0.2.194 → 0.2.195

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/env.d.ts CHANGED
@@ -30,6 +30,9 @@ export interface Env {
30
30
  ADMIN_TOKEN?: string;
31
31
  MEMBER_DAY_ASK?: string;
32
32
  ENRICH_MODEL?: string;
33
+ VISION_FALLBACK_KEY?: string;
34
+ VISION_FALLBACK_MODEL?: string;
35
+ VISION_FALLBACK_URL?: string;
33
36
  OIDC_ISSUER?: string;
34
37
  OIDC_CLIENT_ID?: string;
35
38
  OIDC_CLIENT_SECRET?: string;
@@ -0,0 +1,21 @@
1
+ export interface VisionFallbackConfig {
2
+ url: string;
3
+ key: string;
4
+ model: string;
5
+ }
6
+ export declare const DEFAULT_VISION_FALLBACK_URL = "https://api.z.ai/api/paas/v4/chat/completions";
7
+ type FallbackEnv = {
8
+ VISION_FALLBACK_KEY?: string;
9
+ VISION_FALLBACK_MODEL?: string;
10
+ VISION_FALLBACK_URL?: string;
11
+ };
12
+ export declare function visionFallbackConfig(env: FallbackEnv): VisionFallbackConfig | null;
13
+ /** One image-conditioned completion. Returns the message text, or null
14
+ * for any failure — the caller treats null as "no description". */
15
+ export declare function visionFallbackComplete(cfg: VisionFallbackConfig, ask: {
16
+ prompt: string;
17
+ b64: string;
18
+ mime: string;
19
+ maxTokens: number;
20
+ }, fetchFn?: typeof fetch, timeoutMs?: number): Promise<string | null>;
21
+ export {};
@@ -391,6 +391,50 @@ var relevancy_default = `You judge ANSWER RELEVANCY for a legal-metrology Q&A sy
391
391
  // workers/worker_public/prompts/precision.md
392
392
  var precision_default = 'You judge CONTEXT PRECISION for a retrieval system over {{PUBLISHER_NAME}} publications. Given the question and the ranked passages (in the order they were presented), score the fraction of passages that contain material USEFUL for answering the question: 1.0 = all useful; 0.5 = half; 0.0 = none. Judge each passage on its own content, not its rank. Reply with ONLY: {"score": 0.0-1.0}\n';
393
393
 
394
+ // workers/worker_public/src/visionFallback.ts
395
+ var DEFAULT_VISION_FALLBACK_URL = "https://api.z.ai/api/paas/v4/chat/completions";
396
+ function visionFallbackConfig(env) {
397
+ const key = typeof env.VISION_FALLBACK_KEY === "string" ? env.VISION_FALLBACK_KEY.trim() : "";
398
+ const model = typeof env.VISION_FALLBACK_MODEL === "string" ? env.VISION_FALLBACK_MODEL.trim() : "";
399
+ if (!key || !model) return null;
400
+ const override = typeof env.VISION_FALLBACK_URL === "string" ? env.VISION_FALLBACK_URL.trim() : "";
401
+ const url = /^https:\/\/\S+$/.test(override) ? override : DEFAULT_VISION_FALLBACK_URL;
402
+ return { url, key, model };
403
+ }
404
+ async function visionFallbackComplete(cfg, ask, fetchFn = fetch, timeoutMs = 6e4) {
405
+ try {
406
+ const res = await fetchFn(cfg.url, {
407
+ method: "POST",
408
+ headers: { authorization: `Bearer ${cfg.key}`, "content-type": "application/json" },
409
+ body: JSON.stringify({
410
+ model: cfg.model,
411
+ max_tokens: ask.maxTokens,
412
+ messages: [
413
+ {
414
+ role: "user",
415
+ content: [
416
+ { type: "text", text: ask.prompt },
417
+ { type: "image_url", image_url: { url: `data:${ask.mime};base64,${ask.b64}` } }
418
+ ]
419
+ }
420
+ ]
421
+ }),
422
+ signal: AbortSignal.timeout(timeoutMs)
423
+ });
424
+ if (!res.ok) {
425
+ console.log("vision fallback: HTTP", res.status);
426
+ return null;
427
+ }
428
+ const d = await res.json();
429
+ const content = d?.choices?.[0]?.message?.content;
430
+ const text = typeof content === "string" ? content : "";
431
+ return text.trim() || null;
432
+ } catch (e) {
433
+ console.log("vision fallback failed:", String(e).slice(0, 120));
434
+ return null;
435
+ }
436
+ }
437
+
394
438
  // workers/worker_public/src/admin.ts
395
439
  async function handleEnrich(env, ctx, req) {
396
440
  if (!env.ADMIN_TOKEN) return err(501, "admin_disabled", "ADMIN_TOKEN secret is not configured");
@@ -624,18 +668,19 @@ async function handleVisionJudge(env, req) {
624
668
  const swap = Math.random() < 0.5;
625
669
  const first = swap ? capB : capA;
626
670
  const second = swap ? capA : capB;
627
- const res = await env.AI.run(roleModel(env, "visionJudge"), {
628
- messages: [
629
- {
630
- role: "user",
631
- content: [
632
- { type: "text", text: `You are judging two descriptions of the same figure (from ${loaded.row.docidentifier}) written for a reader who cannot see it. The figure is attached.
671
+ const prompt = `You are judging two descriptions of the same figure (from ${loaded.row.docidentifier}) written for a reader who cannot see it. The figure is attached.
633
672
 
634
673
  Description 1: ${first}
635
674
 
636
675
  Description 2: ${second}
637
676
 
638
- Which description better tells the reader what the figure shows and its normative point? Reply with ONLY JSON: {"better": 1 or 2, "reason": "one sentence"}.` },
677
+ Which description better tells the reader what the figure shows and its normative point? Reply with ONLY JSON: {"better": 1 or 2, "reason": "one sentence"}.`;
678
+ const res = await env.AI.run(roleModel(env, "visionJudge"), {
679
+ messages: [
680
+ {
681
+ role: "user",
682
+ content: [
683
+ { type: "text", text: prompt },
639
684
  { type: "image_url", image_url: { url: `data:${loaded.mime};base64,${loaded.b64}` } }
640
685
  ]
641
686
  }
@@ -646,12 +691,23 @@ Which description better tells the reader what the figure shows and its normativ
646
691
  max_tokens: 4096
647
692
  });
648
693
  const anyRes = res;
649
- const text = typeof anyRes?.response === "string" ? anyRes.response : anyRes?.choices?.[0]?.message?.content ?? "";
694
+ let text = typeof anyRes?.response === "string" ? anyRes.response : anyRes?.choices?.[0]?.message?.content ?? "";
695
+ let judge = roleModel(env, "visionJudge");
696
+ if (!text.trim()) {
697
+ const fb = visionFallbackConfig(env);
698
+ if (fb) {
699
+ const out = await visionFallbackComplete(fb, { prompt, b64: loaded.b64, mime: loaded.mime, maxTokens: 4096 });
700
+ if (out) {
701
+ text = out;
702
+ judge = `fallback:${fb.model}`;
703
+ }
704
+ }
705
+ }
650
706
  const parsed = JSON.parse(text.replace(/^[^\{]*/, "").replace(/[^\}]*$/, ""));
651
707
  const said = parsed?.better === 1 ? "first" : parsed?.better === 2 ? "second" : null;
652
708
  if (!said) return err(502, "judge_failed", "no decision in the judge's reply: " + text.slice(0, 120));
653
709
  const winner = said === "first" === swap ? "b" : "a";
654
- return json({ ok: true, unit_id: unitId, better: winner, judge: roleModel(env, "visionJudge"), reason: String(parsed.reason ?? "").slice(0, 500) });
710
+ return json({ ok: true, unit_id: unitId, better: winner, judge, reason: String(parsed.reason ?? "").slice(0, 500) });
655
711
  } catch (e) {
656
712
  return err(502, "vision_judge_failed", String(e).slice(0, 200));
657
713
  }
@@ -673,6 +729,8 @@ async function handleCaption(env, req) {
673
729
  const row = loaded.row;
674
730
  const b64 = loaded.b64;
675
731
  const mime = loaded.mime;
732
+ const budget = Math.min(8192, Math.max(256, Math.floor(Number(body?.max_tokens) || 1024)));
733
+ const prompt = `Describe this figure from ${row.docidentifier}${context ? ` (${context})` : ""} for a reader who cannot see it: what is plotted/shown, the axes or structure, and the normative point it makes. 2-3 plain sentences.`;
676
734
  let res = null;
677
735
  for (let attempt = 0; attempt < 2 && !res; attempt++) {
678
736
  try {
@@ -681,12 +739,12 @@ async function handleCaption(env, req) {
681
739
  {
682
740
  role: "user",
683
741
  content: [
684
- { type: "text", text: `Describe this figure from ${row.docidentifier}${context ? ` (${context})` : ""} for a reader who cannot see it: what is plotted/shown, the axes or structure, and the normative point it makes. 2-3 plain sentences.` },
742
+ { type: "text", text: prompt },
685
743
  { type: "image_url", image_url: { url: `data:${mime};base64,${b64}` } }
686
744
  ]
687
745
  }
688
746
  ],
689
- max_tokens: 1024,
747
+ max_tokens: budget,
690
748
  // GLM-5.3-Flash defaults to reasoning_effort "max" when the parameter
691
749
  // is absent — max-effort reasoning starves a 1024-token budget and
692
750
  // the caption comes back empty (the u:fig-2 straggler)
@@ -695,7 +753,20 @@ async function handleCaption(env, req) {
695
753
  } catch {
696
754
  }
697
755
  }
698
- const text = typeof res?.response === "string" ? res.response : res?.choices?.[0]?.message?.content;
756
+ let text = typeof res?.response === "string" ? res.response : res?.choices?.[0]?.message?.content;
757
+ let model = override ?? roleModel(env, "caption");
758
+ let viaFallback = false;
759
+ if (!text?.trim()) {
760
+ const fb = visionFallbackConfig(env);
761
+ if (fb) {
762
+ const out = await visionFallbackComplete(fb, { prompt, b64, mime, maxTokens: budget });
763
+ if (out) {
764
+ text = out;
765
+ model = `fallback:${fb.model}`;
766
+ viaFallback = true;
767
+ }
768
+ }
769
+ }
699
770
  if (!text?.trim()) return err(502, "generation_failed", "vision model returned no description");
700
771
  const trimmed = text.trim();
701
772
  const cap = 900;
@@ -705,7 +776,7 @@ async function handleCaption(env, req) {
705
776
  return end === -1 ? cut.slice(0, cut.lastIndexOf(" ")) : cut.slice(0, end + 1);
706
777
  })();
707
778
  if (!dryRun) await writeUnitDescription(env.DB, unitId, desc, docId);
708
- return json({ ok: true, unit_id: unitId, doc_id: docId || void 0, model: override ?? roleModel(env, "caption"), dry_run: dryRun || void 0, description: desc });
779
+ return json({ ok: true, unit_id: unitId, doc_id: docId || void 0, model, max_tokens: budget, fallback: viaFallback || void 0, dry_run: dryRun || void 0, description: desc });
709
780
  } catch (e) {
710
781
  return err(502, "caption_failed", String(e).slice(0, 200));
711
782
  }
package/package.json CHANGED
@@ -27,7 +27,7 @@
27
27
  "playwright": "^1.62.1",
28
28
  "yaml": "^2.9.1"
29
29
  },
30
- "version": "0.2.194",
30
+ "version": "0.2.195",
31
31
  "description": "The Konneal engine: the publisher-agnostic build pipeline and API plane for standards intelligence (retrieval, answer contract, verdicts, evaluation).",
32
32
  "license": "BSD-3-Clause",
33
33
  "type": "module",
@@ -16,6 +16,7 @@ import { scoreFaithfulness } from "./faithfulness";
16
16
  import { scoreJudge } from "./grader";
17
17
  import { portModelRunner } from "./env.ts";
18
18
  import { unitPayloadRows, writeUnitDescription } from "./unitPayloads.ts";
19
+ import { visionFallbackComplete, visionFallbackConfig } from "./visionFallback.ts";
19
20
  import { P } from "./profile.ts";
20
21
  import { fill, promptVars } from "./pipeline.ts";
21
22
 
@@ -311,12 +312,13 @@ export async function handleVisionJudge(env: Env, req: Request): Promise<Respons
311
312
  const swap = Math.random() < 0.5;
312
313
  const first = swap ? capB : capA;
313
314
  const second = swap ? capA : capB;
315
+ const prompt = `You are judging two descriptions of the same figure (from ${loaded.row.docidentifier}) written for a reader who cannot see it. The figure is attached.\n\nDescription 1: ${first}\n\nDescription 2: ${second}\n\nWhich description better tells the reader what the figure shows and its normative point? Reply with ONLY JSON: {"better": 1 or 2, "reason": "one sentence"}.`;
314
316
  const res = await env.AI.run(roleModel(env, "visionJudge"), {
315
317
  messages: [
316
318
  {
317
319
  role: "user",
318
320
  content: [
319
- { type: "text", text: `You are judging two descriptions of the same figure (from ${loaded.row.docidentifier}) written for a reader who cannot see it. The figure is attached.\n\nDescription 1: ${first}\n\nDescription 2: ${second}\n\nWhich description better tells the reader what the figure shows and its normative point? Reply with ONLY JSON: {"better": 1 or 2, "reason": "one sentence"}.` },
321
+ { type: "text", text: prompt },
320
322
  { type: "image_url", image_url: { url: `data:${loaded.mime};base64,${loaded.b64}` } },
321
323
  ],
322
324
  },
@@ -327,13 +329,26 @@ export async function handleVisionJudge(env: Env, req: Request): Promise<Respons
327
329
  max_tokens: 4096,
328
330
  });
329
331
  const anyRes = res as any;
330
- const text = typeof anyRes?.response === "string" ? anyRes.response : anyRes?.choices?.[0]?.message?.content ?? "";
332
+ let text = typeof anyRes?.response === "string" ? anyRes.response : anyRes?.choices?.[0]?.message?.content ?? "";
333
+ let judge = roleModel(env, "visionJudge");
334
+ if (!text.trim()) {
335
+ // the platform's one image-capable model emptied on this figure —
336
+ // the configured outside model judges before the route gives up
337
+ const fb = visionFallbackConfig(env);
338
+ if (fb) {
339
+ const out = await visionFallbackComplete(fb, { prompt, b64: loaded.b64, mime: loaded.mime, maxTokens: 4096 });
340
+ if (out) {
341
+ text = out;
342
+ judge = `fallback:${fb.model}`;
343
+ }
344
+ }
345
+ }
331
346
  const parsed = JSON.parse(text.replace(/^[^\{]*/, "").replace(/[^\}]*$/, ""));
332
347
  const said = parsed?.better === 1 ? "first" : parsed?.better === 2 ? "second" : null;
333
348
  if (!said) return err(502, "judge_failed", "no decision in the judge's reply: " + text.slice(0, 120));
334
349
  // map back through the presentation swap
335
350
  const winner = (said === "first") === swap ? "b" : "a";
336
- return json({ ok: true, unit_id: unitId, better: winner, judge: roleModel(env, "visionJudge"), reason: String(parsed.reason ?? "").slice(0, 500) });
351
+ return json({ ok: true, unit_id: unitId, better: winner, judge, reason: String(parsed.reason ?? "").slice(0, 500) });
337
352
  } catch (e) {
338
353
  return err(502, "vision_judge_failed", String(e).slice(0, 200));
339
354
  }
@@ -362,6 +377,12 @@ export async function handleCaption(env: Env, req: Request): Promise<Response> {
362
377
  const row = loaded.row;
363
378
  const b64 = loaded.b64;
364
379
  const mime = loaded.mime;
380
+ // the output budget is the caller's to raise: the platform's model
381
+ // reasons inside it, and a dense figure can spend the whole 1024 on
382
+ // reasoning and return no description at all (3 of 4 figures in the
383
+ // 2026-12-05 dry-runs)
384
+ const budget = Math.min(8192, Math.max(256, Math.floor(Number(body?.max_tokens) || 1024)));
385
+ const prompt = `Describe this figure from ${row.docidentifier}${context ? ` (${context})` : ""} for a reader who cannot see it: what is plotted/shown, the axes or structure, and the normative point it makes. 2-3 plain sentences.`;
365
386
  let res: any = null;
366
387
  for (let attempt = 0; attempt < 2 && !res; attempt++) {
367
388
  try {
@@ -370,12 +391,12 @@ export async function handleCaption(env: Env, req: Request): Promise<Response> {
370
391
  {
371
392
  role: "user",
372
393
  content: [
373
- { type: "text", text: `Describe this figure from ${row.docidentifier}${context ? ` (${context})` : ""} for a reader who cannot see it: what is plotted/shown, the axes or structure, and the normative point it makes. 2-3 plain sentences.` },
394
+ { type: "text", text: prompt },
374
395
  { type: "image_url", image_url: { url: `data:${mime};base64,${b64}` } },
375
396
  ],
376
397
  },
377
398
  ],
378
- max_tokens: 1024,
399
+ max_tokens: budget,
379
400
  // GLM-5.3-Flash defaults to reasoning_effort "max" when the parameter
380
401
  // is absent — max-effort reasoning starves a 1024-token budget and
381
402
  // the caption comes back empty (the u:fig-2 straggler)
@@ -385,7 +406,22 @@ export async function handleCaption(env: Env, req: Request): Promise<Response> {
385
406
  // transient Workers AI flake (8005) — retry once
386
407
  }
387
408
  }
388
- const text = typeof res?.response === "string" ? res.response : res?.choices?.[0]?.message?.content;
409
+ let text = typeof res?.response === "string" ? res.response : res?.choices?.[0]?.message?.content;
410
+ let model = override ?? roleModel(env, "caption");
411
+ let viaFallback = false;
412
+ if (!text?.trim()) {
413
+ // the platform's one image-capable model emptied on this figure — the
414
+ // configured outside model is asked before the route gives up
415
+ const fb = visionFallbackConfig(env);
416
+ if (fb) {
417
+ const out = await visionFallbackComplete(fb, { prompt, b64, mime, maxTokens: budget });
418
+ if (out) {
419
+ text = out;
420
+ model = `fallback:${fb.model}`;
421
+ viaFallback = true;
422
+ }
423
+ }
424
+ }
389
425
  if (!text?.trim()) return err(502, "generation_failed", "vision model returned no description");
390
426
  // store complete sentences: a description cut mid-word reads as an
391
427
  // error to the reader, so the cap trims to the last sentence
@@ -401,7 +437,7 @@ export async function handleCaption(env: Env, req: Request): Promise<Response> {
401
437
  return end === -1 ? cut.slice(0, cut.lastIndexOf(" ")) : cut.slice(0, end + 1);
402
438
  })();
403
439
  if (!dryRun) await writeUnitDescription(env.DB, unitId, desc, docId);
404
- return json({ ok: true, unit_id: unitId, doc_id: docId || undefined, model: override ?? roleModel(env, "caption"), dry_run: dryRun || undefined, description: desc });
440
+ return json({ ok: true, unit_id: unitId, doc_id: docId || undefined, model, max_tokens: budget, fallback: viaFallback || undefined, dry_run: dryRun || undefined, description: desc });
405
441
  } catch (e) {
406
442
  return err(502, "caption_failed", String(e).slice(0, 200));
407
443
  }
@@ -32,6 +32,9 @@ export interface Env {
32
32
  ADMIN_TOKEN?: string;
33
33
  MEMBER_DAY_ASK?: string;
34
34
  ENRICH_MODEL?: string;
35
+ VISION_FALLBACK_KEY?: string;
36
+ VISION_FALLBACK_MODEL?: string;
37
+ VISION_FALLBACK_URL?: string;
35
38
  OIDC_ISSUER?: string;
36
39
  OIDC_CLIENT_ID?: string;
37
40
  OIDC_CLIENT_SECRET?: string;
@@ -0,0 +1,69 @@
1
+ // The vision fallback — the model ladder's third rung, for the one-time
2
+ // caption and judge lanes only. The platform's single image-capable model
3
+ // returns an empty generation for some figures (8 of 24 in the 2026-10-27
4
+ // A/B; 3 of 4 dry-runs on 2026-12-05); when it does, the same question is
5
+ // asked of an OpenAI-compatible vision model outside the platform (the
6
+ // estate's z.ai account, directly or through an AI Gateway). Configured,
7
+ // never assumed: no key or no model, no fallback — the route reports the
8
+ // empty generation exactly as it does today. Serving never calls this: the
9
+ // answer path reads the description a figure carries, and this is how a
10
+ // figure gets one.
11
+ export interface VisionFallbackConfig {
12
+ url: string;
13
+ key: string;
14
+ model: string;
15
+ }
16
+
17
+ export const DEFAULT_VISION_FALLBACK_URL = "https://api.z.ai/api/paas/v4/chat/completions";
18
+
19
+ type FallbackEnv = { VISION_FALLBACK_KEY?: string; VISION_FALLBACK_MODEL?: string; VISION_FALLBACK_URL?: string };
20
+
21
+ export function visionFallbackConfig(env: FallbackEnv): VisionFallbackConfig | null {
22
+ const key = typeof env.VISION_FALLBACK_KEY === "string" ? env.VISION_FALLBACK_KEY.trim() : "";
23
+ const model = typeof env.VISION_FALLBACK_MODEL === "string" ? env.VISION_FALLBACK_MODEL.trim() : "";
24
+ if (!key || !model) return null;
25
+ const override = typeof env.VISION_FALLBACK_URL === "string" ? env.VISION_FALLBACK_URL.trim() : "";
26
+ const url = /^https:\/\/\S+$/.test(override) ? override : DEFAULT_VISION_FALLBACK_URL;
27
+ return { url, key, model };
28
+ }
29
+
30
+ /** One image-conditioned completion. Returns the message text, or null
31
+ * for any failure — the caller treats null as "no description". */
32
+ export async function visionFallbackComplete(
33
+ cfg: VisionFallbackConfig,
34
+ ask: { prompt: string; b64: string; mime: string; maxTokens: number },
35
+ fetchFn: typeof fetch = fetch,
36
+ timeoutMs = 60_000,
37
+ ): Promise<string | null> {
38
+ try {
39
+ const res = await fetchFn(cfg.url, {
40
+ method: "POST",
41
+ headers: { authorization: `Bearer ${cfg.key}`, "content-type": "application/json" },
42
+ body: JSON.stringify({
43
+ model: cfg.model,
44
+ max_tokens: ask.maxTokens,
45
+ messages: [
46
+ {
47
+ role: "user",
48
+ content: [
49
+ { type: "text", text: ask.prompt },
50
+ { type: "image_url", image_url: { url: `data:${ask.mime};base64,${ask.b64}` } },
51
+ ],
52
+ },
53
+ ],
54
+ }),
55
+ signal: AbortSignal.timeout(timeoutMs),
56
+ });
57
+ if (!res.ok) {
58
+ console.log("vision fallback: HTTP", res.status);
59
+ return null;
60
+ }
61
+ const d = (await res.json()) as any;
62
+ const content = d?.choices?.[0]?.message?.content;
63
+ const text = typeof content === "string" ? content : "";
64
+ return text.trim() || null;
65
+ } catch (e) {
66
+ console.log("vision fallback failed:", String(e).slice(0, 120));
67
+ return null;
68
+ }
69
+ }