video-wire.test.ts 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. // video 输入的 wire 形状测试:
  2. // - openai-compatible: video block → {type:"video_url", video_url:{url:"data:..."}}
  3. // - anthropic: video block → {type:"video", source:{type:"base64",...}}
  4. // - tool result(Read 视频)媒体拆后置 user part(全 provider kind)
  5. // - inputFormat.supportsVideo=false 时 strip 为占位文本(wire 不出现视频内容)
  6. import { createAnthropic } from "@ai-sdk/anthropic";
  7. import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
  8. import { generateText } from "ai";
  9. import { describe, expect, it } from "vitest";
  10. import type { ModelMessageContent } from "@zcode/contracts";
  11. import { createGenerateTextOptions } from "../src/model/runner-options.js";
  12. import type { ResolvedAiSdkModel } from "../src/model/runner-runtime.js";
  13. import { createTestModelProperties } from "./test-model-format.js";
  14. const VIDEO_BASE64 = Buffer.from("fake-mp4-bytes").toString("base64");
  15. const VIDEO_DATA_URL = `data:video/mp4;base64,${VIDEO_BASE64}`;
  16. function videoBlock() {
  17. return {
  18. type: "video" as const,
  19. mediaType: "video/mp4",
  20. dataUrl: VIDEO_DATA_URL,
  21. source: {
  22. id: "turn-attachment-1",
  23. kind: "inline" as const,
  24. mimeType: "video/mp4",
  25. placeholder: "demo.mp4",
  26. },
  27. };
  28. }
  29. describe("Video input wire shape", () => {
  30. it("openai-compatible serializes video as video_url with a data URL", async () => {
  31. const body = await captureProviderBody("openai-compatible", {
  32. messages: [{ role: "user", content: [videoBlock(), { type: "text", text: "summarize" }] }],
  33. });
  34. expect(body?.messages?.[0]).toMatchObject({
  35. role: "user",
  36. content: [
  37. { type: "video_url", video_url: { url: VIDEO_DATA_URL } },
  38. { type: "text", text: "summarize" },
  39. ],
  40. });
  41. });
  42. it("anthropic serializes video as a base64 video block", async () => {
  43. const body = await captureProviderBody("anthropic", {
  44. messages: [{ role: "user", content: [videoBlock(), { type: "text", text: "summarize" }] }],
  45. });
  46. expect(body?.messages?.[0]).toMatchObject({
  47. role: "user",
  48. content: [
  49. {
  50. type: "video",
  51. source: { type: "base64", media_type: "video/mp4", data: VIDEO_BASE64 },
  52. },
  53. { type: "text", text: "summarize" },
  54. ],
  55. });
  56. });
  57. it("openai-compatible projects Read tool-result video into a follow-up user part", async () => {
  58. const body = await captureProviderBody("openai-compatible", {
  59. messages: [
  60. {
  61. role: "assistant",
  62. content: [{ type: "text", text: "reading" }],
  63. toolCalls: [{ id: "call_1", name: "Read", input: { file_path: "/tmp/demo.mp4" } }],
  64. },
  65. {
  66. role: "tool",
  67. toolCallId: "call_1",
  68. toolName: "Read",
  69. content: [videoBlock()],
  70. },
  71. ],
  72. });
  73. const messages = body?.messages as Array<Record<string, unknown>>;
  74. expect(messages).toBeDefined();
  75. const userMessages = messages.filter((message) => message.role === "user");
  76. const mediaUserMessage = userMessages.find((message) =>
  77. JSON.stringify(message).includes("Tool result media from Read:"),
  78. );
  79. expect(mediaUserMessage).toBeDefined();
  80. expect(JSON.stringify(mediaUserMessage)).toContain('"type":"video_url"');
  81. });
  82. it("anthropic also projects Read tool-result video into a follow-up user part", async () => {
  83. const body = await captureProviderBody("anthropic", {
  84. messages: [
  85. {
  86. role: "assistant",
  87. content: [{ type: "text", text: "reading" }],
  88. toolCalls: [{ id: "call_1", name: "Read", input: { file_path: "/tmp/demo.mp4" } }],
  89. },
  90. {
  91. role: "tool",
  92. toolCallId: "call_1",
  93. toolName: "Read",
  94. content: [videoBlock()],
  95. },
  96. ],
  97. });
  98. const serialized = JSON.stringify(body?.messages);
  99. expect(serialized).toContain("Tool result media from Read:");
  100. expect(serialized).toContain('"type":"video"');
  101. expect(serialized).toContain(VIDEO_BASE64);
  102. });
  103. it("strips video to placeholder text when the model does not support video", async () => {
  104. const body = await captureProviderBody("openai-compatible", {
  105. messages: [{ role: "user", content: [videoBlock()] }],
  106. supportVideo: false,
  107. });
  108. const serialized = JSON.stringify(body?.messages);
  109. expect(serialized).not.toContain("video_url");
  110. expect(serialized).toContain("does not support video input");
  111. });
  112. });
  113. interface CaptureProviderBodyInput {
  114. messages: Array<{
  115. role: string;
  116. content: ModelMessageContent;
  117. toolCalls?: unknown[];
  118. toolCallId?: string;
  119. toolName?: string;
  120. }>;
  121. supportVideo?: boolean;
  122. }
  123. async function captureProviderBody(
  124. providerKind: "anthropic" | "openai-compatible",
  125. input: CaptureProviderBodyInput,
  126. ): Promise<Record<string, unknown> | undefined> {
  127. let capturedBody: Record<string, unknown> | undefined;
  128. const baseURL =
  129. providerKind === "anthropic" ? "https://example.com/v1" : "https://api.example.test/v1";
  130. const providerId = providerKind === "anthropic" ? "custom-anthropic" : "custom-compatible";
  131. const captureFetch = async (_request: RequestInfo | URL, init?: RequestInit) => {
  132. if (typeof init?.body !== "string") {
  133. throw new Error("Expected a JSON request body");
  134. }
  135. capturedBody = JSON.parse(init.body) as Record<string, unknown>;
  136. return new Response(
  137. JSON.stringify(
  138. providerKind === "anthropic"
  139. ? {
  140. content: [{ text: "ok", type: "text" }],
  141. id: "msg_video_wire",
  142. model: "glm-5v-turbo",
  143. role: "assistant",
  144. stop_reason: "end_turn",
  145. stop_sequence: null,
  146. type: "message",
  147. usage: { input_tokens: 1, output_tokens: 1 },
  148. }
  149. : {
  150. choices: [{ finish_reason: "stop", message: { content: "ok", role: "assistant" } }],
  151. id: "chatcmpl-video-wire",
  152. model: "glm-5v-turbo",
  153. },
  154. ),
  155. { headers: { "content-type": "application/json" } },
  156. );
  157. };
  158. const model =
  159. providerKind === "anthropic"
  160. ? createAnthropic({ apiKey: "fake-ak", baseURL, fetch: captureFetch })("glm-5v-turbo")
  161. : createOpenAICompatible({
  162. apiKey: "fake-ak",
  163. baseURL,
  164. name: "video wire",
  165. fetch: captureFetch,
  166. })("glm-5v-turbo");
  167. const options = createGenerateTextOptions({
  168. includeModelIO: false,
  169. request: {
  170. messages: input.messages as never,
  171. },
  172. resolved: {
  173. baseURL,
  174. properties: createTestModelProperties({ supportsVideo: input.supportVideo ?? true }),
  175. model,
  176. providerKind,
  177. providerId,
  178. modelId: "glm-5v-turbo",
  179. } as ResolvedAiSdkModel,
  180. statusContext: {
  181. providerId,
  182. modelId: "glm-5v-turbo",
  183. providerKind,
  184. requestId: `req_video_wire_${providerKind}`,
  185. sessionId: `sess_video_wire_${providerKind}`,
  186. traceContext: { traceId: `trace_video_wire_${providerKind}` },
  187. } as never,
  188. });
  189. await generateText(options);
  190. return capturedBody;
  191. }