Core Feature: Prompt Optimization
Relevant source files
The following files were used as context for generating this wiki page:
The Prompt Optimization feature is an integrated AI-powered tool designed to enhance user-supplied text prompts. It transforms simple ideas into detailed, cinematic descriptions optimized for advanced image generation models. This process is handled by an external API service, abstracting the complexity of prompt engineering from the end-user and aiming to produce more visually stunning results.
The feature is exposed to the user through a simple "Optimize" button in the main interface. When triggered, it sends the current prompt to the service and replaces the user's text with the AI-enhanced version, ready for image generation.
Sources: README.md, App.tsx:280-294, services/hfService.ts:233-287
UI Integration and User Flow
The prompt optimization feature is initiated from the main control panel, located directly adjacent to the prompt input area.
Sources: App.tsx:482-500
Component Breakdown
| Component | Description | File & Lines |
|---|---|---|
| Optimize Button | A button labeled "Optimize" (or "Optimizing...") that triggers the enhancement process. It is disabled if the prompt text area is empty or if an optimization is already in progress. | App.tsx:487-498 |
Wand2 Icon | A visual indicator on the button, suggesting a "magic" enhancement. It is replaced by a Loader2 spinner icon during the API call. | App.tsx:493-496 |
prompt State | A React state variable that holds the text for the image prompt. It is both the input for the optimization and the target for the returned, enhanced prompt. | App.tsx:75 |
isOptimizing State | A boolean React state that tracks the loading status of the optimization process. It controls the button's disabled state and the display of the loading spinner. | App.tsx:81 |
User Interaction Flow
The following diagram illustrates the sequence of events from the user's perspective when they interact with the optimization feature.
This diagram shows the end-to-end flow for prompt optimization, from user action to the final UI update.
Sources: App.tsx:280-294, services/hfService.ts:233-287
Service Layer and API Communication
The core logic resides in the optimizePrompt function within services/hfService.ts. This function is responsible for communicating with the external Pollinations.ai API.
Sources: services/hfService.ts:233-287
API Endpoint
- URL:
https://text.pollinations.ai/openai - Method:
POST - Service: Pollinations.ai
Sources: services/hfService.ts:4
Request Payload
The service sends a structured JSON payload to the API. The most critical part is the messages array, which contains a system message that instructs the AI on how to behave.
| Field | Type | Description | Source |
|---|---|---|---|
model | string | The specific AI model to use. Set to 'openai-fast'. | services/hfService.ts:241 |
messages | array | An array of message objects defining the conversation context. | services/hfService.ts:242 |
stream | boolean | Determines if the response should be streamed. Set to false. | services/hfService.ts:259 |
The system message within the messages array contains specific instructions for the AI model:
- Persona: "master AI image prompt engineering advisor"
- Goal: Rewrite, expand, and enhance user prompts for cinematic, hyper-realistic results.
- Key Elements: Optimize for dramatic lighting, intricate textures, and compelling composition.
- Constraints:
- Output must be under 300 words.
- Output must be only the refined prompt text (no markdown, quotes, or preambles).
- Output language must match the user's prompt language.
Sources: services/hfService.ts:245-256
Core Implementation
The optimizePrompt function orchestrates the API call and response handling.
// Source: services/hfService.ts:233-287
export const optimizePrompt = async (originalPrompt: string): Promise<string> => {
try {
const response = await fetch(POLLINATIONS_API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: 'openai-fast',
messages: [
{
role: 'system',
content: `I am a master AI image prompt engineering advisor...`
},
{
role: 'user',
content: originalPrompt
}
],
stream: false
}),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
const content = data.choices?.[0]?.message?.content;
return content || originalPrompt;
} catch (error) {
console.error("Prompt Optimization Error:", error);
throw error;
}
};
Sources: services/hfService.ts:233-287
State Management and Data Flow
Within the main App component, several state variables manage the optimization feature's lifecycle. The handleOptimizePrompt function orchestrates the state changes and service calls.
Sources: App.tsx:280-294
State Transition Flowchart
This diagram illustrates the internal state transitions within the App component when the feature is used.
This flowchart shows how the isOptimizing, prompt, and error states are managed during the optimization process.
Sources: App.tsx:280-294
Handler Function
The handleOptimizePrompt function in App.tsx connects the UI to the service layer and manages the component's state.
// Source: App.tsx:280-294
const handleOptimizePrompt = async () => {
if (!prompt.trim()) return;
setIsOptimizing(true);
setError(null);
try {
const optimized = await optimizePrompt(prompt);
setPrompt(optimized);
} catch (err: any) {
console.error("Optimization failed", err);
setError("Failed to optimize prompt. Please try again.");
} finally {
setIsOptimizing(false);
}
};
Sources: App.tsx:280-294
Summary
The Prompt Optimization feature is a powerful utility that significantly enhances the user experience by automating the craft of writing effective image generation prompts. It is implemented through a clean separation of concerns: the App.tsx component handles UI and state management, while services/hfService.ts encapsulates the external API communication. By leveraging the Pollinations.ai service with a carefully crafted system prompt, the application can transform basic user input into rich, descriptive text, leading to higher-quality image outputs.
Sources: README.md, App.tsx, services/hfService.ts