(messages: unknown[])
| 63 | * @throws ImageSizeError if any image exceeds the API limit |
| 64 | */ |
| 65 | export 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 | } |
no test coverage detected