openai-completions-retry.test.ts 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. import { beforeEach, describe, expect, it, vi } from "vitest";
  2. import { streamOpenAICompletions } from "../src/providers/openai-completions.ts";
  3. import { streamOpenAIResponses } from "../src/providers/openai-responses.ts";
  4. import type { Context, Model } from "../src/types.ts";
  5. const mockState = vi.hoisted(() => ({
  6. clientOptions: [] as unknown[],
  7. requestOptions: [] as unknown[],
  8. terminalError: undefined as unknown,
  9. }));
  10. vi.mock("openai", () => {
  11. class FakeOpenAI {
  12. constructor(options: unknown) {
  13. mockState.clientOptions.push(options);
  14. }
  15. chat = {
  16. completions: {
  17. create: (_params: unknown, options: unknown) => {
  18. mockState.requestOptions.push(options);
  19. const stream = {
  20. async *[Symbol.asyncIterator]() {
  21. yield {
  22. id: "chatcmpl-test",
  23. choices: [{ index: 0, delta: { content: "ok" } }],
  24. };
  25. yield {
  26. id: "chatcmpl-test",
  27. choices: [{ index: 0, delta: {}, finish_reason: "stop" }],
  28. };
  29. },
  30. };
  31. const promise = Promise.resolve(stream) as Promise<typeof stream> & {
  32. withResponse: () => Promise<{
  33. data: typeof stream;
  34. response: { status: number; headers: Headers };
  35. }>;
  36. };
  37. promise.withResponse = async () => {
  38. if (mockState.terminalError !== undefined) throw mockState.terminalError;
  39. return {
  40. data: stream,
  41. response: { status: 200, headers: new Headers() },
  42. };
  43. };
  44. return promise;
  45. },
  46. },
  47. };
  48. responses = {
  49. create: (_params: unknown, options: unknown) => {
  50. mockState.requestOptions.push(options);
  51. const stream = {
  52. async *[Symbol.asyncIterator]() {
  53. yield {
  54. type: "response.completed",
  55. response: {
  56. id: "resp-test",
  57. status: "completed",
  58. usage: {
  59. input_tokens: 1,
  60. output_tokens: 1,
  61. total_tokens: 2,
  62. input_tokens_details: { cached_tokens: 0 },
  63. },
  64. },
  65. };
  66. },
  67. };
  68. return {
  69. withResponse: async () => {
  70. if (mockState.terminalError !== undefined) throw mockState.terminalError;
  71. return {
  72. data: stream,
  73. response: { status: 200, headers: new Headers() },
  74. };
  75. },
  76. };
  77. },
  78. };
  79. }
  80. return { default: FakeOpenAI };
  81. });
  82. const model: Model<"openai-completions"> = {
  83. id: "test-model",
  84. name: "Test Model",
  85. api: "openai-completions",
  86. provider: "opencode-go",
  87. baseUrl: "https://opencode.ai/zen/go/v1",
  88. reasoning: false,
  89. input: ["text"],
  90. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
  91. contextWindow: 1000,
  92. maxTokens: 100,
  93. };
  94. const responsesModel: Model<"openai-responses"> = {
  95. id: "test-responses-model",
  96. name: "Test Responses Model",
  97. api: "openai-responses",
  98. provider: "openai",
  99. baseUrl: "https://api.openai.com/v1",
  100. reasoning: false,
  101. input: ["text"],
  102. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
  103. contextWindow: 1000,
  104. maxTokens: 100,
  105. };
  106. const context: Context = {
  107. systemPrompt: "",
  108. messages: [{ role: "user", content: [{ type: "text", text: "hi" }], timestamp: 0 }],
  109. tools: [],
  110. };
  111. async function consume(options?: {
  112. maxRetries?: number;
  113. fetch?: typeof globalThis.fetch;
  114. onProviderError?: (error: unknown, model: Model) => void;
  115. onProviderStreamEvent?: (event: unknown, model: Model) => void;
  116. }) {
  117. const stream = streamOpenAICompletions(model, context, { apiKey: "test", ...options });
  118. for await (const _event of stream) {
  119. void _event;
  120. }
  121. return stream.result();
  122. }
  123. async function consumeResponses(options?: {
  124. fetch?: typeof globalThis.fetch;
  125. onProviderStreamEvent?: (event: unknown, model: Model) => void;
  126. }) {
  127. const stream = streamOpenAIResponses(responsesModel, context, { apiKey: "test", ...options });
  128. for await (const _event of stream) {
  129. void _event;
  130. }
  131. return stream.result();
  132. }
  133. describe("openai-completions provider retries", () => {
  134. beforeEach(() => {
  135. mockState.clientOptions = [];
  136. mockState.requestOptions = [];
  137. mockState.terminalError = undefined;
  138. });
  139. it("disables SDK retries by default", async () => {
  140. await consume();
  141. expect(mockState.requestOptions).toEqual([expect.objectContaining({ maxRetries: 0 })]);
  142. });
  143. it("honors explicit provider retry settings", async () => {
  144. await consume({ maxRetries: 2 });
  145. expect(mockState.requestOptions).toEqual([expect.objectContaining({ maxRetries: 2 })]);
  146. });
  147. it("passes custom fetch to the OpenAI completions SDK client", async () => {
  148. const fetchImpl = (async () => new Response()) as typeof globalThis.fetch;
  149. await consume({ fetch: fetchImpl });
  150. expect(mockState.clientOptions[0]).toEqual(expect.objectContaining({ fetch: fetchImpl }));
  151. });
  152. it("passes custom fetch to the OpenAI responses SDK client", async () => {
  153. const fetchImpl = (async () => new Response()) as typeof globalThis.fetch;
  154. await consumeResponses({ fetch: fetchImpl });
  155. expect(mockState.clientOptions[0]).toEqual(expect.objectContaining({ fetch: fetchImpl }));
  156. });
  157. it("delivers parsed Chat Completions chunks to the provider observer", async () => {
  158. const observed: unknown[] = [];
  159. await consume({ onProviderStreamEvent: (event) => observed.push(event) });
  160. expect(observed).toEqual([
  161. {
  162. id: "chatcmpl-test",
  163. choices: [{ index: 0, delta: { content: "ok" } }],
  164. },
  165. {
  166. id: "chatcmpl-test",
  167. choices: [{ index: 0, delta: {}, finish_reason: "stop" }],
  168. },
  169. ]);
  170. });
  171. it("delivers parsed Responses events through the shared processor observer", async () => {
  172. const observed: unknown[] = [];
  173. await consumeResponses({ onProviderStreamEvent: (event) => observed.push(event) });
  174. expect(observed).toEqual([
  175. {
  176. type: "response.completed",
  177. response: {
  178. id: "resp-test",
  179. status: "completed",
  180. usage: {
  181. input_tokens: 1,
  182. output_tokens: 1,
  183. total_tokens: 2,
  184. input_tokens_details: { cached_tokens: 0 },
  185. },
  186. },
  187. },
  188. ]);
  189. });
  190. it("把 provider 捕获到的原始异常交给宿主回调", async () => {
  191. const cause = Object.assign(new Error("getaddrinfo ENOTFOUND missing.example.com"), {
  192. code: "ENOTFOUND",
  193. hostname: "missing.example.com",
  194. });
  195. const original = new Error("Connection error.", { cause });
  196. const onProviderError = vi.fn();
  197. mockState.terminalError = original;
  198. const result = await consume({ onProviderError });
  199. expect(result.stopReason).toBe("error");
  200. expect(result.errorMessage).toBe("Connection error.");
  201. expect(onProviderError).toHaveBeenCalledOnce();
  202. expect(onProviderError).toHaveBeenCalledWith(original, model);
  203. });
  204. it("宿主错误回调抛错时仍保留原 provider 失败", async () => {
  205. const original = new Error("provider failed");
  206. mockState.terminalError = original;
  207. const result = await consume({
  208. onProviderError: () => {
  209. throw new Error("observer failed");
  210. },
  211. });
  212. expect(result.stopReason).toBe("error");
  213. expect(result.errorMessage).toBe("provider failed");
  214. });
  215. });