openrouter-cache-write-repro.test.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import { describe, expect, it } from "vitest";
  2. import { getModel } from "../src/models.ts";
  3. import { completeSimple } from "../src/stream.ts";
  4. function createLongSystemPrompt(): string {
  5. const nonce = `${Date.now()}-${Math.random()}`;
  6. return `You are a concise assistant.\nCache nonce: ${nonce}\n\n${Array(80)
  7. .fill(
  8. "Prompt-caching probe content. Keep this exact text stable across requests so the provider can reuse prefix tokens and report cache read and cache write usage.",
  9. )
  10. .join("\n\n")}`;
  11. }
  12. describe.skipIf(!process.env.OPENROUTER_API_KEY)("OpenRouter cache_write repro E2E", () => {
  13. it(
  14. "regression: preserves cache_write_tokens on openai-completions stream path",
  15. { retry: 2, timeout: 90000 },
  16. async () => {
  17. const model = getModel("openrouter", "google/gemini-2.5-flash");
  18. const context = {
  19. systemPrompt: createLongSystemPrompt(),
  20. messages: [
  21. {
  22. role: "user" as const,
  23. content: "Reply with exactly: OK",
  24. timestamp: Date.now(),
  25. },
  26. ],
  27. };
  28. const options = {
  29. apiKey: process.env.OPENROUTER_API_KEY!,
  30. maxTokens: 32,
  31. temperature: 0,
  32. onPayload: (payload: unknown) => {
  33. const params = payload as {
  34. messages?: Array<{
  35. role?: string;
  36. content?: string | Array<{ type?: string; text?: string; cache_control?: { type: string } }>;
  37. }>;
  38. };
  39. const messages = params.messages;
  40. if (!Array.isArray(messages)) return payload;
  41. for (let i = messages.length - 1; i >= 0; i--) {
  42. const msg = messages[i];
  43. if (msg.role !== "user") continue;
  44. if (typeof msg.content === "string") {
  45. msg.content = [{ type: "text", text: msg.content, cache_control: { type: "ephemeral" } }];
  46. break;
  47. }
  48. if (!Array.isArray(msg.content)) continue;
  49. for (let j = msg.content.length - 1; j >= 0; j--) {
  50. const part = msg.content[j];
  51. if (part.type === "text") {
  52. part.cache_control = { type: "ephemeral" };
  53. break;
  54. }
  55. }
  56. break;
  57. }
  58. return payload;
  59. },
  60. };
  61. const first = await completeSimple(model, context, options);
  62. expect(first.stopReason, first.errorMessage).toBe("stop");
  63. const second = await completeSimple(model, context, options);
  64. expect(second.stopReason, second.errorMessage).toBe("stop");
  65. // Regression expectation: cache_write_tokens from provider usage must be preserved.
  66. // With the cache_control marker above, at least one of the two calls should create cache.
  67. const hasCacheWrite = first.usage.cacheWrite > 0 || second.usage.cacheWrite > 0;
  68. expect(hasCacheWrite).toBe(true);
  69. },
  70. );
  71. });