MCPcopy Create free account
hub / github.com/freecodexyz/free-code / validateImagesForAPI

Function validateImagesForAPI

src/utils/imageValidation.ts:65–104  ·  view source on GitHub ↗
(messages: unknown[])

Source from the content-addressed store, hash-verified

63 * @throws ImageSizeError if any image exceeds the API limit
64 */
65export function validateImagesForAPI(messages: unknown[]): void {
66 const oversizedImages: OversizedImage[] = []
67 let imageIndex = 0
68
69 for (const msg of messages) {
70 if (typeof msg !== 'object' || msg === null) continue
71
72 const m = msg as Record<string, unknown>
73
74 // Handle wrapped message format { type: 'user', message: { role, content } }
75 // Only check user messages
76 if (m.type !== 'user') continue
77
78 const innerMessage = m.message as Record<string, unknown> | undefined
79 if (!innerMessage) continue
80
81 const content = innerMessage.content
82 if (typeof content === 'string' || !Array.isArray(content)) continue
83
84 for (const block of content) {
85 if (isBase64ImageBlock(block)) {
86 imageIndex++
87 // Check the base64-encoded string length directly (not decoded bytes)
88 // The API limit applies to the base64 payload size
89 const base64Size = block.source.data.length
90 if (base64Size > API_IMAGE_MAX_BASE64_SIZE) {
91 logEvent('tengu_image_api_validation_failed', {
92 base64_size_bytes: base64Size,
93 max_bytes: API_IMAGE_MAX_BASE64_SIZE,
94 })
95 oversizedImages.push({ index: imageIndex, size: base64Size })
96 }
97 }
98 }
99 }
100
101 if (oversizedImages.length > 0) {
102 throw new ImageSizeError(oversizedImages, API_IMAGE_MAX_BASE64_SIZE)
103 }
104}

Callers 1

normalizeMessagesForAPIFunction · 0.85

Calls 2

isBase64ImageBlockFunction · 0.85
logEventFunction · 0.85

Tested by

no test coverage detected