multimodal-tool-result-p0.mjs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. #!/usr/bin/env node
  2. import crypto from "node:crypto";
  3. import { pathToFileURL } from "node:url";
  4. import { renderMarkerPng } from "./multimodal-marker-png.mjs";
  5. const MODEL = process.env.ZCODE_MODEL?.trim() || "glm-x-preview-f";
  6. const BASE_URL = (process.env.ZCODE_BASE_URL?.trim() || "https://open.bigmodel.cn/api/anthropic")
  7. .replace(/\/+$/u, "")
  8. .replace(/\/v1$/u, "");
  9. const ENDPOINT = `${BASE_URL}/v1/messages`;
  10. const API_KEY = process.env.ANTHROPIC_API_KEY?.trim();
  11. const MAX_TOKENS = parsePositiveInt(process.env.MM_P0_MAX_TOKENS, 256);
  12. const MAX_RETRIES = parseNonNegativeInt(process.env.MM_P0_RETRIES, 2);
  13. const RETRY_DELAY_MS = parseNonNegativeInt(process.env.MM_P0_RETRY_DELAY_MS, 3_000);
  14. const REQUEST_TIMEOUT_MS = parsePositiveInt(process.env.MM_P0_TIMEOUT_MS, 90_000);
  15. export const CASE_NAMES = [
  16. "text-three-blocks",
  17. "mcp-text-image-text",
  18. "android-screenshot-shape",
  19. "ios-screenshot-shape",
  20. "browser-multiple-images",
  21. "cua-observation",
  22. "multiple-tool-results",
  23. ];
  24. const SELECTED_CASES = parseSelectedCases(process.env.MM_P0_CASES);
  25. if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
  26. main().catch((error) => {
  27. console.error(error instanceof Error ? error.message : String(error));
  28. process.exitCode = 1;
  29. });
  30. }
  31. async function main() {
  32. if (!API_KEY) {
  33. throw new Error("ANTHROPIC_API_KEY is required; it is intentionally not read from a file.");
  34. }
  35. const results = [];
  36. for (const caseName of SELECTED_CASES) {
  37. const result = await runCase(caseName);
  38. results.push(result);
  39. console.log(JSON.stringify(result));
  40. }
  41. const failed = results.filter((result) => result.outcome === "FAIL");
  42. const blocked = results.filter((result) => result.outcome === "BLOCKED");
  43. console.log(
  44. JSON.stringify({
  45. model: MODEL,
  46. endpoint: ENDPOINT,
  47. cases: results.length,
  48. passed: results.filter((result) => result.outcome === "PASS").length,
  49. failed: failed.length,
  50. blocked: blocked.length,
  51. }),
  52. );
  53. if (failed.length > 0 || blocked.length === results.length) process.exitCode = 1;
  54. }
  55. async function runCase(caseName) {
  56. const nonce = crypto.randomBytes(5).toString("hex");
  57. const probe = await buildCase(caseName, nonce);
  58. const response = await callModel(probe.messages);
  59. if (!response.ok) {
  60. return {
  61. case: caseName,
  62. nonce,
  63. outcome: "BLOCKED",
  64. http: response.status,
  65. error: response.error,
  66. };
  67. }
  68. const text = response.text;
  69. const seen = probe.expected.filter((marker) => text.includes(marker));
  70. const missing = probe.expected.filter((marker) => !seen.includes(marker));
  71. const orderOk = hasOrderedMarkers(text, probe.expected);
  72. return {
  73. case: caseName,
  74. nonce,
  75. outcome: missing.length === 0 && orderOk ? "PASS" : "FAIL",
  76. http: response.status,
  77. expected: probe.expected,
  78. seen,
  79. missing,
  80. orderOk,
  81. response: text.slice(0, 800),
  82. };
  83. }
  84. export async function buildCase(caseName, nonce) {
  85. const toolUseId = `toolu_${caseName}`;
  86. const image = (label) => ({
  87. type: "image",
  88. source: {
  89. type: "base64",
  90. media_type: "image/png",
  91. data: label,
  92. },
  93. });
  94. const text = (value) => ({ type: "text", text: value });
  95. const toolUse = (id, name) => ({ type: "tool_use", id, name, input: {} });
  96. const instruction = text(
  97. "Return a JSON array of every marker actually visible in the tool result, including text and text inside images. " +
  98. "Do not invent markers from this instruction.",
  99. );
  100. switch (caseName) {
  101. case "text-three-blocks": {
  102. const expected = [`BLOCK0_${nonce}`, `BLOCK1_${nonce}`, `BLOCK2_${nonce}`];
  103. return {
  104. expected,
  105. messages: messagesForOneTool(
  106. toolUseId,
  107. "probe",
  108. [text(expected[0]), text(expected[1]), text(expected[2])],
  109. instruction,
  110. ),
  111. };
  112. }
  113. case "mcp-text-image-text": {
  114. const expected = [`TEXT0_${nonce}`, `P0_VISUAL_${nonce}`, `TEXT2_${nonce}`];
  115. return {
  116. expected,
  117. messages: messagesForOneTool(
  118. toolUseId,
  119. "mcp_probe",
  120. [text(expected[0]), image(await makePng(expected[1])), text(expected[2])],
  121. instruction,
  122. ),
  123. };
  124. }
  125. case "android-screenshot-shape":
  126. return await buildTextImageCase(toolUseId, "android_screenshot", "ANDROID", nonce);
  127. case "ios-screenshot-shape":
  128. return await buildTextImageCase(toolUseId, "ios_screenshot", "IOS", nonce);
  129. case "browser-multiple-images": {
  130. const expected = [`BROWSER_A_${nonce}`, `BROWSER_B_${nonce}`, `BROWSER_TEXT_${nonce}`];
  131. return {
  132. expected,
  133. messages: messagesForOneTool(
  134. toolUseId,
  135. "browser_js",
  136. [image(await makePng(expected[0])), image(await makePng(expected[1])), text(expected[2])],
  137. instruction,
  138. ),
  139. };
  140. }
  141. case "cua-observation": {
  142. const expected = [
  143. `CUA_RASTER_${nonce}`,
  144. `FRAME_REF_${nonce}`,
  145. `AX_TREE_${nonce}`,
  146. `ACTION_OUTCOME_${nonce}`,
  147. ];
  148. return {
  149. expected,
  150. messages: messagesForOneTool(
  151. toolUseId,
  152. "get_app_state",
  153. [
  154. image(await makePng(expected[0])),
  155. text(expected[1]),
  156. text(expected[2]),
  157. text(expected[3]),
  158. ],
  159. instruction,
  160. ),
  161. };
  162. }
  163. case "multiple-tool-results": {
  164. const expected = [`A0_${nonce}`, `A1_${nonce}`, `B0_${nonce}`, `B1_${nonce}`];
  165. return {
  166. expected,
  167. messages: [
  168. {
  169. role: "assistant",
  170. content: [toolUse("toolu_a", "probe_a"), toolUse("toolu_b", "probe_b")],
  171. },
  172. {
  173. role: "user",
  174. content: [
  175. {
  176. type: "tool_result",
  177. tool_use_id: "toolu_a",
  178. content: [text(expected[0]), text(expected[1])],
  179. },
  180. {
  181. type: "tool_result",
  182. tool_use_id: "toolu_b",
  183. content: [text(expected[2]), text(expected[3])],
  184. },
  185. instruction,
  186. ],
  187. },
  188. ],
  189. };
  190. }
  191. default:
  192. throw new Error(`Unknown case: ${caseName}`);
  193. }
  194. }
  195. async function buildTextImageCase(toolUseId, toolName, prefix, nonce) {
  196. const expected = [`${prefix}_META_${nonce}`, `${prefix}_VISUAL_${nonce}`];
  197. return {
  198. expected,
  199. messages: messagesForOneTool(
  200. toolUseId,
  201. toolName,
  202. [
  203. { type: "text", text: expected[0] },
  204. {
  205. type: "image",
  206. source: { type: "base64", media_type: "image/png", data: await makePng(expected[1]) },
  207. },
  208. ],
  209. {
  210. type: "text",
  211. text: "Return a JSON array of every marker actually visible in the tool result, including text and text inside the image. Do not invent markers from this instruction.",
  212. },
  213. ),
  214. };
  215. }
  216. function messagesForOneTool(toolUseId, toolName, content, instruction) {
  217. return [
  218. {
  219. role: "assistant",
  220. content: [{ type: "tool_use", id: toolUseId, name: toolName, input: {} }],
  221. },
  222. {
  223. role: "user",
  224. content: [{ type: "tool_result", tool_use_id: toolUseId, content }, instruction],
  225. },
  226. ];
  227. }
  228. async function callModel(messages) {
  229. const body = JSON.stringify({ model: MODEL, max_tokens: MAX_TOKENS, messages });
  230. let lastError;
  231. for (let attempt = 0; attempt <= MAX_RETRIES; attempt += 1) {
  232. try {
  233. const response = await fetch(ENDPOINT, {
  234. method: "POST",
  235. headers: {
  236. "content-type": "application/json",
  237. "x-api-key": API_KEY,
  238. "anthropic-version": "2023-06-01",
  239. },
  240. body,
  241. signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
  242. });
  243. const raw = await response.text();
  244. const parsed = parseJson(raw);
  245. if (response.ok) {
  246. return {
  247. ok: true,
  248. status: response.status,
  249. text: Array.isArray(parsed?.content)
  250. ? parsed.content
  251. .filter((part) => part?.type === "text")
  252. .map((part) => part.text)
  253. .join("\n")
  254. : "",
  255. };
  256. }
  257. lastError = {
  258. status: response.status,
  259. error: parsed?.error?.message || `HTTP ${response.status}`,
  260. };
  261. if (!isRetryableStatus(response.status) || attempt === MAX_RETRIES) break;
  262. } catch (error) {
  263. lastError = {
  264. status: undefined,
  265. error: error instanceof Error ? error.message : String(error),
  266. };
  267. if (attempt === MAX_RETRIES) break;
  268. }
  269. await delay(RETRY_DELAY_MS * (attempt + 1));
  270. }
  271. return { ok: false, ...lastError };
  272. }
  273. async function makePng(label) {
  274. return renderMarkerPng(label).toString("base64");
  275. }
  276. export function parseSelectedCases(value) {
  277. if (!value?.trim()) return CASE_NAMES;
  278. const selected = value
  279. .split(",")
  280. .map((item) => item.trim())
  281. .filter(Boolean);
  282. const unknown = selected.filter((item) => !CASE_NAMES.includes(item));
  283. if (unknown.length > 0) throw new Error(`Unknown MM_P0_CASES: ${unknown.join(", ")}`);
  284. return selected;
  285. }
  286. export function hasOrderedMarkers(value, markers) {
  287. let cursor = -1;
  288. for (const marker of markers) {
  289. const index = value.indexOf(marker, cursor + 1);
  290. if (index < 0) return false;
  291. cursor = index;
  292. }
  293. return true;
  294. }
  295. function parseJson(value) {
  296. try {
  297. return JSON.parse(value);
  298. } catch {
  299. return undefined;
  300. }
  301. }
  302. function isRetryableStatus(status) {
  303. return status === 429 || status === 500 || status === 502 || status === 503 || status === 529;
  304. }
  305. function delay(ms) {
  306. return new Promise((resolve) => setTimeout(resolve, ms));
  307. }
  308. function parsePositiveInt(value, fallback) {
  309. const parsed = Number.parseInt(value ?? "", 10);
  310. return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
  311. }
  312. function parseNonNegativeInt(value, fallback) {
  313. const parsed = Number.parseInt(value ?? "", 10);
  314. return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback;
  315. }