Compare commits

..
11 Commits
Author SHA1 Message Date
THE_BEAST\me ecdf1e0995 add custom Llama path preference option 2025-12-16 13:14:15 -05:00
Francois Beaudry 39575f137c Fix llama.cpp URL in README
Updated the README to correct the URL for llama.cpp.
2025-12-16 09:52:20 -05:00
THE_BEAST\me e993546fa4 Improve error message handling in Prompt Generator 2025-12-16 03:52:14 -05:00
Francois Beaudry ce12566998 Revise README for better readability and organization
Updated README to improve clarity and formatting.
2025-12-16 00:56:38 -05:00
THE_BEAST\me c61dcaad2c - Bumped version to 1.8.0.
- Added support for Qwen3VL Thinking model variants and improved model management.
- Enhanced error handling and console output for better debugging.
- Improved options node for better user experience and functionality.
2025-12-16 00:44:07 -05:00
THE_BEAST\me 1ba2d214f6 Added Better Llama Shutdown logic, should force close it when Comfy closes. Improved system prompts for "Analyze Image with Prompt". Previous one was preventing LLM to be creative. Now uses the models default values by default. Option node can be used to overide them.
Refactor preference management: move API endpoints to model_manager.py and remove in-memory cache from prompt_manager.py
2025-12-15 18:37:07 -05:00
THE_BEAST\me 473d96084c Enhance model management and prompt generation capabilities
- Added support for additional Qwen3VL models in model_manager.py.
- Improved mmproj file path retrieval logic to search for relevant files based on model name components.
- Introduced new functions in prompt_generator.py for better handling of server processes, including cleanup on exit and signal handling.
- Enhanced prompt generation with detailed console output options, including enabling/disabling thinking mode and showing detailed debug information.
- Updated prompt_generator_options.py to allow connecting multiple images for analysis and added options for enabling thinking mode and console output.
- Minor cleanup in prompt_manager.py to remove unnecessary whitespace.
2025-12-15 04:10:10 -05:00
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
11 changed files with 1266 additions and 209 deletions
+99 -21
View File
@@ -1,13 +1,27 @@
# ComfyUI Prompt Manager
A custom node for [ComfyUI](https://github.com/comfyanonymous/ComfyUI) that allows both saving and generating new prompts using llama.cpp.
**A custom [ComfyUI](https://github.com/comfyanonymous/ComfyUI) node for Organizing, Generating or Enhancing prompts.**
(**Llama.cpp needs to be installed and accessible from command prompt.**)
This addon started off as a simple prompt Manager, to help save and retrieve prompts.
But has since evolved to be a complete toolset to help Generate prompts also.
***
Uses an existing install of [llama.cpp](https://github.com/ggerganov/llama.cpp), preventing install conflicts with ComfyUI.
Provides options to automatically download Qwen3 and Qwen3VL models.
Supports prompt enhancing, image analysis, or custom image processing, with up to 5 images at once.
Custom GGUF models can be used if supported by llama.cpp; simply drop them in the models/gguf folder.
Users can set a custom Llama-server path, if not defined in your System Path.
<div align="center">
<figcaption>Simple Prompt Generator Usage</figcaption>
<img src="docs/prompt_manager.png" alt="Prompt Manager">
</div>
<div align="center">
<figcaption>Advanced Prompt Generator Usage</figcaption>
<img src="docs/prompt_manager_advanced.png" alt="Prompt Manager">
</div>
### Key features:
### Prompt Manager:
- **Category Organization**: Create and manage multiple categories to organize your prompts
@@ -17,16 +31,24 @@ A custom node for [ComfyUI](https://github.com/comfyanonymous/ComfyUI) that allo
- **Persistent Storage**: All prompts saved in your ComfyUI user folder
### Prompt Generator
- **Automatic llama.cpp Server Management**: Automatically starts llama.cpp server as needed
- **Server Control**: Toggle to stop server after generation (frees VRAM)
- **AI-Powered Prompt Enhancement**: Transform basic prompts into detailed, vivid descriptions optimized for image generation
- **Local Model Support**: Automatically detects and uses first .gguf model found in the models/guff folder.
- **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
- **Thinking Support**: Support Thinking models to perform deeper generative reasoning.
- **Automatic Server Management**: Starts/stops llama.cpp server as needed, with automatic shut off at exit.
- **Smart Model Selection**: Auto-selects appropriate model (vision or text) based on mode or Thinking mode.
- **Model Preferences**: Set preferred models in ComfyUI preferences for automatic selection.
- **Custom Llama path**: In preferences you can set a custom Llama install Path, if not defined in your System Path.
### Prompt Generator Options
- **Model Selection**: Choose from local models or download from HuggingFace
- **Model Auto-Download**: Easy download of Qwen3 1.7B, 4B, or 8B from HuggingFace.
- **LLM Parameters**: Fine-tune temperature, top_k, top_p, min_p, repeat_penalty
- **Custom Instructions**: Override default system prompt for different enhancement styles
- **Model Selection**: Choose from local models or download Qwen3, Qwen3VL and Qwen3VL Thinking models from HuggingFace
- **Auto-Download**: Automatically downloads both model and required mmproj files for vision models
- **LLM Parameters**: Fine-tune temperature, top_k, top_p, min_p, repeat_penalty and context size.
- **Custom Instructions**: Override default system prompt for different enhancement styles.
- **Extra Image Inputs**: Combine up to 5 images to generate your prompt.
- **Console Debugging**: Enable outputing the entire process to the console for debugging purposes.
## Installation
@@ -50,7 +72,6 @@ A custom node for [ComfyUI](https://github.com/comfyanonymous/ComfyUI) that allo
5. If you have them, place your .gguf models in the models/gguf folder. (Create folder if not present)
6. Restart ComfyUI
## Usage
@@ -67,33 +88,54 @@ A custom node for [ComfyUI](https://github.com/comfyanonymous/ComfyUI) that allo
**Basic Usage** (assuming a model is present in models\gguf):
1. **Add the Node**: Add Node → Prompt Generator
2. **Connect llm_output to prompt manager**: If you want to save your generated prompt connect to prompt manager.
3. **type your prompt**: Type in your basic prompt that will be embelished
4. **Save memory**: Toggle "stop_server_after" ON to free VRAM after generation, if seed is set to fix, it won't restart unless prompt changes.
4. **Run Workflow**: Once calculated, the prompt will display in the Prompt Manager window and allow you to save it.
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. **Output as Json**: Use Format_as_Json to experiment with Json prompts.
5. **Push the LLM**: Use enable_thinking to enable the model to perform deeper generative reasoning before producing the final prompt.
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
**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.
3. **Analyze multiple images**: Connect up to 4 additional images, for a total of 5.
4. **Select from available models**: Select from models found in your models\gguf folder. Qwen models will be available to download.
5. **Adjust settings**: Adjust LLM parameters (temperature, top_k, etc.)
6. **Customize LLM**: Customize the default LLM instructions to modify the responses llama returns.
7. **Enable Debugging**: Enable complete printout of process to console using show_everything_in_console
**Size of Qwen models found in options**
**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)
- Qwen3VL-4B-Thinking-Q8_0.gguf: Vision model, Thinking variant, balanced performance (~5GB VRAM)
- Qwen3VL-8B-Thinking-Q8_0.gguf: Vision model, Thinking variant, best quality (~9GB VRAM)
**Model Management**:
- Place gguf files in models/gguf folder
- Downloaded models are also placed in this folder.
**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
## Requirements
- 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
@@ -122,11 +164,47 @@ A custom node for [ComfyUI](https://github.com/comfyanonymous/ComfyUI) that allo
**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.
**Problem**: Default Model used is not what I want
- **Solution**: You can set your preferred model in the ComfyUI settings. Simply add its full name for both the VL and base models. Enabling Thinking in the Generator might change what is used.
## Changelog
### Version 1.8.1
- Added option to set a custom Llama path in preferences, for those that have specific installs.
### Version 1.8.0
- Added support for Qwen3VL Thinking model variants, with download options thru the Generator Options node.
- Model manager now searches for relevant `mmproj` files using model-name components for more reliable vision-model linking.
- Detailed console output options (debug logging)
- `enable_thinking` toggle to enable/disable the model's reasoning/thinking mode.
- Options node now accepts multiple images for analysis.
- Better Llama shutdown behavior to force-close the server when Comfy exits.
- Uses model-reported sampling params by default when available; the Options node can override them per-parameter.
- Moved preference API endpoints and cache handling into `model_manager.py` for cleaner management and persistence.
### 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
- Model 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
- LLM output remains available when use_llm is off, so it can be edited.
- Improved caching detection: any change to options will be detected and force a new output.
- Improved some UI quirks
### Version 1.5.0
+1 -1
View File
@@ -2,7 +2,7 @@
ComfyUI Prompt Manager - A simple custom node for saving and reusing prompts
A prompt management system for ComfyUI with LLM input support
"""
__version__ = "1.5.1"
__version__ = "1.8.1"
__author__ = "François Beaudry"
__license__ = "MIT"
Binary file not shown.

Before

Width:  |  Height:  |  Size: 64 KiB

After

Width:  |  Height:  |  Size: 450 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 766 KiB

+126 -1
View File
@@ -4,6 +4,90 @@ 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);
}
}
},
{
id: "PromptManager.LlamaPath",
category: ["Prompt Manager", "Llama Preferences", "Custom Llama Path"],
name: "Custom Llama Path",
tooltip: "Path to custom Llama installation (Can leave empty if it's defined in your system Path)",
type: "text",
defaultValue: "",
async onChange(value) {
try {
await fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "custom_llama_path", value: value })
});
} catch (error) {
console.error("[PromptManager] Error saving Llama path 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;
@@ -118,10 +202,51 @@ app.registerExtension({
// Enforce minimum node width
const onResize = nodeType.prototype.onResize;
nodeType.prototype.onResize = function(size) {
size[0] = Math.max(400, size[0]);
size[0] = Math.max(300, size[0]);
return onResize ? onResize.apply(this, arguments) : size;
};
}
// Make the Options node taller/wider by default so the system_prompt area is roomier
if (nodeData.name === "PromptGenOptions") {
const onNodeCreated = nodeType.prototype.onNodeCreated;
nodeType.prototype.onNodeCreated = function () {
const result = onNodeCreated?.apply(this, arguments);
// Set a default size (width x height)
try {
this.setSize([400, 420]);
} catch (e) {
// ignore if method unavailable
}
return result;
};
// Enforce sensible minimums when the user resizes the options node
const onResizeOpt = nodeType.prototype.onResize;
nodeType.prototype.onResize = function(size) {
size[0] = Math.max(300, size[0]);
return onResizeOpt ? onResizeOpt.apply(this, arguments) : size;
};
}
// Enforce minimum size for ModelGenerator node (no default size)
if (nodeData.name === "PromptGenerator") {
const onNodeCreated = nodeType.prototype.onNodeCreated;
nodeType.prototype.onNodeCreated = function () {
const result = onNodeCreated?.apply(this, arguments);
// Set a default size (width x height)
try {
this.setSize([400, 300]);
} catch (e) {
// ignore if method unavailable
}
return result;
};
const onResizeModel = nodeType.prototype.onResize;
nodeType.prototype.onResize = function(size) {
size[0] = Math.max(300, size[0]);
return onResizeModel ? onResizeModel.apply(this, arguments) : size;
};
}
}
});
+187 -55
View File
@@ -3,11 +3,20 @@ Utility functions for managing llama.cpp models
"""
import os
import glob
import json
import folder_paths
import server
from huggingface_hub import HfApi
from tqdm.auto import tqdm
import requests
# Add preference cache and API endpoints for preferences
_preferences_cache = {
"preferred_base_model": "",
"preferred_vision_model": "",
"custom_llama_path": ""
}
# Predefined models - use real filenames as keys
QWEN_MODELS = {
"Qwen3-1.7B-Q8_0.gguf": {
@@ -18,69 +27,176 @@ QWEN_MODELS = {
},
"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"
},
"Qwen3VL-4B-Thinking-Q8_0.gguf": {
"repo": "Qwen/Qwen3-VL-4B-Thinking-GGUF",
"mmproj": "mmproj-Qwen3VL-4B-Thinking-Q8_0.gguf"
},
"Qwen3VL-8B-Thinking-Q8_0.gguf": {
"repo": "Qwen/Qwen3-VL-8B-Thinking-GGUF",
"mmproj": "mmproj-Qwen3VL-8B-Thinking-Q8_0.gguf"
}
}
@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", "custom_llama_path"]:
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"[Model Manager] Error saving preference: {e}")
return server.web.json_response({"success": False, "error": str(e)}, status=500)
def get_models_directory():
"""Get the path to the models directory (ComfyUI/models/gguf)"""
# Get the custom_nodes directory (parent of this extension)
custom_nodes_dir = os.path.dirname(os.path.dirname(__file__))
# Go up to ComfyUI root
comfyui_root = os.path.dirname(custom_nodes_dir)
# Path to models/gguf
models_dir = os.path.join(comfyui_root, "models", "gguf")
"""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_local_models():
"""Get list of local .gguf model files"""
models_dir = get_models_directory()
def get_all_model_directories():
"""Get all directories where models can be found"""
get_models_directory() # Ensure folders are registered
gguf_files = glob.glob(os.path.join(models_dir, "*.gguf"))
# Return just the filenames, not full paths
return [os.path.basename(f) for f in sorted(gguf_files)]
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"""
local_models = get_local_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
# Add local models first (already filtered by get_local_models)
if local_models:
all_models.extend(local_models)
# Add remote models (not present locally)
# Add remote models (not present locally), excluding mmproj files
for filename in QWEN_MODELS.keys():
if filename not in all_models:
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"""
"""Check if a model exists locally in any of the model directories"""
if model_name == "--- Download from HuggingFace ---":
return False
models_dir = get_models_directory()
model_path = os.path.join(models_dir, model_name)
return os.path.exists(model_path)
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"""
"""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
Searches for mmproj files that contain all parts of the model name
"""
# Get all parts of the model name (excluding .gguf)
model_parts = model_name.replace('.gguf', '').split('-')
# Get all local mmproj files
all_dirs = get_all_model_directories()
mmproj_files = []
for models_dir in all_dirs:
if os.path.exists(models_dir):
for f in os.listdir(models_dir):
if f.startswith('mmproj-') and f.endswith('.gguf'):
mmproj_files.append(f)
# Find mmproj that contains all model parts
for mmproj_file in mmproj_files:
mmproj_parts = mmproj_file.replace('mmproj-', '').replace('.gguf', '').split('-')
if all(part in mmproj_parts for part in model_parts):
return get_model_path(mmproj_file)
def download_model(model_name):
"""
Download a model from HuggingFace with automatic progress display
"""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")
@@ -88,42 +204,58 @@ def download_model(model_name):
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"]
filename = model_name
models_dir = get_models_directory()
local_path = os.path.join(models_dir, filename)
# Check if already downloaded
if os.path.exists(local_path):
print(f"[Model Manager] Model already exists: {filename}")
return local_path
# Build list of files to download
files_to_download = [
{"filename": model_name, "desc": "Downloading model"}
]
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_info = next((f for f in repo_info.siblings if f.rfilename == filename), None)
if not file_info or file_info.size is None:
print(f"[Model Manager] Could not find file size for {filename} in {repo_id}")
# 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
total_size = file_info.size
download_url = f"https://huggingface.co/{repo_id}/resolve/main/{filename}"
pbar = tqdm(total=total_size, unit="B", unit_scale=True, desc="Downloading")
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}")
return local_path
except Exception as e:
print(f"[Model Manager] Error downloading model: {e}")
return None
return os.path.join(models_dir, model_name)
+776 -110
View File
File diff suppressed because it is too large Load Diff
+70 -19
View File
@@ -1,4 +1,4 @@
from .model_manager import get_all_models, is_model_local, download_model
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
@@ -26,11 +26,27 @@ class PromptGenOptions:
"default": available_models[0] if available_models else "",
"tooltip": "Select model to use (local models listed first, then HuggingFace models)"
}),
"image2": ("IMAGE", {
"tooltip": "Connect an image (required for 'Analyze Image' and 'Analyze Image with Prompt' modes)"
}),
"image3": ("IMAGE", {
"tooltip": "Connect an image (required for 'Analyze Image' and 'Analyze Image with Prompt' modes)"
}),
"image4": ("IMAGE", {
"tooltip": "Connect an image (required for 'Analyze Image' and 'Analyze Image with Prompt' modes)"
}),
"image5": ("IMAGE", {
"tooltip": "Connect an image (required for 'Analyze Image' and 'Analyze Image with Prompt' modes)"
}),
"system_prompt": ("STRING", {
"multiline": True,
"default": "",
"placeholder": "Replace LLM Instructions...",
"tooltip": "Custom LLM Instructions (leave empty to use default)"
"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."
}),
"use_model_default_sampling": ("BOOLEAN", {
"default": False,
"tooltip": "Use the model's default sampling parameters (overrides temperature, top_p, etc)"
}),
"temperature": ("FLOAT", {
"default": 0.8,
@@ -67,6 +83,17 @@ class PromptGenOptions:
"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)"
}),
"show_everything_in_console": ("BOOLEAN", {
"default": False,
"tooltip": "Print system prompt, user prompt, thinking process, and raw model response to console"
})
}
}
@@ -80,19 +107,34 @@ class PromptGenOptions:
"""Force refresh when models are updated"""
return _last_model_update
def create_options(self, model: str = None,
system_prompt: str = None, temperature: float = None,
def create_options(self, model: str = None, image2=None, image3=None, image4=None, image5=None,
system_prompt: str = None, use_model_default_sampling: bool = None, temperature: float = None,
top_k: int = None, top_p: float = None, min_p: float = None,
repeat_penalty: float = None) -> dict:
"""Create options dictionary with model and LLM parameters"""
repeat_penalty: float = None, context_size: int = None,
show_everything_in_console: bool = None) -> dict:
"""Create options dictionary with model, LLM parameters, and extra images"""
options = {}
# Handle model selection and download if needed
if model and model != "No models found - check HuggingFace":
# Re-check if model is local (in case it was just downloaded but UI not refreshed)
if not is_model_local(model):
print(f"[Prompt Generator Options] Model not found locally, downloading: {model}")
# 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()
@@ -102,19 +144,28 @@ class PromptGenOptions:
else:
options["model"] = model
# Add extra images if provided
if image2 is not None:
options["image2"] = image2
if image3 is not None:
options["image3"] = image3
if image4 is not None:
options["image4"] = image4
if image5 is not None:
options["image5"] = image5
# 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
options["use_model_default_sampling"] = use_model_default_sampling
options["temperature"] = temperature
options["top_p"] = top_p
options["top_k"] = top_k
options["min_p"] = min_p
options["repeat_penalty"] = repeat_penalty
options["context_size"] = context_size
options["show_everything_in_console"] = show_everything_in_console
return (options,)
+1
View File
@@ -3,6 +3,7 @@ import json
import folder_paths
import server
class PromptManager:
@classmethod
+2 -2
View File
@@ -1,7 +1,7 @@
[project]
name = "comfyui-prompt-manager"
description = "Prompt Manager for ComfyUI, with llama.cpp integration for prompt generation. Allowing users to generate and save prompts."
version = "1.5.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.8.1"
[project.urls]
Repository = "https://github.com/FranckyB/ComfyUI-Prompt-Manager"
+4
View File
@@ -1,3 +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