openrouter-images.test.ts 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. import { beforeEach, describe, expect, it, vi } from "vitest";
  2. import { generateImages } from "../src/images.ts";
  3. import type { ImagesContext, ImagesModel } from "../src/types.ts";
  4. const mockState = vi.hoisted(() => ({
  5. clientOptions: [] as unknown[],
  6. lastParams: undefined as unknown,
  7. lastRequestOptions: undefined as unknown,
  8. }));
  9. vi.mock("openai", () => {
  10. class FakeOpenAI {
  11. constructor(options: unknown) {
  12. mockState.clientOptions.push(options);
  13. }
  14. chat = {
  15. completions: {
  16. create: (params: unknown, requestOptions?: unknown) => {
  17. mockState.lastParams = params;
  18. mockState.lastRequestOptions = requestOptions;
  19. const signal = (requestOptions as { signal?: AbortSignal } | undefined)?.signal;
  20. if (signal?.aborted) {
  21. const error = new Error("Request aborted");
  22. return {
  23. withResponse: async () => {
  24. throw error;
  25. },
  26. };
  27. }
  28. const response = {
  29. id: "img-1",
  30. usage: {
  31. prompt_tokens: 12,
  32. completion_tokens: 34,
  33. prompt_tokens_details: { cached_tokens: 0 },
  34. },
  35. choices: [
  36. {
  37. message: {
  38. content: "Here is your image.",
  39. images: [{ image_url: "data:image/png;base64,ZmFrZS1wbmc=" }],
  40. },
  41. },
  42. ],
  43. };
  44. const promise = Promise.resolve(response) as Promise<typeof response> & {
  45. withResponse: () => Promise<{
  46. data: typeof response;
  47. response: { status: number; headers: Headers };
  48. }>;
  49. };
  50. promise.withResponse = async () => ({
  51. data: response,
  52. response: { status: 200, headers: new Headers() },
  53. });
  54. return promise;
  55. },
  56. },
  57. };
  58. }
  59. return { default: FakeOpenAI };
  60. });
  61. describe("openrouter images", () => {
  62. beforeEach(() => {
  63. mockState.clientOptions = [];
  64. mockState.lastParams = undefined;
  65. mockState.lastRequestOptions = undefined;
  66. });
  67. it("returns text plus images in final output", async () => {
  68. const model: ImagesModel<"openrouter-images"> = {
  69. id: "google/gemini-3.1-flash-image-preview",
  70. name: "Gemini 3.1 Flash Image Preview",
  71. api: "openrouter-images",
  72. provider: "openrouter",
  73. baseUrl: "https://openrouter.ai/api/v1",
  74. input: ["text", "image"],
  75. output: ["text", "image"],
  76. cost: { input: 0.015, output: 0.03, cacheRead: 0, cacheWrite: 0 },
  77. headers: { "HTTP-Referer": "https://example.com" },
  78. };
  79. const context: ImagesContext = {
  80. input: [{ type: "text", text: "Generate a dog" }],
  81. };
  82. const output = await generateImages(model, context, { apiKey: "test" });
  83. expect(output.stopReason).toBe("stop");
  84. expect(output.responseId).toBe("img-1");
  85. expect(output.output[0]).toMatchObject({ type: "text", text: "Here is your image." });
  86. expect(output.output[1]).toMatchObject({ type: "image", mimeType: "image/png", data: "ZmFrZS1wbmc=" });
  87. const params = mockState.lastParams as {
  88. stream?: boolean;
  89. modalities?: string[];
  90. messages?: [{ content?: [{ type: string; text?: string }] }];
  91. };
  92. expect(params.stream).toBe(false);
  93. expect(params.modalities).toEqual(["image", "text"]);
  94. expect(params.messages?.[0]?.content?.[0]).toMatchObject({ type: "text", text: "Generate a dog" });
  95. });
  96. it("passes custom fetch to the OpenAI image SDK client", async () => {
  97. const model: ImagesModel<"openrouter-images"> = {
  98. id: "google/gemini-3.1-flash-image-preview",
  99. name: "Gemini 3.1 Flash Image Preview",
  100. api: "openrouter-images",
  101. provider: "openrouter",
  102. baseUrl: "https://openrouter.ai/api/v1",
  103. input: ["text"],
  104. output: ["image"],
  105. cost: { input: 0.015, output: 0.03, cacheRead: 0, cacheWrite: 0 },
  106. };
  107. const fetchImpl = (async () => new Response()) as typeof globalThis.fetch;
  108. await generateImages(model, { input: [{ type: "text", text: "Generate a dog" }] }, { apiKey: "test", fetch: fetchImpl });
  109. expect(mockState.clientOptions[0]).toEqual(expect.objectContaining({ fetch: fetchImpl }));
  110. });
  111. it("passes through abort signal and returns aborted result", async () => {
  112. const model: ImagesModel<"openrouter-images"> = {
  113. id: "black-forest-labs/flux.2-pro",
  114. name: "FLUX.2 Pro",
  115. api: "openrouter-images",
  116. provider: "openrouter",
  117. baseUrl: "https://openrouter.ai/api/v1",
  118. input: ["text", "image"],
  119. output: ["image"],
  120. cost: { input: 0.015, output: 0.03, cacheRead: 0, cacheWrite: 0 },
  121. };
  122. const context: ImagesContext = {
  123. input: [{ type: "text", text: "Generate a dog" }],
  124. };
  125. const controller = new AbortController();
  126. controller.abort();
  127. const output = await generateImages(model, context, { apiKey: "test", signal: controller.signal });
  128. expect(output.stopReason).toBe("aborted");
  129. expect(output.errorMessage).toBe("Request aborted");
  130. expect(mockState.lastRequestOptions).toMatchObject({ signal: controller.signal });
  131. });
  132. it("generateImages resolves the final assistant images result", async () => {
  133. const model: ImagesModel<"openrouter-images"> = {
  134. id: "black-forest-labs/flux.2-pro",
  135. name: "FLUX.2 Pro",
  136. api: "openrouter-images",
  137. provider: "openrouter",
  138. baseUrl: "https://openrouter.ai/api/v1",
  139. input: ["text", "image"],
  140. output: ["image"],
  141. cost: { input: 0.015, output: 0.03, cacheRead: 0, cacheWrite: 0 },
  142. };
  143. const context: ImagesContext = {
  144. input: [{ type: "text", text: "Generate a dog" }],
  145. };
  146. const output = await generateImages(model, context, { apiKey: "test" });
  147. expect(output.output.some((item) => item.type === "image")).toBe(true);
  148. });
  149. });