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

+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;
}
}