stream.test.ts 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633
  1. import { type ChildProcess, execSync, spawn } from "child_process";
  2. import { readFileSync } from "fs";
  3. import { dirname, join } from "path";
  4. import { Type } from "typebox";
  5. import { fileURLToPath } from "url";
  6. import { afterAll, beforeAll, describe, expect, it } from "vitest";
  7. import { getModel } from "../src/models.ts";
  8. import { complete, stream } from "../src/stream.ts";
  9. import type { Api, Context, ImageContent, Model, StreamOptions, Tool, ToolResultMessage } from "../src/types.ts";
  10. type StreamOptionsWithExtras = StreamOptions & Record<string, unknown>;
  11. import { StringEnum } from "../src/utils/typebox-helpers.ts";
  12. import { hasAzureOpenAICredentials, resolveAzureDeploymentName } from "./azure-utils.ts";
  13. import { hasBedrockCredentials } from "./bedrock-utils.ts";
  14. import { hasCloudflareAiGatewayCredentials, hasCloudflareWorkersAICredentials } from "./cloudflare-utils.ts";
  15. import { resolveApiKey } from "./oauth.ts";
  16. const __filename = fileURLToPath(import.meta.url);
  17. const __dirname = dirname(__filename);
  18. // Resolve OAuth tokens at module level (async, runs before tests)
  19. const oauthTokens = await Promise.all([
  20. resolveApiKey("anthropic"),
  21. resolveApiKey("github-copilot"),
  22. resolveApiKey("openai-codex"),
  23. ]);
  24. const [anthropicOAuthToken, githubCopilotToken, openaiCodexToken] = oauthTokens;
  25. // Calculator tool definition (same as examples)
  26. // Note: Using StringEnum helper because Google's API doesn't support anyOf/const patterns
  27. // that Type.Enum generates. Google requires { type: "string", enum: [...] } format.
  28. const calculatorSchema = Type.Object({
  29. a: Type.Number({ description: "First number" }),
  30. b: Type.Number({ description: "Second number" }),
  31. operation: StringEnum(["add", "subtract", "multiply", "divide"], {
  32. description: "The operation to perform. One of 'add', 'subtract', 'multiply', 'divide'.",
  33. }),
  34. });
  35. const calculatorTool: Tool<typeof calculatorSchema> = {
  36. name: "math_operation",
  37. description: "Perform basic arithmetic operations",
  38. parameters: calculatorSchema,
  39. };
  40. async function basicTextGeneration<TApi extends Api>(model: Model<TApi>, options?: StreamOptionsWithExtras) {
  41. const context: Context = {
  42. systemPrompt: "You are a helpful assistant. Be concise.",
  43. messages: [{ role: "user", content: "Reply with exactly: 'Hello test successful'", timestamp: Date.now() }],
  44. };
  45. const response = await complete(model, context, options);
  46. expect(response.role).toBe("assistant");
  47. expect(response.content).toBeTruthy();
  48. expect(response.usage.input + response.usage.cacheRead).toBeGreaterThan(0);
  49. expect(response.usage.output).toBeGreaterThan(0);
  50. expect(response.errorMessage).toBeFalsy();
  51. expect(response.content.map((b) => (b.type === "text" ? b.text : "")).join("")).toContain("Hello test successful");
  52. context.messages.push(response);
  53. context.messages.push({ role: "user", content: "Now say 'Goodbye test successful'", timestamp: Date.now() });
  54. const secondResponse = await complete(model, context, options);
  55. expect(secondResponse.role).toBe("assistant");
  56. expect(secondResponse.content).toBeTruthy();
  57. expect(secondResponse.usage.input + secondResponse.usage.cacheRead).toBeGreaterThan(0);
  58. expect(secondResponse.usage.output).toBeGreaterThan(0);
  59. expect(secondResponse.errorMessage).toBeFalsy();
  60. expect(secondResponse.content.map((b) => (b.type === "text" ? b.text : "")).join("")).toContain(
  61. "Goodbye test successful",
  62. );
  63. }
  64. async function handleToolCall<TApi extends Api>(model: Model<TApi>, options?: StreamOptionsWithExtras) {
  65. const context: Context = {
  66. systemPrompt: "You are a helpful assistant that uses tools when asked.",
  67. messages: [
  68. {
  69. role: "user",
  70. content: "Calculate 15 + 27 using the math_operation tool.",
  71. timestamp: Date.now(),
  72. },
  73. ],
  74. tools: [calculatorTool],
  75. };
  76. const s = await stream(model, context, options);
  77. let hasToolStart = false;
  78. let hasToolDelta = false;
  79. let hasToolEnd = false;
  80. let accumulatedToolArgs = "";
  81. let index = 0;
  82. for await (const event of s) {
  83. if (event.type === "toolcall_start") {
  84. hasToolStart = true;
  85. const toolCall = event.partial.content[event.contentIndex];
  86. index = event.contentIndex;
  87. expect(toolCall.type).toBe("toolCall");
  88. if (toolCall.type === "toolCall") {
  89. expect(toolCall.name).toBe("math_operation");
  90. expect(toolCall.id).toBeTruthy();
  91. }
  92. }
  93. if (event.type === "toolcall_delta") {
  94. hasToolDelta = true;
  95. const toolCall = event.partial.content[event.contentIndex];
  96. expect(event.contentIndex).toBe(index);
  97. expect(toolCall.type).toBe("toolCall");
  98. if (toolCall.type === "toolCall") {
  99. expect(toolCall.name).toBe("math_operation");
  100. accumulatedToolArgs += event.delta;
  101. // Check that we have a parsed arguments object during streaming
  102. expect(toolCall.arguments).toBeDefined();
  103. expect(typeof toolCall.arguments).toBe("object");
  104. // The arguments should be partially populated as we stream
  105. // At minimum it should be an empty object, never undefined
  106. expect(toolCall.arguments).not.toBeNull();
  107. }
  108. }
  109. if (event.type === "toolcall_end") {
  110. hasToolEnd = true;
  111. const toolCall = event.partial.content[event.contentIndex];
  112. expect(event.contentIndex).toBe(index);
  113. expect(toolCall.type).toBe("toolCall");
  114. if (toolCall.type === "toolCall") {
  115. expect(toolCall.name).toBe("math_operation");
  116. JSON.parse(accumulatedToolArgs);
  117. expect(toolCall.arguments).not.toBeUndefined();
  118. expect((toolCall.arguments as any).a).toBe(15);
  119. expect((toolCall.arguments as any).b).toBe(27);
  120. expect((toolCall.arguments as any).operation).oneOf(["add", "subtract", "multiply", "divide"]);
  121. }
  122. }
  123. }
  124. expect(hasToolStart).toBe(true);
  125. expect(hasToolDelta).toBe(true);
  126. expect(hasToolEnd).toBe(true);
  127. const response = await s.result();
  128. expect(response.stopReason).toBe("toolUse");
  129. expect(response.content.some((b) => b.type === "toolCall")).toBeTruthy();
  130. const toolCall = response.content.find((b) => b.type === "toolCall");
  131. if (toolCall && toolCall.type === "toolCall") {
  132. expect(toolCall.name).toBe("math_operation");
  133. expect(toolCall.id).toBeTruthy();
  134. } else {
  135. throw new Error("No tool call found in response");
  136. }
  137. }
  138. async function handleStreaming<TApi extends Api>(model: Model<TApi>, options?: StreamOptionsWithExtras) {
  139. let textStarted = false;
  140. let textChunks = "";
  141. let textCompleted = false;
  142. const context: Context = {
  143. messages: [{ role: "user", content: "Count from 1 to 3", timestamp: Date.now() }],
  144. systemPrompt: "You are a helpful assistant.",
  145. };
  146. const s = stream(model, context, options);
  147. for await (const event of s) {
  148. if (event.type === "text_start") {
  149. textStarted = true;
  150. } else if (event.type === "text_delta") {
  151. textChunks += event.delta;
  152. } else if (event.type === "text_end") {
  153. textCompleted = true;
  154. }
  155. }
  156. const response = await s.result();
  157. expect(textStarted).toBe(true);
  158. expect(textChunks.length).toBeGreaterThan(0);
  159. expect(textCompleted).toBe(true);
  160. expect(response.content.some((b) => b.type === "text")).toBeTruthy();
  161. }
  162. async function handleThinking<TApi extends Api>(model: Model<TApi>, options?: StreamOptionsWithExtras) {
  163. let thinkingStarted = false;
  164. let thinkingChunks = "";
  165. let thinkingCompleted = false;
  166. const context: Context = {
  167. messages: [
  168. {
  169. role: "user",
  170. content: `Think long and hard about ${(Math.random() * 255) | 0} + 27. Think step by step. Then output the result.`,
  171. timestamp: Date.now(),
  172. },
  173. ],
  174. systemPrompt: "You are a helpful assistant.",
  175. };
  176. const s = stream(model, context, options);
  177. for await (const event of s) {
  178. if (event.type === "thinking_start") {
  179. thinkingStarted = true;
  180. } else if (event.type === "thinking_delta") {
  181. thinkingChunks += event.delta;
  182. } else if (event.type === "thinking_end") {
  183. thinkingCompleted = true;
  184. }
  185. }
  186. const response = await s.result();
  187. expect(response.stopReason, `Error: ${response.errorMessage}`).toBe("stop");
  188. expect(thinkingStarted).toBe(true);
  189. expect(thinkingChunks.length).toBeGreaterThan(0);
  190. expect(thinkingCompleted).toBe(true);
  191. expect(response.content.some((b) => b.type === "thinking")).toBeTruthy();
  192. }
  193. async function handleImage<TApi extends Api>(model: Model<TApi>, options?: StreamOptionsWithExtras) {
  194. // Check if the model supports images
  195. if (!model.input.includes("image")) {
  196. console.log(`Skipping image test - model ${model.id} doesn't support images`);
  197. return;
  198. }
  199. // Read the test image
  200. const imagePath = join(__dirname, "data", "red-circle.png");
  201. const imageBuffer = readFileSync(imagePath);
  202. const base64Image = imageBuffer.toString("base64");
  203. const imageContent: ImageContent = {
  204. type: "image",
  205. data: base64Image,
  206. mimeType: "image/png",
  207. };
  208. const context: Context = {
  209. messages: [
  210. {
  211. role: "user",
  212. content: [
  213. {
  214. type: "text",
  215. text: "What do you see in this image? Please describe the shape (circle, rectangle, square, triangle, ...) and color (red, blue, green, ...). You MUST reply in English.",
  216. },
  217. imageContent,
  218. ],
  219. timestamp: Date.now(),
  220. },
  221. ],
  222. systemPrompt: "You are a helpful assistant.",
  223. };
  224. const response = await complete(model, context, options);
  225. // Check the response mentions red and circle
  226. expect(response.content.length > 0).toBeTruthy();
  227. const textContent = response.content.find((b) => b.type === "text");
  228. if (textContent && textContent.type === "text") {
  229. const lowerContent = textContent.text.toLowerCase();
  230. expect(lowerContent).toContain("red");
  231. expect(lowerContent).toContain("circle");
  232. }
  233. }
  234. async function multiTurn<TApi extends Api>(model: Model<TApi>, options?: StreamOptionsWithExtras) {
  235. const context: Context = {
  236. systemPrompt: "You are a helpful assistant that can use tools to answer questions.",
  237. messages: [
  238. {
  239. role: "user",
  240. content: "Think about this briefly, then calculate 42 * 17 and 453 + 434 using the math_operation tool.",
  241. timestamp: Date.now(),
  242. },
  243. ],
  244. tools: [calculatorTool],
  245. };
  246. // Collect all text content from all assistant responses
  247. let allTextContent = "";
  248. let hasSeenThinking = false;
  249. let hasSeenToolCalls = false;
  250. const maxTurns = 5; // Prevent infinite loops
  251. for (let turn = 0; turn < maxTurns; turn++) {
  252. const response = await complete(model, context, options);
  253. // Add the assistant response to context
  254. context.messages.push(response);
  255. // Process content blocks
  256. const results: ToolResultMessage[] = [];
  257. for (const block of response.content) {
  258. if (block.type === "text") {
  259. allTextContent += block.text;
  260. } else if (block.type === "thinking") {
  261. hasSeenThinking = true;
  262. } else if (block.type === "toolCall") {
  263. hasSeenToolCalls = true;
  264. // Process the tool call
  265. expect(block.name).toBe("math_operation");
  266. expect(block.id).toBeTruthy();
  267. expect(block.arguments).toBeTruthy();
  268. const { a, b, operation } = block.arguments;
  269. let result: number;
  270. switch (operation) {
  271. case "add":
  272. result = a + b;
  273. break;
  274. case "multiply":
  275. result = a * b;
  276. break;
  277. default:
  278. result = 0;
  279. }
  280. // Add tool result to context
  281. results.push({
  282. role: "toolResult",
  283. toolCallId: block.id,
  284. toolName: block.name,
  285. content: [{ type: "text", text: `${result}` }],
  286. isError: false,
  287. timestamp: Date.now(),
  288. });
  289. }
  290. }
  291. context.messages.push(...results);
  292. // If we got a stop response with text content, we're likely done
  293. expect(response.stopReason, `Error: ${response.errorMessage}`).not.toBe("error");
  294. if (response.stopReason === "stop") {
  295. break;
  296. }
  297. }
  298. // Verify we got either thinking content or tool calls (or both)
  299. expect(hasSeenThinking || hasSeenToolCalls).toBe(true);
  300. // The accumulated text should reference both calculations
  301. expect(allTextContent).toBeTruthy();
  302. expect(allTextContent.includes("714")).toBe(true);
  303. expect(allTextContent.includes("887")).toBe(true);
  304. }
  305. describe("Generate E2E Tests", () => {
  306. describe.skipIf(!process.env.GEMINI_API_KEY)("Gemini Provider (gemini-2.5-flash)", () => {
  307. const llm = getModel("google", "gemini-2.5-flash");
  308. it("should complete basic text generation", { retry: 3 }, async () => {
  309. await basicTextGeneration(llm);
  310. });
  311. it("should handle tool calling", { retry: 3 }, async () => {
  312. await handleToolCall(llm);
  313. });
  314. it("should handle streaming", { retry: 3 }, async () => {
  315. await handleStreaming(llm);
  316. });
  317. it("should handle thinking", { retry: 3 }, async () => {
  318. await handleThinking(llm, { thinking: { enabled: true, budgetTokens: 1024 } });
  319. });
  320. it("should handle multi-turn with thinking and tools", { retry: 3 }, async () => {
  321. await multiTurn(llm, { thinking: { enabled: true, budgetTokens: 2048 } });
  322. });
  323. it("should handle image input", { retry: 3 }, async () => {
  324. await handleImage(llm);
  325. });
  326. });
  327. describe("Google Vertex Provider (gemini-3-flash-preview)", () => {
  328. const vertexProject = process.env.GOOGLE_CLOUD_PROJECT || process.env.GCLOUD_PROJECT;
  329. const vertexLocation = process.env.GOOGLE_CLOUD_LOCATION;
  330. const vertexApiKey = process.env.GOOGLE_CLOUD_API_KEY;
  331. const isVertexConfigured = Boolean(vertexProject && vertexLocation);
  332. const vertexOptions = { project: vertexProject, location: vertexLocation } as const;
  333. const llm = getModel("google-vertex", "gemini-3-flash-preview");
  334. it.skipIf(!isVertexConfigured)("should complete basic text generation", { retry: 3 }, async () => {
  335. await basicTextGeneration(llm, vertexOptions);
  336. });
  337. it.skipIf(!vertexApiKey)("should complete basic text generation with Vertex API key", { retry: 3 }, async () => {
  338. await basicTextGeneration(llm, { apiKey: vertexApiKey! });
  339. });
  340. it.skipIf(!isVertexConfigured)("should handle tool calling", { retry: 3 }, async () => {
  341. await handleToolCall(llm, vertexOptions);
  342. });
  343. it.skipIf(!isVertexConfigured)("should handle thinking", { retry: 3 }, async () => {
  344. const { ThinkingLevel } = await import("@google/genai");
  345. await handleThinking(llm, {
  346. ...vertexOptions,
  347. thinking: { enabled: true, budgetTokens: 1024, level: ThinkingLevel.LOW },
  348. });
  349. });
  350. it.skipIf(!isVertexConfigured)("should handle streaming", { retry: 3 }, async () => {
  351. await handleStreaming(llm, vertexOptions);
  352. });
  353. it.skipIf(!isVertexConfigured)("should handle multi-turn with thinking and tools", { retry: 3 }, async () => {
  354. const { ThinkingLevel } = await import("@google/genai");
  355. await multiTurn(llm, {
  356. ...vertexOptions,
  357. thinking: { enabled: true, budgetTokens: 1024, level: ThinkingLevel.MEDIUM },
  358. });
  359. });
  360. it.skipIf(!isVertexConfigured)("should handle image input", { retry: 3 }, async () => {
  361. await handleImage(llm, vertexOptions);
  362. });
  363. });
  364. describe.skipIf(!process.env.OPENAI_API_KEY)("OpenAI Completions Provider (gpt-4o-mini)", () => {
  365. const { compat: _compat, ...baseModel } = getModel("openai", "gpt-4o-mini");
  366. void _compat;
  367. const llm: Model<"openai-completions"> = {
  368. ...baseModel,
  369. api: "openai-completions",
  370. };
  371. it("should complete basic text generation", { retry: 3 }, async () => {
  372. await basicTextGeneration(llm);
  373. });
  374. it("should handle tool calling", { retry: 3 }, async () => {
  375. await handleToolCall(llm);
  376. });
  377. it("should handle streaming", { retry: 3 }, async () => {
  378. await handleStreaming(llm);
  379. });
  380. it("should handle image input", { retry: 3 }, async () => {
  381. await handleImage(llm);
  382. });
  383. });
  384. describe.skipIf(!process.env.DEEPSEEK_API_KEY)(
  385. "DeepSeek Provider (deepseek-v4-flash via OpenAI Completions)",
  386. () => {
  387. const llm = getModel("deepseek", "deepseek-v4-flash");
  388. it("should complete basic text generation", { retry: 3 }, async () => {
  389. await basicTextGeneration(llm);
  390. });
  391. it("should handle tool calling", { retry: 3 }, async () => {
  392. await handleToolCall(llm);
  393. });
  394. it("should handle streaming", { retry: 3 }, async () => {
  395. await handleStreaming(llm);
  396. });
  397. it("should handle thinking mode", { retry: 3 }, async () => {
  398. await handleThinking(llm, { reasoningEffort: "high" });
  399. });
  400. it("should handle multi-turn with thinking and tools", { retry: 3 }, async () => {
  401. await multiTurn(llm, { reasoningEffort: "high" });
  402. });
  403. },
  404. );
  405. describe.skipIf(!process.env.OPENAI_API_KEY)("OpenAI Responses Provider (gpt-5.4)", () => {
  406. const llm = getModel("openai", "gpt-5.4");
  407. it("should complete basic text generation", { retry: 3 }, async () => {
  408. await basicTextGeneration(llm);
  409. });
  410. it("should handle tool calling", { retry: 3 }, async () => {
  411. await handleToolCall(llm);
  412. });
  413. it("should handle streaming", { retry: 3 }, async () => {
  414. await handleStreaming(llm);
  415. });
  416. it("should handle thinking", { retry: 2 }, async () => {
  417. await handleThinking(llm, { reasoningEffort: "high" });
  418. });
  419. it("should handle multi-turn with thinking and tools", { retry: 3 }, async () => {
  420. await multiTurn(llm, { reasoningEffort: "high" });
  421. });
  422. it("should handle image input", { retry: 3 }, async () => {
  423. await handleImage(llm);
  424. });
  425. });
  426. describe.skipIf(!process.env.ANTHROPIC_API_KEY)("Anthropic Provider (claude-haiku-4-5)", () => {
  427. const model = getModel("anthropic", "claude-haiku-4-5");
  428. it("should complete basic text generation", { retry: 3 }, async () => {
  429. await basicTextGeneration(model, { thinkingEnabled: true });
  430. });
  431. it("should handle tool calling", { retry: 3 }, async () => {
  432. await handleToolCall(model);
  433. });
  434. it("should handle streaming", { retry: 3 }, async () => {
  435. await handleStreaming(model);
  436. });
  437. it("should handle image input", { retry: 3 }, async () => {
  438. await handleImage(model);
  439. });
  440. });
  441. describe.skipIf(!hasAzureOpenAICredentials())("Azure OpenAI Responses Provider (gpt-4o-mini)", () => {
  442. const llm = getModel("azure-openai-responses", "gpt-4o-mini");
  443. const azureDeploymentName = resolveAzureDeploymentName(llm.id);
  444. const azureOptions = azureDeploymentName ? { azureDeploymentName } : {};
  445. it("should complete basic text generation", { retry: 3 }, async () => {
  446. await basicTextGeneration(llm, azureOptions);
  447. });
  448. it("should handle tool calling", { retry: 3 }, async () => {
  449. await handleToolCall(llm, azureOptions);
  450. });
  451. it("should handle streaming", { retry: 3 }, async () => {
  452. await handleStreaming(llm, azureOptions);
  453. });
  454. it("should handle image input", { retry: 3 }, async () => {
  455. await handleImage(llm, azureOptions);
  456. });
  457. });
  458. describe.skipIf(!process.env.XAI_API_KEY)("xAI Provider (grok-code-fast-1 via OpenAI Completions)", () => {
  459. const llm = getModel("xai", "grok-code-fast-1");
  460. it("should complete basic text generation", { retry: 3 }, async () => {
  461. await basicTextGeneration(llm);
  462. });
  463. it("should handle tool calling", { retry: 3 }, async () => {
  464. await handleToolCall(llm);
  465. });
  466. it("should handle streaming", { retry: 3 }, async () => {
  467. await handleStreaming(llm);
  468. });
  469. it("should handle thinking mode", { retry: 3 }, async () => {
  470. await handleThinking(llm, { reasoningEffort: "medium" });
  471. });
  472. it("should handle multi-turn with thinking and tools", { retry: 3 }, async () => {
  473. await multiTurn(llm, { reasoningEffort: "medium" });
  474. });
  475. });
  476. describe.skipIf(!process.env.GROQ_API_KEY)("Groq Provider (gpt-oss-20b via OpenAI Completions)", () => {
  477. const llm = getModel("groq", "openai/gpt-oss-20b");
  478. it("should complete basic text generation", { retry: 3 }, async () => {
  479. await basicTextGeneration(llm);
  480. });
  481. it("should handle tool calling", { retry: 3 }, async () => {
  482. await handleToolCall(llm);
  483. });
  484. it("should handle streaming", { retry: 3 }, async () => {
  485. await handleStreaming(llm);
  486. });
  487. it("should handle thinking mode", { retry: 3 }, async () => {
  488. await handleThinking(llm, { reasoningEffort: "medium" });
  489. });
  490. it("should handle multi-turn with thinking and tools", { retry: 3 }, async () => {
  491. await multiTurn(llm, { reasoningEffort: "medium" });
  492. });
  493. });
  494. describe.skipIf(!process.env.CEREBRAS_API_KEY)("Cerebras Provider (gpt-oss-120b via OpenAI Completions)", () => {
  495. const llm = getModel("cerebras", "gpt-oss-120b");
  496. it("should complete basic text generation", { retry: 3 }, async () => {
  497. await basicTextGeneration(llm);
  498. });
  499. it("should handle tool calling", { retry: 3 }, async () => {
  500. await handleToolCall(llm);
  501. });
  502. it("should handle streaming", { retry: 3 }, async () => {
  503. await handleStreaming(llm);
  504. });
  505. it("should handle thinking mode", { retry: 3 }, async () => {
  506. await handleThinking(llm, { reasoningEffort: "medium" });
  507. });
  508. it("should handle multi-turn with thinking and tools", { retry: 3 }, async () => {
  509. await multiTurn(llm, { reasoningEffort: "medium" });
  510. });
  511. });
  512. describe.skipIf(!hasCloudflareWorkersAICredentials())(
  513. "Cloudflare Workers AI Provider (Kimi K2.6 via OpenAI Completions)",
  514. () => {
  515. const llm = getModel("cloudflare-workers-ai", "@cf/moonshotai/kimi-k2.6");
  516. it("should complete basic text generation", { retry: 3 }, async () => {
  517. await basicTextGeneration(llm);
  518. });
  519. it("should handle tool calling", { retry: 3 }, async () => {
  520. await handleToolCall(llm);
  521. });
  522. it("should handle streaming", { retry: 3 }, async () => {
  523. await handleStreaming(llm);
  524. });
  525. it("should handle thinking mode", { retry: 3 }, async () => {
  526. await handleThinking(llm, { reasoningEffort: "medium" });
  527. });
  528. it("should handle multi-turn with thinking and tools", { retry: 3 }, async () => {
  529. await multiTurn(llm, { reasoningEffort: "medium" });
  530. });
  531. },
  532. );
  533. describe.skipIf(!hasCloudflareAiGatewayCredentials())(
  534. "Cloudflare AI Gateway → Workers AI (Kimi K2.6 via /compat)",
  535. () => {
  536. const llm = getModel("cloudflare-ai-gateway", "workers-ai/@cf/moonshotai/kimi-k2.6");
  537. it("should complete basic text generation", { retry: 3 }, async () => {
  538. await basicTextGeneration(llm);
  539. });
  540. it("should handle tool calling", { retry: 3 }, async () => {
  541. await handleToolCall(llm);
  542. });
  543. it("should handle streaming", { retry: 3 }, async () => {
  544. await handleStreaming(llm);
  545. });
  546. it("should handle thinking mode", { retry: 3 }, async () => {
  547. await handleThinking(llm, { reasoningEffort: "medium" });
  548. });
  549. it("should handle multi-turn with thinking and tools", { retry: 3 }, async () => {
  550. await multiTurn(llm, { reasoningEffort: "medium" });
  551. });
  552. },
  553. );
  554. describe.skipIf(!hasCloudflareAiGatewayCredentials() || !process.env.OPENAI_API_KEY)(
  555. "Cloudflare AI Gateway → OpenAI BYOK (gpt-5.1 via /openai responses)",
  556. () => {
  557. const llm = getModel("cloudflare-ai-gateway", "gpt-5.1");
  558. const options = { headers: { Authorization: `Bearer ${process.env.OPENAI_API_KEY}` } };
  559. const thinkingOptions = {
  560. ...options,
  561. thinkingEnabled: true,
  562. reasoningEffort: "medium",
  563. } satisfies StreamOptionsWithExtras;
  564. it("should complete basic text generation", { retry: 3 }, async () => {
  565. await basicTextGeneration(llm, options);
  566. });
  567. it("should handle tool calling", { retry: 3 }, async () => {
  568. await handleToolCall(llm, options);
  569. });
  570. it("should handle streaming", { retry: 3 }, async () => {
  571. await handleStreaming(llm, options);
  572. });
  573. it("should handle thinking mode", { retry: 3 }, async () => {
  574. await handleThinking(llm, thinkingOptions);
  575. });
  576. it("should handle multi-turn with thinking and tools", { retry: 3 }, async () => {
  577. await multiTurn(llm, thinkingOptions);
  578. });
  579. },
  580. );
  581. describe.skipIf(!hasCloudflareAiGatewayCredentials() || !process.env.ANTHROPIC_API_KEY)(
  582. "Cloudflare AI Gateway → Anthropic BYOK (claude-sonnet-4-5 via /anthropic messages)",
  583. () => {
  584. const llm = getModel("cloudflare-ai-gateway", "claude-sonnet-4-5");
  585. const options = { headers: { Authorization: `Bearer ${process.env.ANTHROPIC_API_KEY}` } };
  586. const thinkingOptions = {
  587. ...options,
  588. thinkingEnabled: true,
  589. reasoningEffort: "high",
  590. } satisfies StreamOptionsWithExtras;
  591. it("should complete basic text generation", { retry: 3 }, async () => {
  592. await basicTextGeneration(llm, options);
  593. });
  594. it("should handle tool calling", { retry: 3 }, async () => {
  595. await handleToolCall(llm, options);
  596. });
  597. it("should handle streaming", { retry: 3 }, async () => {
  598. await handleStreaming(llm, options);
  599. });
  600. it("should handle thinking mode", { retry: 3 }, async () => {
  601. await handleThinking(llm, thinkingOptions);
  602. });
  603. it("should handle multi-turn with thinking and tools", { retry: 3 }, async () => {
  604. await multiTurn(llm, thinkingOptions);
  605. });
  606. },
  607. );
  608. describe.skipIf(!process.env.HF_TOKEN)("Hugging Face Provider (Kimi-K2.5 via OpenAI Completions)", () => {
  609. const llm = getModel("huggingface", "moonshotai/Kimi-K2.5");
  610. it("should complete basic text generation", { retry: 3 }, async () => {
  611. await basicTextGeneration(llm);
  612. });
  613. it("should handle tool calling", { retry: 3 }, async () => {
  614. await handleToolCall(llm);
  615. });
  616. it("should handle streaming", { retry: 3 }, async () => {
  617. await handleStreaming(llm);
  618. });
  619. it("should handle thinking mode", { retry: 3 }, async () => {
  620. await handleThinking(llm, { reasoningEffort: "medium" });
  621. });
  622. it("should handle multi-turn with thinking and tools", { retry: 3 }, async () => {
  623. await multiTurn(llm, { reasoningEffort: "medium" });
  624. });
  625. });
  626. describe.skipIf(!process.env.TOGETHER_API_KEY)("Together AI Provider (Kimi-K2.6 via OpenAI Completions)", () => {
  627. const llm = getModel("together", "moonshotai/Kimi-K2.6");
  628. it("should complete basic text generation", { retry: 3 }, async () => {
  629. await basicTextGeneration(llm);
  630. });
  631. it("should handle tool calling", { retry: 3 }, async () => {
  632. await handleToolCall(llm);
  633. });
  634. it("should handle streaming", { retry: 3 }, async () => {
  635. await handleStreaming(llm);
  636. });
  637. it("should handle thinking mode", { retry: 3 }, async () => {
  638. await handleThinking(llm, { reasoningEffort: "high" });
  639. });
  640. it("should handle multi-turn with thinking and tools", { retry: 3 }, async () => {
  641. await multiTurn(llm, { reasoningEffort: "high" });
  642. });
  643. it("should handle image input", { retry: 3 }, async () => {
  644. await handleImage(llm);
  645. });
  646. });
  647. describe.skipIf(!process.env.NVIDIA_API_KEY)("NVIDIA NIM Provider (Nemotron 3 Super via OpenAI Completions)", () => {
  648. const llm = getModel("nvidia", "nvidia/nemotron-3-super-120b-a12b");
  649. it("should complete basic text generation", { retry: 3 }, async () => {
  650. await basicTextGeneration(llm);
  651. });
  652. it("should handle tool calling", { retry: 3 }, async () => {
  653. await handleToolCall(llm);
  654. });
  655. it("should handle streaming", { retry: 3 }, async () => {
  656. await handleStreaming(llm);
  657. });
  658. it("should handle thinking mode", { retry: 3 }, async () => {
  659. await handleThinking(llm, { reasoningEffort: "high" });
  660. });
  661. it("should handle multi-turn with thinking and tools", { retry: 3 }, async () => {
  662. await multiTurn(llm, { reasoningEffort: "high" });
  663. });
  664. });
  665. describe.skipIf(!process.env.OPENROUTER_API_KEY)("OpenRouter Provider (glm-4.5v via OpenAI Completions)", () => {
  666. const llm = getModel("openrouter", "z-ai/glm-4.5v");
  667. it("should complete basic text generation", { retry: 3 }, async () => {
  668. await basicTextGeneration(llm);
  669. });
  670. it("should handle tool calling", { retry: 3 }, async () => {
  671. await handleToolCall(llm);
  672. });
  673. it("should handle streaming", { retry: 3 }, async () => {
  674. await handleStreaming(llm);
  675. });
  676. it("should handle thinking mode", { retry: 3 }, async () => {
  677. await handleThinking(llm, { reasoningEffort: "medium" });
  678. });
  679. it("should handle multi-turn with thinking and tools", { retry: 2 }, async () => {
  680. await multiTurn(llm, { reasoningEffort: "medium" });
  681. });
  682. it("should handle image input", { retry: 3 }, async () => {
  683. await handleImage(llm);
  684. });
  685. });
  686. describe.skipIf(!process.env.AI_GATEWAY_API_KEY)(
  687. "Vercel AI Gateway Provider (google/gemini-2.5-flash via Anthropic Messages)",
  688. () => {
  689. const llm = getModel("vercel-ai-gateway", "google/gemini-2.5-flash");
  690. it("should complete basic text generation", { retry: 3 }, async () => {
  691. await basicTextGeneration(llm);
  692. });
  693. it("should handle tool calling", { retry: 3 }, async () => {
  694. await handleToolCall(llm);
  695. });
  696. it("should handle streaming", { retry: 3 }, async () => {
  697. await handleStreaming(llm);
  698. });
  699. it("should handle image input", { retry: 3 }, async () => {
  700. await handleImage(llm);
  701. });
  702. it("should handle multi-turn with tools", { retry: 3 }, async () => {
  703. await multiTurn(llm);
  704. });
  705. },
  706. );
  707. describe.skipIf(!process.env.AI_GATEWAY_API_KEY)(
  708. "Vercel AI Gateway Provider (anthropic/claude-opus-4.5 via Anthropic Messages)",
  709. () => {
  710. const llm = getModel("vercel-ai-gateway", "anthropic/claude-opus-4.5");
  711. it("should complete basic text generation", { retry: 3 }, async () => {
  712. await basicTextGeneration(llm);
  713. });
  714. it("should handle tool calling", { retry: 3 }, async () => {
  715. await handleToolCall(llm);
  716. });
  717. it("should handle streaming", { retry: 3 }, async () => {
  718. await handleStreaming(llm);
  719. });
  720. it("should handle image input", { retry: 3 }, async () => {
  721. await handleImage(llm);
  722. });
  723. it("should handle multi-turn with tools", { retry: 3 }, async () => {
  724. await multiTurn(llm);
  725. });
  726. },
  727. );
  728. describe.skipIf(!process.env.AI_GATEWAY_API_KEY)(
  729. "Vercel AI Gateway Provider (openai/gpt-5.1-codex-max via Anthropic Messages)",
  730. () => {
  731. const llm = getModel("vercel-ai-gateway", "openai/gpt-5.1-codex-max");
  732. it("should complete basic text generation", { retry: 3 }, async () => {
  733. await basicTextGeneration(llm);
  734. });
  735. it("should handle tool calling", { retry: 3 }, async () => {
  736. await handleToolCall(llm);
  737. });
  738. it("should handle streaming", { retry: 3 }, async () => {
  739. await handleStreaming(llm);
  740. });
  741. it("should handle image input", { retry: 3 }, async () => {
  742. await handleImage(llm);
  743. });
  744. it("should handle multi-turn with tools", { retry: 3 }, async () => {
  745. await multiTurn(llm);
  746. });
  747. },
  748. );
  749. describe.skipIf(!process.env.ZAI_API_KEY)("zAI Provider (glm-5.1 via OpenAI Completions)", () => {
  750. const llm = getModel("zai", "glm-5.1");
  751. it("should complete basic text generation", { retry: 3 }, async () => {
  752. await basicTextGeneration(llm);
  753. });
  754. it("should handle tool calling", { retry: 3 }, async () => {
  755. await handleToolCall(llm);
  756. });
  757. it("should handle streaming", { retry: 3 }, async () => {
  758. await handleStreaming(llm);
  759. });
  760. it("should handle thinking mode", { retry: 3 }, async () => {
  761. await handleThinking(llm, { reasoningEffort: "medium" });
  762. });
  763. it("should handle multi-turn with thinking and tools", { retry: 3 }, async () => {
  764. await multiTurn(llm, { reasoningEffort: "medium" });
  765. });
  766. it("should handle image input", { retry: 3 }, async () => {
  767. await handleImage(llm);
  768. });
  769. });
  770. describe.skipIf(!process.env.MISTRAL_API_KEY)("Mistral Provider (devstral-medium-latest)", () => {
  771. const llm = getModel("mistral", "devstral-medium-latest");
  772. it("should complete basic text generation", { retry: 3 }, async () => {
  773. await basicTextGeneration(llm);
  774. });
  775. it("should handle tool calling", { retry: 3 }, async () => {
  776. await handleToolCall(llm);
  777. });
  778. it("should handle streaming", { retry: 3 }, async () => {
  779. await handleStreaming(llm);
  780. });
  781. it("should handle thinking mode", { retry: 3 }, async () => {
  782. const llm = getModel("mistral", "magistral-medium-latest");
  783. await handleThinking(llm, { promptMode: "reasoning" });
  784. });
  785. it("should handle multi-turn with thinking and tools", { retry: 3 }, async () => {
  786. const llm = getModel("mistral", "magistral-medium-latest");
  787. await multiTurn(llm, { promptMode: "reasoning" });
  788. });
  789. });
  790. describe.skipIf(!process.env.MISTRAL_API_KEY)("Mistral Provider (pixtral-12b with image support)", () => {
  791. const llm = getModel("mistral", "pixtral-12b");
  792. it("should complete basic text generation", { retry: 3 }, async () => {
  793. await basicTextGeneration(llm);
  794. });
  795. it("should handle tool calling", { retry: 3 }, async () => {
  796. await handleToolCall(llm);
  797. });
  798. it("should handle streaming", { retry: 3 }, async () => {
  799. await handleStreaming(llm);
  800. });
  801. it("should handle image input", { retry: 3 }, async () => {
  802. await handleImage(llm);
  803. });
  804. });
  805. describe.skipIf(!process.env.MINIMAX_API_KEY)("MiniMax Provider (MiniMax-M2.7 via Anthropic Messages)", () => {
  806. const llm = getModel("minimax", "MiniMax-M2.7");
  807. it("should complete basic text generation", { retry: 3 }, async () => {
  808. await basicTextGeneration(llm);
  809. });
  810. it("should handle tool calling", { retry: 3 }, async () => {
  811. await handleToolCall(llm);
  812. });
  813. it("should handle streaming", { retry: 3 }, async () => {
  814. await handleStreaming(llm);
  815. });
  816. it("should handle thinking mode", { retry: 3 }, async () => {
  817. await handleThinking(llm, { thinkingEnabled: true, thinkingBudgetTokens: 2048 });
  818. });
  819. it("should handle multi-turn with thinking and tools", { retry: 3 }, async () => {
  820. await multiTurn(llm, { thinkingEnabled: true, thinkingBudgetTokens: 2048 });
  821. });
  822. });
  823. describe.skipIf(!process.env.KIMI_API_KEY)(
  824. "Kimi For Coding Provider (kimi-k2-thinking via Anthropic Messages)",
  825. () => {
  826. const llm = getModel("kimi-coding", "kimi-k2-thinking");
  827. it("should complete basic text generation", { retry: 3 }, async () => {
  828. await basicTextGeneration(llm);
  829. });
  830. it("should handle tool calling", { retry: 3 }, async () => {
  831. await handleToolCall(llm);
  832. });
  833. it("should handle streaming", { retry: 3 }, async () => {
  834. await handleStreaming(llm);
  835. });
  836. it("should handle thinking mode", { retry: 3 }, async () => {
  837. await handleThinking(llm, { thinkingEnabled: true, thinkingBudgetTokens: 2048 });
  838. });
  839. it("should handle multi-turn with thinking and tools", { retry: 3 }, async () => {
  840. await multiTurn(llm, { thinkingEnabled: true, thinkingBudgetTokens: 2048 });
  841. });
  842. },
  843. );
  844. describe.skipIf(!process.env.XIAOMI_API_KEY)(
  845. "Xiaomi MiMo (API billing) Provider (Xiaomi MiMo-V2.5-Pro via Anthropic Messages)",
  846. () => {
  847. const llm = getModel("xiaomi", "mimo-v2.5-pro");
  848. const thinkingOptions = {
  849. thinkingEnabled: true,
  850. reasoningEffort: "high",
  851. } satisfies StreamOptionsWithExtras;
  852. it("should complete basic text generation", { retry: 3 }, async () => {
  853. await basicTextGeneration(llm);
  854. });
  855. it("should handle tool calling", { retry: 3 }, async () => {
  856. await handleToolCall(llm);
  857. });
  858. it("should handle streaming", { retry: 3 }, async () => {
  859. await handleStreaming(llm);
  860. });
  861. it("should handle thinking mode", { retry: 3 }, async () => {
  862. await handleThinking(llm, thinkingOptions);
  863. });
  864. it("should handle multi-turn with thinking and tools", { retry: 3 }, async () => {
  865. await multiTurn(llm, thinkingOptions);
  866. });
  867. },
  868. );
  869. describe.skipIf(!process.env.XIAOMI_TOKEN_PLAN_CN_API_KEY)(
  870. "Xiaomi MiMo Token Plan Provider (Xiaomi MiMo-V2.5-Pro via Anthropic Messages, CN region)",
  871. () => {
  872. const llm = getModel("xiaomi-token-plan-cn", "mimo-v2.5-pro");
  873. const thinkingOptions = {
  874. thinkingEnabled: true,
  875. reasoningEffort: "high",
  876. } satisfies StreamOptionsWithExtras;
  877. it("should complete basic text generation", { retry: 3 }, async () => {
  878. await basicTextGeneration(llm);
  879. });
  880. it("should handle tool calling", { retry: 3 }, async () => {
  881. await handleToolCall(llm);
  882. });
  883. it("should handle streaming", { retry: 3 }, async () => {
  884. await handleStreaming(llm);
  885. });
  886. it("should handle thinking mode", { retry: 3 }, async () => {
  887. await handleThinking(llm, thinkingOptions);
  888. });
  889. it("should handle multi-turn with thinking and tools", { retry: 3 }, async () => {
  890. await multiTurn(llm, thinkingOptions);
  891. });
  892. },
  893. );
  894. describe.skipIf(!process.env.XIAOMI_TOKEN_PLAN_AMS_API_KEY)(
  895. "Xiaomi MiMo Token Plan Provider (Xiaomi MiMo-V2.5-Pro via Anthropic Messages, AMS region)",
  896. () => {
  897. const llm = getModel("xiaomi-token-plan-ams", "mimo-v2.5-pro");
  898. const thinkingOptions = {
  899. thinkingEnabled: true,
  900. reasoningEffort: "high",
  901. } satisfies StreamOptionsWithExtras;
  902. it("should complete basic text generation", { retry: 3 }, async () => {
  903. await basicTextGeneration(llm);
  904. });
  905. it("should handle tool calling", { retry: 3 }, async () => {
  906. await handleToolCall(llm);
  907. });
  908. it("should handle streaming", { retry: 3 }, async () => {
  909. await handleStreaming(llm);
  910. });
  911. it("should handle thinking mode", { retry: 3 }, async () => {
  912. await handleThinking(llm, thinkingOptions);
  913. });
  914. it("should handle multi-turn with thinking and tools", { retry: 3 }, async () => {
  915. await multiTurn(llm, thinkingOptions);
  916. });
  917. },
  918. );
  919. describe.skipIf(!process.env.XIAOMI_TOKEN_PLAN_SGP_API_KEY)(
  920. "Xiaomi MiMo Token Plan Provider (Xiaomi MiMo-V2.5-Pro via Anthropic Messages, SGP region)",
  921. () => {
  922. const llm = getModel("xiaomi-token-plan-sgp", "mimo-v2.5-pro");
  923. const thinkingOptions = {
  924. thinkingEnabled: true,
  925. reasoningEffort: "high",
  926. } satisfies StreamOptionsWithExtras;
  927. it("should complete basic text generation", { retry: 3 }, async () => {
  928. await basicTextGeneration(llm);
  929. });
  930. it("should handle tool calling", { retry: 3 }, async () => {
  931. await handleToolCall(llm);
  932. });
  933. it("should handle streaming", { retry: 3 }, async () => {
  934. await handleStreaming(llm);
  935. });
  936. it("should handle thinking mode", { retry: 3 }, async () => {
  937. await handleThinking(llm, thinkingOptions);
  938. });
  939. it("should handle multi-turn with thinking and tools", { retry: 3 }, async () => {
  940. await multiTurn(llm, thinkingOptions);
  941. });
  942. },
  943. );
  944. describe.skipIf(!process.env.ANT_LING_API_KEY)("Ant Ling Provider (Ling 2.6 Flash via OpenAI Completions)", () => {
  945. const llm = getModel("ant-ling", "Ling-2.6-flash");
  946. it("should complete basic text generation", { retry: 3 }, async () => {
  947. await basicTextGeneration(llm);
  948. });
  949. it("should handle tool calling", { retry: 3 }, async () => {
  950. await handleToolCall(llm);
  951. });
  952. it("should handle streaming", { retry: 3 }, async () => {
  953. await handleStreaming(llm);
  954. });
  955. it("should handle thinking mode", { retry: 3 }, async () => {
  956. const ringModel = getModel("ant-ling", "Ring-2.6-1T");
  957. await handleThinking(ringModel, { reasoningEffort: "high" });
  958. });
  959. });
  960. // =========================================================================
  961. // OAuth-based providers (credentials from ~/.pi/agent/oauth.json)
  962. // Tokens are resolved at module level (see oauthTokens above)
  963. // =========================================================================
  964. describe("Anthropic OAuth Provider (claude-sonnet-4-6)", () => {
  965. const model = getModel("anthropic", "claude-sonnet-4-6");
  966. it.skipIf(!anthropicOAuthToken)("should complete basic text generation", { retry: 3 }, async () => {
  967. await basicTextGeneration(model, { apiKey: anthropicOAuthToken });
  968. });
  969. it.skipIf(!anthropicOAuthToken)("should handle tool calling", { retry: 3 }, async () => {
  970. await handleToolCall(model, { apiKey: anthropicOAuthToken });
  971. });
  972. it.skipIf(!anthropicOAuthToken)("should handle streaming", { retry: 3 }, async () => {
  973. await handleStreaming(model, { apiKey: anthropicOAuthToken });
  974. });
  975. it.skipIf(!anthropicOAuthToken)("should handle thinking", { retry: 3 }, async () => {
  976. await handleThinking(model, { apiKey: anthropicOAuthToken, thinkingEnabled: true });
  977. });
  978. it.skipIf(!anthropicOAuthToken)("should handle multi-turn with thinking and tools", { retry: 3 }, async () => {
  979. await multiTurn(model, { apiKey: anthropicOAuthToken, thinkingEnabled: true });
  980. });
  981. it.skipIf(!anthropicOAuthToken)("should handle image input", { retry: 3 }, async () => {
  982. await handleImage(model, { apiKey: anthropicOAuthToken });
  983. });
  984. });
  985. describe("Anthropic OAuth Provider (claude-opus-4-6 with adaptive thinking)", () => {
  986. const model = getModel("anthropic", "claude-opus-4-6");
  987. it.skipIf(!anthropicOAuthToken)("should complete basic text generation", { retry: 3 }, async () => {
  988. await basicTextGeneration(model, { apiKey: anthropicOAuthToken });
  989. });
  990. it.skipIf(!anthropicOAuthToken)("should handle tool calling", { retry: 3 }, async () => {
  991. await handleToolCall(model, { apiKey: anthropicOAuthToken });
  992. });
  993. it.skipIf(!anthropicOAuthToken)("should handle streaming", { retry: 3 }, async () => {
  994. await handleStreaming(model, { apiKey: anthropicOAuthToken });
  995. });
  996. it.skipIf(!anthropicOAuthToken)("should handle adaptive thinking with effort high", { retry: 3 }, async () => {
  997. await handleThinking(model, { apiKey: anthropicOAuthToken, thinkingEnabled: true, effort: "high" });
  998. });
  999. it.skipIf(!anthropicOAuthToken)("should handle adaptive thinking with effort medium", { retry: 3 }, async () => {
  1000. await handleThinking(model, { apiKey: anthropicOAuthToken, thinkingEnabled: true, effort: "medium" });
  1001. });
  1002. it.skipIf(!anthropicOAuthToken)(
  1003. "should handle multi-turn with adaptive thinking and tools",
  1004. { retry: 3 },
  1005. async () => {
  1006. await multiTurn(model, { apiKey: anthropicOAuthToken, thinkingEnabled: true, effort: "high" });
  1007. },
  1008. );
  1009. it.skipIf(!anthropicOAuthToken)("should handle image input", { retry: 3 }, async () => {
  1010. await handleImage(model, { apiKey: anthropicOAuthToken });
  1011. });
  1012. });
  1013. describe("GitHub Copilot Provider (gpt-5.3-codex via OpenAI Completions)", () => {
  1014. const llm = getModel("github-copilot", "gpt-5.3-codex");
  1015. it.skipIf(!githubCopilotToken)("should complete basic text generation", { retry: 3 }, async () => {
  1016. await basicTextGeneration(llm, { apiKey: githubCopilotToken });
  1017. });
  1018. it.skipIf(!githubCopilotToken)("should handle tool calling", { retry: 3 }, async () => {
  1019. await handleToolCall(llm, { apiKey: githubCopilotToken });
  1020. });
  1021. it.skipIf(!githubCopilotToken)("should handle streaming", { retry: 3 }, async () => {
  1022. await handleStreaming(llm, { apiKey: githubCopilotToken });
  1023. });
  1024. it.skipIf(!githubCopilotToken)("should handle thinking", { retry: 2 }, async () => {
  1025. const thinkingModel = getModel("github-copilot", "gpt-5-mini");
  1026. await handleThinking(thinkingModel, { apiKey: githubCopilotToken, reasoningEffort: "high" });
  1027. });
  1028. it.skipIf(!githubCopilotToken)("should handle multi-turn with thinking and tools", { retry: 3 }, async () => {
  1029. const thinkingModel = getModel("github-copilot", "gpt-5-mini");
  1030. await multiTurn(thinkingModel, { apiKey: githubCopilotToken, reasoningEffort: "high" });
  1031. });
  1032. it.skipIf(!githubCopilotToken)("should handle image input", { retry: 3 }, async () => {
  1033. await handleImage(llm, { apiKey: githubCopilotToken });
  1034. });
  1035. });
  1036. describe("GitHub Copilot Provider (claude-sonnet-4 via Anthropic Messages)", () => {
  1037. const llm = getModel("github-copilot", "claude-sonnet-4.6");
  1038. it.skipIf(!githubCopilotToken)("should complete basic text generation", { retry: 3 }, async () => {
  1039. await basicTextGeneration(llm, { apiKey: githubCopilotToken });
  1040. });
  1041. it.skipIf(!githubCopilotToken)("should handle tool calling", { retry: 3 }, async () => {
  1042. await handleToolCall(llm, { apiKey: githubCopilotToken });
  1043. });
  1044. it.skipIf(!githubCopilotToken)("should handle streaming", { retry: 3 }, async () => {
  1045. await handleStreaming(llm, { apiKey: githubCopilotToken });
  1046. });
  1047. it.skipIf(!githubCopilotToken)("should handle thinking", { retry: 2 }, async () => {
  1048. await handleThinking(llm, { apiKey: githubCopilotToken, thinkingEnabled: true });
  1049. });
  1050. it.skipIf(!githubCopilotToken)("should handle multi-turn with thinking and tools", { retry: 3 }, async () => {
  1051. await multiTurn(llm, { apiKey: githubCopilotToken, thinkingEnabled: true });
  1052. });
  1053. it.skipIf(!githubCopilotToken)("should handle image input", { retry: 3 }, async () => {
  1054. await handleImage(llm, { apiKey: githubCopilotToken });
  1055. });
  1056. });
  1057. describe("OpenAI Codex Provider (gpt-5.4)", () => {
  1058. const llm = getModel("openai-codex", "gpt-5.4");
  1059. it.skipIf(!openaiCodexToken)("should complete basic text generation", { retry: 3 }, async () => {
  1060. await basicTextGeneration(llm, { apiKey: openaiCodexToken });
  1061. });
  1062. it.skipIf(!openaiCodexToken)("should handle tool calling", { retry: 3 }, async () => {
  1063. await handleToolCall(llm, { apiKey: openaiCodexToken });
  1064. });
  1065. it.skipIf(!openaiCodexToken)("should handle streaming", { retry: 3 }, async () => {
  1066. await handleStreaming(llm, { apiKey: openaiCodexToken });
  1067. });
  1068. it.skipIf(!openaiCodexToken)("should handle thinking", { retry: 3 }, async () => {
  1069. await handleThinking(llm, { apiKey: openaiCodexToken, reasoningEffort: "high" });
  1070. });
  1071. it.skipIf(!openaiCodexToken)("should handle multi-turn with thinking and tools", { retry: 3 }, async () => {
  1072. await multiTurn(llm, { apiKey: openaiCodexToken });
  1073. });
  1074. it.skipIf(!openaiCodexToken)("should handle image input", { retry: 3 }, async () => {
  1075. await handleImage(llm, { apiKey: openaiCodexToken });
  1076. });
  1077. });
  1078. describe("OpenAI Codex Provider (gpt-5.5)", () => {
  1079. const llm = getModel("openai-codex", "gpt-5.5");
  1080. it.skipIf(!openaiCodexToken)("should complete basic text generation", { retry: 3 }, async () => {
  1081. await basicTextGeneration(llm, { apiKey: openaiCodexToken });
  1082. });
  1083. it.skipIf(!openaiCodexToken)("should handle tool calling", { retry: 3 }, async () => {
  1084. await handleToolCall(llm, { apiKey: openaiCodexToken });
  1085. });
  1086. it.skipIf(!openaiCodexToken)("should handle streaming", { retry: 3 }, async () => {
  1087. await handleStreaming(llm, { apiKey: openaiCodexToken });
  1088. });
  1089. it.skipIf(!openaiCodexToken)("should handle thinking with reasoningEffort xhigh", { retry: 3 }, async () => {
  1090. await handleThinking(llm, { apiKey: openaiCodexToken, reasoningEffort: "xhigh" });
  1091. });
  1092. it.skipIf(!openaiCodexToken)("should handle multi-turn with thinking and tools", { retry: 3 }, async () => {
  1093. await multiTurn(llm, { apiKey: openaiCodexToken, reasoningEffort: "xhigh" });
  1094. });
  1095. it.skipIf(!openaiCodexToken)("should handle image input", { retry: 3 }, async () => {
  1096. await handleImage(llm, { apiKey: openaiCodexToken });
  1097. });
  1098. });
  1099. describe("OpenAI Codex Provider (gpt-5.5 via WebSocket)", () => {
  1100. const llm = getModel("openai-codex", "gpt-5.5");
  1101. const wsOptions = { apiKey: openaiCodexToken, transport: "websocket" as const };
  1102. it.skipIf(!openaiCodexToken)("should complete basic text generation", { retry: 3 }, async () => {
  1103. await basicTextGeneration(llm, wsOptions);
  1104. });
  1105. it.skipIf(!openaiCodexToken)("should handle tool calling", { retry: 3 }, async () => {
  1106. await handleToolCall(llm, wsOptions);
  1107. });
  1108. it.skipIf(!openaiCodexToken)("should handle streaming", { retry: 3 }, async () => {
  1109. await handleStreaming(llm, wsOptions);
  1110. });
  1111. it.skipIf(!openaiCodexToken)("should handle thinking with reasoningEffort xhigh", { retry: 3 }, async () => {
  1112. await handleThinking(llm, { ...wsOptions, reasoningEffort: "xhigh" });
  1113. });
  1114. it.skipIf(!openaiCodexToken)("should handle multi-turn with thinking and tools", { retry: 3 }, async () => {
  1115. await multiTurn(llm, { ...wsOptions, reasoningEffort: "xhigh" });
  1116. });
  1117. it.skipIf(!openaiCodexToken)("should handle image input", { retry: 3 }, async () => {
  1118. await handleImage(llm, wsOptions);
  1119. });
  1120. });
  1121. describe.skipIf(!hasBedrockCredentials())("Amazon Bedrock Provider (claude-sonnet-4-5)", () => {
  1122. const llm = getModel("amazon-bedrock", "global.anthropic.claude-sonnet-4-5-20250929-v1:0");
  1123. it("should complete basic text generation", { retry: 3 }, async () => {
  1124. await basicTextGeneration(llm);
  1125. });
  1126. it("should handle tool calling", { retry: 3 }, async () => {
  1127. await handleToolCall(llm);
  1128. });
  1129. it("should handle streaming", { retry: 3 }, async () => {
  1130. await handleStreaming(llm);
  1131. });
  1132. it("should handle thinking", { retry: 3 }, async () => {
  1133. await handleThinking(llm, { reasoning: "medium" });
  1134. });
  1135. it("should handle multi-turn with thinking and tools", { retry: 3 }, async () => {
  1136. await multiTurn(llm, { reasoning: "high" });
  1137. });
  1138. it("should handle image input", { retry: 3 }, async () => {
  1139. await handleImage(llm);
  1140. });
  1141. });
  1142. describe.skipIf(!hasBedrockCredentials())("Amazon Bedrock Provider (claude-opus-4-6 interleaved thinking)", () => {
  1143. const llm = getModel("amazon-bedrock", "global.anthropic.claude-opus-4-6-v1");
  1144. it("should use adaptive thinking without anthropic_beta", { retry: 3 }, async () => {
  1145. let capturedPayload: unknown;
  1146. const response = await complete(
  1147. llm,
  1148. {
  1149. systemPrompt: "You are a helpful assistant that uses tools when asked.",
  1150. messages: [
  1151. {
  1152. role: "user",
  1153. content: "Think first, then calculate 15 + 27 using the math_operation tool.",
  1154. timestamp: Date.now(),
  1155. },
  1156. ],
  1157. tools: [calculatorTool],
  1158. },
  1159. {
  1160. reasoning: "xhigh",
  1161. interleavedThinking: true,
  1162. onPayload: (payload) => {
  1163. capturedPayload = payload;
  1164. },
  1165. },
  1166. );
  1167. expect(response.stopReason, `Error: ${response.errorMessage}`).not.toBe("error");
  1168. expect(capturedPayload).toBeTruthy();
  1169. const payload = capturedPayload as {
  1170. additionalModelRequestFields?: {
  1171. thinking?: { type?: string; display?: string };
  1172. output_config?: { effort?: string };
  1173. anthropic_beta?: string[];
  1174. };
  1175. };
  1176. expect(payload.additionalModelRequestFields?.thinking).toEqual({
  1177. type: "adaptive",
  1178. display: "summarized",
  1179. });
  1180. expect(payload.additionalModelRequestFields?.output_config).toEqual({ effort: "max" });
  1181. expect(payload.additionalModelRequestFields?.anthropic_beta).toBeUndefined();
  1182. });
  1183. it("should pass requestMetadata to the SDK payload", { retry: 3 }, async () => {
  1184. const llmSonnet = getModel("amazon-bedrock", "global.anthropic.claude-sonnet-4-5-20250929-v1:0");
  1185. let capturedPayload: unknown;
  1186. const metadata = { app: "pi-test", env: "ci" };
  1187. const response = await complete(
  1188. llmSonnet,
  1189. {
  1190. messages: [
  1191. {
  1192. role: "user",
  1193. content: "Say hi.",
  1194. timestamp: Date.now(),
  1195. },
  1196. ],
  1197. },
  1198. {
  1199. requestMetadata: metadata,
  1200. onPayload: (payload) => {
  1201. capturedPayload = payload;
  1202. },
  1203. },
  1204. );
  1205. expect(response.stopReason, `Error: ${response.errorMessage}`).not.toBe("error");
  1206. expect(capturedPayload).toBeTruthy();
  1207. expect((capturedPayload as { requestMetadata?: unknown }).requestMetadata).toEqual(metadata);
  1208. });
  1209. it("should omit requestMetadata from payload when not provided", { retry: 3 }, async () => {
  1210. const llmSonnet = getModel("amazon-bedrock", "global.anthropic.claude-sonnet-4-5-20250929-v1:0");
  1211. let capturedPayload: unknown;
  1212. const response = await complete(
  1213. llmSonnet,
  1214. {
  1215. messages: [
  1216. {
  1217. role: "user",
  1218. content: "Say hi.",
  1219. timestamp: Date.now(),
  1220. },
  1221. ],
  1222. },
  1223. {
  1224. onPayload: (payload) => {
  1225. capturedPayload = payload;
  1226. },
  1227. },
  1228. );
  1229. expect(response.stopReason, `Error: ${response.errorMessage}`).not.toBe("error");
  1230. expect(capturedPayload).toBeTruthy();
  1231. expect("requestMetadata" in (capturedPayload as object)).toBe(false);
  1232. });
  1233. });
  1234. // Check if ollama is installed and local LLM tests are enabled
  1235. let ollamaInstalled = false;
  1236. if (!process.env.PI_NO_LOCAL_LLM) {
  1237. try {
  1238. execSync("which ollama", { stdio: "ignore" });
  1239. ollamaInstalled = true;
  1240. } catch {
  1241. ollamaInstalled = false;
  1242. }
  1243. }
  1244. describe.skipIf(!ollamaInstalled)("Ollama Provider (gpt-oss-20b via OpenAI Completions)", () => {
  1245. let llm: Model<"openai-completions">;
  1246. let ollamaProcess: ChildProcess | null = null;
  1247. beforeAll(async () => {
  1248. // Check if model is available, if not pull it
  1249. try {
  1250. execSync("ollama list | grep -q 'gpt-oss:20b'", { stdio: "ignore" });
  1251. } catch {
  1252. console.log("Pulling gpt-oss:20b model for Ollama tests...");
  1253. try {
  1254. execSync("ollama pull gpt-oss:20b", { stdio: "inherit" });
  1255. } catch (_e) {
  1256. console.warn("Failed to pull gpt-oss:20b model, tests will be skipped");
  1257. return;
  1258. }
  1259. }
  1260. // Start ollama server
  1261. ollamaProcess = spawn("ollama", ["serve"], {
  1262. detached: false,
  1263. stdio: "ignore",
  1264. });
  1265. // Wait for server to be ready
  1266. await new Promise<void>((resolve) => {
  1267. const checkServer = async () => {
  1268. try {
  1269. const response = await fetch("http://localhost:11434/api/tags");
  1270. if (response.ok) {
  1271. resolve();
  1272. } else {
  1273. setTimeout(checkServer, 500);
  1274. }
  1275. } catch {
  1276. setTimeout(checkServer, 500);
  1277. }
  1278. };
  1279. setTimeout(checkServer, 1000); // Initial delay
  1280. });
  1281. llm = {
  1282. id: "gpt-oss:20b",
  1283. api: "openai-completions",
  1284. provider: "ollama",
  1285. baseUrl: "http://localhost:11434/v1",
  1286. reasoning: true,
  1287. input: ["text"],
  1288. contextWindow: 128000,
  1289. maxTokens: 16000,
  1290. cost: {
  1291. input: 0,
  1292. output: 0,
  1293. cacheRead: 0,
  1294. cacheWrite: 0,
  1295. },
  1296. name: "Ollama GPT-OSS 20B",
  1297. };
  1298. }, 30000); // 30 second timeout for setup
  1299. afterAll(() => {
  1300. // Kill ollama server
  1301. if (ollamaProcess) {
  1302. ollamaProcess.kill("SIGTERM");
  1303. ollamaProcess = null;
  1304. }
  1305. });
  1306. it("should complete basic text generation", { retry: 3 }, async () => {
  1307. await basicTextGeneration(llm, { apiKey: "test" });
  1308. });
  1309. it("should handle tool calling", { retry: 3 }, async () => {
  1310. await handleToolCall(llm, { apiKey: "test" });
  1311. });
  1312. it("should handle streaming", { retry: 3 }, async () => {
  1313. await handleStreaming(llm, { apiKey: "test" });
  1314. });
  1315. it("should handle thinking mode", { retry: 3 }, async () => {
  1316. await handleThinking(llm, { apiKey: "test", reasoningEffort: "medium" });
  1317. });
  1318. it("should handle multi-turn with thinking and tools", { retry: 3 }, async () => {
  1319. await multiTurn(llm, { apiKey: "test", reasoningEffort: "medium" });
  1320. });
  1321. });
  1322. });