Add tools to configure an image model, add image model to system prompt

This commit is contained in:
Alex Gleason committed 2025-12-07 21:44:28 -06:00
1 parent 0d524f7c36
commit 60a4f77364
9 files changed
+389 -45

No files matched your search

+110
View File
@@ -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 (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[500px]">
<DialogHeader>
<DialogTitle>Configure Image Model</DialogTitle>
<DialogDescription>
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.
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label htmlFor="image-model">Image Model</Label>
<ModelSelector
value={selectedModel}
onChange={setSelectedModel}
placeholder="Select an image model..."
/>
</div>
{selectedModel && !selectedModelSupportsImage && (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>
The selected model does not support image generation. Please choose a different model.
</AlertDescription>
</Alert>
)}
{imageModels.length === 0 && (
<Alert>
<AlertCircle className="h-4 w-4" />
<AlertDescription>
No models with image generation capabilities found. Please configure an AI provider that supports image generation in Settings &gt; AI.
</AlertDescription>
</Alert>
)}
{selectedModel && selectedModelSupportsImage && (
<div className="rounded-lg border p-3 bg-muted/50">
<p className="text-sm text-muted-foreground">
Selected: <span className="font-medium text-foreground">{selectedModel}</span>
</p>
</div>
)}
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>
Cancel
</Button>
<Button onClick={handleSave} disabled={!selectedModel || !selectedModelSupportsImage}>
Save
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
+5
View File
@@ -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'),
+68 -41
View File
@@ -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 (
<div className="py-2 px-3 bg-primary/5 border border-primary/20 rounded-lg">
<div className="flex items-start gap-2">
<QuillySVG className="h-20 px-2 flex-shrink-0" fillColor="hsl(var(--primary))" />
<div className="flex-1 min-w-0">
<div className="space-y-1">
<h4 className="font-semibold text-primary">
Pardon the interruption
</h4>
<p className="text-sm text-muted-foreground">
{message}
{showCreditsButton && provider && (
<>
{' '}
<QuillyCreditsButton provider={provider} />
</>
)}
{actions.length > 0 && (
<>
{' '}
{actions.map((action, i) => (
<span key={action.label}>
<button className="text-primary underline" onClick={action.onClick}>
{action.label}
</button>
{i < actions.length - 1 && <> or </>}
</span>
))}
</>
)}
</p>
<>
<div className="py-2 px-3 bg-primary/5 border border-primary/20 rounded-lg">
<div className="flex items-start gap-2">
<QuillySVG className="h-20 px-2 flex-shrink-0" fillColor="hsl(var(--primary))" />
<div className="flex-1 min-w-0">
<div className="space-y-1">
<h4 className="font-semibold text-primary">
Pardon the interruption
</h4>
<p className="text-sm text-muted-foreground">
{message}
{showCreditsButton && provider && (
<>
{' '}
<QuillyCreditsButton provider={provider} />
</>
)}
{showImageModelButton && (
<>
{' '}
<button className="text-primary underline" onClick={() => setShowImageModelDialog(true)}>
Change image model
</button>
</>
)}
{actions.length > 0 && (
<>
{' '}
{actions.map((action, i) => (
<span key={action.label}>
<button className="text-primary underline" onClick={action.onClick}>
{action.label}
</button>
{i < actions.length - 1 && <> or </>}
</span>
))}
</>
)}
</p>
</div>
</div>
<Button
variant="ghost"
size="sm"
onClick={onDismiss}
className="h-5 w-5 p-0 hover:text-foreground/70 hover:bg-transparent flex-shrink-0"
>
<X className="h-4 w-4" />
</Button>
</div>
<Button
variant="ghost"
size="sm"
onClick={onDismiss}
className="h-5 w-5 p-0 hover:text-foreground/70 hover:bg-transparent flex-shrink-0"
>
<X className="h-4 w-4" />
</Button>
</div>
</div>
<ImageModelDialog
open={showImageModelDialog}
onOpenChange={setShowImageModelDialog}
/>
</>
);
}
+15 -2
View File
@@ -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<ChatPaneRef, ChatPaneProps>(({
// Use external state if provided, otherwise default to false
const isBuildLoading = externalIsBuildLoading || false;
const scrollAreaRef = useRef<HTMLDivElement>(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<ChatPaneRef, ChatPaneProps>(({
} 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]);
+9
View File
@@ -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';
}
}
+10
View File
@@ -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:
@@ -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<ConfigureImageGenerationParams> {
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<string> {
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;
}
}
+5 -2
View File
@@ -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<GenerateImageParams> {
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
);
}
}
+93
View File
@@ -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<Record<string, never>> {
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<string> {
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<string, ProviderModel[]>();
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;
}
}