cache-retention.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. import { afterEach, beforeEach, describe, expect, it } from "vitest";
  2. import { getModel } from "../src/models.ts";
  3. import { streamAnthropic } from "../src/providers/anthropic.ts";
  4. import { streamOpenAICompletions } from "../src/providers/openai-completions.ts";
  5. import { streamOpenAIResponses } from "../src/providers/openai-responses.ts";
  6. import { stream } from "../src/stream.ts";
  7. import type { Context, Model } from "../src/types.ts";
  8. class PayloadCaptured extends Error {
  9. constructor() {
  10. super("payload captured");
  11. this.name = "PayloadCaptured";
  12. }
  13. }
  14. function stopAfterPayload<TPayload>(capture: (payload: TPayload) => void): (payload: unknown) => never {
  15. return (payload: unknown): never => {
  16. capture(payload as TPayload);
  17. throw new PayloadCaptured();
  18. };
  19. }
  20. describe("Cache Retention (PI_CACHE_RETENTION)", () => {
  21. const originalEnv = process.env.PI_CACHE_RETENTION;
  22. beforeEach(() => {
  23. delete process.env.PI_CACHE_RETENTION;
  24. });
  25. afterEach(() => {
  26. if (originalEnv !== undefined) {
  27. process.env.PI_CACHE_RETENTION = originalEnv;
  28. } else {
  29. delete process.env.PI_CACHE_RETENTION;
  30. }
  31. });
  32. const context: Context = {
  33. systemPrompt: "You are a helpful assistant.",
  34. messages: [{ role: "user", content: "Hello", timestamp: Date.now() }],
  35. };
  36. describe("Anthropic Provider", () => {
  37. it.skipIf(!process.env.ANTHROPIC_API_KEY)(
  38. "should use default cache TTL (no ttl field) when PI_CACHE_RETENTION is not set",
  39. async () => {
  40. const model = getModel("anthropic", "claude-haiku-4-5");
  41. let capturedPayload: any = null;
  42. const s = stream(model, context, {
  43. onPayload: stopAfterPayload((payload) => {
  44. capturedPayload = payload;
  45. }),
  46. });
  47. // Consume the stream to trigger the request
  48. for await (const _ of s) {
  49. // Just consume
  50. }
  51. expect(capturedPayload).not.toBeNull();
  52. // System prompt should have cache_control without ttl
  53. expect(capturedPayload.system).toBeDefined();
  54. expect(capturedPayload.system[0].cache_control).toEqual({ type: "ephemeral" });
  55. },
  56. );
  57. it.skipIf(!process.env.ANTHROPIC_API_KEY)("should use 1h cache TTL when PI_CACHE_RETENTION=long", async () => {
  58. process.env.PI_CACHE_RETENTION = "long";
  59. const model = getModel("anthropic", "claude-haiku-4-5");
  60. let capturedPayload: any = null;
  61. const s = stream(model, context, {
  62. onPayload: stopAfterPayload((payload) => {
  63. capturedPayload = payload;
  64. }),
  65. });
  66. // Consume the stream to trigger the request
  67. for await (const _ of s) {
  68. // Just consume
  69. }
  70. expect(capturedPayload).not.toBeNull();
  71. // System prompt should have cache_control with ttl: "1h"
  72. expect(capturedPayload.system).toBeDefined();
  73. expect(capturedPayload.system[0].cache_control).toEqual({ type: "ephemeral", ttl: "1h" });
  74. });
  75. it("should add ttl for non-api.anthropic.com baseUrl by default", async () => {
  76. process.env.PI_CACHE_RETENTION = "long";
  77. // Create a model with a different baseUrl (simulating a proxy)
  78. const baseModel = getModel("anthropic", "claude-haiku-4-5");
  79. const proxyModel = {
  80. ...baseModel,
  81. baseUrl: "https://my-proxy.example.com/v1",
  82. };
  83. let capturedPayload: any = null;
  84. // We can't actually make the request (no proxy), but we can verify the payload
  85. // by using a mock or checking the logic directly
  86. // For this test, we'll import the helper directly
  87. // Since we can't easily test this without mocking, we'll skip the actual API call
  88. // and just verify the helper logic works correctly
  89. try {
  90. const s = streamAnthropic(proxyModel, context, {
  91. apiKey: "fake-key",
  92. onPayload: stopAfterPayload((payload) => {
  93. capturedPayload = payload;
  94. }),
  95. });
  96. // This will fail since we're using a fake key and fake proxy, but the payload should be captured
  97. for await (const event of s) {
  98. if (event.type === "error") break;
  99. }
  100. } catch {
  101. // Expected to fail
  102. }
  103. expect(capturedPayload).not.toBeNull();
  104. expect(capturedPayload.system[0].cache_control).toEqual({ type: "ephemeral", ttl: "1h" });
  105. });
  106. it("should omit ttl when supportsLongCacheRetention is false", async () => {
  107. const baseModel = getModel("anthropic", "claude-haiku-4-5");
  108. const proxyModel = {
  109. ...baseModel,
  110. baseUrl: "https://my-proxy.example.com/v1",
  111. compat: { supportsLongCacheRetention: false },
  112. };
  113. let capturedPayload: any = null;
  114. try {
  115. const s = streamAnthropic(proxyModel, context, {
  116. apiKey: "fake-key",
  117. cacheRetention: "long",
  118. onPayload: stopAfterPayload((payload) => {
  119. capturedPayload = payload;
  120. }),
  121. });
  122. for await (const event of s) {
  123. if (event.type === "error") break;
  124. }
  125. } catch {
  126. // Expected to fail
  127. }
  128. expect(capturedPayload).not.toBeNull();
  129. expect(capturedPayload.system[0].cache_control).toEqual({ type: "ephemeral" });
  130. });
  131. it("should omit cache_control when cacheRetention is none", async () => {
  132. const baseModel = getModel("anthropic", "claude-haiku-4-5");
  133. let capturedPayload: any = null;
  134. try {
  135. const s = streamAnthropic(baseModel, context, {
  136. apiKey: "fake-key",
  137. cacheRetention: "none",
  138. onPayload: stopAfterPayload((payload) => {
  139. capturedPayload = payload;
  140. }),
  141. });
  142. for await (const event of s) {
  143. if (event.type === "error") break;
  144. }
  145. } catch {
  146. // Expected to fail
  147. }
  148. expect(capturedPayload).not.toBeNull();
  149. expect(capturedPayload.system[0].cache_control).toBeUndefined();
  150. });
  151. it("should add cache_control to string user messages", async () => {
  152. const baseModel = getModel("anthropic", "claude-haiku-4-5");
  153. let capturedPayload: any = null;
  154. try {
  155. const s = streamAnthropic(baseModel, context, {
  156. apiKey: "fake-key",
  157. onPayload: stopAfterPayload((payload) => {
  158. capturedPayload = payload;
  159. }),
  160. });
  161. for await (const event of s) {
  162. if (event.type === "error") break;
  163. }
  164. } catch {
  165. // Expected to fail
  166. }
  167. expect(capturedPayload).not.toBeNull();
  168. const lastMessage = capturedPayload.messages[capturedPayload.messages.length - 1];
  169. expect(Array.isArray(lastMessage.content)).toBe(true);
  170. const lastBlock = lastMessage.content[lastMessage.content.length - 1];
  171. expect(lastBlock.cache_control).toEqual({ type: "ephemeral" });
  172. });
  173. it("should set 1h cache TTL when cacheRetention is long", async () => {
  174. const baseModel = getModel("anthropic", "claude-haiku-4-5");
  175. let capturedPayload: any = null;
  176. try {
  177. const s = streamAnthropic(baseModel, context, {
  178. apiKey: "fake-key",
  179. cacheRetention: "long",
  180. onPayload: stopAfterPayload((payload) => {
  181. capturedPayload = payload;
  182. }),
  183. });
  184. for await (const event of s) {
  185. if (event.type === "error") break;
  186. }
  187. } catch {
  188. // Expected to fail
  189. }
  190. expect(capturedPayload).not.toBeNull();
  191. expect(capturedPayload.system[0].cache_control).toEqual({ type: "ephemeral", ttl: "1h" });
  192. });
  193. });
  194. describe("OpenAI Responses Provider", () => {
  195. it.skipIf(!process.env.OPENAI_API_KEY)(
  196. "should not set prompt_cache_retention when PI_CACHE_RETENTION is not set",
  197. async () => {
  198. const model = getModel("openai", "gpt-4o-mini");
  199. let capturedPayload: any = null;
  200. const s = stream(model, context, {
  201. onPayload: stopAfterPayload((payload) => {
  202. capturedPayload = payload;
  203. }),
  204. });
  205. // Consume the stream to trigger the request
  206. for await (const _ of s) {
  207. // Just consume
  208. }
  209. expect(capturedPayload).not.toBeNull();
  210. expect(capturedPayload.prompt_cache_retention).toBeUndefined();
  211. },
  212. );
  213. it.skipIf(!process.env.OPENAI_API_KEY)(
  214. "should set prompt_cache_retention to 24h when PI_CACHE_RETENTION=long",
  215. async () => {
  216. process.env.PI_CACHE_RETENTION = "long";
  217. const model = getModel("openai", "gpt-4o-mini");
  218. let capturedPayload: any = null;
  219. const s = stream(model, context, {
  220. onPayload: stopAfterPayload((payload) => {
  221. capturedPayload = payload;
  222. }),
  223. });
  224. // Consume the stream to trigger the request
  225. for await (const _ of s) {
  226. // Just consume
  227. }
  228. expect(capturedPayload).not.toBeNull();
  229. expect(capturedPayload.prompt_cache_retention).toBe("24h");
  230. },
  231. );
  232. it("should set prompt_cache_retention for non-api.openai.com baseUrl by default", async () => {
  233. process.env.PI_CACHE_RETENTION = "long";
  234. // Create a model with a different baseUrl (simulating a proxy)
  235. const baseModel = getModel("openai", "gpt-4o-mini");
  236. const proxyModel = {
  237. ...baseModel,
  238. baseUrl: "https://my-proxy.example.com/v1",
  239. };
  240. let capturedPayload: any = null;
  241. try {
  242. const s = streamOpenAIResponses(proxyModel, context, {
  243. apiKey: "fake-key",
  244. onPayload: stopAfterPayload((payload) => {
  245. capturedPayload = payload;
  246. }),
  247. });
  248. // This will fail since we're using a fake key and fake proxy, but the payload should be captured
  249. for await (const event of s) {
  250. if (event.type === "error") break;
  251. }
  252. } catch {
  253. // Expected to fail
  254. }
  255. expect(capturedPayload).not.toBeNull();
  256. expect(capturedPayload.prompt_cache_retention).toBe("24h");
  257. });
  258. it("should omit prompt_cache_retention when supportsLongCacheRetention is false", async () => {
  259. const model = {
  260. ...getModel("openai", "gpt-4o-mini"),
  261. compat: { supportsLongCacheRetention: false },
  262. };
  263. let capturedPayload: any = null;
  264. try {
  265. const s = streamOpenAIResponses(model, context, {
  266. apiKey: "fake-key",
  267. cacheRetention: "long",
  268. sessionId: "session-compat-false",
  269. onPayload: stopAfterPayload((payload) => {
  270. capturedPayload = payload;
  271. }),
  272. });
  273. for await (const event of s) {
  274. if (event.type === "error") break;
  275. }
  276. } catch {
  277. // Expected to fail
  278. }
  279. expect(capturedPayload).not.toBeNull();
  280. expect(capturedPayload.prompt_cache_retention).toBeUndefined();
  281. });
  282. it("should omit prompt_cache_key when cacheRetention is none", async () => {
  283. const model = getModel("openai", "gpt-4o-mini");
  284. let capturedPayload: any = null;
  285. try {
  286. const s = streamOpenAIResponses(model, context, {
  287. apiKey: "fake-key",
  288. cacheRetention: "none",
  289. sessionId: "session-1",
  290. onPayload: stopAfterPayload((payload) => {
  291. capturedPayload = payload;
  292. }),
  293. });
  294. for await (const event of s) {
  295. if (event.type === "error") break;
  296. }
  297. } catch {
  298. // Expected to fail
  299. }
  300. expect(capturedPayload).not.toBeNull();
  301. expect(capturedPayload.prompt_cache_key).toBeUndefined();
  302. expect(capturedPayload.prompt_cache_retention).toBeUndefined();
  303. });
  304. it("should set prompt_cache_retention when cacheRetention is long", async () => {
  305. const model = getModel("openai", "gpt-4o-mini");
  306. let capturedPayload: any = null;
  307. try {
  308. const s = streamOpenAIResponses(model, context, {
  309. apiKey: "fake-key",
  310. cacheRetention: "long",
  311. sessionId: "session-2",
  312. onPayload: stopAfterPayload((payload) => {
  313. capturedPayload = payload;
  314. }),
  315. });
  316. for await (const event of s) {
  317. if (event.type === "error") break;
  318. }
  319. } catch {
  320. // Expected to fail
  321. }
  322. expect(capturedPayload).not.toBeNull();
  323. expect(capturedPayload.prompt_cache_key).toBe("session-2");
  324. expect(capturedPayload.prompt_cache_retention).toBe("24h");
  325. });
  326. });
  327. describe("OpenAI Completions Provider", () => {
  328. function createCompletionsModel(compat?: Model<"openai-completions">["compat"]): Model<"openai-completions"> {
  329. return {
  330. id: "test-model",
  331. name: "Test Model",
  332. api: "openai-completions",
  333. provider: "test-openai-completions",
  334. baseUrl: "https://my-proxy.example.com/v1",
  335. reasoning: false,
  336. input: ["text"],
  337. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
  338. contextWindow: 128000,
  339. maxTokens: 4096,
  340. compat,
  341. };
  342. }
  343. it("should set prompt_cache_retention for non-api.openai.com baseUrl by default", async () => {
  344. let capturedPayload: any = null;
  345. try {
  346. const s = streamOpenAICompletions(createCompletionsModel(), context, {
  347. apiKey: "fake-key",
  348. cacheRetention: "long",
  349. sessionId: "session-completions",
  350. onPayload: stopAfterPayload((payload) => {
  351. capturedPayload = payload;
  352. }),
  353. });
  354. for await (const event of s) {
  355. if (event.type === "error") break;
  356. }
  357. } catch {
  358. // Expected to fail
  359. }
  360. expect(capturedPayload).not.toBeNull();
  361. expect(capturedPayload.prompt_cache_key).toBe("session-completions");
  362. expect(capturedPayload.prompt_cache_retention).toBe("24h");
  363. });
  364. it("should omit prompt_cache_retention when supportsLongCacheRetention is false", async () => {
  365. let capturedPayload: any = null;
  366. try {
  367. const s = streamOpenAICompletions(createCompletionsModel({ supportsLongCacheRetention: false }), context, {
  368. apiKey: "fake-key",
  369. cacheRetention: "long",
  370. sessionId: "session-completions-false",
  371. onPayload: stopAfterPayload((payload) => {
  372. capturedPayload = payload;
  373. }),
  374. });
  375. for await (const event of s) {
  376. if (event.type === "error") break;
  377. }
  378. } catch {
  379. // Expected to fail
  380. }
  381. expect(capturedPayload).not.toBeNull();
  382. expect(capturedPayload.prompt_cache_key).toBeUndefined();
  383. expect(capturedPayload.prompt_cache_retention).toBeUndefined();
  384. });
  385. });
  386. });