Compare commits

...
4 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
9 changed files with 577 additions and 103 deletions
+52 -12
View File
@@ -1,6 +1,6 @@
# 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 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.**)
@@ -17,14 +17,19 @@ 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
- **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 from HuggingFace
- **Model Auto-Download**: Easy download of Qwen3 1.7B, 4B, or 8B from HuggingFace.
- **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
@@ -67,10 +72,13 @@ 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. **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
@@ -79,21 +87,33 @@ A custom node for [ComfyUI](https://github.com/comfyanonymous/ComfyUI) that allo
4. **Adjust settings**: Adjust LLM parameters (temperature, top_k, etc.)
5. **Customize LLM**: Customize the default LLM instructions to modify the responses llama returns.
**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)
**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
@@ -124,6 +144,26 @@ A custom node for [ComfyUI](https://github.com/comfyanonymous/ComfyUI) that allo
## Changelog
### 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
Binary file not shown.

Before

Width:  |  Height:  |  Size: 64 KiB

After

Width:  |  Height:  |  Size: 268 KiB

+65
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;
+134 -54
View File
@@ -3,6 +3,8 @@ 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
@@ -18,69 +20,131 @@ 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"
}
}
# 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 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"""
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
"""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 +152,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)
+258 -29
View File
@@ -4,11 +4,15 @@ import time
import os
import atexit
import psutil
from .model_manager import get_local_models, get_model_path, is_model_local, download_model
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"""
@@ -36,18 +40,77 @@ class PromptGenerator:
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 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."""
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": {
"prompt": ("STRING", {
"multiline": True,
"default": "",
"placeholder": "Enter basic prompt...",
"tooltip": "Enter the prompt you want to embellish"
}),
"seed": ("INT", {
"default": 0,
"min": 0,
@@ -56,6 +119,23 @@ class PromptGenerator:
}),
},
"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)."
@@ -85,13 +165,17 @@ class PromptGenerator:
return False
@staticmethod
def start_server(model_name):
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
global _server_process, _current_model, _current_context_size
# Kill any existing llama-server processes first
PromptGenerator.kill_all_llama_servers()
@@ -138,15 +222,36 @@ class PromptGenerator:
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(
[server_cmd, "-m", model_path, "--port", str(PromptGenerator.SERVER_PORT), "--no-warmup"],
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...")
@@ -210,32 +315,71 @@ class PromptGenerator:
# Also kill any orphaned llama-server processes
PromptGenerator.kill_all_llama_servers()
def convert_prompt(self, prompt: str, seed: int, stop_server_after=False, options=None) -> str:
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
# If prompt is empty, return empty string
if not prompt.strip():
# 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()
# Priority: options node > first local model filename
if options and "model" in options and is_model_local(options["model"]):
model_to_use = options["model"]
# 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:
local_models = get_local_models()
if not local_models:
error_msg = "Error: No models found in models/ folder. Please add a .gguf model or connect options node to download one."
print(f"[Prompt Generator] {error_msg}")
return (error_msg,)
model_to_use = local_models[0]
# 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 are unchanged, return cached result
# 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)
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.")
@@ -244,13 +388,18 @@ class PromptGenerator:
return (self._prompt_cache[cache_key],)
# If the current model is not the one we want, or server is not running, restart
if _current_model != model_to_use or not self.is_server_alive():
# 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()
success, error_msg = self.start_server(model_to_use)
# 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:
@@ -259,17 +408,79 @@ class PromptGenerator:
# Build the endpoint URL
full_url = f"{self.SERVER_URL}/v1/chat/completions"
# Prepare the system prompt - use custom if provided, otherwise use default
# 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},
{"role": "user", "content": prompt}
user_message
],
"stream": False,
"seed": seed
@@ -301,10 +512,28 @@ class PromptGenerator:
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()
+29 -6
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
@@ -30,7 +30,7 @@ class PromptGenOptions:
"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."
}),
"temperature": ("FLOAT", {
"default": 0.8,
@@ -67,6 +67,13 @@ 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)"
}),
}
}
@@ -83,16 +90,30 @@ class PromptGenOptions:
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) -> dict:
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":
# 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()
@@ -115,6 +136,8 @@ class PromptGenOptions:
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,)
+33
View File
@@ -3,6 +3,12 @@ import json
import folder_paths
import server
# Store preferences in memory (ComfyUI settings is the source of truth)
_preferences_cache = {
"preferred_base_model": "",
"preferred_vision_model": ""
}
class PromptManager:
@classmethod
@@ -252,3 +258,30 @@ async def delete_prompt(request):
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 = "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.7.0"
[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