Compare commits

...
16 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
THE_BEAST\me bc682b3680 Enhance LLM input handling and caching logic in PromptManager and PromptGenerator 2025-11-30 21:38:38 -05:00
Francois Beaudry 9982853cac Fix formatting of Llama.cpp installation note 2025-11-30 00:03:23 -05:00
THE_BEAST\me 7cc4478aa0 Version 1.5.0 - Introduced Prompt Generator and Options nodes with llama.cpp integration, enhanced prompt management features, and improved model handling. 2025-11-29 23:57:05 -05:00
THE_BEAST\me 9f70a8634a Version 1.1.0 - Added LLM input toggle feature 2025-11-28 17:58:31 -05:00
THE_BEAST\me 5d0ea866ab Simplified readme 2025-11-28 16:53:56 -05:00
11 changed files with 1915 additions and 199 deletions
+173 -109
View File
@@ -1,20 +1,54 @@
# 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 [ComfyUI](https://github.com/comfyanonymous/ComfyUI) node for Organizing, Generating or Enhancing prompts.**
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>
## Features
- **Category Organization**: Create and manage multiple categories to organize your prompts (e.g., Character, Style, Environment, Lighting, Mood)
<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
- **Save & Load Prompts**: Quickly save and recall your favorite prompts with custom names
- **LLM Integration**: Connect text outputs from other nodes (like LLM generators) and save them directly
- **Direct Editing**: Edit prompts directly in the node or select from your saved library
- **Persistent Storage**: All prompts are saved in your ComfyUI user folder and persist across sessions
- **Pre-loaded Templates**: Comes with example prompts across various categories
- **Easy Management**: Delete categories or individual prompts with confirmation dialogs
- **LLM Input Toggle**: Connect text outputs from other nodes and toggle between using them or your internal prompts
- **LLM Input Toggle**: When in use, display of categories and prompt is disabled, allowing user to switch category and save.
- **Persistent Storage**: All prompts saved in your ComfyUI user folder
### Prompt Generator
- **Three Generation Modes**: Enhance text prompts, analyze images, or analyze images with custom instructions
- **Prompt Enhancement**: Transform basic prompts into detailed descriptions using local LLMs
- **Vision Analysis**: Analyze images with Qwen3VL models to generate detailed descriptions
- **Custom Image Analysis**: Provide your own instructions for image analysis
- **JSON Output**: Optional structured JSON output with scene breakdown
- **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 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
@@ -28,112 +62,81 @@ A simple custom node for [ComfyUI](https://github.com/comfyanonymous/ComfyUI) th
git clone https://github.com/FranckyB/ComfyUI-Prompt-Manager.git
```
3. Restart ComfyUI
3. Install dependencies:
```bash
cd ComfyUI-Prompt-Manager
pip install -r requirements.txt
```
4. Install llama.cpp. It can be found here: [llama.cpp install](https://github.com/ggml-org/llama.cpp/blob/master/docs/install.md)
5. If you have them, place your .gguf models in the models/gguf folder. (Create folder if not present)
6. Restart ComfyUI
## Usage
### Basic Usage
### Prompt Manager
1. **Add the Node**: Right-click in ComfyUI → Add Node → Prompt Manager → Prompt Manager
1. **Add the Node**: Add Node → Prompt Manager
2. **Select a Category**: Use the dropdown to choose from your categories
3. **Choose a Prompt**: Select a saved prompt from the name dropdown
4. **Connect prompt output**: Connect Prompt Manager output to your clip text encode node.
2. **Select a Category**: Use the dropdown to choose from your categories (Character, Style, Environment, etc.)
3. **Choose a Prompt**: Select a saved prompt from the dropdown
### Prompt Generator
4. **Use the Output**: Connect the output to any node that accepts text/string input
**Basic Usage** (assuming a model is present in models\gguf):
1. **Add the Node**: Add Node → Prompt Generator
2. **Select Mode**: Choose from:
- "Enhance User Prompt" - Improve text prompts with LLM
- "Analyze Image" - Generate detailed image descriptions
- "Analyze Image with Prompt" - Analyze images with custom instructions
3. **Connect inputs**: Connect image for vision modes, or just use text for enhancement mode
4. **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
### 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. **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
#### Saving a Prompt
1. Type or paste your prompt into the text field (or have it connected from another node)
2. Click the **"Save Prompt"** button
3. Enter a name for your prompt
4. Click OK
> **Note**: If a prompt with the same name exists in the current category, you'll be asked to confirm before overwriting.
**Qwen models found in options**
- Qwen3-1.7B-Q8_0.gguf: Fastest, lowest VRAM (~2GB)
- Qwen3-4B-Q8_0.gguf: Balanced performance (~4GB VRAM)
- Qwen3-8B-Q8_0.gguf: Best quality, highest VRAM (~8GB)
- Qwen3VL-4B-Instruct-Q8_0.gguf: Vision model, balanced performance (~5GB VRAM)
- Qwen3VL-8B-Instruct-Q8_0.gguf: Vision model, best quality (~9GB VRAM)
- 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)
#### Creating a New Category
1. Click the **"New Category"** button
2. Enter a name for your category
3. Click OK
**Model Management**:
- Place gguf files in models/gguf folder
- Downloaded models are also placed in this folder.
#### Deleting a Category
1. Select the category you want to delete
2. Click the **"Del Category"** button
3. Confirm the deletion
**Model Preferences**:
- Set preferred models in ComfyUI Settings → Prompt Manager → Model Preferences
- **Preferred Base Model**: Used for "Enhance User Prompt" mode (text-only models)
- **Preferred Vision Model**: Used for "Analyze Image" modes (Qwen3VL models)
- Leave empty to auto-select smallest available model
- Changes are saved automatically in ComfyUI settings
#### Deleting a Prompt
1. Select the prompt you want to delete
2. Click the **"Del Prompt"** button
3. Confirm the deletion
## Requirements
### Working with LLM Outputs
You can capture and save outputs from LLM nodes:
1. Connect an LLM output (or any text output) to the **"text"** input of the Prompt Manager node
2. Run your workflow - the generated text will appear in the prompt field
3. Click **"Save Prompt"** to save the LLM-generated text to your library
4. Give it a descriptive name for future use
This is perfect for:
- Saving interesting prompts generated by LLMs
- Building a library of AI-generated variations
- Quickly iterating and saving the best results
## File Structure
```
comfyui-prompt-manager/
├── __init__.py # Node registration
├── prompt_manager.py # Main node logic and API endpoints
├── default_prompts.json # Default prompt templates
├── js/
│ └── prompt_manager.js # Frontend UI and interactions
└── README.md # This file
```
## Data Storage
Prompts are stored in:
```
ComfyUI/user/default/prompt_manager.json
```
The file is automatically created on first use, copying from `default_prompts.json`. You can:
- Back up this file to save your prompt library
- Share it with others
- Edit it directly (with caution)
## Default Categories
The node comes pre-loaded with example prompts in the following categories:
- **Character**: Fantasy warriors, sci-fi explorers, medieval knights, etc.
- **Style**: Cinematic, oil painting, watercolor, photorealistic, etc.
- **Environment**: Forests, cyberpunk cities, space stations, ancient temples, etc.
- **Lighting**: Golden hour, Rembrandt lighting, neon atmosphere, moonlight, etc.
- **Composition**: Dynamic action, minimalist zen, panoramic vistas, etc.
- **Mood**: Dark and ominous, peaceful, energetic, melancholic, etc.
- **Illustrious**: Anime-style character prompts and scene descriptions
Feel free to modify or delete these to suit your needs!
## Tips & Tricks
### Workflow Organization
- Create categories that match your workflow (e.g., "Characters", "Backgrounds", "Styles")
- Use descriptive names for your prompts to find them easily later
- Regularly backup your `prompt_manager.json` file
### LLM Integration
- Connect multiple Prompt Manager nodes to capture different LLM variations
- Use one node to store "seeds" and another for "final results"
- Combine with LLM nodes to build an iterative prompt refinement workflow
### Editing Prompts
- You can edit prompts directly in the text field even when loaded from the library
- Changes are not saved automatically - click "Save Prompt" to update
- Use "Save Prompt" with the same name to overwrite an existing prompt
- ComfyUI
- Python 3.8+
- requests >= 2.31.0
- huggingface_hub >= 0.20.0
- psutil >= 5.9.0
- tqdm >= 4.66.0
- Pillow >= 10.0.0
- llama-server (from llama.cpp)
## Troubleshooting
@@ -144,17 +147,78 @@ 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.
**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.0.1
### 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 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
- 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.8.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: 450 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 766 KiB

+235 -69
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;
@@ -28,11 +112,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 +159,7 @@ app.registerExtension({
addButtonBar(node);
setupCategoryChangeHandler(node);
filterPromptDropdown(node);
setupInputConnectionHandler(node);
setupUseExternalToggleHandler(node);
// After buttons are added, ensure height is sufficient
setTimeout(() => {
@@ -76,7 +191,7 @@ app.registerExtension({
if (!node.buttonBarAttached) {
addButtonBar(node);
setupCategoryChangeHandler(node);
setupInputConnectionHandler(node);
setupUseExternalToggleHandler(node);
}
});
}, 100);
@@ -87,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;
};
}
}
});
@@ -231,15 +387,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 +406,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 +432,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 +478,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) {
+261
View File
@@ -0,0 +1,261 @@
"""
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": {
"repo": "Qwen/Qwen3-1.7B-GGUF"
},
"Qwen3-4B-Q8_0.gguf": {
"repo": "Qwen/Qwen3-4B-GGUF"
},
"Qwen3-8B-Q8_0.gguf": {
"repo": "Qwen/Qwen3-8B-GGUF"
},
"Qwen3VL-4B-Instruct-Q8_0.gguf": {
"repo": "Qwen/Qwen3-VL-4B-Instruct-GGUF",
"mmproj": "mmproj-Qwen3VL-4B-Instruct-Q8_0.gguf"
},
"Qwen3VL-8B-Instruct-Q8_0.gguf": {
"repo": "Qwen/Qwen3-VL-8B-Instruct-GGUF",
"mmproj": "mmproj-Qwen3VL-8B-Instruct-Q8_0.gguf"
},
"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 primary models directory (ComfyUI/models/gguf) for downloads"""
# Register both gguf and LLM folders
if "gguf" not in folder_paths.folder_names_and_paths:
gguf_dir = os.path.join(folder_paths.models_dir, "gguf")
folder_paths.add_model_folder_path("gguf", gguf_dir)
if "LLM" not in folder_paths.folder_names_and_paths:
llm_dir = os.path.join(folder_paths.models_dir, "LLM")
folder_paths.add_model_folder_path("LLM", llm_dir)
# Return gguf as the primary directory (for downloads)
models_dir = folder_paths.get_folder_paths("gguf")[0]
# Create directory if it doesn't exist
os.makedirs(models_dir, exist_ok=True)
return models_dir
def get_all_model_directories():
"""Get all directories where models can be found"""
get_models_directory() # Ensure folders are registered
directories = []
for folder_type in ["gguf", "LLM"]:
if folder_type in folder_paths.folder_names_and_paths:
dirs = folder_paths.get_folder_paths(folder_type)
directories.extend(dirs)
return directories
def get_local_models():
"""Get list of local .gguf model files from all model directories"""
all_dirs = get_all_model_directories()
all_models = set() # Use set to avoid duplicates
for models_dir in all_dirs:
if os.path.exists(models_dir):
gguf_files = glob.glob(os.path.join(models_dir, "*.gguf"))
for f in gguf_files:
basename = os.path.basename(f)
# Filter out mmproj files
if not basename.startswith("mmproj-"):
all_models.add(basename)
# Return sorted list of unique filenames
return sorted(list(all_models))
def get_huggingface_models():
"""Get list of predefined Qwen models available for download"""
return list(QWEN_MODELS.keys())
def get_all_models():
"""Get combined list of local and HuggingFace models, excluding already downloaded ones and mmproj files"""
local_models = get_local_models() # Already filtered
models_dir = get_models_directory()
# List all known filenames, local ones first
all_models = []
# Add local models first (already filtered by get_local_models)
if local_models:
all_models.extend(local_models)
# Add remote models (not present locally), excluding mmproj files
for filename in QWEN_MODELS.keys():
if filename not in all_models and not filename.startswith("mmproj-"):
all_models.append(filename)
return all_models
def is_model_local(model_name):
"""Check if a model exists locally in any of the model directories"""
if model_name == "--- Download from HuggingFace ---":
return False
all_dirs = get_all_model_directories()
for models_dir in all_dirs:
model_path = os.path.join(models_dir, model_name)
if os.path.exists(model_path):
return True
return False
def get_model_path(model_name):
"""Get the full path to a model file, searching all model directories"""
all_dirs = get_all_model_directories()
# Check each directory for the model
for models_dir in all_dirs:
model_path = os.path.join(models_dir, model_name)
if os.path.exists(model_path):
return model_path
# If not found, return path in primary directory (gguf)
models_dir = get_models_directory()
return os.path.join(models_dir, model_name)
def get_mmproj_for_model(model_name):
"""Get the mmproj filename for a given vision model"""
if model_name in QWEN_MODELS and "mmproj" in QWEN_MODELS[model_name]:
return QWEN_MODELS[model_name]["mmproj"]
return None
def get_mmproj_path(model_name):
"""Get the path to the mmproj file for a vision model, if it exists
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
For VL models, also downloads the matching mmproj file if needed
Args:
model_name: Filename of the model (e.g., "Qwen3-4B-Q8_0.gguf")
Returns:
Path to downloaded model or None on error
"""
if model_name not in QWEN_MODELS:
print(f"[Model Manager] Error: Unknown model: {model_name}")
return None
model_info = QWEN_MODELS[model_name]
repo_id = model_info["repo"]
models_dir = get_models_directory()
# Build list of files to download
files_to_download = [
{"filename": model_name, "desc": "Downloading model"}
]
# Add mmproj file if this is a VL model
mmproj_name = get_mmproj_for_model(model_name)
if mmproj_name:
files_to_download.append({
"filename": mmproj_name,
"desc": "Downloading mmproj"
})
# Download each file if it doesn't exist
for file_info in files_to_download:
filename = file_info["filename"]
local_path = os.path.join(models_dir, filename)
if os.path.exists(local_path):
print(f"[Model Manager] File already exists: {filename}")
continue
# Download the file
try:
print(f"[Model Manager] Downloading {filename} from {repo_id}...")
api = HfApi()
repo_info = api.repo_info(repo_id=repo_id, files_metadata=True)
file_metadata = next((f for f in repo_info.siblings if f.rfilename == filename), None)
if not file_metadata or file_metadata.size is None:
print(f"[Model Manager] Could not find file size for {filename} in {repo_id}")
return None
total_size = file_metadata.size
download_url = f"https://huggingface.co/{repo_id}/resolve/main/{filename}"
pbar = tqdm(total=total_size, unit="B", unit_scale=True, desc=file_info["desc"])
with requests.get(download_url, stream=True) as r, open(local_path, "wb") as f:
r.raise_for_status()
for chunk in r.iter_content(chunk_size=65536):
if chunk:
f.write(chunk)
pbar.update(len(chunk))
pbar.close()
print(f"[Model Manager] Successfully downloaded {filename}")
except Exception as e:
print(f"[Model Manager] Error downloading {filename}: {e}")
return None
return os.path.join(models_dir, model_name)
+1015
View File
File diff suppressed because it is too large Load Diff
+179
View File
@@ -0,0 +1,179 @@
from .model_manager import get_all_models, is_model_local, download_model, get_mmproj_for_model, get_mmproj_path
import time
# Global timestamp to track when models were last updated
_last_model_update = time.time()
def trigger_model_list_refresh():
"""Call this after downloading a model to trigger UI refresh"""
global _last_model_update
_last_model_update = time.time()
class PromptGenOptions:
"""Node that provides optional configuration for llama.cpp servers"""
@classmethod
def INPUT_TYPES(cls):
available_models = get_all_models()
# If no models found, show a placeholder
if not available_models:
available_models = ["No models found - check HuggingFace"]
return {
"optional": {
"model": (available_models, {
"default": available_models[0] if available_models else "",
"tooltip": "Select model to use (local models listed first, then HuggingFace models)"
}),
"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)\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,
"min": 0.0,
"max": 2.0,
"step": 0.01,
"tooltip": "Controls randomness (0.0 = deterministic, 2.0 = very random)"
}),
"top_k": ("INT", {
"default": 40,
"min": 0,
"max": 100,
"step": 1,
"tooltip": "Sample from top K most likely tokens (0 = disabled)"
}),
"top_p": ("FLOAT", {
"default": 0.95,
"min": 0.0,
"max": 1.0,
"step": 0.01,
"tooltip": "Nucleus sampling: consider tokens with top_p probability mass"
}),
"min_p": ("FLOAT", {
"default": 0.05,
"min": 0.0,
"max": 1.0,
"step": 0.01,
"tooltip": "Minimum probability threshold relative to top token"
}),
"repeat_penalty": ("FLOAT", {
"default": 1.0,
"min": 1.0,
"max": 2.0,
"step": 0.01,
"tooltip": "Penalty for repeating tokens (1.0 = no penalty)"
}),
"context_size": ("INT", {
"default": 4096,
"min": 512,
"max": 32768,
"step": 512,
"tooltip": "Context size (increase for vision models or large prompts)"
}),
"show_everything_in_console": ("BOOLEAN", {
"default": False,
"tooltip": "Print system prompt, user prompt, thinking process, and raw model response to console"
})
}
}
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, 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, 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":
# Check if model is local
model_exists = is_model_local(model)
# For VL models, also check if mmproj exists
needs_download = not model_exists
if model_exists:
mmproj_name = get_mmproj_for_model(model)
if mmproj_name:
# This is a VL model, check if mmproj is present
mmproj_path = get_mmproj_path(model)
if not mmproj_path:
print(f"[Prompt Generator Options] Vision model found but mmproj missing, downloading: {mmproj_name}")
needs_download = True
if needs_download:
if not model_exists:
print(f"[Prompt Generator Options] Model not found locally, downloading: {model}")
downloaded_path = download_model(model)
if downloaded_path:
trigger_model_list_refresh()
options["model"] = model
else:
print(f"[Prompt Generator Options] Failed to download model: {model}")
else:
options["model"] = model
# 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
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,)
NODE_CLASS_MAPPINGS = {
"PromptGenOptions": PromptGenOptions
}
NODE_DISPLAY_NAME_MAPPINGS = {
"PromptGenOptions": "Prompt Generator Options"
}
+33 -16
View File
@@ -3,11 +3,12 @@ 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 +33,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 +106,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 +153,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 +161,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 +181,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 +198,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 +216,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 +241,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 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"
+7
View File
@@ -0,0 +1,7 @@
requests>=2.31.0
huggingface_hub>=0.20.0
psutil>=5.9.0
tqdm>=4.66.0
Pillow>=10.0.0
torch>=2.0.0
numpy>=1.24.0