mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Fix generate_image tool, fix rendering of image from VFS
This commit is contained in:
6 files changed
+288
-118
No files matched your search
@@ -4,6 +4,7 @@ import { Wrench, Eye, FileText, Edit, Package, PackageMinus, GitCommit, BookOpen
|
||||
import type { AIMessage } from '@/lib/SessionManager';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { UserMessage } from '@/components/UserMessage';
|
||||
import { VFSImage } from '@/components/VFSImage';
|
||||
import OpenAI from 'openai';
|
||||
import { useTheme } from '@/hooks/useTheme';
|
||||
import { isEmptyMessage } from '@/lib/isEmptyMessage';
|
||||
@@ -274,18 +275,13 @@ export const AIMessageItem = memo(({
|
||||
const filename = imagePath.split('/').pop() || imagePath;
|
||||
|
||||
return (
|
||||
<div className="mt-1 p-3 bg-muted/30 rounded border">
|
||||
<div className="space-y-2">
|
||||
<div className="text-xs text-muted-foreground font-mono">
|
||||
{imagePath}
|
||||
</div>
|
||||
<img
|
||||
src={imagePath}
|
||||
alt={filename}
|
||||
className="max-w-full h-auto rounded cursor-pointer hover:opacity-90 transition-opacity"
|
||||
onClick={() => setExpandedImageUrl(imagePath)}
|
||||
/>
|
||||
</div>
|
||||
<div className="mt-1 p-3 bg-muted/30 rounded border max-w-xs">
|
||||
<VFSImage
|
||||
path={imagePath}
|
||||
alt={filename}
|
||||
className="max-w-full h-auto rounded cursor-pointer hover:opacity-90 transition-opacity"
|
||||
onClick={() => setExpandedImageUrl(imagePath)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -398,11 +394,19 @@ export const AIMessageItem = memo(({
|
||||
>
|
||||
{expandedImageUrl && (
|
||||
<div className="relative flex items-center justify-center">
|
||||
<img
|
||||
src={expandedImageUrl}
|
||||
alt="Expanded image"
|
||||
className="max-w-full max-h-[95vh] w-auto h-auto object-contain rounded-lg"
|
||||
/>
|
||||
{expandedImageUrl.startsWith('/') ? (
|
||||
<VFSImage
|
||||
path={expandedImageUrl}
|
||||
alt="Expanded image"
|
||||
className="max-w-full max-h-[95vh] w-auto h-auto object-contain rounded-lg"
|
||||
/>
|
||||
) : (
|
||||
<img
|
||||
src={expandedImageUrl}
|
||||
alt="Expanded image"
|
||||
className="max-w-full max-h-[95vh] w-auto h-auto object-contain rounded-lg"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</DialogPrimitive.Content>
|
||||
|
||||
@@ -49,6 +49,8 @@ const AppConfigSchema = z.object({
|
||||
fsPathTemplates: z.string().min(1),
|
||||
sentryDsn: z.string(),
|
||||
sentryEnabled: z.boolean(),
|
||||
systemPrompt: z.string(),
|
||||
imageModel: z.string(),
|
||||
}) satisfies z.ZodType<AppConfig>;
|
||||
|
||||
export function AppProvider(props: AppProviderProps) {
|
||||
|
||||
@@ -47,6 +47,7 @@ import { ShakespeareLogo } from '@/components/ShakespeareLogo';
|
||||
import { ChatInput } from '@/components/Shakespeare/ChatInput';
|
||||
import { buildMessageContent } from '@/lib/buildMessageContent';
|
||||
import { DotAI } from '@/lib/DotAI';
|
||||
import { parseProviderModel } from '@/lib/parseProviderModel';
|
||||
|
||||
// Clean interfaces now handled by proper hooks
|
||||
|
||||
@@ -186,19 +187,18 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
|
||||
// Add generate_image tool if imageModel is configured
|
||||
if (config.imageModel) {
|
||||
// Extract provider ID from imageModel (format: "provider/model")
|
||||
const providerId = config.imageModel.split('/')[0];
|
||||
const provider = settings.providers.find(p => p.id === providerId);
|
||||
|
||||
if (provider) {
|
||||
try {
|
||||
const { provider, model } = parseProviderModel(config.imageModel, settings.providers);
|
||||
tools.generate_image = new GenerateImageTool(
|
||||
fs,
|
||||
tmpPath,
|
||||
provider,
|
||||
config.imageModel,
|
||||
model,
|
||||
user,
|
||||
config.corsProxy
|
||||
);
|
||||
} catch (error) {
|
||||
console.warn('Failed to parse imageModel:', error);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { AlertCircle } from 'lucide-react';
|
||||
|
||||
interface VFSImageProps {
|
||||
path: string;
|
||||
alt: string;
|
||||
className?: string;
|
||||
onClick?: () => void;
|
||||
}
|
||||
|
||||
export function VFSImage({ path, alt, className, onClick }: VFSImageProps) {
|
||||
const { fs } = useFS();
|
||||
const [dataUri, setDataUri] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
let isMounted = true;
|
||||
|
||||
async function loadImage() {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
// Read the file from VFS
|
||||
const imageData = await fs.readFile(path);
|
||||
|
||||
if (!isMounted) return;
|
||||
|
||||
// Determine MIME type from file extension
|
||||
const extension = path.split('.').pop()?.toLowerCase() || '';
|
||||
const mimeTypes: Record<string, string> = {
|
||||
'png': 'image/png',
|
||||
'jpg': 'image/jpeg',
|
||||
'jpeg': 'image/jpeg',
|
||||
'gif': 'image/gif',
|
||||
'webp': 'image/webp',
|
||||
'svg': 'image/svg+xml',
|
||||
'bmp': 'image/bmp',
|
||||
};
|
||||
const mimeType = mimeTypes[extension] || 'image/png';
|
||||
|
||||
// Convert bytes to base64
|
||||
const base64 = btoa(
|
||||
Array.from(imageData)
|
||||
.map(byte => String.fromCharCode(byte))
|
||||
.join('')
|
||||
);
|
||||
|
||||
// Create data URI
|
||||
const uri = `data:${mimeType};base64,${base64}`;
|
||||
|
||||
if (isMounted) {
|
||||
setDataUri(uri);
|
||||
setIsLoading(false);
|
||||
}
|
||||
} catch (err) {
|
||||
if (isMounted) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to load image');
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
loadImage();
|
||||
|
||||
return () => {
|
||||
isMounted = false;
|
||||
};
|
||||
}, [fs, path]);
|
||||
|
||||
if (isLoading) {
|
||||
return <Skeleton className={className || 'w-full h-64'} />;
|
||||
}
|
||||
|
||||
if (error || !dataUri) {
|
||||
return (
|
||||
<div className={className || 'w-full h-64 flex items-center justify-center bg-muted rounded'}>
|
||||
<div className="text-center text-muted-foreground space-y-2">
|
||||
<AlertCircle className="h-8 w-8 mx-auto" />
|
||||
<p className="text-xs">{error || 'Failed to load image'}</p>
|
||||
<p className="text-xs font-mono">{path}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<img
|
||||
src={dataUri}
|
||||
alt={alt}
|
||||
className={className}
|
||||
onClick={onClick}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -44,9 +44,6 @@ describe('GenerateImageTool', () => {
|
||||
|
||||
// Mock createAIClient to return our mock
|
||||
(createAIClient as ReturnType<typeof vi.fn>).mockReturnValue(mockOpenAI);
|
||||
|
||||
// Mock fetch globally
|
||||
global.fetch = vi.fn();
|
||||
});
|
||||
|
||||
it('should have correct description', () => {
|
||||
@@ -54,7 +51,7 @@ describe('GenerateImageTool', () => {
|
||||
mockFS,
|
||||
'/tmp',
|
||||
mockProvider,
|
||||
'openai/dall-e-3',
|
||||
'dall-e-3',
|
||||
undefined,
|
||||
undefined
|
||||
);
|
||||
@@ -69,7 +66,7 @@ describe('GenerateImageTool', () => {
|
||||
mockFS,
|
||||
'/tmp',
|
||||
mockProvider,
|
||||
'openai/dall-e-3',
|
||||
'dall-e-3',
|
||||
undefined,
|
||||
undefined
|
||||
);
|
||||
@@ -83,7 +80,7 @@ describe('GenerateImageTool', () => {
|
||||
mockFS,
|
||||
'/tmp',
|
||||
mockProvider,
|
||||
'openai/dall-e-3',
|
||||
'dall-e-3',
|
||||
undefined,
|
||||
undefined
|
||||
);
|
||||
@@ -97,31 +94,26 @@ describe('GenerateImageTool', () => {
|
||||
mockFS,
|
||||
'/tmp',
|
||||
mockProvider,
|
||||
'openai/dall-e-3',
|
||||
'dall-e-3',
|
||||
undefined,
|
||||
undefined
|
||||
);
|
||||
|
||||
// Mock the image generation API response
|
||||
const mockImageUrl = 'https://example.com/image.png';
|
||||
// Mock the image generation API response with b64_json
|
||||
const mockImageData = new Uint8Array([1, 2, 3, 4]);
|
||||
const base64Data = btoa(String.fromCharCode(...mockImageData));
|
||||
|
||||
mockOpenAI.images.generate.mockResolvedValue({
|
||||
data: [{ url: mockImageUrl }],
|
||||
data: [{ b64_json: base64Data }],
|
||||
});
|
||||
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
headers: new Headers({ 'content-type': 'image/png' }),
|
||||
blob: async () => ({
|
||||
arrayBuffer: async () => mockImageData.buffer,
|
||||
}),
|
||||
} as Response);
|
||||
|
||||
const result = await tool.execute({ prompt: 'a beautiful sunset' });
|
||||
|
||||
expect(result).toMatch(/^Generated image: \/tmp\/generated-\d+\.png$/);
|
||||
expect(mockFS.writeFile).toHaveBeenCalled();
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
||||
expect.stringMatching(/^\/tmp\/generated-\d+\.png$/),
|
||||
expect.any(Uint8Array)
|
||||
);
|
||||
});
|
||||
|
||||
it('should handle OpenRouter provider with modalities', async () => {
|
||||
@@ -136,22 +128,24 @@ describe('GenerateImageTool', () => {
|
||||
mockFS,
|
||||
'/tmp',
|
||||
openRouterProvider,
|
||||
'openrouter/flux-1.1-pro',
|
||||
'flux-1.1-pro',
|
||||
undefined,
|
||||
undefined
|
||||
);
|
||||
|
||||
const mockImageUrl = 'https://example.com/image.png';
|
||||
// Create a data URI with base64 encoded image data
|
||||
const mockImageData = new Uint8Array([1, 2, 3, 4]);
|
||||
const base64Data = btoa(String.fromCharCode(...mockImageData));
|
||||
const dataUri = `data:image/png;base64,${base64Data}`;
|
||||
|
||||
mockOpenAI.chat.completions.create.mockResolvedValue({
|
||||
choices: [
|
||||
{
|
||||
message: {
|
||||
content: [
|
||||
images: [
|
||||
{
|
||||
type: 'image_url',
|
||||
image_url: { url: mockImageUrl },
|
||||
image_url: { url: dataUri },
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -159,26 +153,21 @@ describe('GenerateImageTool', () => {
|
||||
],
|
||||
});
|
||||
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
headers: new Headers({ 'content-type': 'image/png' }),
|
||||
blob: async () => ({
|
||||
arrayBuffer: async () => mockImageData.buffer,
|
||||
}),
|
||||
} as Response);
|
||||
|
||||
const result = await tool.execute({ prompt: 'a beautiful sunset' });
|
||||
|
||||
expect(result).toMatch(/^Generated image: \/tmp\/generated-\d+\.png$/);
|
||||
expect(mockFS.writeFile).toHaveBeenCalled();
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
||||
expect.stringMatching(/^\/tmp\/generated-\d+\.png$/),
|
||||
expect.any(Uint8Array)
|
||||
);
|
||||
});
|
||||
|
||||
it('should throw error when no image URL is returned', async () => {
|
||||
it('should throw error when no image data is returned', async () => {
|
||||
const tool = new GenerateImageTool(
|
||||
mockFS,
|
||||
'/tmp',
|
||||
mockProvider,
|
||||
'openai/dall-e-3',
|
||||
'dall-e-3',
|
||||
undefined,
|
||||
undefined
|
||||
);
|
||||
@@ -188,63 +177,118 @@ describe('GenerateImageTool', () => {
|
||||
});
|
||||
|
||||
await expect(tool.execute({ prompt: 'test' })).rejects.toThrow(
|
||||
'No image URL returned from the API'
|
||||
'No base64 image data returned from the API'
|
||||
);
|
||||
});
|
||||
|
||||
it('should throw error when image download fails', async () => {
|
||||
it('should throw error when OpenRouter returns invalid response', async () => {
|
||||
const openRouterProvider: AIProvider = {
|
||||
id: 'openrouter',
|
||||
name: 'OpenRouter',
|
||||
baseURL: 'https://openrouter.ai/api/v1',
|
||||
apiKey: 'test-key',
|
||||
};
|
||||
|
||||
const tool = new GenerateImageTool(
|
||||
mockFS,
|
||||
'/tmp',
|
||||
mockProvider,
|
||||
'openai/dall-e-3',
|
||||
openRouterProvider,
|
||||
'flux-1.1-pro',
|
||||
undefined,
|
||||
undefined
|
||||
);
|
||||
|
||||
const mockImageUrl = 'https://example.com/image.png';
|
||||
|
||||
mockOpenAI.images.generate.mockResolvedValue({
|
||||
data: [{ url: mockImageUrl }],
|
||||
mockOpenAI.chat.completions.create.mockResolvedValue({
|
||||
choices: [
|
||||
{
|
||||
message: {
|
||||
content: 'Invalid response',
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
ok: false,
|
||||
statusText: 'Not Found',
|
||||
} as Response);
|
||||
|
||||
await expect(tool.execute({ prompt: 'test' })).rejects.toThrow(
|
||||
'Failed to download image: Not Found'
|
||||
'Failed to generate image: Invalid response format from the API'
|
||||
);
|
||||
});
|
||||
|
||||
it('should determine file extension from content type', async () => {
|
||||
it('should determine file extension from OpenRouter data URI', async () => {
|
||||
const openRouterProvider: AIProvider = {
|
||||
id: 'openrouter',
|
||||
name: 'OpenRouter',
|
||||
baseURL: 'https://openrouter.ai/api/v1',
|
||||
apiKey: 'test-key',
|
||||
};
|
||||
|
||||
const tool = new GenerateImageTool(
|
||||
mockFS,
|
||||
'/tmp',
|
||||
mockProvider,
|
||||
'openai/dall-e-3',
|
||||
openRouterProvider,
|
||||
'flux-1.1-pro',
|
||||
undefined,
|
||||
undefined
|
||||
);
|
||||
|
||||
const mockImageUrl = 'https://example.com/image.jpg';
|
||||
// Create a data URI with JPEG format
|
||||
const mockImageData = new Uint8Array([1, 2, 3, 4]);
|
||||
const base64Data = btoa(String.fromCharCode(...mockImageData));
|
||||
const dataUri = `data:image/jpeg;base64,${base64Data}`;
|
||||
|
||||
mockOpenAI.images.generate.mockResolvedValue({
|
||||
data: [{ url: mockImageUrl }],
|
||||
mockOpenAI.chat.completions.create.mockResolvedValue({
|
||||
choices: [
|
||||
{
|
||||
message: {
|
||||
images: [
|
||||
{
|
||||
type: 'image_url',
|
||||
image_url: { url: dataUri },
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
headers: new Headers({ 'content-type': 'image/jpeg' }),
|
||||
blob: async () => ({
|
||||
arrayBuffer: async () => mockImageData.buffer,
|
||||
}),
|
||||
} as Response);
|
||||
|
||||
const result = await tool.execute({ prompt: 'a beautiful sunset' });
|
||||
|
||||
expect(result).toMatch(/^Generated image: \/tmp\/generated-\d+\.jpeg$/);
|
||||
});
|
||||
|
||||
it('should throw error when OpenRouter returns invalid data URI', async () => {
|
||||
const openRouterProvider: AIProvider = {
|
||||
id: 'openrouter',
|
||||
name: 'OpenRouter',
|
||||
baseURL: 'https://openrouter.ai/api/v1',
|
||||
apiKey: 'test-key',
|
||||
};
|
||||
|
||||
const tool = new GenerateImageTool(
|
||||
mockFS,
|
||||
'/tmp',
|
||||
openRouterProvider,
|
||||
'flux-1.1-pro',
|
||||
undefined,
|
||||
undefined
|
||||
);
|
||||
|
||||
mockOpenAI.chat.completions.create.mockResolvedValue({
|
||||
choices: [
|
||||
{
|
||||
message: {
|
||||
images: [
|
||||
{
|
||||
type: 'image_url',
|
||||
image_url: { url: 'https://example.com/image.png' },
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await expect(tool.execute({ prompt: 'test' })).rejects.toThrow(
|
||||
'Invalid data URI format'
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -20,7 +20,7 @@ export class GenerateImageTool implements Tool<GenerateImageParams> {
|
||||
private fs: JSRuntimeFS,
|
||||
private tmpPath: string,
|
||||
private provider: AIProvider,
|
||||
private imageModel: string,
|
||||
private model: string,
|
||||
private user?: NUser,
|
||||
private corsProxy?: string,
|
||||
) {}
|
||||
@@ -31,12 +31,13 @@ export class GenerateImageTool implements Tool<GenerateImageParams> {
|
||||
try {
|
||||
const client = createAIClient(this.provider, this.user, this.corsProxy);
|
||||
|
||||
let imageUrl: string | undefined;
|
||||
let imageData: Uint8Array;
|
||||
let extension = 'png';
|
||||
|
||||
// OpenRouter uses chat completions with modalities
|
||||
if (this.provider.id === 'openrouter') {
|
||||
const response = await client.chat.completions.create({
|
||||
model: this.imageModel,
|
||||
model: this.model,
|
||||
messages: [
|
||||
{
|
||||
role: 'user',
|
||||
@@ -46,45 +47,66 @@ export class GenerateImageTool implements Tool<GenerateImageParams> {
|
||||
modalities: ['image'] as never[], // Type assertion needed as OpenAI SDK doesn't have this typed
|
||||
});
|
||||
|
||||
// Extract image URL from response
|
||||
// Extract image data URI from response
|
||||
const message = response.choices[0]?.message;
|
||||
if (message?.content) {
|
||||
const content = Array.isArray(message.content) ? message.content : [{ type: 'text', text: message.content }];
|
||||
const imageContent = content.find((part: { type: string; image_url?: { url: string } }) => part.type === 'image_url');
|
||||
if (imageContent && 'image_url' in imageContent) {
|
||||
imageUrl = imageContent.image_url?.url;
|
||||
}
|
||||
if (!message) {
|
||||
throw new Error('No message returned from the API');
|
||||
}
|
||||
|
||||
const result = z.object({
|
||||
images: z.object({
|
||||
type: z.literal('image_url'),
|
||||
image_url: z.object({
|
||||
url: z.string(),
|
||||
}),
|
||||
}).array().min(1),
|
||||
}).safeParse(message);
|
||||
|
||||
if (!result.success) {
|
||||
throw new Error('Invalid response format from the API');
|
||||
}
|
||||
|
||||
const dataUri = result.data.images[0].image_url.url;
|
||||
|
||||
// Parse data URI: data:image/png;base64,iVBORw0KGgoAAAANS...
|
||||
const dataUriMatch = dataUri.match(/^data:image\/([^;]+);base64,(.+)$/);
|
||||
if (!dataUriMatch) {
|
||||
throw new Error('Invalid data URI format');
|
||||
}
|
||||
|
||||
extension = dataUriMatch[1];
|
||||
const base64Data = dataUriMatch[2];
|
||||
|
||||
// Decode base64 to bytes
|
||||
const binaryString = atob(base64Data);
|
||||
imageData = new Uint8Array(binaryString.length);
|
||||
for (let i = 0; i < binaryString.length; i++) {
|
||||
imageData[i] = binaryString.charCodeAt(i);
|
||||
}
|
||||
} else {
|
||||
// Standard OpenAI image generation
|
||||
// Standard OpenAI image generation - use b64_json format
|
||||
const response = await client.images.generate({
|
||||
model: this.imageModel,
|
||||
model: this.model,
|
||||
prompt,
|
||||
n: 1,
|
||||
response_format: 'url',
|
||||
response_format: 'b64_json',
|
||||
});
|
||||
|
||||
imageUrl = response.data?.[0]?.url;
|
||||
const b64Json = response.data?.[0]?.b64_json;
|
||||
if (!b64Json) {
|
||||
throw new Error('No base64 image data returned from the API');
|
||||
}
|
||||
|
||||
// Decode base64 to bytes
|
||||
const binaryString = atob(b64Json);
|
||||
imageData = new Uint8Array(binaryString.length);
|
||||
for (let i = 0; i < binaryString.length; i++) {
|
||||
imageData[i] = binaryString.charCodeAt(i);
|
||||
}
|
||||
|
||||
// Extension is PNG for standard OpenAI responses
|
||||
extension = 'png';
|
||||
}
|
||||
|
||||
if (!imageUrl) {
|
||||
throw new Error('No image URL returned from the API');
|
||||
}
|
||||
|
||||
// Download the image
|
||||
const imageResponse = await fetch(imageUrl);
|
||||
if (!imageResponse.ok) {
|
||||
throw new Error(`Failed to download image: ${imageResponse.statusText}`);
|
||||
}
|
||||
|
||||
const imageBlob = await imageResponse.blob();
|
||||
const imageBuffer = await imageBlob.arrayBuffer();
|
||||
const imageData = new Uint8Array(imageBuffer);
|
||||
|
||||
// Determine file extension from content type
|
||||
const contentType = imageResponse.headers.get('content-type') || 'image/png';
|
||||
const extension = contentType.split('/')[1]?.split(';')[0] || 'png';
|
||||
|
||||
// Generate unique filename
|
||||
const timestamp = Date.now();
|
||||
const filename = `generated-${timestamp}.${extension}`;
|
||||
|
||||
Reference in new issue
Block a user