openai-completions-cache-control-format.test.ts 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. import { Type } from "typebox";
  2. import { beforeEach, describe, expect, it, vi } from "vitest";
  3. import { getModel } from "../src/models.ts";
  4. import { streamOpenAICompletions } from "../src/providers/openai-completions.ts";
  5. import type { Model } from "../src/types.ts";
  6. interface CacheControl {
  7. type: "ephemeral";
  8. ttl?: string;
  9. }
  10. interface TextPart {
  11. type: "text";
  12. text: string;
  13. cache_control?: CacheControl;
  14. }
  15. interface ToolWithCacheControl {
  16. type: string;
  17. cache_control?: CacheControl;
  18. }
  19. interface CapturedParams {
  20. messages: Array<{
  21. role: string;
  22. content: string | TextPart[] | null;
  23. }>;
  24. tools?: ToolWithCacheControl[];
  25. }
  26. const mockState = vi.hoisted(() => ({
  27. lastParams: undefined as CapturedParams | undefined,
  28. }));
  29. vi.mock("openai", () => {
  30. class FakeOpenAI {
  31. chat = {
  32. completions: {
  33. create: (params: CapturedParams) => {
  34. mockState.lastParams = params;
  35. const stream = {
  36. async *[Symbol.asyncIterator]() {
  37. yield {
  38. id: "chatcmpl-test",
  39. choices: [{ delta: {}, finish_reason: "stop" }],
  40. usage: {
  41. prompt_tokens: 1,
  42. completion_tokens: 1,
  43. prompt_tokens_details: { cached_tokens: 0 },
  44. completion_tokens_details: { reasoning_tokens: 0 },
  45. },
  46. };
  47. },
  48. };
  49. const promise = Promise.resolve(stream) as Promise<typeof stream> & {
  50. withResponse: () => Promise<{
  51. data: typeof stream;
  52. response: { status: number; headers: Headers };
  53. }>;
  54. };
  55. promise.withResponse = async () => ({
  56. data: stream,
  57. response: { status: 200, headers: new Headers() },
  58. });
  59. return promise;
  60. },
  61. },
  62. };
  63. }
  64. return { default: FakeOpenAI };
  65. });
  66. async function capturePayload(
  67. model: Model<"openai-completions">,
  68. options?: { cacheRetention?: "none" | "short" | "long" },
  69. ): Promise<CapturedParams> {
  70. const timestamp = Date.now();
  71. await streamOpenAICompletions(
  72. model,
  73. {
  74. systemPrompt: "System prompt",
  75. messages: [{ role: "user", content: "Hello", timestamp }],
  76. tools: [
  77. {
  78. name: "read",
  79. description: "Read a file",
  80. parameters: Type.Object({
  81. path: Type.String(),
  82. }),
  83. },
  84. ],
  85. },
  86. { apiKey: "test-key", ...options },
  87. ).result();
  88. if (!mockState.lastParams) {
  89. throw new Error("Expected payload to be captured");
  90. }
  91. return mockState.lastParams;
  92. }
  93. function getInstructionMessage(params: CapturedParams) {
  94. return params.messages.find((message) => message.role === "system" || message.role === "developer");
  95. }
  96. function expectAnthropicCacheMarkers(params: CapturedParams): void {
  97. const instructionMessage = getInstructionMessage(params);
  98. expect(instructionMessage).toBeDefined();
  99. expect(Array.isArray(instructionMessage?.content)).toBe(true);
  100. expect((instructionMessage?.content as TextPart[])[0]?.cache_control).toEqual({ type: "ephemeral" });
  101. expect(params.tools).toHaveLength(1);
  102. expect(params.tools?.[0]?.cache_control).toEqual({ type: "ephemeral" });
  103. const lastMessage = params.messages[params.messages.length - 1];
  104. expect(lastMessage.role).toBe("user");
  105. expect(Array.isArray(lastMessage.content)).toBe(true);
  106. expect((lastMessage.content as TextPart[])[0]?.cache_control).toEqual({ type: "ephemeral" });
  107. }
  108. describe("openai-completions cacheControlFormat", () => {
  109. beforeEach(() => {
  110. mockState.lastParams = undefined;
  111. });
  112. it("applies Anthropic-style cache markers when model compat enables them", async () => {
  113. const model: Model<"openai-completions"> = {
  114. id: "custom-qwen",
  115. name: "Custom Qwen",
  116. api: "openai-completions",
  117. provider: "openrouter",
  118. baseUrl: "https://example.com/v1",
  119. reasoning: true,
  120. input: ["text"],
  121. cost: {
  122. input: 0,
  123. output: 0,
  124. cacheRead: 0,
  125. cacheWrite: 0,
  126. },
  127. contextWindow: 128000,
  128. maxTokens: 32000,
  129. compat: {
  130. cacheControlFormat: "anthropic",
  131. },
  132. };
  133. const params = await capturePayload(model);
  134. expectAnthropicCacheMarkers(params);
  135. });
  136. it("preserves Anthropic-style cache markers for OpenRouter Anthropic models", async () => {
  137. const model = getModel("openrouter", "anthropic/claude-sonnet-4");
  138. const params = await capturePayload(model);
  139. expectAnthropicCacheMarkers(params);
  140. });
  141. it("omits Anthropic-style cache markers when cacheRetention is none", async () => {
  142. const model: Model<"openai-completions"> = {
  143. id: "custom-qwen",
  144. name: "Custom Qwen",
  145. api: "openai-completions",
  146. provider: "openrouter",
  147. baseUrl: "https://example.com/v1",
  148. reasoning: true,
  149. input: ["text"],
  150. cost: {
  151. input: 0,
  152. output: 0,
  153. cacheRead: 0,
  154. cacheWrite: 0,
  155. },
  156. contextWindow: 128000,
  157. maxTokens: 32000,
  158. compat: {
  159. cacheControlFormat: "anthropic",
  160. },
  161. };
  162. const params = await capturePayload(model, { cacheRetention: "none" });
  163. const instructionMessage = getInstructionMessage(params);
  164. expect(Array.isArray(instructionMessage?.content)).toBe(false);
  165. expect(params.tools?.[0]?.cache_control).toBeUndefined();
  166. expect(typeof params.messages[params.messages.length - 1]?.content).toBe("string");
  167. });
  168. });