Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

3.7 KB
Raw Blame
/**
 * chatCore semantic-cache store (Quality Gate v2 / Fase 9 — chatCore god-file decomposition,
 * #3501).
 *
 * Extracted from handleChatCore's non-streaming success path (Phase 9.1): when semantic caching is
 * enabled and the request/response are cacheable, store the translated response under its signature
 * so a later temp=0 request can be served from cache. Side-effect only (cache write + debug log);
 * no early-return, no outer-variable reassignment. Behaviour is byte-identical to the previous
 * inline block, including the `prompt + completion || 0` token-saved precedence.
 */
import {
  generateSignature as defaultGenerateSignature,
  outputContractOf,
  setCachedResponse as defaultSetCachedResponse,
  isCacheableForWrite as defaultIsCacheableForWrite,
  isTruncatedCompletion as defaultIsTruncatedCompletion,
} from "@/lib/semanticCache";
import { isSmallEnoughForSemanticCache as defaultIsSmallEnough } from "../../utils/estimateSize.ts";
import { getSemanticCacheManager } from "../../services/cache/semanticCacheManager.ts";

type LoggerLike = { debug?: (...args: unknown[]) => void } | null | undefined;

type CacheBody = {
  messages?: unknown;
  input?: unknown;
  temperature?: number;
  top_p?: number;
};

type UsageLike = { prompt_tokens?: number; completion_tokens?: number } | null | undefined;

export interface SemanticCacheStoreDeps {
  isCacheableForWrite: typeof defaultIsCacheableForWrite;
  /** Optional so pre-existing callers/tests with partial deps keep working. */
  isTruncatedCompletion?: typeof defaultIsTruncatedCompletion;
  isSmallEnoughForSemanticCache: typeof defaultIsSmallEnough;
  generateSignature: typeof defaultGenerateSignature;
  setCachedResponse: typeof defaultSetCachedResponse;
}

const DEFAULT_DEPS: SemanticCacheStoreDeps = {
  isCacheableForWrite: defaultIsCacheableForWrite,
  isTruncatedCompletion: defaultIsTruncatedCompletion,
  isSmallEnoughForSemanticCache: defaultIsSmallEnough,
  generateSignature: defaultGenerateSignature,
  setCachedResponse: defaultSetCachedResponse,
};

export function storeSemanticCacheResponse(
  args: {
    enabled: boolean;
    body: CacheBody;
    headers: unknown;
    translatedResponse: unknown;
    model: string;
    provider?: string;
    apiKeyId?: string;
    usage?: UsageLike;
    log?: LoggerLike;
    videoTranscriptSensitive?: boolean;
  },
  deps: SemanticCacheStoreDeps = DEFAULT_DEPS
): void {
  if (
    args.videoTranscriptSensitive ||
    !args.enabled ||
    !deps.isCacheableForWrite(args.body, args.headers) ||
    (deps.isTruncatedCompletion ?? defaultIsTruncatedCompletion)(args.translatedResponse) ||
    !deps.isSmallEnoughForSemanticCache(args.translatedResponse)
  ) {
    return;
  }
  const signature = deps.generateSignature(
    args.model,
    args.body.messages ?? args.body.input,
    args.body.temperature,
    args.body.top_p,
    args.apiKeyId ?? undefined,
    outputContractOf(args.body)
  );
  const tokensSaved = args.usage?.prompt_tokens + args.usage?.completion_tokens || 0;
  deps.setCachedResponse(signature, args.model, args.translatedResponse, tokensSaved);
  args.log?.debug?.("CACHE", `Stored response for ${args.model} (${tokensSaved} tokens)`);

  if (args.translatedResponse && typeof args.translatedResponse === "object") {
    getSemanticCacheManager()
      .store({
        body: args.body as Record<string, unknown>,
        headers: args.headers,
        response: args.translatedResponse as Record<string, unknown>,
        model: args.model,
        provider:
          args.provider ||
          ((args.translatedResponse as Record<string, unknown>).provider as string) ||
          "",
        apiKeyId: args.apiKeyId,
        signature,
        tokensSaved,
      })
      .catch(() => {});
  }
}