mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-06 08:37:22 +00:00
Add generate_image tool
This commit is contained in:
8 files changed
+613
-3
No files matched your search
@@ -0,0 +1,250 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { GenerateImageTool } from './GenerateImageTool';
|
||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
|
||||
// Mock the createAIClient function
|
||||
vi.mock('@/lib/ai-client', () => ({
|
||||
createAIClient: vi.fn(),
|
||||
}));
|
||||
|
||||
import { createAIClient } from '@/lib/ai-client';
|
||||
|
||||
describe('GenerateImageTool', () => {
|
||||
let mockFS: JSRuntimeFS;
|
||||
let mockProvider: AIProvider;
|
||||
let mockOpenAI: {
|
||||
images: { generate: ReturnType<typeof vi.fn> };
|
||||
chat: { completions: { create: ReturnType<typeof vi.fn> } };
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
mockFS = {
|
||||
writeFile: vi.fn(),
|
||||
} as unknown as JSRuntimeFS;
|
||||
|
||||
mockProvider = {
|
||||
id: 'openai',
|
||||
name: 'OpenAI',
|
||||
baseURL: 'https://api.openai.com/v1',
|
||||
apiKey: 'test-key',
|
||||
};
|
||||
|
||||
// Create mock OpenAI client
|
||||
mockOpenAI = {
|
||||
images: {
|
||||
generate: vi.fn(),
|
||||
},
|
||||
chat: {
|
||||
completions: {
|
||||
create: vi.fn(),
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
// 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', () => {
|
||||
const tool = new GenerateImageTool(
|
||||
mockFS,
|
||||
'/tmp',
|
||||
mockProvider,
|
||||
'openai/dall-e-3',
|
||||
undefined,
|
||||
undefined
|
||||
);
|
||||
|
||||
expect(tool.description).toBe(
|
||||
'Generate an image from a text prompt and save it to the virtual filesystem'
|
||||
);
|
||||
});
|
||||
|
||||
it('should validate prompt parameter', () => {
|
||||
const tool = new GenerateImageTool(
|
||||
mockFS,
|
||||
'/tmp',
|
||||
mockProvider,
|
||||
'openai/dall-e-3',
|
||||
undefined,
|
||||
undefined
|
||||
);
|
||||
|
||||
const result = tool.inputSchema.safeParse({ prompt: 'a beautiful sunset' });
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('should reject missing prompt', () => {
|
||||
const tool = new GenerateImageTool(
|
||||
mockFS,
|
||||
'/tmp',
|
||||
mockProvider,
|
||||
'openai/dall-e-3',
|
||||
undefined,
|
||||
undefined
|
||||
);
|
||||
|
||||
const result = tool.inputSchema.safeParse({});
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it('should generate image with standard OpenAI provider', async () => {
|
||||
const tool = new GenerateImageTool(
|
||||
mockFS,
|
||||
'/tmp',
|
||||
mockProvider,
|
||||
'openai/dall-e-3',
|
||||
undefined,
|
||||
undefined
|
||||
);
|
||||
|
||||
// Mock the image generation API response
|
||||
const mockImageUrl = 'https://example.com/image.png';
|
||||
const mockImageData = new Uint8Array([1, 2, 3, 4]);
|
||||
|
||||
mockOpenAI.images.generate.mockResolvedValue({
|
||||
data: [{ url: mockImageUrl }],
|
||||
});
|
||||
|
||||
(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();
|
||||
});
|
||||
|
||||
it('should handle OpenRouter provider with modalities', async () => {
|
||||
const openRouterProvider: AIProvider = {
|
||||
id: 'openrouter',
|
||||
name: 'OpenRouter',
|
||||
baseURL: 'https://openrouter.ai/api/v1',
|
||||
apiKey: 'test-key',
|
||||
};
|
||||
|
||||
const tool = new GenerateImageTool(
|
||||
mockFS,
|
||||
'/tmp',
|
||||
openRouterProvider,
|
||||
'openrouter/flux-1.1-pro',
|
||||
undefined,
|
||||
undefined
|
||||
);
|
||||
|
||||
const mockImageUrl = 'https://example.com/image.png';
|
||||
const mockImageData = new Uint8Array([1, 2, 3, 4]);
|
||||
|
||||
mockOpenAI.chat.completions.create.mockResolvedValue({
|
||||
choices: [
|
||||
{
|
||||
message: {
|
||||
content: [
|
||||
{
|
||||
type: 'image_url',
|
||||
image_url: { url: mockImageUrl },
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
(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();
|
||||
});
|
||||
|
||||
it('should throw error when no image URL is returned', async () => {
|
||||
const tool = new GenerateImageTool(
|
||||
mockFS,
|
||||
'/tmp',
|
||||
mockProvider,
|
||||
'openai/dall-e-3',
|
||||
undefined,
|
||||
undefined
|
||||
);
|
||||
|
||||
mockOpenAI.images.generate.mockResolvedValue({
|
||||
data: [],
|
||||
});
|
||||
|
||||
await expect(tool.execute({ prompt: 'test' })).rejects.toThrow(
|
||||
'No image URL returned from the API'
|
||||
);
|
||||
});
|
||||
|
||||
it('should throw error when image download fails', async () => {
|
||||
const tool = new GenerateImageTool(
|
||||
mockFS,
|
||||
'/tmp',
|
||||
mockProvider,
|
||||
'openai/dall-e-3',
|
||||
undefined,
|
||||
undefined
|
||||
);
|
||||
|
||||
const mockImageUrl = 'https://example.com/image.png';
|
||||
|
||||
mockOpenAI.images.generate.mockResolvedValue({
|
||||
data: [{ url: mockImageUrl }],
|
||||
});
|
||||
|
||||
(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'
|
||||
);
|
||||
});
|
||||
|
||||
it('should determine file extension from content type', async () => {
|
||||
const tool = new GenerateImageTool(
|
||||
mockFS,
|
||||
'/tmp',
|
||||
mockProvider,
|
||||
'openai/dall-e-3',
|
||||
undefined,
|
||||
undefined
|
||||
);
|
||||
|
||||
const mockImageUrl = 'https://example.com/image.jpg';
|
||||
const mockImageData = new Uint8Array([1, 2, 3, 4]);
|
||||
|
||||
mockOpenAI.images.generate.mockResolvedValue({
|
||||
data: [{ url: mockImageUrl }],
|
||||
});
|
||||
|
||||
(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$/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,103 @@
|
||||
import { z } from 'zod';
|
||||
import type { Tool } from './Tool';
|
||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
import type { NUser } from '@nostrify/react/login';
|
||||
import { createAIClient } from '@/lib/ai-client';
|
||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||
|
||||
interface GenerateImageParams {
|
||||
prompt: string;
|
||||
}
|
||||
|
||||
export class GenerateImageTool implements Tool<GenerateImageParams> {
|
||||
readonly description = 'Generate an image from a text prompt and save it to the virtual filesystem';
|
||||
|
||||
readonly inputSchema = z.object({
|
||||
prompt: z.string().describe('A detailed text description of the image to generate'),
|
||||
});
|
||||
|
||||
constructor(
|
||||
private fs: JSRuntimeFS,
|
||||
private tmpPath: string,
|
||||
private provider: AIProvider,
|
||||
private imageModel: string,
|
||||
private user?: NUser,
|
||||
private corsProxy?: string,
|
||||
) {}
|
||||
|
||||
async execute(args: GenerateImageParams): Promise<string> {
|
||||
const { prompt } = args;
|
||||
|
||||
try {
|
||||
const client = createAIClient(this.provider, this.user, this.corsProxy);
|
||||
|
||||
let imageUrl: string | undefined;
|
||||
|
||||
// OpenRouter uses chat completions with modalities
|
||||
if (this.provider.id === 'openrouter') {
|
||||
const response = await client.chat.completions.create({
|
||||
model: this.imageModel,
|
||||
messages: [
|
||||
{
|
||||
role: 'user',
|
||||
content: prompt,
|
||||
},
|
||||
],
|
||||
modalities: ['image'] as never[], // Type assertion needed as OpenAI SDK doesn't have this typed
|
||||
});
|
||||
|
||||
// Extract image URL 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;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Standard OpenAI image generation
|
||||
const response = await client.images.generate({
|
||||
model: this.imageModel,
|
||||
prompt,
|
||||
n: 1,
|
||||
response_format: 'url',
|
||||
});
|
||||
|
||||
imageUrl = response.data?.[0]?.url;
|
||||
}
|
||||
|
||||
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}`;
|
||||
const filepath = `${this.tmpPath}/${filename}`;
|
||||
|
||||
// Write image to VFS
|
||||
await this.fs.writeFile(filepath, imageData);
|
||||
|
||||
return `Generated image: ${filepath}`;
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`Failed to generate image: ${error instanceof Error ? error.message : String(error)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user