diff --git a/src/components/ImageModelDialog.tsx b/src/components/ImageModelDialog.tsx new file mode 100644 index 00000000..b06fc1f4 --- /dev/null +++ b/src/components/ImageModelDialog.tsx @@ -0,0 +1,110 @@ +import { useState, useEffect } from 'react'; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from '@/components/ui/dialog'; +import { Button } from '@/components/ui/button'; +import { Label } from '@/components/ui/label'; +import { Alert, AlertDescription } from '@/components/ui/alert'; +import { AlertCircle } from 'lucide-react'; +import { useAISettings } from '@/hooks/useAISettings'; +import { useProviderModels } from '@/hooks/useProviderModels'; +import { ModelSelector } from '@/components/ModelSelector'; + +interface ImageModelDialogProps { + open: boolean; + onOpenChange: (open: boolean) => void; +} + +export function ImageModelDialog({ open, onOpenChange }: ImageModelDialogProps) { + const { settings, updateSettings } = useAISettings(); + const { models } = useProviderModels(); + const [selectedModel, setSelectedModel] = useState(settings.imageModel || ''); + + // Update selected model when settings change + useEffect(() => { + if (settings.imageModel) { + setSelectedModel(settings.imageModel); + } + }, [settings.imageModel]); + + // Filter models to only show those with image generation capability + const imageModels = models.filter(model => + model.modalities?.includes('image') + ); + + // Check if the selected model supports image generation + const selectedModelSupportsImage = selectedModel + ? imageModels.some(m => m.fullId === selectedModel) + : false; + + const handleSave = () => { + if (selectedModel && selectedModelSupportsImage) { + updateSettings({ imageModel: selectedModel }); + onOpenChange(false); + } + }; + + return ( + + + + Configure Image Model + + Select an AI model that supports image generation. The model selector will show all available models, but only models with image generation capabilities can be saved. + + + +
+
+ + +
+ + {selectedModel && !selectedModelSupportsImage && ( + + + + The selected model does not support image generation. Please choose a different model. + + + )} + + {imageModels.length === 0 && ( + + + + No models with image generation capabilities found. Please configure an AI provider that supports image generation in Settings > AI. + + + )} + + {selectedModel && selectedModelSupportsImage && ( +
+

+ Selected: {selectedModel} +

+
+ )} +
+ + + + + +
+
+ ); +} diff --git a/src/components/Quilly.test.tsx b/src/components/Quilly.test.tsx index 59d388e1..ffaa00a2 100644 --- a/src/components/Quilly.test.tsx +++ b/src/components/Quilly.test.tsx @@ -28,6 +28,11 @@ vi.mock('./CreditsDialog', () => ({ CreditsDialog: () => null })); +// Mock ImageModelDialog to avoid NostrProvider dependency +vi.mock('./ImageModelDialog', () => ({ + ImageModelDialog: () => null +})); + describe('Quilly', () => { const defaultProps = { error: new Error('Generic error'), diff --git a/src/components/Quilly.tsx b/src/components/Quilly.tsx index b7f275b4..76cd3e51 100644 --- a/src/components/Quilly.tsx +++ b/src/components/Quilly.tsx @@ -11,7 +11,9 @@ import { ProjectPreviewConsoleError } from '@/lib/consoleMessages'; import { useState } from 'react'; import { MalformedToolCallError } from '@/lib/errors/MalformedToolCallError'; import { EmptyMessageError } from '@/lib/errors/EmptyMessageError'; +import { ImageGenerationError } from '@/lib/errors/ImageGenerationError'; import { AIProvider } from '@/contexts/AISettingsContext'; +import { ImageModelDialog } from '@/components/ImageModelDialog'; export interface QuillyProps { error: Error; @@ -29,6 +31,7 @@ interface ErrorBody { label: string; onClick: () => void; }>; + showImageModelButton?: boolean; } interface QuillyContentProps { @@ -43,8 +46,18 @@ interface QuillyContentProps { function QuillyContent({ error, onDismiss, onNewChat, onOpenModelSelector, onTryAgain, onRequestConsoleErrorHelp, provider }: QuillyContentProps) { const navigate = useNavigate(); + const [showImageModelDialog, setShowImageModelDialog] = useState(false); + + const renderBody = (error: Error | APIError | MalformedToolCallError | ProjectPreviewConsoleError | ImageGenerationError): ErrorBody & { showCreditsButton?: boolean } => { + // Handle Image Generation Errors + if (error instanceof ImageGenerationError) { + return { + message: 'Image generation failed. This could be due to an issue with the selected image model or the AI provider. Try selecting a different image model.', + showImageModelButton: true, + actions: [], + }; + } - const renderBody = (error: Error | APIError | MalformedToolCallError | ProjectPreviewConsoleError): ErrorBody & { showCreditsButton?: boolean } => { // Handle Project Preview Console Errors if (error instanceof ProjectPreviewConsoleError) { return { @@ -207,51 +220,65 @@ function QuillyContent({ error, onDismiss, onNewChat, onOpenModelSelector, onTry }; }; - const { message, actions = [], showCreditsButton } = renderBody(error); + const { message, actions = [], showCreditsButton, showImageModelButton } = renderBody(error); return ( -
-
- -
-
-

- Pardon the interruption -

-

- {message} - {showCreditsButton && provider && ( - <> - {' '} - - - )} - {actions.length > 0 && ( - <> - {' '} - {actions.map((action, i) => ( - - - {i < actions.length - 1 && <> or } - - ))} - - )} -

+ <> +
+
+ +
+
+

+ Pardon the interruption +

+

+ {message} + {showCreditsButton && provider && ( + <> + {' '} + + + )} + {showImageModelButton && ( + <> + {' '} + + + )} + {actions.length > 0 && ( + <> + {' '} + {actions.map((action, i) => ( + + + {i < actions.length - 1 && <> or } + + ))} + + )} +

+
+
-
-
+ + ); } diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index cf268a52..28e68d8d 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -36,6 +36,8 @@ import { ShellTool } from '@/lib/tools/ShellTool'; import { ReadConsoleMessagesTool } from '@/lib/tools/ReadConsoleMessagesTool'; import { SkillTool } from '@/lib/tools/SkillTool'; import { GenerateImageTool } from '@/lib/tools/GenerateImageTool'; +import { ViewAvailableModelsTool } from '@/lib/tools/ViewAvailableModelsTool'; +import { ConfigureImageGenerationTool } from '@/lib/tools/ConfigureImageGenerationTool'; import { createMCPTools } from '@/lib/tools/MCPTool'; import { ProjectPreviewConsoleError } from '@/lib/consoleMessages'; import { toolToOpenAI } from '@/lib/tools/openai-adapter'; @@ -100,7 +102,8 @@ export const ChatPane = forwardRef(({ // Use external state if provided, otherwise default to false const isBuildLoading = externalIsBuildLoading || false; const scrollAreaRef = useRef(null); - const { isConfigured, settings, addRecentlyUsedModel } = useAISettings(); + const aiSettings = useAISettings(); + const { isConfigured, settings, addRecentlyUsedModel } = aiSettings; const [providerModel, setProviderModel] = useState(() => { // Initialize with first recently used model if available, otherwise empty return settings.recentlyUsedModels?.[0] || ''; @@ -206,10 +209,20 @@ export const ChatPane = forwardRef(({ } catch (error) { console.warn('Failed to parse imageModel:', error); } + } else { + // If imageModel is not configured, provide tools to help configure it + tools.view_available_models = new ViewAvailableModelsTool( + models, + settings.imageModel + ); + tools.configure_image_generation = new ConfigureImageGenerationTool( + aiSettings, + models + ); } return tools; - }, [fs, git, cwd, user, projectId, projectsPath, tmpPath, pluginsPath, config.corsProxy, settings.imageModel, settings.providers, models, handleFileChanged]); + }, [fs, git, cwd, user, projectId, projectsPath, tmpPath, pluginsPath, config.corsProxy, settings, aiSettings, models, handleFileChanged]); // MCP tools wrapped for execution const mcpToolWrappers = useMemo(() => createMCPTools(mcpClients), [mcpClients]); diff --git a/src/lib/errors/ImageGenerationError.ts b/src/lib/errors/ImageGenerationError.ts new file mode 100644 index 00000000..719d35b9 --- /dev/null +++ b/src/lib/errors/ImageGenerationError.ts @@ -0,0 +1,9 @@ +/** + * Error thrown when image generation fails + */ +export class ImageGenerationError extends Error { + constructor(message: string, public readonly originalError?: Error) { + super(message); + this.name = 'ImageGenerationError'; + } +} diff --git a/src/lib/system.ts b/src/lib/system.ts index e4fa3a00..62e6f9c7 100644 --- a/src/lib/system.ts +++ b/src/lib/system.ts @@ -165,6 +165,16 @@ When a project is first created, you (the AI) choose an appropriate template fro - URL: {{ template.url }} {% endfor %} +## Image Generation + +Shakespeare supports AI-powered image generation. Users can configure an image model in **Settings > AI** under the "Advanced" section. + +**Important Notes:** +- Only models that support image generation (with "image" in their modalities) can be used +- If users experience issues with image generation, they should try selecting a different image model in Settings > AI +- Recommended models include gpt-image-1, dall-e-3, or similar high-quality yet affordable options +- The generate_image tool will only be available once a compatible image model is configured + ## Available Tools {% if tools.length > 0 %} You have access to the following tools: diff --git a/src/lib/tools/ConfigureImageGenerationTool.ts b/src/lib/tools/ConfigureImageGenerationTool.ts new file mode 100644 index 00000000..6b880943 --- /dev/null +++ b/src/lib/tools/ConfigureImageGenerationTool.ts @@ -0,0 +1,74 @@ +import { z } from 'zod'; +import type { Tool } from './Tool'; +import type { AISettingsContextType } from '@/contexts/AISettingsContext'; + +interface ConfigureImageGenerationParams { + modelId: string; +} + +interface ProviderModel { + id: string; + name?: string; + provider: string; + fullId: string; + description?: string; + contextLength?: number; + modalities?: string[]; +} + +export class ConfigureImageGenerationTool implements Tool { + readonly description = 'Configure the AI model to use for image generation. The modelId must be a complete model identifier in the format "provider/model" (e.g., "openrouter/openai/gpt-image-1", "openai/dall-e-3", or "shakespeare/gpt-image-1"). IMPORTANT: You MUST call the view_available_models tool FIRST to see which models are available and support image generation (look for models with "image" in their modalities). Select a high-quality yet affordable model like gpt-image-1 or dall-e-3 unless the user has specific requirements. Consider the currently configured model (if any) to understand user preferences.'; + + readonly inputSchema = z.object({ + modelId: z.string().describe('The complete model identifier in "provider/model" format (e.g., "openrouter/openai/gpt-image-1", "openai/dall-e-3"). Must be from the available models list.'), + }); + + constructor( + private aiSettings: AISettingsContextType, + private models: ProviderModel[], + ) {} + + async execute(args: ConfigureImageGenerationParams): Promise { + const { modelId } = args; + + // Validate model ID format + if (!modelId.includes('/')) { + return 'ERROR: Invalid model ID format. The modelId must be in "provider/model" format (e.g., "openrouter/openai/gpt-image-1" or "openai/dall-e-3").\n\n' + + 'Please call the view_available_models tool first to see the list of available models and their full IDs, then use one of those full IDs.'; + } + + // Check if model exists in available models + const model = this.models.find(m => m.fullId === modelId); + + if (!model) { + return `ERROR: Model "${modelId}" is not available in the configured providers.\n\n` + + 'Please call the view_available_models tool to see the list of available models, then select one from that list.'; + } + + // Check if model supports image generation + const supportsImage = model.modalities?.includes('image'); + + if (!supportsImage) { + return `ERROR: Model "${modelId}" does not support image generation.\n\n` + + 'Please call the view_available_models tool and select a model that has "image" listed in its modalities (look for models marked with "✅ Supports image generation").'; + } + + // Update the settings + this.aiSettings.updateSettings({ imageModel: modelId }); + + let response = `✅ Successfully configured image generation!\n\n`; + response += `**Image Model**: ${modelId}\n`; + + if (model.name) { + response += `**Name**: ${model.name}\n`; + } + + if (model.description) { + response += `**Description**: ${model.description}\n`; + } + + response += `\nThe generate_image tool is now available and ready to use. You can generate images by calling the generate_image tool with a detailed text prompt.`; + + return response; + } +} diff --git a/src/lib/tools/GenerateImageTool.ts b/src/lib/tools/GenerateImageTool.ts index 25132fd9..fa43a378 100644 --- a/src/lib/tools/GenerateImageTool.ts +++ b/src/lib/tools/GenerateImageTool.ts @@ -5,6 +5,7 @@ import type { NUser } from '@nostrify/react/login'; import { createAIClient } from '@/lib/ai-client'; import type { JSRuntimeFS } from '@/lib/JSRuntime'; import { proxyUrl } from '../proxyUrl'; +import { ImageGenerationError } from '@/lib/errors/ImageGenerationError'; interface GenerateImageParams { prompt: string; @@ -154,8 +155,10 @@ export class GenerateImageTool implements Tool { return `Generated image: ${filepath}`; } catch (error) { - throw new Error( - `Failed to generate image: ${error instanceof Error ? error.message : String(error)}` + const errorMessage = error instanceof Error ? error.message : String(error); + throw new ImageGenerationError( + `Failed to generate image: ${errorMessage}`, + error instanceof Error ? error : undefined ); } } diff --git a/src/lib/tools/ViewAvailableModelsTool.ts b/src/lib/tools/ViewAvailableModelsTool.ts new file mode 100644 index 00000000..99fceb5a --- /dev/null +++ b/src/lib/tools/ViewAvailableModelsTool.ts @@ -0,0 +1,93 @@ +import { z } from 'zod'; +import type { Tool } from './Tool'; + +interface ProviderModel { + id: string; + name?: string; + provider: string; + fullId: string; + description?: string; + contextLength?: number; + modalities?: string[]; +} + +export class ViewAvailableModelsTool implements Tool> { + readonly description = 'View all available AI models across all configured providers, including their capabilities. This tool MUST be called before attempting to configure an image model, as it shows which models support image generation and displays the currently configured model (if any) to understand user preferences.'; + + readonly inputSchema = z.object({}); + + constructor( + private models: ProviderModel[], + private currentImageModel?: string, + ) {} + + async execute(): Promise { + if (this.models.length === 0) { + return 'No AI models are currently available. Please configure at least one AI provider in Settings > AI.'; + } + + // Group models by provider + const modelsByProvider = new Map(); + for (const model of this.models) { + const providerModels = modelsByProvider.get(model.provider) || []; + providerModels.push(model); + modelsByProvider.set(model.provider, providerModels); + } + + // Build output + let output = '# Available AI Models\n\n'; + + // Add note about current image model if configured + if (this.currentImageModel) { + output += `**Current Image Model**: ${this.currentImageModel}\n\n`; + output += 'This indicates the user\'s current preference. When selecting a new model, consider choosing a similar provider or model family unless the user requests otherwise.\n\n'; + } else { + output += '**Current Image Model**: Not configured\n\n'; + } + + output += '## Models by Provider\n\n'; + + for (const [provider, providerModels] of modelsByProvider) { + output += `### ${provider}\n\n`; + + for (const model of providerModels) { + const isCurrentModel = this.currentImageModel === model.fullId; + const marker = isCurrentModel ? ' ⭐ **CURRENT**' : ''; + + output += `- **${model.fullId}**${marker}\n`; + + if (model.name && model.name !== model.id) { + output += ` - Name: ${model.name}\n`; + } + + if (model.description) { + output += ` - Description: ${model.description}\n`; + } + + if (model.contextLength) { + output += ` - Context Length: ${model.contextLength.toLocaleString()} tokens\n`; + } + + if (model.modalities && model.modalities.length > 0) { + output += ` - Modalities: ${model.modalities.join(', ')}\n`; + + // Highlight image generation capability + if (model.modalities.includes('image')) { + output += ` - ✅ **Supports image generation**\n`; + } + } + + output += '\n'; + } + } + + output += '\n## Image Generation Recommendations\n\n'; + output += 'When selecting an image model:\n'; + output += '1. **Look for models with "image" in their modalities** - these support image generation\n'; + output += '2. **Consider cost and quality** - Models like gpt-image-1, dall-e-3, or similar are good balanced choices\n'; + output += '3. **Check the current model** (marked with ⭐) to understand user preferences\n'; + output += '4. **Prefer models from the same provider** as the current model when possible\n'; + + return output; + } +}