Quickstart

npm install dejahit

Wrap the call you already make. The callback runs only on a miss.

import { createCache } from "dejahit";

const cache = createCache({ apiKey: process.env.DEJAHIT_KEY });

const answer = await cache.ask(question, () => callMyLLM(question), {
  scope: ["support-bot", "v3"],
  ttl: "24h",
});

Need hit/miss details? cache.askDetailed(...) returns { answer, cached, source, score, id, reason }.

How a lookup works

  1. Exact match (case, spacing and trailing punctuation ignored) inside the scope: hit, no model call.
  2. Embedding lookup (e5-small-v2): the 3 nearest cached questions in the scope with similarity ≥ 0.86. None: miss with no verifier call.
  3. Verification: our proprietary verification checks whether each candidate really asks the same thing. Only confident matches are served.
  4. Miss: your callback runs. In parallel, a check classifies the question as reusable, time-sensitive, personal or creative. Only reusable answers are stored.

High similarity alone never produces a hit. Questions that differ in a number, date, name, direction or negation often score above 0.95; verification rejected all 123 such pairs in our test set.

Scope

scope is required. An answer is only reused for a question with exactly the same scope. Put everything that changes the right answer into it, except the question itself:

scope: ["support-bot", "v3", user.locale]        // shared across all users of this bot version
scope: ["assistant", user.id]                  // per user only
scope: { bot: "faq", plan: account.plan, kb: kbVersion }

Change the system prompt or knowledge base? Change the scope (e.g. bump "v3" to "v4"). The provider wrappers build the scope automatically from model, system prompt and settings.

Options

OptionDefaultWhat it does
scoperequiredWho may reuse the answer (see above).
ttl7 daysSeconds or "30s" "15m" "24h" "7d". Max 90 days.
store"all""prompt" keeps answers in your own store; needs adapter.
keyinput(input) => string: what is sent and matched. Use it to redact names or pick part of the input.
shouldStore-(answer) => boolean: return false to keep an answer out.
cacheableautotrue skips the cacheability check (e.g. support how-to); false never stores.
strictness"balanced""strict" also checks that the cached answer fits the new question: about 51% hits / 1.0% wrong vs 61% / 1.6% on LmArena.
tags[]Labels for invalidation, e.g. ["doc:refund-policy"].
mode"on""shadow" or "off"; also settable on createCache.
speculativefalseStart the callback alongside the lookup; it receives an AbortSignal that fires on a hit.
waitUntil-Serverless: pass ctx.waitUntil to store in the background instead of awaiting it.

createCache({ apiKey, baseUrl, timeoutMs: 800, mode, auditRate: 0.02, adapter, strictness, breakerThreshold: 5, breakerCooldownMs: 30000, onError })

Keeping answers yourself

With store: "prompt" we keep the question only. Answers go to your adapter, keyed by entry ID.

import { createCache, redisAdapter } from "dejahit";
const cache = createCache({ apiKey, adapter: redisAdapter(redis) });     // or memoryAdapter()
await cache.ask(q, () => llm(q), { scope, store: "prompt" });

An adapter is { get(id), set(id, answer, ttlSec), delete?(id) }. If your copy is gone, the SDK treats it as a miss and removes the entry. Strict mode and audit sampling need store: "all".

Streaming

const stream = await cache.askStream(q, () => llmStream(q), { scope });
for await (const chunk of stream) process.stdout.write(chunk);

The callback may return a ReadableStream or async iterable. It is passed through untouched and stored only if it completes; hits are replayed as a stream (stream.cached === true).

Provider wrappers

import OpenAI from "openai";
import { wrapOpenAI } from "dejahit/openai";
const openai = wrapOpenAI(new OpenAI(), cache, { scope: "support-bot" });

import Anthropic from "@anthropic-ai/sdk";
import { wrapAnthropic } from "dejahit/anthropic";
const claude = wrapAnthropic(new Anthropic(), cache);

// Vercel AI SDK
import { wrapLanguageModel } from "ai";
import { dejahitMiddleware } from "dejahit/ai-sdk";
const model = wrapLanguageModel({ model: openai("gpt-4o-mini"), middleware: dejahitMiddleware(cache) });

Only single-turn, text-only calls without tools are cached, streaming or not; everything else passes straight through. Streamed misses are saved once they finish cleanly, and hits are replayed in the provider's own stream format. The scope is built from provider, model, system prompt and settings, plus any scope you add. Only clean text answers (finish reason "stop") are stored. The AI SDK middleware handles both generateText and streamText.

Shadow mode

createCache({ apiKey, mode: "shadow" }) always runs your callback, but records whether each question would have been a hit. The cache fills up in the background. The dashboard shows your shadow hit rate, so you can see the savings before serving anything.

Invalidation and reports

await cache.ask(q, fn, { scope, tags: ["doc:refund-policy"] });
await cache.invalidate({ tag: "doc:refund-policy" });   // when the source changes
await cache.invalidate({ scope: ["support-bot", "v3"] });
await cache.report(result.id);                              // a user flagged a wrong answer: removed
await cache.deleteAll();                                     // every entry in your account

Audit sampling

On 2% of hits (auditRate), the SDK also runs your callback in the background and sends the fresh answer. Verification compares it with the cached one; wrong entries are removed and counted, giving you a measured wrong-hit rate on your own traffic. Set auditRate: 0 to turn it off.

Self-hosting

Need everything inside your own infrastructure? A self-hosted edition (Docker image, your database) is available on request: contact us.

Testing

An API key is always required. In your test suite, create the cache with mode: "off": every call goes straight to your callback and nothing is cached or sent.

const cache = createCache({ apiKey: process.env.DEJAHIT_KEY, mode: process.env.NODE_ENV === "test" ? "off" : "on" });

Failure handling

Python

pip install dejahit

from dejahit import Cache, AsyncCache
cache = Cache(api_key=os.environ["DEJAHIT_KEY"])
answer = cache.ask(question, lambda: call_my_llm(question), scope=["support-bot", "v3"], ttl="24h")

acache = AsyncCache(api_key=...)
answer = await acache.ask(question, lambda: llm_async(question), scope=..., speculative=True)

Same options in snake_case: should_store, cacheable, strictness, tags, mode, store + adapter=MemoryAdapter(), ask_stream, invalidate, report.

REST API

All endpoints take Authorization: Bearer <key> and JSON.

POST /v1/lookup{ scope, text, strictness?, shadow?, cacheable? } → hit with answer, or miss with a ticket
POST /v1/store{ ticket, answer, store?, ttlSec?, tags?, cacheable? } (within 10 minutes of the lookup)
POST /v1/invalidate{ id } | { tag } | { scope }
POST /v1/report{ id, reason? }
POST /v1/audit{ id, fresh }
GET /v1/stats · GET /v1/entries · DELETE /v1/entriesusage and entries; delete all