export const MAX_BODY = 40 * 1024 * 1024; export function normalizeRequest(body) { const fail = (message) => { throw new Error(message); }; if ( !body || !Array.isArray(body.messages) || !body.messages.length || body.messages.length > 40 ) fail("对话需包含 1–40 条消息;过长时请新建对话。"); if ("webSearch" in body) fail("需求解析器不支持联网搜索。"); const input = body.messages.map((message, index) => { if (!message || !["user", "assistant"].includes(message.role)) fail("消息角色不合法。"); if (typeof message.text !== "string" || message.text.length > 20000) fail("每条消息最多 20000 个字符。"); const images = message.images ?? []; if ( !Array.isArray(images) || images.length > 4 || (message.role === "assistant" && images.length) ) fail("每条用户消息最多附带 4 张图片。"); const messageId = message.id || `message_${index}`; if ( typeof messageId !== "string" || !/^[A-Za-z0-9_-]{1,80}$/.test(messageId) ) fail("消息ID不合法"); const content = [{ type: "input_text", text: `[messageId:${messageId}]` }]; if (message.text.trim()) content.push({ type: "input_text", text: message.text, }); for (const [imageIndex, attachment] of images.entries()) { const image = typeof attachment === "string" ? attachment : attachment?.url; const imageId = typeof attachment === "string" ? `image_${index}_${imageIndex}` : attachment?.id; if (typeof imageId !== "string" || !/^[A-Za-z0-9_-]{1,80}$/.test(imageId)) fail("图片ID不合法"); if ( typeof image !== "string" || !/^data:image\/(png|jpeg|webp);base64,[A-Za-z0-9+/]+={0,2}$/.test(image) ) fail("图片仅支持 PNG、JPEG、WebP。"); const [header, base64] = image.split(","); const bytes = Buffer.from(base64, "base64"); if (bytes.length > 8 * 1024 * 1024) fail("每张图片不能超过 8 MiB。"); const png = bytes .subarray(0, 8) .equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])); const jpeg = bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255; const webp = bytes.toString("ascii", 0, 4) === "RIFF" && bytes.toString("ascii", 8, 12) === "WEBP"; if ( !(header.includes("png") ? png : header.includes("jpeg") ? jpeg : webp) ) fail("图片内容与格式不符。"); content.push({ type: "input_text", text: `[imageId:${imageId}]` }); content.push({ type: "input_image", image_url: image, detail: "high" }); } if (!message.text.trim() && !images.length) fail("消息内容不能为空。"); return { role: message.role, content }; }); if (input.at(-1).role !== "user") fail("最后一条消息必须是用户消息。"); return { input, messages: body.messages }; }