| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459 |
- import { afterEach, beforeEach, describe, expect, it } from "vitest";
- import { getModel } from "../src/models.ts";
- import { streamAnthropic } from "../src/providers/anthropic.ts";
- import { streamOpenAICompletions } from "../src/providers/openai-completions.ts";
- import { streamOpenAIResponses } from "../src/providers/openai-responses.ts";
- import { stream } from "../src/stream.ts";
- import type { Context, Model } from "../src/types.ts";
- class PayloadCaptured extends Error {
- constructor() {
- super("payload captured");
- this.name = "PayloadCaptured";
- }
- }
- function stopAfterPayload<TPayload>(capture: (payload: TPayload) => void): (payload: unknown) => never {
- return (payload: unknown): never => {
- capture(payload as TPayload);
- throw new PayloadCaptured();
- };
- }
- describe("Cache Retention (PI_CACHE_RETENTION)", () => {
- const originalEnv = process.env.PI_CACHE_RETENTION;
- beforeEach(() => {
- delete process.env.PI_CACHE_RETENTION;
- });
- afterEach(() => {
- if (originalEnv !== undefined) {
- process.env.PI_CACHE_RETENTION = originalEnv;
- } else {
- delete process.env.PI_CACHE_RETENTION;
- }
- });
- const context: Context = {
- systemPrompt: "You are a helpful assistant.",
- messages: [{ role: "user", content: "Hello", timestamp: Date.now() }],
- };
- describe("Anthropic Provider", () => {
- it.skipIf(!process.env.ANTHROPIC_API_KEY)(
- "should use default cache TTL (no ttl field) when PI_CACHE_RETENTION is not set",
- async () => {
- const model = getModel("anthropic", "claude-haiku-4-5");
- let capturedPayload: any = null;
- const s = stream(model, context, {
- onPayload: stopAfterPayload((payload) => {
- capturedPayload = payload;
- }),
- });
- // Consume the stream to trigger the request
- for await (const _ of s) {
- // Just consume
- }
- expect(capturedPayload).not.toBeNull();
- // System prompt should have cache_control without ttl
- expect(capturedPayload.system).toBeDefined();
- expect(capturedPayload.system[0].cache_control).toEqual({ type: "ephemeral" });
- },
- );
- it.skipIf(!process.env.ANTHROPIC_API_KEY)("should use 1h cache TTL when PI_CACHE_RETENTION=long", async () => {
- process.env.PI_CACHE_RETENTION = "long";
- const model = getModel("anthropic", "claude-haiku-4-5");
- let capturedPayload: any = null;
- const s = stream(model, context, {
- onPayload: stopAfterPayload((payload) => {
- capturedPayload = payload;
- }),
- });
- // Consume the stream to trigger the request
- for await (const _ of s) {
- // Just consume
- }
- expect(capturedPayload).not.toBeNull();
- // System prompt should have cache_control with ttl: "1h"
- expect(capturedPayload.system).toBeDefined();
- expect(capturedPayload.system[0].cache_control).toEqual({ type: "ephemeral", ttl: "1h" });
- });
- it("should add ttl for non-api.anthropic.com baseUrl by default", async () => {
- process.env.PI_CACHE_RETENTION = "long";
- // Create a model with a different baseUrl (simulating a proxy)
- const baseModel = getModel("anthropic", "claude-haiku-4-5");
- const proxyModel = {
- ...baseModel,
- baseUrl: "https://my-proxy.example.com/v1",
- };
- let capturedPayload: any = null;
- // We can't actually make the request (no proxy), but we can verify the payload
- // by using a mock or checking the logic directly
- // For this test, we'll import the helper directly
- // Since we can't easily test this without mocking, we'll skip the actual API call
- // and just verify the helper logic works correctly
- try {
- const s = streamAnthropic(proxyModel, context, {
- apiKey: "fake-key",
- onPayload: stopAfterPayload((payload) => {
- capturedPayload = payload;
- }),
- });
- // This will fail since we're using a fake key and fake proxy, but the payload should be captured
- for await (const event of s) {
- if (event.type === "error") break;
- }
- } catch {
- // Expected to fail
- }
- expect(capturedPayload).not.toBeNull();
- expect(capturedPayload.system[0].cache_control).toEqual({ type: "ephemeral", ttl: "1h" });
- });
- it("should omit ttl when supportsLongCacheRetention is false", async () => {
- const baseModel = getModel("anthropic", "claude-haiku-4-5");
- const proxyModel = {
- ...baseModel,
- baseUrl: "https://my-proxy.example.com/v1",
- compat: { supportsLongCacheRetention: false },
- };
- let capturedPayload: any = null;
- try {
- const s = streamAnthropic(proxyModel, context, {
- apiKey: "fake-key",
- cacheRetention: "long",
- onPayload: stopAfterPayload((payload) => {
- capturedPayload = payload;
- }),
- });
- for await (const event of s) {
- if (event.type === "error") break;
- }
- } catch {
- // Expected to fail
- }
- expect(capturedPayload).not.toBeNull();
- expect(capturedPayload.system[0].cache_control).toEqual({ type: "ephemeral" });
- });
- it("should omit cache_control when cacheRetention is none", async () => {
- const baseModel = getModel("anthropic", "claude-haiku-4-5");
- let capturedPayload: any = null;
- try {
- const s = streamAnthropic(baseModel, context, {
- apiKey: "fake-key",
- cacheRetention: "none",
- onPayload: stopAfterPayload((payload) => {
- capturedPayload = payload;
- }),
- });
- for await (const event of s) {
- if (event.type === "error") break;
- }
- } catch {
- // Expected to fail
- }
- expect(capturedPayload).not.toBeNull();
- expect(capturedPayload.system[0].cache_control).toBeUndefined();
- });
- it("should add cache_control to string user messages", async () => {
- const baseModel = getModel("anthropic", "claude-haiku-4-5");
- let capturedPayload: any = null;
- try {
- const s = streamAnthropic(baseModel, context, {
- apiKey: "fake-key",
- onPayload: stopAfterPayload((payload) => {
- capturedPayload = payload;
- }),
- });
- for await (const event of s) {
- if (event.type === "error") break;
- }
- } catch {
- // Expected to fail
- }
- expect(capturedPayload).not.toBeNull();
- const lastMessage = capturedPayload.messages[capturedPayload.messages.length - 1];
- expect(Array.isArray(lastMessage.content)).toBe(true);
- const lastBlock = lastMessage.content[lastMessage.content.length - 1];
- expect(lastBlock.cache_control).toEqual({ type: "ephemeral" });
- });
- it("should set 1h cache TTL when cacheRetention is long", async () => {
- const baseModel = getModel("anthropic", "claude-haiku-4-5");
- let capturedPayload: any = null;
- try {
- const s = streamAnthropic(baseModel, context, {
- apiKey: "fake-key",
- cacheRetention: "long",
- onPayload: stopAfterPayload((payload) => {
- capturedPayload = payload;
- }),
- });
- for await (const event of s) {
- if (event.type === "error") break;
- }
- } catch {
- // Expected to fail
- }
- expect(capturedPayload).not.toBeNull();
- expect(capturedPayload.system[0].cache_control).toEqual({ type: "ephemeral", ttl: "1h" });
- });
- });
- describe("OpenAI Responses Provider", () => {
- it.skipIf(!process.env.OPENAI_API_KEY)(
- "should not set prompt_cache_retention when PI_CACHE_RETENTION is not set",
- async () => {
- const model = getModel("openai", "gpt-4o-mini");
- let capturedPayload: any = null;
- const s = stream(model, context, {
- onPayload: stopAfterPayload((payload) => {
- capturedPayload = payload;
- }),
- });
- // Consume the stream to trigger the request
- for await (const _ of s) {
- // Just consume
- }
- expect(capturedPayload).not.toBeNull();
- expect(capturedPayload.prompt_cache_retention).toBeUndefined();
- },
- );
- it.skipIf(!process.env.OPENAI_API_KEY)(
- "should set prompt_cache_retention to 24h when PI_CACHE_RETENTION=long",
- async () => {
- process.env.PI_CACHE_RETENTION = "long";
- const model = getModel("openai", "gpt-4o-mini");
- let capturedPayload: any = null;
- const s = stream(model, context, {
- onPayload: stopAfterPayload((payload) => {
- capturedPayload = payload;
- }),
- });
- // Consume the stream to trigger the request
- for await (const _ of s) {
- // Just consume
- }
- expect(capturedPayload).not.toBeNull();
- expect(capturedPayload.prompt_cache_retention).toBe("24h");
- },
- );
- it("should set prompt_cache_retention for non-api.openai.com baseUrl by default", async () => {
- process.env.PI_CACHE_RETENTION = "long";
- // Create a model with a different baseUrl (simulating a proxy)
- const baseModel = getModel("openai", "gpt-4o-mini");
- const proxyModel = {
- ...baseModel,
- baseUrl: "https://my-proxy.example.com/v1",
- };
- let capturedPayload: any = null;
- try {
- const s = streamOpenAIResponses(proxyModel, context, {
- apiKey: "fake-key",
- onPayload: stopAfterPayload((payload) => {
- capturedPayload = payload;
- }),
- });
- // This will fail since we're using a fake key and fake proxy, but the payload should be captured
- for await (const event of s) {
- if (event.type === "error") break;
- }
- } catch {
- // Expected to fail
- }
- expect(capturedPayload).not.toBeNull();
- expect(capturedPayload.prompt_cache_retention).toBe("24h");
- });
- it("should omit prompt_cache_retention when supportsLongCacheRetention is false", async () => {
- const model = {
- ...getModel("openai", "gpt-4o-mini"),
- compat: { supportsLongCacheRetention: false },
- };
- let capturedPayload: any = null;
- try {
- const s = streamOpenAIResponses(model, context, {
- apiKey: "fake-key",
- cacheRetention: "long",
- sessionId: "session-compat-false",
- onPayload: stopAfterPayload((payload) => {
- capturedPayload = payload;
- }),
- });
- for await (const event of s) {
- if (event.type === "error") break;
- }
- } catch {
- // Expected to fail
- }
- expect(capturedPayload).not.toBeNull();
- expect(capturedPayload.prompt_cache_retention).toBeUndefined();
- });
- it("should omit prompt_cache_key when cacheRetention is none", async () => {
- const model = getModel("openai", "gpt-4o-mini");
- let capturedPayload: any = null;
- try {
- const s = streamOpenAIResponses(model, context, {
- apiKey: "fake-key",
- cacheRetention: "none",
- sessionId: "session-1",
- onPayload: stopAfterPayload((payload) => {
- capturedPayload = payload;
- }),
- });
- for await (const event of s) {
- if (event.type === "error") break;
- }
- } catch {
- // Expected to fail
- }
- expect(capturedPayload).not.toBeNull();
- expect(capturedPayload.prompt_cache_key).toBeUndefined();
- expect(capturedPayload.prompt_cache_retention).toBeUndefined();
- });
- it("should set prompt_cache_retention when cacheRetention is long", async () => {
- const model = getModel("openai", "gpt-4o-mini");
- let capturedPayload: any = null;
- try {
- const s = streamOpenAIResponses(model, context, {
- apiKey: "fake-key",
- cacheRetention: "long",
- sessionId: "session-2",
- onPayload: stopAfterPayload((payload) => {
- capturedPayload = payload;
- }),
- });
- for await (const event of s) {
- if (event.type === "error") break;
- }
- } catch {
- // Expected to fail
- }
- expect(capturedPayload).not.toBeNull();
- expect(capturedPayload.prompt_cache_key).toBe("session-2");
- expect(capturedPayload.prompt_cache_retention).toBe("24h");
- });
- });
- describe("OpenAI Completions Provider", () => {
- function createCompletionsModel(compat?: Model<"openai-completions">["compat"]): Model<"openai-completions"> {
- return {
- id: "test-model",
- name: "Test Model",
- api: "openai-completions",
- provider: "test-openai-completions",
- baseUrl: "https://my-proxy.example.com/v1",
- reasoning: false,
- input: ["text"],
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
- contextWindow: 128000,
- maxTokens: 4096,
- compat,
- };
- }
- it("should set prompt_cache_retention for non-api.openai.com baseUrl by default", async () => {
- let capturedPayload: any = null;
- try {
- const s = streamOpenAICompletions(createCompletionsModel(), context, {
- apiKey: "fake-key",
- cacheRetention: "long",
- sessionId: "session-completions",
- onPayload: stopAfterPayload((payload) => {
- capturedPayload = payload;
- }),
- });
- for await (const event of s) {
- if (event.type === "error") break;
- }
- } catch {
- // Expected to fail
- }
- expect(capturedPayload).not.toBeNull();
- expect(capturedPayload.prompt_cache_key).toBe("session-completions");
- expect(capturedPayload.prompt_cache_retention).toBe("24h");
- });
- it("should omit prompt_cache_retention when supportsLongCacheRetention is false", async () => {
- let capturedPayload: any = null;
- try {
- const s = streamOpenAICompletions(createCompletionsModel({ supportsLongCacheRetention: false }), context, {
- apiKey: "fake-key",
- cacheRetention: "long",
- sessionId: "session-completions-false",
- onPayload: stopAfterPayload((payload) => {
- capturedPayload = payload;
- }),
- });
- for await (const event of s) {
- if (event.type === "error") break;
- }
- } catch {
- // Expected to fail
- }
- expect(capturedPayload).not.toBeNull();
- expect(capturedPayload.prompt_cache_key).toBeUndefined();
- expect(capturedPayload.prompt_cache_retention).toBeUndefined();
- });
- });
- });
|