Skip to content

Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥

feat(branding): export Prometheus metrics for Jev and LLM routing (#5134)

Abimael Martell9a04a5f41afa
diff --git a/apps/api/src/__tests__/lib/branding/jev.test.ts b/apps/api/src/__tests__/lib/branding/jev.test.ts
index bb88869d1..bbbe9ec43 100644
--- a/apps/api/src/__tests__/lib/branding/jev.test.ts
+++ b/apps/api/src/__tests__/lib/branding/jev.test.ts
@@ -1,6 +1,7 @@
import { vi, describe, it, expect, beforeEach, afterEach } from "vitest";
import type { Mock } from "vitest";
import { generateObject } from "ai";
+import { APITimeoutError, RateLimitError } from "@typesafe-ai/sdk";
const mocks = vi.hoisted(() => ({ systemOne: vi.fn() }));
@@ -26,6 +27,11 @@ import {
resetJevBreaker,
} from "../../../lib/branding/jev";
import { enhanceBrandingWithLLM } from "../../../lib/branding/llm";
+import {
+ brandingRoutedTotal,
+ brandingJevBreakerOpensTotal,
+ brandingJevCallsTotal,
+} from "../../../lib/branding/metrics";
import { mergeBrandingResults } from "../../../lib/branding/merge";
import { BrandingLLMInput } from "../../../lib/branding/types";
import { CostTracking } from "../../../lib/cost-tracking";
@@ -911,3 +917,78 @@ describe("Jev request building", () => {
]);
});
});
+
+describe("branding metrics", () => {
+ const value = async (
+ metric: {
+ get: () => Promise<{ values: { labels: object; value: number }[] }>;
+ },
+ labels: Record<string, string> = {},
+ ) =>
+ (await metric.get()).values.find(v =>
+ Object.entries(labels).every(
+ ([k, want]) => (v.labels as Record<string, string>)[k] === want,
+ ),
+ )?.value ?? 0;
+
+ it("counts which model answered and how each Jev call ended", async () => {
+ const jevOk = { outcome: "ok", shadow: "false" };
+ const rateLimited = { outcome: "rate_limited", shadow: "false" };
+ const timedOut = { outcome: "timeout", shadow: "false" };
+ const byJev = { model: "jev", reason: "rollout" };
+ const fellBack = { model: "llm", reason: "jev_unavailable" };
+ const before = {
+ jevOk: await value(brandingJevCallsTotal, jevOk),
+ rateLimited: await value(brandingJevCallsTotal, rateLimited),
+ timedOut: await value(brandingJevCallsTotal, timedOut),
+ byJev: await value(brandingRoutedTotal, byJev),
+ fellBack: await value(brandingRoutedTotal, fellBack),
+ };
+
+ respondWith(jevResponse());
+ await enhanceBrandingWithLLM(baseInput(new CostTracking()));
+ mocks.systemOne.mockRejectedValueOnce(
+ new RateLimitError(429, {}, new Headers()),
+ );
+ await enhanceBrandingWithLLM(baseInput(new CostTracking()));
+ mocks.systemOne.mockRejectedValueOnce(new APITimeoutError(1500));
+ await enhanceBrandingWithLLM(baseInput(new CostTracking()));
+
+ expect(await value(brandingJevCallsTotal, jevOk)).toBe(before.jevOk + 1);
+ expect(await value(brandingJevCallsTotal, rateLimited)).toBe(
+ before.rateLimited + 1,
+ );
+ expect(await value(brandingJevCallsTotal, timedOut)).toBe(
+ before.timedOut + 1,
+ );
+ expect(await value(brandingRoutedTotal, byJev)).toBe(before.byJev + 1);
+ expect(await value(brandingRoutedTotal, fellBack)).toBe(
+ before.fellBack + 2,
+ );
+ });
+
+ it("counts the breaker opening and the calls it skips", async () => {
+ const skipped = { outcome: "breaker_open", shadow: "false" };
+ const opensBefore = await value(brandingJevBreakerOpensTotal);
+ const skippedBefore = await value(brandingJevCallsTotal, skipped);
+ mocks.systemOne.mockRejectedValue(new Error("529 high traffic"));
+
+ for (let i = 0; i < 6; i++) {
+ await enhanceBrandingWithLLM(baseInput(new CostTracking()));
+ }
+
+ expect(await value(brandingJevBreakerOpensTotal)).toBe(opensBefore + 1);
+ expect(await value(brandingJevCallsTotal, skipped)).toBe(skippedBefore + 1);
+ });
+
+ it("counts teams outside the rollout as answered by the LLM", async () => {
+ const outside = { model: "llm", reason: "not_in_rollout" };
+ const before = await value(brandingRoutedTotal, outside);
+ config.BRANDING_JEV_TEAM_IDS = [];
+
+ await enhanceBrandingWithLLM(baseInput(new CostTracking()));
+
+ expect(await value(brandingRoutedTotal, outside)).toBe(before + 1);
+ expect(mocks.systemOne).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/api/src/lib/branding/jev.ts b/apps/api/src/lib/branding/jev.ts
index ea3ba0eba..483eab6e0 100644
--- a/apps/api/src/lib/branding/jev.ts
+++ b/apps/api/src/lib/branding/jev.ts
@@ -11,6 +11,13 @@ import { config } from "../../config";
import { setSpanAttributes, SpanKind, withSpan } from "../otel-tracer";
import { sampled } from "../rollout";
import { getTypeSafeClient } from "../typesafe";
+import { APITimeoutError, RateLimitError } from "@typesafe-ai/sdk";
+import {
+ brandingJevBreakerOpensTotal,
+ brandingJevCallsTotal,
+ brandingJevDurationSeconds,
+ JevCallOutcome,
+} from "./metrics";
import { BrandingEnhancement } from "./schema";
import { BrandingLLMInput } from "./types";
@@ -42,6 +49,7 @@ function recordJevFailure(input: BrandingLLMInput): void {
consecutiveFailures++;
if (consecutiveFailures >= BREAKER_FAILURES && !isJevBreakerOpen()) {
breakerOpenUntil = Date.now() + BREAKER_COOLDOWN_MS;
+ brandingJevBreakerOpensTotal.inc();
input.logger.warn("Jev branding calls failing, using the LLM for a while", {
consecutiveFailures,
cooldownMs: BREAKER_COOLDOWN_MS,
@@ -902,7 +910,14 @@ export async function enhanceBrandingWithJev(
options: { shadow?: boolean } = {},
): Promise<JevBrandingResult | null> {
const typesafe = getTypeSafeClient();
- if (!typesafe || isJevBreakerOpen()) return null;
+ if (!typesafe) return null;
+ const shadow = options.shadow ? "true" : "false";
+ const count = (outcome: JevCallOutcome) =>
+ brandingJevCallsTotal.inc({ outcome, shadow });
+ if (isJevBreakerOpen()) {
+ count("breaker_open");
+ return null;
+ }
const started = Date.now();
let request: JevRequest;
let response: JevResponse;
@@ -947,7 +962,20 @@ export async function enhanceBrandingWithJev(
);
} catch (error) {
// Only TypeSafe's own failures say anything about its health.
- if (called) recordJevFailure(input);
+ if (called) {
+ recordJevFailure(input);
+ brandingJevDurationSeconds.observe(
+ { shadow },
+ (Date.now() - started) / 1000,
+ );
+ count(
+ error instanceof RateLimitError
+ ? "rate_limited"
+ : error instanceof APITimeoutError
+ ? "timeout"
+ : "error",
+ );
+ }
input.logger.warn(
options.shadow
? "Jev branding shadow call failed"
@@ -962,6 +990,7 @@ export async function enhanceBrandingWithJev(
// A call that started before the breaker opened and succeeds late doesn't
// close it: the next failure after the cooldown should reopen it at once.
if (!isJevBreakerOpen()) consecutiveFailures = 0;
+ brandingJevDurationSeconds.observe({ shadow }, (Date.now() - started) / 1000);
const inputTokens = response.usage?.input_tokens ?? 0;
const outputTokens = response.usage?.output_tokens ?? 0;
@@ -978,6 +1007,7 @@ export async function enhanceBrandingWithJev(
result = mapJevAnswers(request, response);
} catch (error) {
// A successful call whose answers don't have the expected shape.
+ count("unusable");
input.logger.warn(
options.shadow
? "Jev branding shadow answers unusable"
@@ -989,6 +1019,7 @@ export async function enhanceBrandingWithJev(
);
return null;
}
+ count("ok");
input.logger.info("Jev branding call", {
model: response.model,
shadow: options.shadow === true,
diff --git a/apps/api/src/lib/branding/llm.ts b/apps/api/src/lib/branding/llm.ts
index e3ad72337..9cabc4814 100644
--- a/apps/api/src/lib/branding/llm.ts
+++ b/apps/api/src/lib/branding/llm.ts
@@ -5,6 +5,7 @@ import { calculateCost } from "../../scraper/scrapeURL/transformers/llmExtract";
import { CostLimitExceededError } from "../cost-tracking";
import { BrandingEnhancement, getBrandingEnhancementSchema } from "./schema";
import { enhanceBrandingWithJev, isJevBrandingEnabled } from "./jev";
+import { brandingRoutedTotal } from "./metrics";
import { shadowJev, shouldShadowJev } from "./jev-shadow";
import { buildBrandingPrompt } from "./prompt";
import { BrandingLLMInput } from "./types";
@@ -109,14 +110,23 @@ export async function enhanceBrandingWithLLM(
const logger = input.logger;
const triedJev = isJevBrandingEnabled(input);
- if (triedJev) {
+ if (!triedJev) {
+ brandingRoutedTotal.inc({ model: "llm", reason: "not_in_rollout" });
+ } else {
const jev = await enhanceBrandingWithJev(input);
const escalateBelow = config.BRANDING_JEV_ESCALATE_BELOW;
const unsureOfLogo =
escalateBelow !== undefined &&
jev?.logoConfidence !== undefined &&
jev.logoConfidence < escalateBelow;
- if (jev && !unsureOfLogo) return jev.enhancement;
+ if (jev && !unsureOfLogo) {
+ brandingRoutedTotal.inc({ model: "jev", reason: "rollout" });
+ return jev.enhancement;
+ }
+ brandingRoutedTotal.inc({
+ model: "llm",
+ reason: jev ? "logo_escalation" : "jev_unavailable",
+ });
if (jev) {
logger.info("Jev unsure of the logo, escalating branding to the LLM", {
logoConfidence: jev.logoConfidence,
diff --git a/apps/api/src/lib/branding/metrics.ts b/apps/api/src/lib/branding/metrics.ts
new file mode 100644
index 000000000..b3893e06b
--- /dev/null
+++ b/apps/api/src/lib/branding/metrics.ts
@@ -0,0 +1,59 @@
+import { Counter, Histogram } from "prom-client";
+
+// Fixed labels only: never team ids or anything from the page.
+
+export const brandingRoutedTotal = new Counter({
+ name: "firecrawl_branding_routed_total",
+ help: "Each branding request once, by the model it was finally sent to and why: jev (rollout), or llm when the team isn't in the rollout, Jev was unavailable (failed or breaker open), or Jev was unsure of the logo; every Jev attempt is in firecrawl_branding_jev_calls_total",
+ labelNames: ["model", "reason"],
+});
+
+export const brandingJevCallsTotal = new Counter({
+ name: "firecrawl_branding_jev_calls_total",
+ help: "Jev branding call outcomes; shadow calls are labelled separately",
+ labelNames: ["outcome", "shadow"],
+});
+
+export const brandingJevBreakerOpensTotal = new Counter({
+ name: "firecrawl_branding_jev_breaker_opens_total",
+ help: "Times the Jev breaker opened and sent branding to the LLM for its cooldown",
+});
+
+export const brandingJevDurationSeconds = new Histogram({
+ name: "firecrawl_branding_jev_duration_seconds",
+ help: "Jev branding call time, for calls that reached TypeSafe",
+ labelNames: ["shadow"],
+ // Up to the default timeout with its one retry.
+ buckets: [0.1, 0.15, 0.2, 0.3, 0.5, 0.75, 1, 1.5, 2, 3, 5, 7.5, 10],
+});
+
+export type JevCallOutcome =
+ | "ok"
+ | "timeout"
+ | "rate_limited"
+ | "error"
+ | "unusable"
+ | "breaker_open";
+
+// Export quiet series before their first event, so rates read 0, not missing.
+for (const [model, reason] of [
+ ["jev", "rollout"],
+ ["llm", "not_in_rollout"],
+ ["llm", "jev_unavailable"],
+ ["llm", "logo_escalation"],
+]) {
+ brandingRoutedTotal.inc({ model, reason }, 0);
+}
+for (const shadow of ["true", "false"]) {
+ for (const outcome of [
+ "ok",
+ "timeout",
+ "rate_limited",
+ "error",
+ "unusable",
+ "breaker_open",
+ ] satisfies JevCallOutcome[]) {
+ brandingJevCallsTotal.inc({ outcome, shadow }, 0);
+ }
+}
+brandingJevBreakerOpensTotal.inc(0);