openai-compatible-stream-usage-wire.test.ts 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. import { jsonSchema, streamText, tool } from "ai";
  2. import { afterEach, describe, expect, it, vi } from "vitest";
  3. import { TestProviderConfigFixture } from "./test-provider-config.js";
  4. describe("OpenAI-compatible stream usage requests", () => {
  5. afterEach(() => {
  6. vi.unstubAllGlobals();
  7. });
  8. it("always requests stream usage", async () => {
  9. let capturedBody: Record<string, unknown> | undefined;
  10. vi.stubGlobal("fetch", async (_input: RequestInfo | URL, init?: RequestInit) => {
  11. capturedBody = JSON.parse(String(init?.body)) as Record<string, unknown>;
  12. return new Response(
  13. [
  14. 'data: {"id":"chatcmpl-test","object":"chat.completion.chunk","created":1,"model":"test-model","choices":[{"index":0,"delta":{"content":"ok"},"finish_reason":null}]}',
  15. 'data: {"id":"chatcmpl-test","object":"chat.completion.chunk","created":1,"model":"test-model","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}',
  16. 'data: {"id":"chatcmpl-test","object":"chat.completion.chunk","created":1,"model":"test-model","choices":[],"usage":{"prompt_tokens":3,"completion_tokens":2,"total_tokens":5}}',
  17. "data: [DONE]",
  18. "",
  19. ].join("\n\n"),
  20. { headers: { "content-type": "text/event-stream" } },
  21. );
  22. });
  23. const registry = new TestProviderConfigFixture({
  24. env: {},
  25. providers: {
  26. compatible: {
  27. apiKey: "test-key",
  28. baseURL: "https://api.example.test/v1",
  29. kind: "openai-compatible",
  30. },
  31. },
  32. });
  33. const result = streamText({
  34. model: registry.resolve("compatible/test-model").model,
  35. prompt: "hello",
  36. });
  37. await expect(result.text).resolves.toBe("ok");
  38. expect(capturedBody?.stream_options).toEqual({ include_usage: true });
  39. await expect(result.usage).resolves.toMatchObject({
  40. inputTokens: 3,
  41. outputTokens: 2,
  42. totalTokens: 5,
  43. });
  44. });
  45. it("preserves a nonstandard max_tokens raw reason when normalized finish is other", async () => {
  46. vi.stubGlobal("fetch", async () => {
  47. return new Response(
  48. [
  49. 'data: {"id":"chatcmpl-max-tokens","object":"chat.completion.chunk","created":1,"model":"test-model","choices":[{"index":0,"delta":{"content":"partial"},"finish_reason":null}]}',
  50. 'data: {"id":"chatcmpl-max-tokens","object":"chat.completion.chunk","created":1,"model":"test-model","choices":[{"index":0,"delta":{},"finish_reason":"max_tokens"}]}',
  51. "data: [DONE]",
  52. "",
  53. ].join("\n\n"),
  54. { headers: { "content-type": "text/event-stream" } },
  55. );
  56. });
  57. // 修复原因:此断言遗漏了旧 Registry 测试替身迁移;保持真实请求和 raw reason 断言不变。
  58. const registry = new TestProviderConfigFixture({
  59. env: {},
  60. providers: {
  61. compatible: {
  62. apiKey: "test-key",
  63. baseURL: "https://api.example.test/v1",
  64. kind: "openai-compatible",
  65. },
  66. },
  67. });
  68. const result = streamText({
  69. model: registry.resolve("compatible/test-model").model,
  70. prompt: "continue",
  71. });
  72. await expect(result.text).resolves.toBe("partial");
  73. await expect(result.finishReason).resolves.toBe("other");
  74. await expect(result.rawFinishReason).resolves.toBe("max_tokens");
  75. });
  76. it("keeps parsable partial tool input open until the response stream flushes", async () => {
  77. vi.stubGlobal("fetch", async () => {
  78. return new Response(
  79. [
  80. 'data: {"id":"chatcmpl-tool","object":"chat.completion.chunk","created":1,"model":"test-model","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_1","type":"function","function":{"name":"Count","arguments":"1"}}]},"finish_reason":null}]}',
  81. 'data: {"id":"chatcmpl-tool","object":"chat.completion.chunk","created":1,"model":"test-model","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"0"}}]},"finish_reason":null}]}',
  82. 'data: {"id":"chatcmpl-tool","object":"chat.completion.chunk","created":1,"model":"test-model","choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}',
  83. "data: [DONE]",
  84. "",
  85. ].join("\n\n"),
  86. { headers: { "content-type": "text/event-stream" } },
  87. );
  88. });
  89. const registry = new TestProviderConfigFixture({
  90. env: {},
  91. providers: {
  92. compatible: {
  93. apiKey: "test-key",
  94. baseURL: "https://api.example.test/v1",
  95. kind: "openai-compatible",
  96. },
  97. },
  98. });
  99. const result = streamText({
  100. model: registry.resolve("compatible/test-model").model,
  101. prompt: "count",
  102. tools: {
  103. Count: tool({
  104. description: "Return a count",
  105. inputSchema: jsonSchema<number>({ type: "number" }),
  106. }),
  107. },
  108. });
  109. const toolParts = [];
  110. for await (const part of result.fullStream) {
  111. if (
  112. part.type === "tool-input-start" ||
  113. part.type === "tool-input-delta" ||
  114. part.type === "tool-input-end" ||
  115. part.type === "tool-call"
  116. ) {
  117. toolParts.push(part);
  118. }
  119. }
  120. expect(toolParts.map((part) => part.type)).toEqual([
  121. "tool-input-start",
  122. "tool-input-delta",
  123. "tool-input-delta",
  124. "tool-input-end",
  125. "tool-call",
  126. ]);
  127. expect(toolParts.filter((part) => part.type === "tool-input-delta")).toMatchObject([
  128. { delta: "1" },
  129. { delta: "0" },
  130. ]);
  131. expect(toolParts.at(-1)).toMatchObject({
  132. input: 10,
  133. toolCallId: "call_1",
  134. toolName: "Count",
  135. type: "tool-call",
  136. });
  137. });
  138. });