tokens.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. import { describe, expect, it } from "vitest";
  2. import { getModel, getModels } from "../src/models.ts";
  3. import { stream } from "../src/stream.ts";
  4. import type { Api, Context, Model, StreamOptions } from "../src/types.ts";
  5. type StreamOptionsWithExtras = StreamOptions & Record<string, unknown>;
  6. import { hasAzureOpenAICredentials, resolveAzureDeploymentName } from "./azure-utils.ts";
  7. import { hasBedrockCredentials } from "./bedrock-utils.ts";
  8. import { hasCloudflareAiGatewayCredentials, hasCloudflareWorkersAICredentials } from "./cloudflare-utils.ts";
  9. import { resolveApiKey } from "./oauth.ts";
  10. // Resolve OAuth tokens at module level (async, runs before tests)
  11. const oauthTokens = await Promise.all([
  12. resolveApiKey("anthropic"),
  13. resolveApiKey("github-copilot"),
  14. resolveApiKey("openai-codex"),
  15. ]);
  16. const [anthropicOAuthToken, githubCopilotToken, openaiCodexToken] = oauthTokens;
  17. async function testTokensOnAbort<TApi extends Api>(llm: Model<TApi>, options: StreamOptionsWithExtras = {}) {
  18. const context: Context = {
  19. messages: [
  20. {
  21. role: "user",
  22. content: "Write a long poem with 20 stanzas about the beauty of nature.",
  23. timestamp: Date.now(),
  24. },
  25. ],
  26. systemPrompt: "You are a helpful assistant.",
  27. };
  28. const controller = new AbortController();
  29. const response = stream(llm, context, { ...options, signal: controller.signal });
  30. let abortFired = false;
  31. let text = "";
  32. for await (const event of response) {
  33. if (!abortFired && (event.type === "text_delta" || event.type === "thinking_delta")) {
  34. text += event.delta;
  35. if (text.length >= 1000) {
  36. abortFired = true;
  37. controller.abort();
  38. }
  39. }
  40. }
  41. const msg = await response.result();
  42. expect(msg.stopReason).toBe("aborted");
  43. // OpenAI providers, OpenAI Codex, zai, and Amazon Bedrock only send usage in the final chunk,
  44. // so when aborted they have no token stats. Anthropic and Google send usage information early in the stream.
  45. // MiniMax and Kimi report input tokens but not output tokens differently on aborted requests.
  46. if (
  47. llm.api === "openai-completions" ||
  48. llm.api === "mistral-conversations" ||
  49. llm.api === "openai-responses" ||
  50. llm.api === "azure-openai-responses" ||
  51. llm.api === "openai-codex-responses" ||
  52. llm.provider === "zai" ||
  53. llm.provider === "amazon-bedrock" ||
  54. llm.provider === "vercel-ai-gateway"
  55. ) {
  56. expect(msg.usage.input).toBe(0);
  57. expect(msg.usage.output).toBe(0);
  58. } else if (llm.provider === "minimax") {
  59. // MiniMax M2.7 does not report token usage for aborted requests.
  60. expect(msg.usage.input).toBe(0);
  61. expect(msg.usage.output).toBe(0);
  62. } else if (llm.provider === "kimi-coding") {
  63. // Kimi reports input tokens early but output tokens only in the final chunk.
  64. expect(msg.usage.input).toBeGreaterThan(0);
  65. expect(msg.usage.output).toBe(0);
  66. } else {
  67. expect(msg.usage.input).toBeGreaterThan(0);
  68. expect(msg.usage.output).toBeGreaterThan(0);
  69. // Some providers (Copilot) have zero cost rates
  70. if (llm.cost.input > 0) {
  71. expect(msg.usage.cost.input).toBeGreaterThan(0);
  72. expect(msg.usage.cost.total).toBeGreaterThan(0);
  73. }
  74. }
  75. }
  76. describe("Token Statistics on Abort", () => {
  77. describe.skipIf(!process.env.GEMINI_API_KEY)("Google Provider", () => {
  78. const llm = getModel("google", "gemini-2.5-flash");
  79. it("should include token stats when aborted mid-stream", { retry: 3, timeout: 30000 }, async () => {
  80. await testTokensOnAbort(llm, { thinking: { enabled: true } });
  81. });
  82. });
  83. describe.skipIf(!process.env.OPENAI_API_KEY)("OpenAI Completions Provider", () => {
  84. const { compat: _compat, ...baseModel } = getModel("openai", "gpt-4o-mini")!;
  85. void _compat;
  86. const llm: Model<"openai-completions"> = {
  87. ...baseModel,
  88. api: "openai-completions",
  89. };
  90. it("should include token stats when aborted mid-stream", { retry: 3, timeout: 30000 }, async () => {
  91. await testTokensOnAbort(llm);
  92. });
  93. });
  94. describe.skipIf(!process.env.OPENAI_API_KEY)("OpenAI Responses Provider", () => {
  95. const llm = getModel("openai", "gpt-5.4-mini");
  96. it("should include token stats when aborted mid-stream", { retry: 3, timeout: 30000 }, async () => {
  97. await testTokensOnAbort(llm, { reasoningEffort: "low" });
  98. });
  99. });
  100. describe.skipIf(!hasAzureOpenAICredentials())("Azure OpenAI Responses Provider", () => {
  101. const llm = getModel("azure-openai-responses", "gpt-4o-mini");
  102. const azureDeploymentName = resolveAzureDeploymentName(llm.id);
  103. const azureOptions = azureDeploymentName ? { azureDeploymentName } : {};
  104. it("should include token stats when aborted mid-stream", { retry: 3, timeout: 30000 }, async () => {
  105. await testTokensOnAbort(llm, azureOptions);
  106. });
  107. });
  108. describe.skipIf(!process.env.ANTHROPIC_API_KEY)("Anthropic Provider", () => {
  109. const llm = getModel("anthropic", "claude-sonnet-4-6");
  110. it("should include token stats when aborted mid-stream", { retry: 3, timeout: 30000 }, async () => {
  111. await testTokensOnAbort(llm);
  112. });
  113. });
  114. describe.skipIf(!process.env.XAI_API_KEY)("xAI Provider", () => {
  115. const llm = getModel("xai", "grok-3-fast");
  116. it("should include token stats when aborted mid-stream", { retry: 3, timeout: 30000 }, async () => {
  117. await testTokensOnAbort(llm);
  118. });
  119. });
  120. describe.skipIf(!process.env.GROQ_API_KEY)("Groq Provider", () => {
  121. const llm = getModel("groq", "openai/gpt-oss-20b");
  122. it("should include token stats when aborted mid-stream", { retry: 3, timeout: 30000 }, async () => {
  123. await testTokensOnAbort(llm);
  124. });
  125. });
  126. describe.skipIf(!process.env.CEREBRAS_API_KEY)("Cerebras Provider", () => {
  127. const preferredCerebrasModelIds: string[] = ["gpt-oss-120b", "zai-glm-4.7", "llama3.1-8b"];
  128. const cerebrasModels = getModels("cerebras");
  129. const llm = cerebrasModels.find((model) => preferredCerebrasModelIds.includes(model.id)) ?? cerebrasModels[0];
  130. it("should include token stats when aborted mid-stream", { retry: 3, timeout: 30000 }, async () => {
  131. if (!llm) {
  132. throw new Error("No Cerebras models available");
  133. }
  134. await testTokensOnAbort(llm);
  135. });
  136. });
  137. describe.skipIf(!hasCloudflareWorkersAICredentials())("Cloudflare Workers AI Provider", () => {
  138. const llm = getModel("cloudflare-workers-ai", "@cf/moonshotai/kimi-k2.6");
  139. it("should include token stats when aborted mid-stream", { retry: 3, timeout: 30000 }, async () => {
  140. await testTokensOnAbort(llm);
  141. });
  142. });
  143. describe.skipIf(!hasCloudflareAiGatewayCredentials())("Cloudflare AI Gateway Provider", () => {
  144. const llm = getModel("cloudflare-ai-gateway", "workers-ai/@cf/moonshotai/kimi-k2.6");
  145. it("should include token stats when aborted mid-stream", { retry: 3, timeout: 30000 }, async () => {
  146. await testTokensOnAbort(llm);
  147. });
  148. });
  149. describe.skipIf(!process.env.HF_TOKEN)("Hugging Face Provider", () => {
  150. const llm = getModel("huggingface", "moonshotai/Kimi-K2.5");
  151. it("should include token stats when aborted mid-stream", { retry: 3, timeout: 30000 }, async () => {
  152. await testTokensOnAbort(llm);
  153. });
  154. });
  155. describe.skipIf(!process.env.TOGETHER_API_KEY)("Together AI Provider", () => {
  156. const llm = getModel("together", "moonshotai/Kimi-K2.6");
  157. it("should include token stats when aborted mid-stream", { retry: 3, timeout: 30000 }, async () => {
  158. await testTokensOnAbort(llm);
  159. });
  160. });
  161. describe.skipIf(!process.env.ZAI_API_KEY)("zAI Provider", () => {
  162. const llm = getModel("zai", "glm-4.5-air");
  163. it("should include token stats when aborted mid-stream", { retry: 3, timeout: 30000 }, async () => {
  164. await testTokensOnAbort(llm);
  165. });
  166. });
  167. describe.skipIf(!process.env.MISTRAL_API_KEY)("Mistral Provider", () => {
  168. const llm = getModel("mistral", "devstral-medium-latest");
  169. it("should include token stats when aborted mid-stream", { retry: 3, timeout: 30000 }, async () => {
  170. await testTokensOnAbort(llm);
  171. });
  172. });
  173. describe.skipIf(!process.env.MINIMAX_API_KEY)("MiniMax Provider", () => {
  174. const llm = getModel("minimax", "MiniMax-M2.7");
  175. it("should include token stats when aborted mid-stream", { retry: 3, timeout: 30000 }, async () => {
  176. await testTokensOnAbort(llm);
  177. });
  178. });
  179. describe.skipIf(!process.env.KIMI_API_KEY)("Kimi For Coding Provider", () => {
  180. const llm = getModel("kimi-coding", "kimi-for-coding");
  181. it("should include token stats when aborted mid-stream", { retry: 3, timeout: 30000 }, async () => {
  182. await testTokensOnAbort(llm);
  183. });
  184. });
  185. describe.skipIf(!process.env.AI_GATEWAY_API_KEY)("Vercel AI Gateway Provider", () => {
  186. const llm = getModel("vercel-ai-gateway", "google/gemini-2.5-flash");
  187. it("should include token stats when aborted mid-stream", { retry: 3, timeout: 30000 }, async () => {
  188. await testTokensOnAbort(llm);
  189. });
  190. });
  191. describe.skipIf(!process.env.XIAOMI_API_KEY)("Xiaomi MiMo (API billing) Provider", () => {
  192. const llm = getModel("xiaomi", "mimo-v2.5-pro");
  193. // FIXME(xiaomi): Xiaomi's Anthropic-compatible stream does not populate
  194. // usage in the message_start event the way Anthropic does — usage only
  195. // arrives at message_stop. Aborting mid-stream therefore loses input/output
  196. // token counts. Non-streaming usage works (see total-tokens.test.ts).
  197. // Re-enable once upstream sends usage in message_start.
  198. it.skip("should include token stats when aborted mid-stream", { retry: 3, timeout: 30000 }, async () => {
  199. await testTokensOnAbort(llm);
  200. });
  201. });
  202. describe.skipIf(!process.env.XIAOMI_TOKEN_PLAN_CN_API_KEY)("Xiaomi MiMo Token Plan (CN) Provider", () => {
  203. const llm = getModel("xiaomi-token-plan-cn", "mimo-v2.5-pro");
  204. // FIXME(xiaomi): see the API-billing block above — same upstream streaming
  205. // usage limitation applies to Token Plan endpoints.
  206. it.skip("should include token stats when aborted mid-stream", { retry: 3, timeout: 30000 }, async () => {
  207. await testTokensOnAbort(llm);
  208. });
  209. });
  210. describe.skipIf(!process.env.XIAOMI_TOKEN_PLAN_AMS_API_KEY)("Xiaomi MiMo Token Plan (AMS) Provider", () => {
  211. const llm = getModel("xiaomi-token-plan-ams", "mimo-v2.5-pro");
  212. // FIXME(xiaomi): see the API-billing block above — same upstream streaming
  213. // usage limitation applies to Token Plan endpoints.
  214. it.skip("should include token stats when aborted mid-stream", { retry: 3, timeout: 30000 }, async () => {
  215. await testTokensOnAbort(llm);
  216. });
  217. });
  218. describe.skipIf(!process.env.XIAOMI_TOKEN_PLAN_SGP_API_KEY)("Xiaomi MiMo Token Plan (SGP) Provider", () => {
  219. const llm = getModel("xiaomi-token-plan-sgp", "mimo-v2.5-pro");
  220. // FIXME(xiaomi): see the API-billing block above — same upstream streaming
  221. // usage limitation applies to Token Plan endpoints.
  222. it.skip("should include token stats when aborted mid-stream", { retry: 3, timeout: 30000 }, async () => {
  223. await testTokensOnAbort(llm);
  224. });
  225. });
  226. // =========================================================================
  227. // OAuth-based providers (credentials from ~/.pi/agent/oauth.json)
  228. // =========================================================================
  229. describe("Anthropic OAuth Provider", () => {
  230. const llm = getModel("anthropic", "claude-sonnet-4-6");
  231. it.skipIf(!anthropicOAuthToken)(
  232. "should include token stats when aborted mid-stream",
  233. { retry: 3, timeout: 30000 },
  234. async () => {
  235. await testTokensOnAbort(llm, { apiKey: anthropicOAuthToken });
  236. },
  237. );
  238. });
  239. describe("GitHub Copilot Provider", () => {
  240. it.skipIf(!githubCopilotToken)(
  241. "claude-haiku-4.5 - should include token stats when aborted mid-stream",
  242. { retry: 3, timeout: 30000 },
  243. async () => {
  244. const llm = getModel("github-copilot", "claude-haiku-4.5");
  245. await testTokensOnAbort(llm, { apiKey: githubCopilotToken });
  246. },
  247. );
  248. it.skipIf(!githubCopilotToken)(
  249. "claude-sonnet-4 - should include token stats when aborted mid-stream",
  250. { retry: 3, timeout: 30000 },
  251. async () => {
  252. const llm = getModel("github-copilot", "claude-sonnet-4.6");
  253. await testTokensOnAbort(llm, { apiKey: githubCopilotToken });
  254. },
  255. );
  256. });
  257. describe("OpenAI Codex Provider", () => {
  258. it.skipIf(!openaiCodexToken)(
  259. "gpt-5.5 - should include token stats when aborted mid-stream",
  260. { retry: 3, timeout: 30000 },
  261. async () => {
  262. const llm = getModel("openai-codex", "gpt-5.5");
  263. await testTokensOnAbort(llm, { apiKey: openaiCodexToken });
  264. },
  265. );
  266. });
  267. describe.skipIf(!hasBedrockCredentials())("Amazon Bedrock Provider", () => {
  268. const llm = getModel("amazon-bedrock", "global.anthropic.claude-sonnet-4-5-20250929-v1:0");
  269. it("should include token stats when aborted mid-stream", { retry: 3, timeout: 30000 }, async () => {
  270. await testTokensOnAbort(llm);
  271. });
  272. });
  273. });