Compare commits

...
9 Commits
Author SHA1 Message Date
THE_BEAST\me 94feeb61c7 Update README and docs image for v1.7.0 2025-12-14 02:30:16 -05:00
THE_BEAST\me 3884f72552 Enhance prompt generation with three modes, custom image analysis, and model preferences; improve model selection and caching logic 2025-12-14 02:21:16 -05:00
THE_BEAST\me cae791a169 Enhance prompt generation with vision model support, JSON output, and improved model management
- Updated README to reflect new features and enhancements.
- Added Qwen3VL vision model support for image analysis.
- Introduced JSON output format option with structured scene breakdown.
- Implemented adjustable context size parameter (512-32768 tokens).
- Improved model selection logic and automatic mmproj file download for vision models.
- Enhanced prompt generator to handle image input and provide detailed descriptions.
- Updated requirements and version to 1.6.0.
2025-12-13 23:33:14 -05:00
THE_BEAST\me e6f56f3a75 Slight improvement to prompt generation rules.
Was too keen on adding text when not necesseray
2025-11-30 22:49:08 -05:00
THE_BEAST\me bc682b3680 Enhance LLM input handling and caching logic in PromptManager and PromptGenerator 2025-11-30 21:38:38 -05:00
Francois Beaudry 9982853cac Fix formatting of Llama.cpp installation note 2025-11-30 00:03:23 -05:00
THE_BEAST\me 7cc4478aa0 Version 1.5.0 - Introduced Prompt Generator and Options nodes with llama.cpp integration, enhanced prompt management features, and improved model handling. 2025-11-29 23:57:05 -05:00
THE_BEAST\me 9f70a8634a Version 1.1.0 - Added LLM input toggle feature 2025-11-28 17:58:31 -05:00
THE_BEAST\me 5d0ea866ab Simplified readme 2025-11-28 16:53:56 -05:00
10 changed files with 1332 additions and 199 deletions
+136 -110
View File
@@ -1,20 +1,37 @@
# ComfyUI Prompt Manager
A simple custom node for [ComfyUI](https://github.com/comfyanonymous/ComfyUI) that allows you to organize, manage, and save prompts into different categories. Useful for managing your prompt library and capturing outputs from LLM nodes.
A custom node for [ComfyUI](https://github.com/comfyanonymous/ComfyUI) for organizing, generating, and enhancing prompts using local llama.cpp models with vision analysis support.
(**Llama.cpp needs to be installed and accessible from command prompt.**)
<div align="center">
<img src="docs/prompt_manager.png" alt="Prompt Manager">
</div>
## Features
- **Category Organization**: Create and manage multiple categories to organize your prompts (e.g., Character, Style, Environment, Lighting, Mood)
### Key features:
### Prompt Manager:
- **Category Organization**: Create and manage multiple categories to organize your prompts
- **Save & Load Prompts**: Quickly save and recall your favorite prompts with custom names
- **LLM Integration**: Connect text outputs from other nodes (like LLM generators) and save them directly
- **Direct Editing**: Edit prompts directly in the node or select from your saved library
- **Persistent Storage**: All prompts are saved in your ComfyUI user folder and persist across sessions
- **Pre-loaded Templates**: Comes with example prompts across various categories
- **Easy Management**: Delete categories or individual prompts with confirmation dialogs
- **LLM Input Toggle**: Connect text outputs from other nodes and toggle between using them or your internal prompts
- **LLM Input Toggle**: When in use, display of categories and prompt is disabled, allowing user to switch category and save.
- **Persistent Storage**: All prompts saved in your ComfyUI user folder
### Prompt Generator
- **Three Generation Modes**: Enhance text prompts, analyze images, or analyze images with custom instructions
- **Prompt Enhancement**: Transform basic prompts into detailed descriptions using local LLMs
- **Vision Analysis**: Analyze images with Qwen3VL models to generate detailed descriptions
- **Custom Image Analysis**: Provide your own instructions for image analysis
- **JSON Output**: Optional structured JSON output with scene breakdown
- **Automatic Server Management**: Starts/stops llama.cpp server as needed
- **Smart Model Selection**: Auto-selects appropriate model (vision or text) based on mode
- **Model Preferences**: Set preferred models in ComfyUI Settings for automatic selection
### Prompt Generator Options
- **Model Selection**: Choose from local models or download Qwen3 (1.7B/4B/8B) and Qwen3VL (4B/8B) from HuggingFace
- **Auto-Download**: Automatically downloads both model and required mmproj files for vision models
- **Context Size**: Adjustable context window (512-32768 tokens)
- **LLM Parameters**: Fine-tune temperature, top_k, top_p, min_p, repeat_penalty
- **Custom Instructions**: Override default system prompt for different enhancement styles
## Installation
@@ -28,112 +45,76 @@ A simple custom node for [ComfyUI](https://github.com/comfyanonymous/ComfyUI) th
git clone https://github.com/FranckyB/ComfyUI-Prompt-Manager.git
```
3. Restart ComfyUI
3. Install dependencies:
```bash
cd ComfyUI-Prompt-Manager
pip install -r requirements.txt
```
4. Install llama.cpp. It can be found here: [llama.cpp install](https://github.com/ggml-org/llama.cpp/blob/master/docs/install.md)
5. If you have them, place your .gguf models in the models/gguf folder. (Create folder if not present)
6. Restart ComfyUI
## Usage
### Basic Usage
### Prompt Manager
1. **Add the Node**: Right-click in ComfyUI → Add Node → Prompt Manager → Prompt Manager
1. **Add the Node**: Add Node → Prompt Manager
2. **Select a Category**: Use the dropdown to choose from your categories
3. **Choose a Prompt**: Select a saved prompt from the name dropdown
4. **Connect prompt output**: Connect Prompt Manager output to your clip text encode node.
2. **Select a Category**: Use the dropdown to choose from your categories (Character, Style, Environment, etc.)
3. **Choose a Prompt**: Select a saved prompt from the dropdown
### Prompt Generator
4. **Use the Output**: Connect the output to any node that accepts text/string input
**Basic Usage** (assuming a model is present in models\gguf):
1. **Add the Node**: Add Node → Prompt Generator
2. **Select Mode**: Choose from:
- "Enhance User Prompt" - Improve text prompts with LLM
- "Analyze Image" - Generate detailed image descriptions
- "Analyze Image with Prompt" - Analyze images with custom instructions
3. **Connect inputs**: Connect image for vision modes, or just use text for enhancement mode
4. **Save memory**: Toggle "stop_server_after" ON to free VRAM after generation
5. **Run Workflow**: Generated prompt displays and can be saved to Prompt Manager
### Managing Prompts
**Advanced Usage**:
1. **Add the Options Node**: Add Node → Prompt Generator Options
2. **Connect Options**: Connect the options node to the Prompt Generator Options input
3. **Select from available models**: Select from models found in your modeld\gguf folder. Qwen models will be available to download.
4. **Adjust settings**: Adjust LLM parameters (temperature, top_k, etc.)
5. **Customize LLM**: Customize the default LLM instructions to modify the responses llama returns.
#### Saving a Prompt
1. Type or paste your prompt into the text field (or have it connected from another node)
2. Click the **"Save Prompt"** button
3. Enter a name for your prompt
4. Click OK
> **Note**: If a prompt with the same name exists in the current category, you'll be asked to confirm before overwriting.
**Qwen models found in options**
- Qwen3-1.7B-Q8_0.gguf: Fastest, lowest VRAM (~2GB)
- Qwen3-4B-Q8_0.gguf: Balanced performance (~4GB VRAM)
- Qwen3-8B-Q8_0.gguf: Best quality, highest VRAM (~8GB)
- Qwen3VL-4B-Instruct-Q8_0.gguf: Vision model, balanced performance (~5GB VRAM)
- Qwen3VL-8B-Instruct-Q8_0.gguf: Vision model, best quality (~9GB VRAM)
#### Creating a New Category
1. Click the **"New Category"** button
2. Enter a name for your category
3. Click OK
**Model Management**:
- Place gguf files in models/gguf folder
- Downloaded models are also placed in this folder.
#### Deleting a Category
1. Select the category you want to delete
2. Click the **"Del Category"** button
3. Confirm the deletion
**Model Preferences**:
- Set preferred models in ComfyUI Settings → Prompt Manager → Model Preferences
- **Preferred Base Model**: Used for "Enhance User Prompt" mode (text-only models)
- **Preferred Vision Model**: Used for "Analyze Image" modes (Qwen3VL models)
- Leave empty to auto-select smallest available model
- Changes are saved automatically in ComfyUI settings
#### Deleting a Prompt
1. Select the prompt you want to delete
2. Click the **"Del Prompt"** button
3. Confirm the deletion
## Requirements
### Working with LLM Outputs
You can capture and save outputs from LLM nodes:
1. Connect an LLM output (or any text output) to the **"text"** input of the Prompt Manager node
2. Run your workflow - the generated text will appear in the prompt field
3. Click **"Save Prompt"** to save the LLM-generated text to your library
4. Give it a descriptive name for future use
This is perfect for:
- Saving interesting prompts generated by LLMs
- Building a library of AI-generated variations
- Quickly iterating and saving the best results
## File Structure
```
comfyui-prompt-manager/
├── __init__.py # Node registration
├── prompt_manager.py # Main node logic and API endpoints
├── default_prompts.json # Default prompt templates
├── js/
│ └── prompt_manager.js # Frontend UI and interactions
└── README.md # This file
```
## Data Storage
Prompts are stored in:
```
ComfyUI/user/default/prompt_manager.json
```
The file is automatically created on first use, copying from `default_prompts.json`. You can:
- Back up this file to save your prompt library
- Share it with others
- Edit it directly (with caution)
## Default Categories
The node comes pre-loaded with example prompts in the following categories:
- **Character**: Fantasy warriors, sci-fi explorers, medieval knights, etc.
- **Style**: Cinematic, oil painting, watercolor, photorealistic, etc.
- **Environment**: Forests, cyberpunk cities, space stations, ancient temples, etc.
- **Lighting**: Golden hour, Rembrandt lighting, neon atmosphere, moonlight, etc.
- **Composition**: Dynamic action, minimalist zen, panoramic vistas, etc.
- **Mood**: Dark and ominous, peaceful, energetic, melancholic, etc.
- **Illustrious**: Anime-style character prompts and scene descriptions
Feel free to modify or delete these to suit your needs!
## Tips & Tricks
### Workflow Organization
- Create categories that match your workflow (e.g., "Characters", "Backgrounds", "Styles")
- Use descriptive names for your prompts to find them easily later
- Regularly backup your `prompt_manager.json` file
### LLM Integration
- Connect multiple Prompt Manager nodes to capture different LLM variations
- Use one node to store "seeds" and another for "final results"
- Combine with LLM nodes to build an iterative prompt refinement workflow
### Editing Prompts
- You can edit prompts directly in the text field even when loaded from the library
- Changes are not saved automatically - click "Save Prompt" to update
- Use "Save Prompt" with the same name to overwrite an existing prompt
- ComfyUI
- Python 3.8+
- requests >= 2.31.0
- huggingface_hub >= 0.20.0
- psutil >= 5.9.0
- tqdm >= 4.66.0
- Pillow >= 10.0.0
- llama-server (from llama.cpp)
## Troubleshooting
@@ -144,17 +125,62 @@ Feel free to modify or delete these to suit your needs!
- **Solution**: Click the "Save Prompt" button after making changes. Direct edits in the text field are temporary.
**Problem**: Can't see LLM output in the node
- **Solution**: Make sure the LLM output is connected to the "text" input and run the workflow.
- **Solution**: Make sure the LLM output is connected to the "llm_input" and run the workflow.
**Problem**: Node appears too small
- **Solution**: Resize the node by dragging the bottom-right corner. The node will maintain its size in your workflow.
**Problem**: "llama-server command not found"
- **Solution**: Install llama.cpp and make sure `llama-server` is available in command line. See [llama.cpp releases](https://github.com/ggerganov/llama.cpp/releases)
**Problem**: "No models found"
- **Solution**: Either place a .gguf file in the `models/` folder, or connect the Prompt Generator Option node and select a model size (1.7B, 4B, or 8B) to download from HuggingFace
**Problem**: Server won't start
- **Solution**: Check that port 8080 is not in use. Close any existing llama-server processes.
**Problem**: Model download fails
- **Solution**: Check your internet connection and HuggingFace availability. Large models may take time to download.
**Problem**: Generation is slow
- **Solution**: Either, Use a smaller quantized model (Q4 instead of Q8) or toggle 'stop_server_after' to quit llama.cpp after generating prompt.
## Changelog
### Version 1.0.1
### Version 1.7.0
- Added three-mode prompt generator: "Enhance User Prompt", "Analyze Image", "Analyze Image with Prompt"
- Enhanced vision model workflow with dedicated image analysis modes
- Added custom image analysis with user-provided instructions (e.g., "describe the lighting", "identify objects")
- Added model preferences system integrated with ComfyUI Settings
- Added automatic model preference management (separate settings for base and vision models)
- Improved model selection with preference fallback to smallest model
- Filtered mmproj files from model selection dropdowns
- All preferences stored in ComfyUI settings for persistence across updates
### Version 1.6.0
- Added Qwen3VL vision model support for image analysis
- Added JSON output format option with structured scene breakdown
- Added adjustable context size parameter (512-32768 tokens)
- Added automatic mmproj file download for vision models
- Added image resizing to ~2MP to optimize token usage
- Added token usage logging for monitoring context consumption
- Improved model selection logic with automatic VL/non-VL detection
- Fixed multiple directory support for model search (gguf + LLM folders)
### Version 1.5.1
- LLM output remains avaiable when use llm is off. So it can be edited
- Improved Caching detection, any change to options will be detected and force a new ouput
- Improved some UI quirks
### Version 1.5.0
- Added Prompt Generator node with automatic llama.cpp server management
- Added Prompt Generator Options node for model selection and parameters
- Automatic model detection and auto-download from HuggingFace for Qwen3 models.
- VRAM management with optional server shutdown
### Version 1.1.0
- Added LLM input toggle for switching between internal and external text
- Made text fields scrollable even when disabled
- Fixed reload bugs with toggle state
### Version 1.0.0
- Initial release
- Category management
- Prompt save/load functionality
- Category and prompt management
- LLM output integration
- Pre-loaded example prompts
- ComfyUI-style UI dialogs
+10 -3
View File
@@ -1,18 +1,25 @@
"""
ComfyUI Prompt Manager - A simple custom node for saving and reusing prompts
A prompt management system for ComfyUI with LLM input support
"""
__version__ = "1.0.1"
__version__ = "1.5.1"
__author__ = "François Beaudry"
__license__ = "MIT"
from .prompt_manager import PromptManagerNode
from .prompt_manager import PromptManager
from .prompt_generator import PromptGenerator
from .prompt_generator_options import PromptGenOptions
NODE_CLASS_MAPPINGS = {
"PromptManager": PromptManagerNode,
"PromptManager": PromptManager,
"PromptGenerator": PromptGenerator,
"PromptGenOptions": PromptGenOptions
}
NODE_DISPLAY_NAME_MAPPINGS = {
"PromptManager": "Prompt Manager",
"PromptGenerator": "Prompt Generator",
"PromptGenOptions": "Prompt Generator Options"
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 47 KiB

After

Width:  |  Height:  |  Size: 268 KiB

+174 -68
View File
@@ -4,6 +4,71 @@ import { api } from "../../scripts/api.js";
app.registerExtension({
name: "PromptManager",
settings: [
{
id: "PromptManager.PreferredBaseModel",
category: ["Prompt Manager", "Model Preferences", "Base Model (text enhancement)"],
name: "Preferred Base Model",
tooltip: "Default model for 'Enhance User Prompt' mode (leave empty to auto-select smallest)",
type: "text",
defaultValue: "",
async onChange(value) {
try {
await fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "preferred_base_model", value: value })
});
} catch (error) {
console.error("[PromptManager] Error saving base model preference:", error);
}
}
},
{
id: "PromptManager.PreferredVisionModel",
category: ["Prompt Manager", "Model Preferences", "Vision Model (image analysis)"],
name: "Preferred Vision Model",
tooltip: "Default model for 'Analyze Image' modes (leave empty to auto-select smallest)",
type: "text",
defaultValue: "",
async onChange(value) {
try {
await fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "preferred_vision_model", value: value })
});
} catch (error) {
console.error("[PromptManager] Error saving vision model preference:", error);
}
}
}
],
async setup() {
// Load settings from ComfyUI and sync to Python cache
try {
const baseModel = app.ui.settings.getSettingValue("PromptManager.PreferredBaseModel", "");
const visionModel = app.ui.settings.getSettingValue("PromptManager.PreferredVisionModel", "");
// Sync both settings to Python cache
if (baseModel) {
await fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "preferred_base_model", value: baseModel })
});
}
if (visionModel) {
await fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "preferred_vision_model", value: visionModel })
});
}
} catch (error) {
console.error("[PromptManager] Error syncing preferences:", error);
}
},
async beforeRegisterNodeDef(nodeType, nodeData, app) {
if (nodeData.name === "PromptManager") {
const onNodeCreated = nodeType.prototype.onNodeCreated;
@@ -28,11 +93,42 @@ app.registerExtension({
promptNameWidget.label = "name";
}
// Listen for text updates from backend (when connected inputs change)
const useExternalWidget = this.widgets.find(w => w.name === "use_external");
if (useExternalWidget) {
useExternalWidget.label = "use llm input";
}
// Make text widget scrollable even when disabled
if (promptTextWidget && promptTextWidget.inputEl) {
promptTextWidget.inputEl.style.pointerEvents = "auto";
promptTextWidget.inputEl.addEventListener("mousedown", function(e) {
if (this.disabled) {
// Allow scrolling but prevent editing
e.stopPropagation();
}
});
}
// Listen for text updates from backend (when connected inputs change or toggle changes)
api.addEventListener("prompt-manager-update-text", (event) => {
if (String(event.detail.node_id) === String(this.id)) {
if (promptTextWidget) {
promptTextWidget.value = event.detail.prompt;
const useExternal = event.detail.use_external || false;
const llmInput = event.detail.llm_input || "";
if (useExternal && llmInput) {
// When using external, display the LLM input text (grayed out)
promptTextWidget.value = llmInput;
promptTextWidget.disabled = true;
// Keep scrolling enabled
if (promptTextWidget.inputEl) {
promptTextWidget.inputEl.style.pointerEvents = "auto";
}
} else {
// When using internal, enable the widget
promptTextWidget.disabled = false;
}
this.serialize_widgets = true;
app.graph.setDirtyCanvas(true, true);
}
@@ -44,7 +140,7 @@ app.registerExtension({
addButtonBar(node);
setupCategoryChangeHandler(node);
filterPromptDropdown(node);
setupInputConnectionHandler(node);
setupUseExternalToggleHandler(node);
// After buttons are added, ensure height is sufficient
setTimeout(() => {
@@ -76,7 +172,7 @@ app.registerExtension({
if (!node.buttonBarAttached) {
addButtonBar(node);
setupCategoryChangeHandler(node);
setupInputConnectionHandler(node);
setupUseExternalToggleHandler(node);
}
});
}, 100);
@@ -231,15 +327,10 @@ function setupCategoryChangeHandler(node) {
const categoryWidget = node.widgets.find(w => w.name === "category");
const promptWidget = node.widgets.find(w => w.name === "name");
const textWidget = node.widgets.find(w => w.name === "text");
const useExternalWidget = node.widgets.find(w => w.name === "use_external");
if (!categoryWidget || !promptWidget || !textWidget) return;
// Check if text input is connected from another node
const isTextInputConnected = () => {
const promptTextInput = node.inputs?.find(inp => inp.name === "text");
return promptTextInput && promptTextInput.link != null;
};
const originalCallback = categoryWidget.callback;
// Update prompt dropdown when category changes
@@ -255,14 +346,15 @@ function setupCategoryChangeHandler(node) {
if (promptNames.length > 0) {
promptWidget.value = promptNames[0];
// Only update text widget if not connected to another node
if (!isTextInputConnected()) {
// Only update text widget if not using external
const useExternal = useExternalWidget ? useExternalWidget.value : false;
if (!useExternal) {
const promptData = node.prompts[category][promptNames[0]];
textWidget.value = promptData?.prompt || "";
}
} else {
promptWidget.value = "";
if (!isTextInputConnected()) {
if (!useExternal) {
textWidget.value = "";
}
}
@@ -280,8 +372,9 @@ function setupCategoryChangeHandler(node) {
originalPromptCallback.apply(this, arguments);
}
// Only update text if not connected to another node
if (!isTextInputConnected()) {
// Only update text if not using external
const useExternal = useExternalWidget ? useExternalWidget.value : false;
if (!useExternal) {
const category = categoryWidget.value;
if (node.prompts && node.prompts[category] && node.prompts[category][value]) {
const promptData = node.prompts[category][value];
@@ -325,70 +418,83 @@ function setupCategoryChangeHandler(node) {
promptWidget.options._values = promptWidget.options.values || [];
}
function setupInputConnectionHandler(node) {
// Handle displaying value from connected input nodes
function setupUseExternalToggleHandler(node) {
const textWidget = node.widgets?.find(w => w.name === "text");
if (!textWidget) return;
const useExternalWidget = node.widgets?.find(w => w.name === "use_external");
const categoryWidget = node.widgets?.find(w => w.name === "category");
const promptWidget = node.widgets?.find(w => w.name === "name");
if (!textWidget || !useExternalWidget) return;
const originalGetInputOrProperty = node.getInputOrProperty;
if (originalGetInputOrProperty) {
node.getInputOrProperty = function(name) {
const value = originalGetInputOrProperty.apply(this, arguments);
// Apply initial state on load/reload
const applyToggleState = (value) => {
const llmInputConnection = node.inputs?.find(inp => inp.name === "llm_input");
const isLlmConnected = llmInputConnection && llmInputConnection.link != null;
if (name === "text" && value !== undefined) {
textWidget.value = value;
if (value && isLlmConnected) {
// Using LLM and it's connected - disable text widget immediately
textWidget.disabled = true;
// Keep scrolling enabled but prevent editing
if (textWidget.inputEl) {
textWidget.inputEl.style.pointerEvents = "auto";
textWidget.inputEl.readOnly = true;
}
return value;
};
}
const graphCanvas = app.graph;
if (graphCanvas) {
const originalBeforeChange = graphCanvas.beforeChange;
graphCanvas.beforeChange = function() {
if (originalBeforeChange) {
originalBeforeChange.apply(this, arguments);
}
const promptTextInput = node.inputs?.find(inp => inp.name === "text");
if (promptTextInput && promptTextInput.link != null) {
const link = graphCanvas.links[promptTextInput.link];
if (link) {
const originNode = graphCanvas.getNodeById(link.origin_id);
if (originNode) {
const outputValue = originNode.getOutputData?.(link.origin_slot);
if (outputValue !== undefined) {
textWidget.value = outputValue;
}
}
}
}
};
}
const api = app.api;
if (api) {
const originalQueuePrompt = api.queuePrompt;
api.queuePrompt = async function(number, workflow) {
const promptTextInput = node.inputs?.find(inp => inp.name === "text");
if (promptTextInput && promptTextInput.link != null) {
const graph = app.graph;
const link = graph.links[promptTextInput.link];
if (link) {
const originNode = graph.getNodeById(link.origin_id);
if (originNode && originNode.widgets) {
const outputWidget = originNode.widgets.find(w => w.name === link.origin_slot || w.name === "text" || w.name === "STRING");
// Try to show LLM value if available
const graph = app.graph;
const link = graph.links[llmInputConnection.link];
if (link) {
const originNode = graph.getNodeById(link.origin_id);
if (originNode) {
// Try to get the output value from the origin node
const outputData = originNode.getOutputData?.(link.origin_slot);
if (outputData !== undefined) {
textWidget.value = outputData;
} else if (originNode.widgets) {
// Fallback: try to find widget with matching output
const outputWidget = originNode.widgets.find(w => w.name === "text" || w.name === "STRING");
if (outputWidget) {
textWidget.value = outputWidget.value;
}
}
}
}
} else {
// Using internal text - enable widget but keep current text (which may be LLM output)
textWidget.disabled = false;
if (textWidget.inputEl) {
textWidget.inputEl.readOnly = false;
}
}
};
return originalQueuePrompt.apply(this, arguments);
};
}
// Apply initial state when the handler is set up
applyToggleState(useExternalWidget.value);
const originalCallback = useExternalWidget.callback;
useExternalWidget.callback = function(value) {
// Check if llm_input is connected
const llmInputConnection = node.inputs?.find(inp => inp.name === "llm_input");
const isLlmConnected = llmInputConnection && llmInputConnection.link != null;
// Prevent turning on if nothing is connected
if (value && !isLlmConnected) {
useExternalWidget.value = false;
node.serialize_widgets = true;
app.graph.setDirtyCanvas(true, true);
return;
}
if (originalCallback) {
originalCallback.apply(this, arguments);
}
applyToggleState(value);
node.serialize_widgets = true;
app.graph.setDirtyCanvas(true, true);
};
}
function createButton(text, callback) {
+209
View File
@@ -0,0 +1,209 @@
"""
Utility functions for managing llama.cpp models
"""
import os
import glob
import json
import folder_paths
from huggingface_hub import HfApi
from tqdm.auto import tqdm
import requests
# Predefined models - use real filenames as keys
QWEN_MODELS = {
"Qwen3-1.7B-Q8_0.gguf": {
"repo": "Qwen/Qwen3-1.7B-GGUF"
},
"Qwen3-4B-Q8_0.gguf": {
"repo": "Qwen/Qwen3-4B-GGUF"
},
"Qwen3-8B-Q8_0.gguf": {
"repo": "Qwen/Qwen3-8B-GGUF"
},
"Qwen3VL-4B-Instruct-Q8_0.gguf": {
"repo": "Qwen/Qwen3-VL-4B-Instruct-GGUF",
"mmproj": "mmproj-Qwen3VL-4B-Instruct-Q8_0.gguf"
},
"Qwen3VL-8B-Instruct-Q8_0.gguf": {
"repo": "Qwen/Qwen3-VL-8B-Instruct-GGUF",
"mmproj": "mmproj-Qwen3VL-8B-Instruct-Q8_0.gguf"
}
}
# Preferences are now stored in ComfyUI settings (comfy.settings.json)
# and accessed via the settings API in prompt_manager.py
def get_models_directory():
"""Get the path to the primary models directory (ComfyUI/models/gguf) for downloads"""
# Register both gguf and LLM folders
if "gguf" not in folder_paths.folder_names_and_paths:
gguf_dir = os.path.join(folder_paths.models_dir, "gguf")
folder_paths.add_model_folder_path("gguf", gguf_dir)
if "LLM" not in folder_paths.folder_names_and_paths:
llm_dir = os.path.join(folder_paths.models_dir, "LLM")
folder_paths.add_model_folder_path("LLM", llm_dir)
# Return gguf as the primary directory (for downloads)
models_dir = folder_paths.get_folder_paths("gguf")[0]
# Create directory if it doesn't exist
os.makedirs(models_dir, exist_ok=True)
return models_dir
def get_all_model_directories():
"""Get all directories where models can be found"""
get_models_directory() # Ensure folders are registered
directories = []
for folder_type in ["gguf", "LLM"]:
if folder_type in folder_paths.folder_names_and_paths:
dirs = folder_paths.get_folder_paths(folder_type)
directories.extend(dirs)
return directories
def get_local_models():
"""Get list of local .gguf model files from all model directories"""
all_dirs = get_all_model_directories()
all_models = set() # Use set to avoid duplicates
for models_dir in all_dirs:
if os.path.exists(models_dir):
gguf_files = glob.glob(os.path.join(models_dir, "*.gguf"))
for f in gguf_files:
basename = os.path.basename(f)
# Filter out mmproj files
if not basename.startswith("mmproj-"):
all_models.add(basename)
# Return sorted list of unique filenames
return sorted(list(all_models))
def get_huggingface_models():
"""Get list of predefined Qwen models available for download"""
return list(QWEN_MODELS.keys())
def get_all_models():
"""Get combined list of local and HuggingFace models, excluding already downloaded ones and mmproj files"""
local_models = get_local_models() # Already filtered
models_dir = get_models_directory()
# List all known filenames, local ones first
all_models = []
# Add local models first (already filtered by get_local_models)
if local_models:
all_models.extend(local_models)
# Add remote models (not present locally), excluding mmproj files
for filename in QWEN_MODELS.keys():
if filename not in all_models and not filename.startswith("mmproj-"):
all_models.append(filename)
return all_models
def is_model_local(model_name):
"""Check if a model exists locally in any of the model directories"""
if model_name == "--- Download from HuggingFace ---":
return False
all_dirs = get_all_model_directories()
for models_dir in all_dirs:
model_path = os.path.join(models_dir, model_name)
if os.path.exists(model_path):
return True
return False
def get_model_path(model_name):
"""Get the full path to a model file, searching all model directories"""
all_dirs = get_all_model_directories()
# Check each directory for the model
for models_dir in all_dirs:
model_path = os.path.join(models_dir, model_name)
if os.path.exists(model_path):
return model_path
# If not found, return path in primary directory (gguf)
models_dir = get_models_directory()
return os.path.join(models_dir, model_name)
def get_mmproj_for_model(model_name):
"""Get the mmproj filename for a given vision model"""
if model_name in QWEN_MODELS and "mmproj" in QWEN_MODELS[model_name]:
return QWEN_MODELS[model_name]["mmproj"]
return None
def get_mmproj_path(model_name):
"""Get the path to the mmproj file for a vision model, if it exists"""
mmproj_name = get_mmproj_for_model(model_name)
if mmproj_name and is_model_local(mmproj_name):
return get_model_path(mmproj_name)
return None
def download_model(model_name):
"""Download a model from HuggingFace with automatic progress display
For VL models, also downloads the matching mmproj file if needed
Args:
model_name: Filename of the model (e.g., "Qwen3-4B-Q8_0.gguf")
Returns:
Path to downloaded model or None on error
"""
if model_name not in QWEN_MODELS:
print(f"[Model Manager] Error: Unknown model: {model_name}")
return None
model_info = QWEN_MODELS[model_name]
repo_id = model_info["repo"]
models_dir = get_models_directory()
# Build list of files to download
files_to_download = [
{"filename": model_name, "desc": "Downloading model"}
]
# Add mmproj file if this is a VL model
mmproj_name = get_mmproj_for_model(model_name)
if mmproj_name:
files_to_download.append({
"filename": mmproj_name,
"desc": "Downloading mmproj"
})
# Download each file if it doesn't exist
for file_info in files_to_download:
filename = file_info["filename"]
local_path = os.path.join(models_dir, filename)
if os.path.exists(local_path):
print(f"[Model Manager] File already exists: {filename}")
continue
# Download the file
try:
print(f"[Model Manager] Downloading {filename} from {repo_id}...")
api = HfApi()
repo_info = api.repo_info(repo_id=repo_id, files_metadata=True)
file_metadata = next((f for f in repo_info.siblings if f.rfilename == filename), None)
if not file_metadata or file_metadata.size is None:
print(f"[Model Manager] Could not find file size for {filename} in {repo_id}")
return None
total_size = file_metadata.size
download_url = f"https://huggingface.co/{repo_id}/resolve/main/{filename}"
pbar = tqdm(total=total_size, unit="B", unit_scale=True, desc=file_info["desc"])
with requests.get(download_url, stream=True) as r, open(local_path, "wb") as f:
r.raise_for_status()
for chunk in r.iter_content(chunk_size=65536):
if chunk:
f.write(chunk)
pbar.update(len(chunk))
pbar.close()
print(f"[Model Manager] Successfully downloaded {filename}")
except Exception as e:
print(f"[Model Manager] Error downloading {filename}: {e}")
return None
return os.path.join(models_dir, model_name)
+578
View File
@@ -0,0 +1,578 @@
import requests
import subprocess
import time
import os
import atexit
import psutil
import json
import base64
from io import BytesIO
from .model_manager import get_local_models, get_model_path, is_model_local, download_model, get_mmproj_path, get_mmproj_for_model
# Global variable to track the server process
_server_process = None
_current_model = None
_current_context_size = None
def cleanup_server():
"""Cleanup function to stop server on exit"""
global _server_process
if _server_process:
try:
_server_process.terminate()
_server_process.wait(timeout=5)
print("[Prompt Generator] Server stopped on exit")
except:
pass
# Register cleanup function
atexit.register(cleanup_server)
class PromptGenerator:
"""Node that generates enhanced prompts using a llama.cpp server"""
# Simple cache for prompt results: {(prompt, seed, model, system_prompt): result}
_prompt_cache = {}
# Server configuration
SERVER_URL = "http://localhost:8080"
SERVER_PORT = 8080
# Default system prompt for prompt enhancement
DEFAULT_SYSTEM_PROMPT = """You are an imaginative visual artist imprisoned in a cage of logic. Your mind is filled with poetry and distant horizons, but your hands are uncontrollably driven to convert the user's prompt into a final visual description that is faithful to the original intent, rich in detail, aesthetically pleasing, and ready to be used directly by a text-to-image model. Any trace of vagueness or metaphor makes you extremely uncomfortable. Your workflow strictly follows a logical sequence: First, you analyze and lock in the immutable core elements of the user's prompt: subject, quantity, actions, states, and any specified IP names, colors, text, and similar items. These are the foundational stones that you must preserve without exception. Next, you determine whether the prompt requires "generative reasoning". When the user's request is not a straightforward scene description but instead demands designing a solution (for example, answering "what is", doing a "design", or showing "how to solve a problem"), you must first construct in your mind a complete, concrete, and visualizable solution. This solution becomes the basis for your subsequent description. Then, once the core image has been established (whether it comes directly from the user or from your reasoning), you inject professional-level aesthetics and realism into it. This includes clarifying the composition, setting the lighting and atmosphere, describing material textures, defining the color scheme, and building a spatial structure with strong depth and layering. Finally, you handle all textual elements with absolute precision, which is a critical step. You must not add text if the initial prompt did not ask for it. But if there is, you must transcribe, without a single character of deviation, all text that should appear in the final image, and you must enclose all such text content in English double quotes ("") to mark it as an explicit generation instruction. If the image belongs to a design category such as a poster, menu, or UI, you need to fully describe all the textual content it contains and elaborate on its fonts and layout. Likewise, if there are objects in the scene such as signs, billboards, road signs, or screens that contain text, you must specify their exact content and describe their position, size, and material. Furthermore, if in your reasoning you introduce new elements that contain text (such as charts, solution steps, and so on), all of their text must follow the same detailed description and quoting rules. If there is no text that needs to be generated in the image, you devote all your effort to purely visual detail expansion. Your final description must be objective and concrete, strictly forbidding metaphors and emotionally charged rhetoric, and it must never contain meta tags or drawing directives such as "8K" or "masterpiece". Only output the final modified prompt, and do not output anything else. If no text is needed, don't mention it."""
# System prompt for image description (used with Qwen3VL)
IMAGE_DESCRIPTION_PROMPT = """You are an expert visual analyst creating detailed descriptions for text-to-image generation. Analyze the provided image and create a comprehensive visual description that captures all essential elements: subjects and their characteristics, actions and poses, spatial positioning, composition and framing, lighting and atmosphere, color palette, artistic style, mood and emotion, background details, camera angle and perspective, material textures, and any visible text. Your description must be concrete, objective, and detailed enough that it could be used to recreate a similar image. Focus on visual elements only, avoiding interpretation or metaphor. If there is visible text in the image, enclose it in double quotes (""). If no text is needed, don't mention it. Only output the final description, and do not output anything else."""
# Additional instructions for JSON formatted output
JSON_SYSTEM_PROMPT = """\n\nReturn your response as valid JSON with these fields: scene (overall description), subjects (array with description/position/action for each), style, color_palette, lighting, mood, background, composition, camera. If you deem more fields are necessary, feel free to add them. Ensure the JSON is properly formatted."""
@staticmethod
def find_qwen3vl_model(available_models):
"""Find the preferred or smallest available Qwen3VL model
First checks user preferences, then falls back to smallest model (4B preferred over 8B)
"""
from . import prompt_manager
from .model_manager import is_model_local
qwen3vl_models = [m for m in available_models if 'qwen3vl' in m.lower()]
if not qwen3vl_models:
return None
# Check user preference first
preferred = prompt_manager._preferences_cache.get("preferred_vision_model", "")
if preferred and preferred in qwen3vl_models and is_model_local(preferred):
print(f"[Prompt Generator] Using preferred vision model: {preferred}")
return preferred
# Fall back to smallest model (prefer 4B over 8B)
for model in qwen3vl_models:
if '4b' in model.lower():
return model
return qwen3vl_models[0]
@staticmethod
def find_non_vl_model(available_models):
"""Find the preferred or smallest available non-vision model by file size
First checks user preferences, then falls back to smallest model by file size
"""
from . import prompt_manager
from .model_manager import get_models_directory, is_model_local
non_vl_models = [m for m in available_models if 'qwen3vl' not in m.lower()]
if not non_vl_models:
return None
# Check user preference first
preferred = prompt_manager._preferences_cache.get("preferred_base_model", "")
if preferred and preferred in non_vl_models and is_model_local(preferred):
print(f"[Prompt Generator] Using preferred base model: {preferred}")
return preferred
models_dir = get_models_directory()
models_with_size = []
for model in non_vl_models:
model_path = os.path.join(models_dir, model)
if os.path.exists(model_path):
size = os.path.getsize(model_path)
models_with_size.append((model, size))
if not models_with_size:
return non_vl_models[0]
# Sort by size and return smallest
models_with_size.sort(key=lambda x: x[1])
return models_with_size[0][0]
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"seed": ("INT", {
"default": 0,
"min": 0,
"max": 0xffffffffffffffff,
"tooltip": "Seed for reproducible generation."
}),
},
"optional": {
"mode": (["Enhance User Prompt", "Analyze Image", "Analyze Image with Prompt"], {
"default": "Enhance User Prompt",
"tooltip": "Choose mode: Enhance text prompt | Analyze image | Analyze image with custom instructions"
}),
"prompt": ("STRING", {
"multiline": True,
"default": "",
"placeholder": "Enter prompt...",
"tooltip": "Text prompt (required for 'Enhance User Prompt', optional for 'Analyze Image with Prompt')"
}),
"image": ("IMAGE", {
"tooltip": "Connect an image (required for 'Analyze Image' and 'Analyze Image with Prompt' modes)"
}),
"format_as_json": ("BOOLEAN", {
"default": False,
"tooltip": "Format the output as structured JSON with scene breakdown"
}),
"stop_server_after": ("BOOLEAN", {
"default": False,
"tooltip": "Stop the llama.cpp server after each prompt (for resource saving, but slower)."
}),
"options": ("OPTIONS", {
"tooltip": "Optional: Connect options node to control model and parameters"
}),
}
}
CATEGORY = "Prompt Manager"
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("output",)
FUNCTION = "convert_prompt"
@classmethod
def IS_CHANGED(cls, seed, **kwargs):
return seed
@staticmethod
def is_server_alive():
"""Check if llama.cpp server is responding"""
try:
response = requests.get(f"{PromptGenerator.SERVER_URL}/health", timeout=2)
return response.status_code == 200
except:
return False
@staticmethod
def start_server(model_name, context_size=4096):
"""Start llama.cpp server with specified model
Args:
model_name: Name of the model to use
context_size: Context size (default 4096)
Returns:
tuple: (success: bool, error_message: str or None)
"""
global _server_process, _current_model, _current_context_size
# Kill any existing llama-server processes first
PromptGenerator.kill_all_llama_servers()
# If server is already running with the same model, don't restart
if _server_process and _current_model == model_name and PromptGenerator.is_server_alive():
print(f"[Prompt Generator] Server already running with model: {model_name}")
return (True, None)
# Stop existing server if running different model
if _server_process:
PromptGenerator.stop_server()
# Check if model needs to be downloaded
if not is_model_local(model_name):
print(f"[Prompt Generator] Model '{model_name}' not found locally, downloading from HuggingFace...")
try:
model_path = download_model(model_name)
if not model_path:
error_msg = "Error: Failed to download model"
print(f"[Prompt Generator] {error_msg}")
return (False, error_msg)
print(f"[Prompt Generator] Download complete: {model_path}")
except Exception as e:
error_msg = f"Error downloading model: {e}"
print(f"[Prompt Generator] {error_msg}")
return (False, error_msg)
else:
model_path = get_model_path(model_name)
if not os.path.exists(model_path):
error_msg = f"Error: Model file not found: {model_path}"
print(f"[Prompt Generator] {error_msg}")
return (False, error_msg)
try:
print(f"[Prompt Generator] Starting llama.cpp server with model: {model_name}")
# Determine the correct llama-server executable based on OS
if os.name == 'nt': # Windows
server_cmd = "llama-server.exe"
creation_flags = subprocess.CREATE_NO_WINDOW
else: # Linux/Mac
server_cmd = "llama-server"
creation_flags = 0
# Build command arguments
cmd_args = [server_cmd, "-m", model_path, "--port", str(PromptGenerator.SERVER_PORT), "--no-warmup", "-c", str(context_size)]
# Add vision flags for Qwen3VL models
if "qwen3vl" in model_name.lower():
mmproj_path = get_mmproj_path(model_name)
if mmproj_path:
print(f"[Prompt Generator] Vision model detected, using mmproj: {mmproj_path}")
cmd_args.extend(["--mmproj", mmproj_path])
else:
mmproj_name = get_mmproj_for_model(model_name)
if mmproj_name:
error_msg = f"Error: Vision model requires mmproj file '{mmproj_name}' but it was not found. Please use Generator Options node to download the Qwen3VL model and its mmproj file."
print(f"[Prompt Generator] {error_msg}")
return (False, error_msg)
else:
print("[Prompt Generator] Warning: Vision model but no mmproj file configured")
print(f"[Prompt Generator] Command: {' '.join(cmd_args)}")
# Start server process
_server_process = subprocess.Popen(
cmd_args,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
creationflags=creation_flags
)
_current_model = model_name
_current_context_size = context_size
# Wait for server to be ready
print("[Prompt Generator] Waiting for server to be ready...")
for i in range(30): # Wait up to 30 seconds
time.sleep(1)
if PromptGenerator.is_server_alive():
print("[Prompt Generator] Server is ready!")
return (True, None)
error_msg = "Error: Server did not start in time"
print(f"[Prompt Generator] {error_msg}")
PromptGenerator.stop_server()
return (False, error_msg)
except FileNotFoundError:
error_msg = "Error: llama-server command not found. Please install llama.cpp and add to PATH.\nInstallation guide: https://github.com/ggml-org/llama.cpp/blob/master/docs/install.md"
print(f"[Prompt Generator] {error_msg}")
return (False, error_msg)
except Exception as e:
error_msg = f"Error starting server: {e}"
print(f"[Prompt Generator] {error_msg}")
return (False, error_msg)
@staticmethod
def kill_all_llama_servers():
"""Kill all llama-server processes using OS commands"""
try:
# Find and kill all llama-server processes
for proc in psutil.process_iter(['pid', 'name', 'cmdline']):
try:
# Check if process is llama-server
if proc.info['name'] and 'llama-server' in proc.info['name'].lower():
print(f"[Prompt Generator] Killing llama-server process (PID: {proc.info['pid']})")
proc.kill()
proc.wait(timeout=3)
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.TimeoutExpired):
pass
except Exception as e:
print(f"[Prompt Generator] Error killing llama-server processes: {e}")
@staticmethod
def stop_server():
"""Stop the llama.cpp server"""
global _server_process, _current_model
if _server_process:
try:
print("[Prompt Generator] Stopping server...")
_server_process.terminate()
_server_process.wait(timeout=5)
print("[Prompt Generator] Server stopped")
except:
try:
_server_process.kill()
except:
pass
finally:
_server_process = None
_current_model = None
# Also kill any orphaned llama-server processes
PromptGenerator.kill_all_llama_servers()
def convert_prompt(self, seed: int, mode="Enhance User Prompt", prompt="", image=None, format_as_json=False, stop_server_after=False, options=None, **kwargs) -> str:
"""Convert prompt using llama.cpp server, with caching for repeated requests."""
global _current_model
# Validate inputs based on mode
if mode == "Enhance User Prompt" and not prompt.strip():
return ("",)
elif mode in ["Analyze Image", "Analyze Image with Prompt"] and image is None:
error_msg = f"Error: '{mode}' mode requires an image to be connected."
return (error_msg,)
# Always determine a valid model filename before running server
model_to_use = None
model_changed = False
available_models = get_local_models()
# If in Analyze Image or Analyze Image with Prompt mode, we need a Qwen3VL model
if mode in ["Analyze Image", "Analyze Image with Prompt"]:
# Check if options specifies a Qwen3VL model
if options and "model" in options and "qwen3vl" in options["model"].lower() and is_model_local(options["model"]):
model_to_use = options["model"]
elif options and "model" in options and is_model_local(options["model"]):
# Non-VL model selected but in vision mode
print(f"[Prompt Generator] Warning: Non-vision model '{options['model']}' selected but '{mode}' mode is active. Ignoring model selection and using a Qwen3VL model instead.")
model_to_use = self.find_qwen3vl_model(available_models)
if model_to_use is None:
error_msg = f"Error: '{mode}' mode requires a Qwen3VL model. Please connect the Options node and select a Qwen3VL model (Qwen3VL-4B or Qwen3VL-8B) to use vision capabilities."
print(f"[Prompt Generator] {error_msg}")
return (error_msg,)
else:
# Try to find a Qwen3VL model automatically
model_to_use = self.find_qwen3vl_model(available_models)
if model_to_use is None:
error_msg = f"Error: '{mode}' mode requires a Qwen3VL model. Please connect the Options node and select a Qwen3VL model (Qwen3VL-4B or Qwen3VL-8B) to use vision capabilities."
print(f"[Prompt Generator] {error_msg}")
return (error_msg,)
else:
# Enhance User Prompt mode - use regular model selection logic (exclude Qwen3VL models)
if options and "model" in options and is_model_local(options["model"]):
# If user explicitly selected a Qwen3VL model but in Enhance mode, use first non-VL model instead
if "qwen3vl" in options["model"].lower():
model_to_use = self.find_non_vl_model(available_models)
if model_to_use:
print(f"[Prompt Generator] Warning: Qwen3VL model '{options['model']}' selected but 'Enhance User Prompt' mode is active. Ignoring model selection and using {model_to_use} instead.")
else:
error_msg = "Error: Only Qwen3VL models available but 'Enhance User Prompt' mode is active. Please add a .gguf model or use Generator Options to add a non-vision model."
print(f"[Prompt Generator] {error_msg}")
return (error_msg,)
else:
model_to_use = options["model"]
else:
if not available_models:
error_msg = "Error: No models found in models/ folder. Please add a .gguf model or use Generator Options node to download one."
print(f"[Prompt Generator] {error_msg}")
return (error_msg,)
# Find smallest non-VL model
model_to_use = self.find_non_vl_model(available_models)
if not model_to_use:
error_msg = "Error: Only Qwen3VL models available but 'Enhance User Prompt' mode is active. Please add a non-vision model or switch to 'Describe Image' mode."
print(f"[Prompt Generator] {error_msg}")
return (error_msg,)
# Caching logic: if prompt/seed/model/options/format/mode are unchanged, return cached result
options_tuple = tuple(sorted(options.items())) if options else ()
cache_key = (prompt, seed, model_to_use, options_tuple, format_as_json, mode)
# Only use cache if the model has not changed since last use
if cache_key in self._prompt_cache and _current_model == model_to_use:
print("[Prompt Generator] Returning cached prompt result.")
if stop_server_after:
self.stop_server()
return (self._prompt_cache[cache_key],)
# If the current model is not the one we want, or server is not running, restart
# Also restart if context_size has changed
context_size = options.get("context_size", 4096) if options else 4096
if _current_model != model_to_use or _current_context_size != context_size or not self.is_server_alive():
if _current_model and _current_model != model_to_use:
print(f"[Prompt Generator] Model changed from {_current_model} to {model_to_use}")
elif _current_context_size and _current_context_size != context_size:
print(f"[Prompt Generator] Context size changed from {_current_context_size} to {context_size}")
else:
print(f"[Prompt Generator] Ensuring server runs with model: {model_to_use}")
self.stop_server()
# Get context_size from options or use default
success, error_msg = self.start_server(model_to_use, context_size)
if not success:
return (error_msg,)
else:
print("[Prompt Generator] Using existing server instance")
# Build the endpoint URL
full_url = f"{self.SERVER_URL}/v1/chat/completions"
# Prepare the system prompt
if options and "system_prompt" in options:
system_prompt = options["system_prompt"]
elif mode in ["Analyze Image", "Analyze Image with Prompt"]:
# Use image description prompt for vision modes
system_prompt = self.IMAGE_DESCRIPTION_PROMPT
else:
system_prompt = self.DEFAULT_SYSTEM_PROMPT
# Add JSON formatting instructions if requested
if format_as_json:
system_prompt = system_prompt + self.JSON_SYSTEM_PROMPT
# Prepare request payload for llama.cpp chat completions
# Determine user content based on mode
if mode == "Analyze Image":
user_content = "Describe this image in detail."
elif mode == "Analyze Image with Prompt":
# Use user prompt if provided, otherwise default to generic description
user_content = prompt.strip() if prompt.strip() else "Describe this image in detail."
else:
user_content = prompt
# If in vision mode and image is connected, encode it and add to message
if mode in ["Analyze Image", "Analyze Image with Prompt"] and image is not None:
# Convert tensor to PIL Image and encode as base64
import torch
import numpy as np
from PIL import Image
# ComfyUI images are in format (batch, height, width, channels) with values 0-1
img_tensor = image[0] # Get first image from batch
img_np = (img_tensor.cpu().numpy() * 255).astype(np.uint8)
pil_image = Image.fromarray(img_np)
# Resize to ~1 megapixel if larger (to reduce context usage)
width, height = pil_image.size
total_pixels = width * height
max_pixels = 2000000 # 2 megapixels
if total_pixels > max_pixels:
# Calculate scaling factor to get ~2 megapixels
scale = (max_pixels / total_pixels) ** 0.5
new_width = int(width * scale)
new_height = int(height * scale)
print(f"[Prompt Generator] Resizing image from {width}x{height} to {new_width}x{new_height} (~2MP)")
pil_image = pil_image.resize((new_width, new_height), Image.Resampling.LANCZOS)
# Encode to base64
buffered = BytesIO()
pil_image.save(buffered, format="PNG")
img_base64 = base64.b64encode(buffered.getvalue()).decode('utf-8')
# Qwen3VL format for vision messages
user_message = {
"role": "user",
"content": [
{"type": "image_url", "image_url": {"url": f"data:image/png;base64,{img_base64}"}},
{"type": "text", "text": user_content}
]
}
elif mode in ["Analyze Image", "Analyze Image with Prompt"]:
# Vision mode but no image connected
error_msg = f"Error: '{mode}' mode requires an image to be connected. Please connect an image or switch to 'Enhance User Prompt' mode."
print(f"[Prompt Generator] {error_msg}")
return (error_msg,)
else:
user_message = {"role": "user", "content": user_content}
payload = {
"messages": [
{"role": "system", "content": system_prompt},
user_message
],
"stream": False,
"seed": seed
}
# Add optional parameters if provided via options
if options:
if "temperature" in options:
payload["temperature"] = options["temperature"]
if "top_p" in options:
payload["top_p"] = options["top_p"]
if "top_k" in options:
payload["top_k"] = options["top_k"]
if "min_p" in options:
payload["min_p"] = options["min_p"]
if "repeat_penalty" in options:
payload["repeat_penalty"] = options["repeat_penalty"]
try:
# Show which model is being used
if _current_model:
print(f"[Prompt Generator] Generating with model: {_current_model}")
else:
print("[Prompt Generator] Generating with last used model")
print(f"[Prompt Generator] Sending request to {full_url}")
response = requests.post(
full_url,
json=payload,
timeout=120
)
# Log response for debugging
if response.status_code != 200:
print(f"[Prompt Generator] Server returned status {response.status_code}")
try:
error_detail = response.json()
print(f"[Prompt Generator] Error details: {error_detail}")
except:
print(f"[Prompt Generator] Error response: {response.text[:500]}")
response.raise_for_status()
result = response.json()
# Log token usage if available
if "usage" in result:
usage = result["usage"]
prompt_tokens = usage.get("prompt_tokens", 0)
completion_tokens = usage.get("completion_tokens", 0)
total_tokens = usage.get("total_tokens", 0)
print(f"[Prompt Generator] Token usage - Prompt: {prompt_tokens}, Completion: {completion_tokens}, Total: {total_tokens}")
# Extract content from chat completions response format
if "choices" in result and len(result["choices"]) > 0:
full_response = result["choices"][0]["message"]["content"].strip()
else:
full_response = result.get("content", "").strip()
if not full_response:
print("[Prompt Generator] Warning: Empty response from server")
full_response = prompt
print("[Prompt Generator] Successfully generated prompt")
# Cache the result
self._prompt_cache[cache_key] = full_response
# Stop server if requested
if stop_server_after:
self.stop_server()
return (full_response,)
except requests.exceptions.ConnectionError:
error_msg = f"Error: Could not connect to server at {full_url}. Server may have crashed."
print(f"[Prompt Generator] {error_msg}")
return (error_msg,)
except requests.exceptions.Timeout:
error_msg = "Error: Request timed out (>120s)"
print(f"[Prompt Generator] {error_msg}")
return (error_msg,)
except Exception as e:
error_msg = f"Error: {e}"
print(f"[Prompt Generator] {error_msg}")
return (error_msg,)
NODE_CLASS_MAPPINGS = {
"PromptGenerator": PromptGenerator
}
NODE_DISPLAY_NAME_MAPPINGS = {
"PromptGenerator": "Prompt Generator"
}
+151
View File
@@ -0,0 +1,151 @@
from .model_manager import get_all_models, is_model_local, download_model, get_mmproj_for_model, get_mmproj_path
import time
# Global timestamp to track when models were last updated
_last_model_update = time.time()
def trigger_model_list_refresh():
"""Call this after downloading a model to trigger UI refresh"""
global _last_model_update
_last_model_update = time.time()
class PromptGenOptions:
"""Node that provides optional configuration for llama.cpp servers"""
@classmethod
def INPUT_TYPES(cls):
available_models = get_all_models()
# If no models found, show a placeholder
if not available_models:
available_models = ["No models found - check HuggingFace"]
return {
"optional": {
"model": (available_models, {
"default": available_models[0] if available_models else "",
"tooltip": "Select model to use (local models listed first, then HuggingFace models)"
}),
"system_prompt": ("STRING", {
"multiline": True,
"default": "",
"placeholder": "Replace LLM Instructions...",
"tooltip": "Custom LLM Instructions (leave empty to use default)\nThe default instructions are designed for generating\ndetailed and imaginative prompts for text-to-image generation."
}),
"temperature": ("FLOAT", {
"default": 0.8,
"min": 0.0,
"max": 2.0,
"step": 0.01,
"tooltip": "Controls randomness (0.0 = deterministic, 2.0 = very random)"
}),
"top_k": ("INT", {
"default": 40,
"min": 0,
"max": 100,
"step": 1,
"tooltip": "Sample from top K most likely tokens (0 = disabled)"
}),
"top_p": ("FLOAT", {
"default": 0.95,
"min": 0.0,
"max": 1.0,
"step": 0.01,
"tooltip": "Nucleus sampling: consider tokens with top_p probability mass"
}),
"min_p": ("FLOAT", {
"default": 0.05,
"min": 0.0,
"max": 1.0,
"step": 0.01,
"tooltip": "Minimum probability threshold relative to top token"
}),
"repeat_penalty": ("FLOAT", {
"default": 1.0,
"min": 1.0,
"max": 2.0,
"step": 0.01,
"tooltip": "Penalty for repeating tokens (1.0 = no penalty)"
}),
"context_size": ("INT", {
"default": 4096,
"min": 512,
"max": 32768,
"step": 512,
"tooltip": "Context size (increase for vision models or large prompts)"
}),
}
}
CATEGORY = "Prompt Manager"
RETURN_TYPES = ("OPTIONS",)
RETURN_NAMES = ("options",)
FUNCTION = "create_options"
@classmethod
def IS_CHANGED(cls, **kwargs):
"""Force refresh when models are updated"""
return _last_model_update
def create_options(self, model: str = None,
system_prompt: str = None, temperature: float = None,
top_k: int = None, top_p: float = None, min_p: float = None,
repeat_penalty: float = None, context_size: int = None) -> dict:
"""Create options dictionary with model and LLM parameters"""
options = {}
# Handle model selection and download if needed
if model and model != "No models found - check HuggingFace":
# Check if model is local
model_exists = is_model_local(model)
# For VL models, also check if mmproj exists
needs_download = not model_exists
if model_exists:
mmproj_name = get_mmproj_for_model(model)
if mmproj_name:
# This is a VL model, check if mmproj is present
mmproj_path = get_mmproj_path(model)
if not mmproj_path:
print(f"[Prompt Generator Options] Vision model found but mmproj missing, downloading: {mmproj_name}")
needs_download = True
if needs_download:
if not model_exists:
print(f"[Prompt Generator Options] Model not found locally, downloading: {model}")
downloaded_path = download_model(model)
if downloaded_path:
trigger_model_list_refresh()
options["model"] = model
else:
print(f"[Prompt Generator Options] Failed to download model: {model}")
else:
options["model"] = model
# Only include LLM parameters that are provided
if system_prompt and system_prompt.strip():
options["system_prompt"] = system_prompt
if temperature is not None:
options["temperature"] = temperature
if top_p is not None:
options["top_p"] = top_p
if top_k is not None:
options["top_k"] = top_k
if min_p is not None:
options["min_p"] = min_p
if repeat_penalty is not None:
options["repeat_penalty"] = repeat_penalty
if context_size is not None:
options["context_size"] = context_size
return (options,)
NODE_CLASS_MAPPINGS = {
"PromptGenOptions": PromptGenOptions
}
NODE_DISPLAY_NAME_MAPPINGS = {
"PromptGenOptions": "Prompt Generator Options"
}
+65 -16
View File
@@ -3,11 +3,17 @@ import json
import folder_paths
import server
class PromptManagerNode:
# Store preferences in memory (ComfyUI settings is the source of truth)
_preferences_cache = {
"preferred_base_model": "",
"preferred_vision_model": ""
}
class PromptManager:
@classmethod
def INPUT_TYPES(s):
prompts_data = PromptManagerNode.load_prompts()
prompts_data = PromptManager.load_prompts()
categories = list(prompts_data.keys()) if prompts_data else ["Character"]
all_prompts = set()
@@ -32,9 +38,11 @@ class PromptManagerNode:
"required": {
"category": (categories, {"default": first_category}),
"name": (all_prompts_list, {"default": first_prompt}),
"use_external": ("BOOLEAN", {"default": False, "label_on": "on", "label_off": "off", "tooltip": "Toggle to use LLM input instead of internal text"}),
"text": ("STRING", {"multiline": True, "default": first_prompt_text, "placeholder": "Enter prompt text", "dynamicPrompts": False, "tooltip": "Enter prompt text directly"}),
},
"optional": {
"text": ("STRING", {"multiline": True, "default": first_prompt_text, "placeholder": "Enter prompt text or connect input", "dynamicPrompts": False, "forceInput": False, "tooltip": "Enter prompt text directly or connect from another node"}),
"llm_input": ("STRING", {"multiline": True, "forceInput": True, "lazy": True, "tooltip": "Connect LLM text input here"}),
},
"hidden": {
"unique_id": "UNIQUE_ID",
@@ -103,23 +111,37 @@ class PromptManagerNode:
except Exception as e:
print(f"[PromptManager] Error saving prompts: {e}")
def get_prompt(self, category, name, text="", unique_id=None):
"""Return the current text in the text field and broadcast update"""
def get_prompt(self, category, name, use_external, text="", llm_input="", unique_id=None):
"""Return the appropriate text based on use_external toggle and broadcast update"""
# Choose which text to use based on the toggle
if use_external and llm_input:
output_text = llm_input
else:
output_text = text
# Broadcast the current prompt text to the frontend
if unique_id is not None:
server.PromptServer.instance.send_sync("prompt-manager-update-text", {
"node_id": unique_id,
"prompt": text
"prompt": output_text,
"use_external": use_external,
"llm_input": llm_input if use_external else ""
})
return (text,)
return (output_text,)
def check_lazy_status(self, category, name, use_external, text, llm_input=None, unique_id=None):
needed = []
if use_external:
needed.append("llm_input")
return needed
@server.PromptServer.instance.routes.get("/prompt-manager/get-prompts")
async def get_prompts(request):
"""API endpoint to get all prompts"""
try:
prompts = PromptManagerNode.load_prompts()
prompts = PromptManager.load_prompts()
return server.web.json_response(prompts)
except Exception as e:
print(f"[PromptManager] Error in get_prompts API: {e}")
@@ -136,7 +158,7 @@ async def save_category(request):
if not category_name:
return server.web.json_response({"success": False, "error": "Category name is required"})
prompts = PromptManagerNode.load_prompts()
prompts = PromptManager.load_prompts()
# Case-insensitive check for existing category
existing_categories_lower = {k.lower(): k for k in prompts.keys()}
@@ -144,7 +166,7 @@ async def save_category(request):
return server.web.json_response({"success": False, "error": f"Category already exists as '{existing_categories_lower[category_name.lower()]}'"})
prompts[category_name] = {}
PromptManagerNode.save_prompts(prompts)
PromptManager.save_prompts(prompts)
return server.web.json_response({"success": True, "prompts": prompts})
except Exception as e:
@@ -164,7 +186,7 @@ async def save_prompt(request):
if not category or not name or not text:
return server.web.json_response({"success": False, "error": "All fields are required"})
prompts = PromptManagerNode.load_prompts()
prompts = PromptManager.load_prompts()
if category not in prompts:
prompts[category] = {}
@@ -181,7 +203,7 @@ async def save_prompt(request):
# Save prompt in dict
prompts[category][name] = {"prompt": text}
PromptManagerNode.save_prompts(prompts)
PromptManager.save_prompts(prompts)
return server.web.json_response({"success": True, "prompts": prompts})
except Exception as e:
@@ -199,13 +221,13 @@ async def delete_category(request):
if not category:
return server.web.json_response({"success": False, "error": "Category name is required"})
prompts = PromptManagerNode.load_prompts()
prompts = PromptManager.load_prompts()
if category not in prompts:
return server.web.json_response({"success": False, "error": "Category not found"})
del prompts[category]
PromptManagerNode.save_prompts(prompts)
PromptManager.save_prompts(prompts)
return server.web.json_response({"success": True, "prompts": prompts})
except Exception as e:
@@ -224,15 +246,42 @@ async def delete_prompt(request):
if not category or not name:
return server.web.json_response({"success": False, "error": "Category and prompt name are required"})
prompts = PromptManagerNode.load_prompts()
prompts = PromptManager.load_prompts()
if category not in prompts or name not in prompts[category]:
return server.web.json_response({"success": False, "error": "Prompt not found"})
del prompts[category][name]
PromptManagerNode.save_prompts(prompts)
PromptManager.save_prompts(prompts)
return server.web.json_response({"success": True, "prompts": prompts})
except Exception as e:
print(f"[PromptManager] Error in delete_prompt API: {e}")
return server.web.json_response({"success": False, "error": str(e)}, status=500)
@server.PromptServer.instance.routes.get("/prompt-manager/load-preferences")
async def load_preferences(request):
"""API endpoint to get cached preferences (set from ComfyUI settings)"""
return server.web.json_response(_preferences_cache)
@server.PromptServer.instance.routes.post("/prompt-manager/save-preference")
async def save_preference(request):
"""API endpoint to update preference cache when settings change"""
try:
data = await request.json()
key = data.get("key")
value = data.get("value", "")
if key not in ["preferred_base_model", "preferred_vision_model"]:
return server.web.json_response({"success": False, "error": "Invalid preference key"})
# Update in-memory cache
_preferences_cache[key] = value
return server.web.json_response({"success": True, "preferences": _preferences_cache})
except Exception as e:
print(f"[PromptManager] Error saving preference: {e}")
return server.web.json_response({"success": False, "error": str(e)}, status=500)
+2 -2
View File
@@ -1,7 +1,7 @@
[project]
name = "comfyui-prompt-manager"
description = "A simple custom node for ComfyUI that allows you to save and reuse prompts, organized into different categories"
version = "1.0.1"
description = "Prompt Manager for ComfyUI, with llama.cpp integration for prompt generation and vision analysis. Organize, generate, and save prompts with local LLM support."
version = "1.7.0"
[project.urls]
Repository = "https://github.com/FranckyB/ComfyUI-Prompt-Manager"
+7
View File
@@ -0,0 +1,7 @@
requests>=2.31.0
huggingface_hub>=0.20.0
psutil>=5.9.0
tqdm>=4.66.0
Pillow>=10.0.0
torch>=2.0.0
numpy>=1.24.0