(prompt: string)
| 118 | * 解析 Markdown 中的图片语法并转换为 content blocks |
| 119 | * 支持格式: |
| 120 | */ |
| 121 | export async function parsePromptWithImages(prompt: string): Promise<ParsedPrompt> { |
| 122 | // 匹配  格式的图片 |
| 123 | const imageRegex = /!\[([^\]]*)\]\(([^)]+)\)/g; |
| 124 | |
| 125 | const contentBlocks: ContentBlock[] = []; |
| 126 | let hasImages = false; |
| 127 | let lastIndex = 0; |
| 128 | let match: RegExpExecArray | null; |
| 129 | |
| 130 | // 遍历所有匹配的图片 |
| 131 | while ((match = imageRegex.exec(prompt)) !== null) { |
| 132 | const [fullMatch, _alt, imagePath] = match; |
| 133 | const matchIndex = match.index; |
| 134 | |
| 135 | // 添加图片前的文本 |
| 136 | if (matchIndex > lastIndex) { |
| 137 | const textBefore = prompt.substring(lastIndex, matchIndex); |
| 138 | if (textBefore) { |
| 139 | contentBlocks.push({ |
| 140 | type: 'text', |
| 141 | text: textBefore, |
| 142 | }); |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | // 检查图片文件是否存在 |
| 147 | const exists = await fileExists(imagePath); |
| 148 | if (!exists) { |
| 149 | console.warn(`[image-utils] Image file not found: ${imagePath}`); |
| 150 | // 如果文件不存在,保留原始 Markdown 文本 |
| 151 | contentBlocks.push({ |
| 152 | type: 'text', |
| 153 | text: fullMatch, |
| 154 | }); |
| 155 | } else { |
| 156 | try { |
| 157 | // 读取图片并转换为 base64 |
| 158 | const base64Data = await readImageAsBase64(imagePath); |
| 159 | const mimeType = getMimeType(imagePath); |
| 160 | |
| 161 | contentBlocks.push({ |
| 162 | type: 'image', |
| 163 | source: { |
| 164 | type: 'base64', |
| 165 | media_type: mimeType, |
| 166 | data: base64Data, |
| 167 | }, |
| 168 | }); |
| 169 | |
| 170 | hasImages = true; |
| 171 | console.log(`[image-utils] Successfully loaded image: ${imagePath} (${mimeType})`); |
| 172 | } catch (error) { |
| 173 | console.error(`[image-utils] Failed to load image: ${imagePath}`, error); |
| 174 | // 如果读取失败,保留原始 Markdown 文本 |
| 175 | contentBlocks.push({ |
| 176 | type: 'text', |
| 177 | text: fullMatch, |
no test coverage detected