录制演示
源码
/* Prompt cache — free block published by UI Stacks (public page source).
Kept verbatim: the author publishes this block free, in full, at https://uistacks.dev/blocks/llm-ops-prompt-cache
See replica/README.md for provenance. */
"use client";
import { useEffect, useId, useRef, useState, type ReactNode } from "react";
import { MotionConfig, motion, useReducedMotion } from "motion/react";
import { CircleAlert, RotateCcw, Settings } from "lucide-react";
import { Button } from "../components/button";
import { Skeleton } from "../components/skeleton";
/* ── Sample data: replace with your own ─────────────────────── */
export type PromptCacheData = {
/** Percent of requests that read at least one cached prefix. */
requestHitRate: number;
/** Percent of input tokens served from the cache. */
tokenHitRate: number;
/** Dollars saved by cheaper cache reads. */
savedOnReads: number;
/** Dollars paid on top for writing prefixes to the cache. */
extraOnWrites: number;
};
export type PromptCacheState = "default" | "loading" | "empty" | "error";
/** Oct 1–26, 2026, every provider routed through the gateway. Net saved = 3,890 − 480 = 3,410. */
const SAMPLE: PromptCacheData = { requestHitRate: 64, tokenHitRate: 38, savedOnReads: 3890, extraOnWrites: 480 };
/* ── Block ──────────────────────────────────────────────────── */
export interface PromptCacheProps {
className?: string;
/** Loading, Empty (caching off) and Error replace the body; the card keeps its height. */
state?: PromptCacheState;
data?: PromptCacheData;
title?: string;
subtitle?: string;
/** The Empty state's action. Without it, the card turns caching on locally and shows the sample. */
onEnableCaching?: () => void;
/** Called by Retry in the Error state. Without it, Retry reloads the sample locally. */
onRetry?: () => void;
}
const usd = (n: number) => (n < 0 ? "−" : "") + "$" + Math.abs(Math.round(n)).toLocaleString("en-US");
/** Empty and Error share one centred, text-only layout. */
function Notice({ icon, title, body, action }: { icon: ReactNode; title: string; body: string; action: ReactNode }) {
return (
<div className="flex h-full flex-col items-center justify-center gap-2 px-2 text-center">
<span aria-hidden className="text-fg-muted [&_svg]:size-5">
{icon}
</span>
<p className="text-[13px] font-medium leading-5">{title}</p>
<p className="max-w-[300px] text-[12px] leading-4 text-fg-muted">{body}</p>
<div className="pt-2">{action}</div>
</div>
);
}
function Meter({ value, label, delay }: { value: number; label: string; delay: number }) {
// Width grows (not scaleX, which squashes the rounded end); MotionConfig doesn't cover width, so check here.
const reduce = useReducedMotion();
return (
<div className="flex flex-col gap-2">
<div
role="meter"
aria-label={label}
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={value}
className="h-2 overflow-hidden rounded-[4px] bg-track"
>
<motion.div
className="h-full rounded-[4px] bg-fg-muted"
initial={{ width: "0%" }}
animate={{ width: `${value}%` }}
transition={{ duration: reduce ? 0 : 0.7, delay: reduce ? 0 : delay, ease: [0.22, 1, 0.36, 1] }}
/>
</div>
<p aria-hidden className="truncate text-[12px] leading-4 tabular-nums">
{label}
</p>
</div>
);
}
export default function LlmOpsPromptCacheBlock({
className = "",
state = "default",
data = SAMPLE,
title = "Prompt cache",
subtitle = "Oct 1–26",
onEnableCaching,
onRetry,
}: PromptCacheProps) {
const id = useId();
const [announce, setAnnounce] = useState("");
// Retry (and Enable caching without a handler): a short loading pass, then the default data.
const [pass, setPass] = useState<{ from: PromptCacheState; phase: "loading" | "done" } | null>(null);
const timer = useRef<ReturnType<typeof setTimeout>>(undefined);
useEffect(() => () => clearTimeout(timer.current), []);
const local = pass?.from === state ? pass : null;
const shown: PromptCacheState = local ? (local.phase === "loading" ? "loading" : "default") : state;
const reload = (start: string, done: string) => {
setPass({ from: state, phase: "loading" });
setAnnounce(start);
clearTimeout(timer.current);
timer.current = setTimeout(() => {
setPass({ from: state, phase: "done" });
setAnnounce(done);
}, 1200);
};
const retryNow = () => (onRetry ? onRetry() : reload("Loading cache savings", "Cache savings loaded"));
const enable = () => (onEnableCaching ? onEnableCaching() : reload("Turning on prompt caching", "Prompt caching is on"));
const net = data.savedOnReads - data.extraOnWrites;
// ≥ 760 (a wide card): figure and meters on the left, the breakdown centred on the right. A 720 card stays one column.
const body = (
<div className="grid gap-4 @min-[760px]:grid-cols-2 @min-[760px]:items-center @min-[760px]:gap-x-10">
<div className="flex flex-col gap-4">
<p className="flex flex-wrap items-baseline gap-x-2">
<span className="text-[32px] font-medium leading-10 tracking-[-0.035em] tabular-nums">{usd(net)}</span>
<span className="text-[12px] leading-4 text-fg-muted">net saved</span>
</p>
<div className="flex flex-col gap-3">
<Meter value={data.requestHitRate} label={`${data.requestHitRate}% of requests hit cache`} delay={0} />
<Meter value={data.tokenHitRate} label={`${data.tokenHitRate}% of input tokens cached`} delay={0.08} />
</div>
</div>
<dl className="flex flex-col gap-1 text-[13px] leading-5">
<div className="flex items-center justify-between gap-3">
<dt className="truncate text-fg-muted">Saved on cache reads</dt>
<dd className="shrink-0 font-medium tabular-nums">{usd(data.savedOnReads)}</dd>
</div>
<div className="flex items-center justify-between gap-3">
<dt className="truncate text-fg-muted">Extra paid for cache writes</dt>
<dd className="shrink-0 font-medium tabular-nums">{usd(-data.extraOnWrites)}</dd>
</div>
</dl>
</div>
);
return (
<MotionConfig reducedMotion="user">
<section
aria-labelledby={id}
aria-busy={shown === "loading" || undefined}
className={"@container flex w-full min-w-0 flex-col gap-4 rounded-[24px] bg-surface p-5 text-fg shadow-[var(--shadow-card)] " + className}
>
<header className="flex min-h-8 items-center justify-between gap-3">
<h2 id={id} className="min-w-0 truncate text-[13px] font-medium leading-5">
{title}
</h2>
<p className="shrink-0 text-[12px] leading-4 text-fg-muted">{subtitle}</p>
</header>
{shown === "default" ? (
body
) : (
// The default body stays in the grid cell, hidden, so every state keeps the card's height at any width.
<div className="grid [&>*]:[grid-area:1/1]">
<div aria-hidden inert className="invisible">
{body}
</div>
{shown === "loading" ? (
<div className="grid gap-4 @min-[760px]:grid-cols-2 @min-[760px]:items-center @min-[760px]:gap-x-10">
<span className="sr-only">Loading cache savings</span>
<div className="flex flex-col gap-4">
<div className="flex h-10 items-center gap-2">
<Skeleton shape="block" width={116} height={32} radius={6} />
<Skeleton width={56} height={12} radius={6} />
</div>
<div className="flex flex-col gap-3">
{[150, 168].map((w) => (
<div key={w} className="flex flex-col gap-2">
<Skeleton height={8} radius={4} />
<Skeleton width={w} height={12} radius={6} />
</div>
))}
</div>
</div>
<div className="flex flex-col gap-2">
{[140, 180].map((w) => (
<div key={w} className="flex justify-between">
<Skeleton width={w} height={12} radius={6} />
<Skeleton width={44} height={12} radius={6} />
</div>
))}
</div>
</div>
) : shown === "empty" ? (
<Notice
icon={<Settings strokeWidth={1.5} />}
title="Caching is off"
body="Turn on prompt caching to reuse long system prompts and pay less for repeated input."
action={
<Button variant="secondary" size="md" leadingIcon={<Settings strokeWidth={1.5} />} onClick={enable}>
Enable caching
</Button>
}
/>
) : (
<div role="alert" className="h-full">
<Notice
icon={<CircleAlert strokeWidth={1.5} />}
title="Couldn't load cache savings"
body="The request timed out after 30 s. Try again."
action={
<Button variant="secondary" size="md" leadingIcon={<RotateCcw strokeWidth={1.5} />} onClick={retryNow}>
Retry
</Button>
}
/>
</div>
)}
</div>
)}
<span className="sr-only" role="status" aria-live="polite">
{announce}
</span>
</section>
</MotionConfig>
);
}
使用说明
把 TSX 加入 React 项目,并安装组件引用的依赖。页面样式依赖 Tailwind CSS 与 主题变量。
包依赖 · lucide-react、motion、react
共享源码 · button.tsx、skeleton.tsx