Compare commits

..
5 Commits
10 changed files with 859 additions and 200 deletions
+97 -111
View File
@@ -1,20 +1,32 @@
# 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) that allows both saving and generating new prompts using llama.cpp.
(**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
- **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.
### 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
## Installation
@@ -28,112 +40,61 @@ 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. **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.
### 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.
**Size of 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)
#### 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
## Requirements
#### Deleting a Prompt
1. Select the prompt you want to delete
2. Click the **"Del Prompt"** button
3. Confirm the deletion
### 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
- llama-server (from llama.cpp)
## Troubleshooting
@@ -144,17 +105,42 @@ 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.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: 64 KiB

+109 -68
View File
@@ -28,11 +28,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 +75,7 @@ app.registerExtension({
addButtonBar(node);
setupCategoryChangeHandler(node);
filterPromptDropdown(node);
setupInputConnectionHandler(node);
setupUseExternalToggleHandler(node);
// After buttons are added, ensure height is sufficient
setTimeout(() => {
@@ -76,7 +107,7 @@ app.registerExtension({
if (!node.buttonBarAttached) {
addButtonBar(node);
setupCategoryChangeHandler(node);
setupInputConnectionHandler(node);
setupUseExternalToggleHandler(node);
}
});
}, 100);
@@ -231,15 +262,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 +281,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 +307,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 +353,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) {
+129
View File
@@ -0,0 +1,129 @@
"""
Utility functions for managing llama.cpp models
"""
import os
import glob
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"
}
}
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")
# 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()
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)]
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()
models_dir = get_models_directory()
# List all known filenames, local ones first
all_models = []
# Add local models first
if local_models:
all_models.extend(local_models)
# Add remote models (not present locally)
for filename in QWEN_MODELS.keys():
if filename not in all_models:
all_models.append(filename)
return all_models
def is_model_local(model_name):
"""Check if a model exists locally"""
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)
def get_model_path(model_name):
"""Get the full path to a model file"""
models_dir = get_models_directory()
return os.path.join(models_dir, model_name)
def download_model(model_name):
"""
Download a model from HuggingFace with automatic progress display
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"]
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
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}")
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
+349
View File
@@ -0,0 +1,349 @@
import requests
import subprocess
import time
import os
import atexit
import psutil
from .model_manager import get_local_models, get_model_path, is_model_local, download_model
# Global variable to track the server process
_server_process = None
_current_model = 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 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."""
@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,
"max": 0xffffffffffffffff,
"tooltip": "Seed for reproducible generation."
}),
},
"optional": {
"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):
"""Start llama.cpp server with specified model
Returns:
tuple: (success: bool, error_message: str or None)
"""
global _server_process, _current_model
# 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
# Start server process
_server_process = subprocess.Popen(
[server_cmd, "-m", model_path, "--port", str(PromptGenerator.SERVER_PORT), "--no-warmup"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
creationflags=creation_flags
)
_current_model = model_name
# 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, prompt: str, seed: int, stop_server_after=False, options=None) -> 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():
return ("",)
# Always determine a valid model filename before running server
model_to_use = None
model_changed = False
# Priority: options node > first local model filename
if options and "model" in options and is_model_local(options["model"]):
model_to_use = options["model"]
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]
# Caching logic: if prompt/seed/model/options are unchanged, return cached result
options_tuple = tuple(sorted(options.items())) if options else ()
cache_key = (prompt, seed, model_to_use, options_tuple)
# 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
if _current_model != model_to_use 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}")
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)
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 - use custom if provided, otherwise use default
if options and "system_prompt" in options:
system_prompt = options["system_prompt"]
else:
system_prompt = self.DEFAULT_SYSTEM_PROMPT
# Prepare request payload for llama.cpp chat completions
payload = {
"messages": [
{"role": "system", "content": system_prompt},
{"role": "user", "content": prompt}
],
"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
)
response.raise_for_status()
result = response.json()
# 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"
}
+128
View File
@@ -0,0 +1,128 @@
from .model_manager import get_all_models, is_model_local, download_model
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)"
}),
"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)"
}),
}
}
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) -> 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}")
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
return (options,)
NODE_CLASS_MAPPINGS = {
"PromptGenOptions": PromptGenOptions
}
NODE_DISPLAY_NAME_MAPPINGS = {
"PromptGenOptions": "Prompt Generator Options"
}
+32 -16
View File
@@ -3,11 +3,11 @@ import json
import folder_paths
import server
class PromptManagerNode:
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 +32,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 +105,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 +152,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 +160,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 +180,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 +197,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 +215,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,13 +240,13 @@ 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:
+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. Allowing users to generate and save prompts."
version = "1.5.1"
[project.urls]
Repository = "https://github.com/FranckyB/ComfyUI-Prompt-Manager"
+3
View File
@@ -0,0 +1,3 @@
requests>=2.31.0
huggingface_hub>=0.20.0
psutil>=5.9.0