1
0

anthropic-messages-cache.recorded.test.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { Redactor } from "@opencode-ai/http-recorder"
  2. import { describe, expect } from "bun:test"
  3. import { Effect } from "effect"
  4. import { CacheHint, LLM } from "../../src"
  5. import { LLMClient } from "../../src/route"
  6. import * as Anthropic from "../../src/providers/anthropic"
  7. import { LARGE_CACHEABLE_SYSTEM } from "../recorded-scenarios"
  8. import { recordedTests } from "../recorded-test"
  9. const model = Anthropic.configure({
  10. apiKey: process.env.ANTHROPIC_API_KEY ?? "fixture",
  11. }).model("claude-haiku-4-5-20251001")
  12. // Two identical generations in a row. The first call writes the prefix into
  13. // Anthropic's cache; the second should report a cache read against the same
  14. // prefix. Cassette captures both interactions in order.
  15. const cacheRequest = LLM.request({
  16. id: "recorded_anthropic_cache",
  17. model,
  18. system: [{ type: "text", text: LARGE_CACHEABLE_SYSTEM, cache: new CacheHint({ type: "ephemeral" }) }],
  19. prompt: "Say hi.",
  20. // Manual hint on the system part is the only marker we want here — skip the
  21. // auto-policy's latest-user-message breakpoint so the cassette body matches.
  22. cache: "none",
  23. generation: { maxTokens: 16, temperature: 0 },
  24. })
  25. const recorded = recordedTests({
  26. prefix: "anthropic-messages-cache",
  27. provider: "anthropic",
  28. protocol: "anthropic-messages",
  29. requires: ["ANTHROPIC_API_KEY"],
  30. // Two identical requests in one cassette — replay walks the cassette in
  31. // recording order so the second call replays the cached-hit interaction.
  32. options: {
  33. redactor: Redactor.defaults({ requestHeaders: { allow: ["content-type", "anthropic-version"] } }),
  34. },
  35. })
  36. describe("Anthropic Messages cache recorded", () => {
  37. recorded.effect.with("writes then reads cache_control on identical second call", { tags: ["cache"] }, () =>
  38. Effect.gen(function* () {
  39. const first = yield* LLMClient.generate(cacheRequest)
  40. // The first call may write the cache (cacheWriteInputTokens > 0) or it
  41. // may be a fresh miss (both fields 0) depending on whether the prefix is
  42. // already warm on Anthropic's side. The assertion that matters is that
  43. // the SECOND call reports a non-zero cache read.
  44. expect(first.usage?.cacheReadInputTokens ?? 0).toBeGreaterThanOrEqual(0)
  45. const second = yield* LLMClient.generate(cacheRequest)
  46. expect(second.usage?.cacheReadInputTokens ?? 0).toBeGreaterThan(0)
  47. }),
  48. )
  49. })