mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 08:23:34 +00:00
Don't parse URLs in user messages as images
This commit is contained in:
3 files changed
+8
-208
No files matched your search
@@ -1,14 +1,12 @@
|
||||
import type OpenAI from 'openai';
|
||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||
import { parseImageUrls } from './parseImageUrls';
|
||||
import { saveFileToTmp } from './fileUtils';
|
||||
import { fileToUrl, urlToFile } from './imageUtils';
|
||||
import { fileToUrl } from './imageUtils';
|
||||
|
||||
type ContentPart = OpenAI.Chat.Completions.ChatCompletionContentPartText | OpenAI.Chat.Completions.ChatCompletionContentPartImage;
|
||||
|
||||
/**
|
||||
* Builds message content from text input, image URLs, and attached files.
|
||||
* Downloads image URLs to VFS and processes uploaded files.
|
||||
* Builds message content from text input and attached files.
|
||||
*
|
||||
* - All image formats are included in the message content for UI display
|
||||
* - SessionManager filters to only pass JPG/JPEG/PNG to the OpenAI API
|
||||
@@ -17,7 +15,7 @@ type ContentPart = OpenAI.Chat.Completions.ChatCompletionContentPartText | OpenA
|
||||
*
|
||||
* Returns content as either a string (for simple text) or an array of content parts.
|
||||
*
|
||||
* @param input - User text input that may contain image URLs
|
||||
* @param input - User text input
|
||||
* @param attachedFiles - Array of files to attach
|
||||
* @param fs - Filesystem instance for saving files
|
||||
* @param tmpPath - Temporary directory path for file storage
|
||||
@@ -31,30 +29,12 @@ export async function buildMessageContent(
|
||||
): Promise<string | ContentPart[]> {
|
||||
const contentParts: ContentPart[] = [];
|
||||
|
||||
// Parse user input to detect image URLs and split into content parts
|
||||
// Add user input as text part if present
|
||||
if (input.trim()) {
|
||||
const parsedParts = parseImageUrls(input.trim());
|
||||
|
||||
// Process each part: download image URLs to VFS and add text parts with VFS paths
|
||||
for (const part of parsedParts) {
|
||||
if (part.type === 'image_url') {
|
||||
// Download image to VFS and get the path
|
||||
const result = await urlToFile(part.image_url.url, fs, tmpPath);
|
||||
|
||||
// Always add image_url part for UI display (all formats)
|
||||
contentParts.push(part);
|
||||
|
||||
// Always add text part with VFS path so AI knows where the file is (can manipulate it)
|
||||
if (result?.vfsPath) {
|
||||
contentParts.push({
|
||||
type: 'text',
|
||||
text: `Added file: ${result.vfsPath}`
|
||||
});
|
||||
}
|
||||
} else {
|
||||
contentParts.push(part);
|
||||
}
|
||||
}
|
||||
contentParts.push({
|
||||
type: 'text',
|
||||
text: input.trim()
|
||||
});
|
||||
}
|
||||
|
||||
// Process attached files: save to VFS and add image_url for UI display (all image types)
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||
import { generateUniqueFilename } from './fileUtils';
|
||||
|
||||
/**
|
||||
* Converts a File to a base64-encoded data URL for API consumption.
|
||||
*
|
||||
@@ -24,101 +21,3 @@ export async function fileToUrl(file: File): Promise<string> {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a URL to a file saved in the VFS.
|
||||
* Downloads an image from a URL and saves it to the VFS.
|
||||
* Returns both the original URL (for API calls) and the VFS path (for reference).
|
||||
*
|
||||
* @param imageUrl - The image URL to download
|
||||
* @param fs - Filesystem instance for saving files
|
||||
* @param tmpPath - Temporary directory path for file storage
|
||||
* @returns Promise resolving to object with originalUrl and vfsPath, or null if download fails
|
||||
*/
|
||||
export async function urlToFile(
|
||||
imageUrl: string,
|
||||
fs: JSRuntimeFS,
|
||||
tmpPath = '/tmp'
|
||||
): Promise<{ originalUrl: string; vfsPath: string } | null> {
|
||||
try {
|
||||
// Handle data URLs - extract and save them
|
||||
if (imageUrl.startsWith('data:image/')) {
|
||||
const [header, base64Data] = imageUrl.split(',');
|
||||
if (!base64Data) {
|
||||
console.warn('Invalid data URL format:', imageUrl);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Extract MIME type and extension from header
|
||||
const mimeMatch = header.match(/data:image\/([^;]+)/);
|
||||
const mimeType = mimeMatch ? mimeMatch[1] : 'png';
|
||||
const extension = mimeType === 'jpeg' ? 'jpg' : mimeType;
|
||||
|
||||
// Generate filename
|
||||
const filename = `downloaded_image_${Date.now()}.${extension}`;
|
||||
const uniqueFilename = await generateUniqueFilename(fs, tmpPath, filename);
|
||||
const vfsPath = `${tmpPath}/${uniqueFilename}`;
|
||||
|
||||
// Convert base64 to Uint8Array
|
||||
const binaryString = atob(base64Data);
|
||||
const bytes = new Uint8Array(binaryString.length);
|
||||
for (let i = 0; i < binaryString.length; i++) {
|
||||
bytes[i] = binaryString.charCodeAt(i);
|
||||
}
|
||||
|
||||
// Write to VFS
|
||||
await fs.writeFile(vfsPath, bytes);
|
||||
|
||||
return { originalUrl: imageUrl, vfsPath };
|
||||
}
|
||||
|
||||
// Handle HTTP/HTTPS URLs
|
||||
const response = await fetch(imageUrl, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Accept': 'image/*',
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
console.warn(`Failed to download image from ${imageUrl}: ${response.status} ${response.statusText}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Determine filename from URL or Content-Type
|
||||
let filename = 'downloaded_image';
|
||||
const urlPath = new URL(imageUrl).pathname;
|
||||
const urlFilename = urlPath.split('/').pop();
|
||||
|
||||
if (urlFilename && /\.(jpg|jpeg|png|gif|webp|svg|bmp|ico)$/i.test(urlFilename)) {
|
||||
filename = urlFilename;
|
||||
} else {
|
||||
// Try to get extension from Content-Type
|
||||
const contentType = response.headers.get('Content-Type');
|
||||
if (contentType?.startsWith('image/')) {
|
||||
const mimeType = contentType.split('/')[1];
|
||||
const extension = mimeType === 'jpeg' ? 'jpg' : mimeType;
|
||||
filename = `downloaded_image_${Date.now()}.${extension}`;
|
||||
} else {
|
||||
filename = `downloaded_image_${Date.now()}.png`;
|
||||
}
|
||||
}
|
||||
|
||||
// Sanitize filename
|
||||
const sanitizedFilename = filename.replace(/\s+/g, '_');
|
||||
const uniqueFilename = await generateUniqueFilename(fs, tmpPath, sanitizedFilename);
|
||||
const vfsPath = `${tmpPath}/${uniqueFilename}`;
|
||||
|
||||
// Read response as array buffer and convert to Uint8Array
|
||||
const arrayBuffer = await response.arrayBuffer();
|
||||
const uint8Array = new Uint8Array(arrayBuffer);
|
||||
|
||||
// Write to VFS
|
||||
await fs.writeFile(vfsPath, uint8Array);
|
||||
|
||||
return { originalUrl: imageUrl, vfsPath };
|
||||
} catch (error) {
|
||||
console.warn(`Error downloading image from ${imageUrl}:`, error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,79 +0,0 @@
|
||||
import type OpenAI from 'openai';
|
||||
|
||||
/**
|
||||
* Detects image URLs in text and splits the text into content parts.
|
||||
* Image URLs are identified by common image file extensions or data URLs.
|
||||
*
|
||||
* @param text - The input text that may contain image URLs
|
||||
* @returns Array of content parts (text and image_url types)
|
||||
*/
|
||||
export function parseImageUrls(
|
||||
text: string
|
||||
): Array<OpenAI.Chat.Completions.ChatCompletionContentPartText | OpenAI.Chat.Completions.ChatCompletionContentPartImage> {
|
||||
const trimmedText = text.trim();
|
||||
|
||||
// Return empty array if input is empty
|
||||
if (!trimmedText) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Regex to match URLs (http/https) that end with image extensions or are data URLs
|
||||
// Matches:
|
||||
// - http:// or https:// URLs ending with image extensions (jpg, jpeg, png, gif, webp, svg, bmp, ico)
|
||||
// - URLs with optional query parameters
|
||||
// - Data URLs (data:image/...;base64,...)
|
||||
const imageUrlRegex = /(https?:\/\/[^\s<>"']+\.(jpg|jpeg|png|gif|webp|svg|bmp|ico)(\?[^\s<>"']*)?|data:image\/[^;]+;base64,[^\s<>"']+)/gi;
|
||||
|
||||
const parts: Array<OpenAI.Chat.Completions.ChatCompletionContentPartText | OpenAI.Chat.Completions.ChatCompletionContentPartImage> = [];
|
||||
let lastIndex = 0;
|
||||
let match: RegExpExecArray | null;
|
||||
|
||||
// Reset regex lastIndex
|
||||
imageUrlRegex.lastIndex = 0;
|
||||
|
||||
while ((match = imageUrlRegex.exec(trimmedText)) !== null) {
|
||||
// Add text before the URL
|
||||
if (match.index > lastIndex) {
|
||||
const textBefore = trimmedText.substring(lastIndex, match.index).trim();
|
||||
if (textBefore) {
|
||||
parts.push({
|
||||
type: 'text',
|
||||
text: textBefore
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Add the image URL
|
||||
const imageUrl = match[0];
|
||||
parts.push({
|
||||
type: 'image_url',
|
||||
image_url: {
|
||||
url: imageUrl
|
||||
}
|
||||
});
|
||||
|
||||
lastIndex = match.index + match[0].length;
|
||||
}
|
||||
|
||||
// Add remaining text after the last URL
|
||||
if (lastIndex < trimmedText.length) {
|
||||
const textAfter = trimmedText.substring(lastIndex).trim();
|
||||
if (textAfter) {
|
||||
parts.push({
|
||||
type: 'text',
|
||||
text: textAfter
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// If no URLs were found, return the original text as a single text part
|
||||
if (parts.length === 0) {
|
||||
return [{
|
||||
type: 'text',
|
||||
text: trimmedText
|
||||
}];
|
||||
}
|
||||
|
||||
return parts;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user