Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ecdf1e0995 | ||
|
|
39575f137c | ||
|
|
e993546fa4 | ||
|
|
ce12566998 | ||
|
|
c61dcaad2c | ||
|
|
1ba2d214f6 | ||
|
|
473d96084c | ||
|
|
94feeb61c7 | ||
|
|
3884f72552 | ||
|
|
cae791a169 | ||
|
|
e6f56f3a75 | ||
|
|
bc682b3680 | ||
|
|
9982853cac | ||
|
|
7cc4478aa0 |
@@ -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 Input Toggle**: Connect text outputs from other nodes (like LLM generators) and toggle between using them or your internal prompts
|
||||
- **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,101 +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
|
||||
|
||||
### Using LLM Input Toggle
|
||||
|
||||
The node includes a toggle to switch between internal prompts and external LLM inputs:
|
||||
|
||||
1. Connect an LLM output (or any text output) to the **"llm_input"** connector
|
||||
2. Click the **"use llm input"** toggle to switch it ON
|
||||
3. The prompt field will display the connected text (grayed out)
|
||||
4. Run your workflow - the node will output the LLM text
|
||||
5. Click **"Save Prompt"** to save the LLM-generated text to your library
|
||||
6. Toggle OFF to switch back to your internal prompts
|
||||
|
||||
**Notes:**
|
||||
- The toggle only works when something is connected to `llm_input`
|
||||
- When toggled ON, the text field becomes read-only and shows the external input
|
||||
- When toggled OFF, it reverts to your selected internal prompt
|
||||
|
||||
## 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 Prompts
|
||||
|
||||
The node comes pre-loaded with example prompts.
|
||||
These were added for testing purposes, feel free to modify or delete them 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
|
||||
|
||||
### 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
|
||||
|
||||
@@ -133,22 +147,78 @@ These were added for testing purposes, feel free to modify or delete them to sui
|
||||
- **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**: "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.1.0
|
||||
- Added LLM input toggle for easy switching between internal and external text sources
|
||||
- Dedicated `llm_input` connector for external text
|
||||
- Toggle prevents activation when no connection is present
|
||||
- Text field becomes read-only when using external input
|
||||
- Auto-reverts to internal prompt when toggle is turned off
|
||||
- Fixed reload bug where toggle state wasn't applied on page load
|
||||
### Version 1.8.1
|
||||
- Added option to set a custom Llama path in preferences, for those that have specific installs.
|
||||
|
||||
### Version 1.0.1
|
||||
### 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
|
||||
|
||||
+9
-3
@@ -2,18 +2,24 @@
|
||||
ComfyUI Prompt Manager - A simple custom node for saving and reusing prompts
|
||||
A prompt management system for ComfyUI with LLM input support
|
||||
"""
|
||||
__version__ = "1.1.0"
|
||||
__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: 66 KiB After Width: | Height: | Size: 450 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 766 KiB |
+153
-13
@@ -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;
|
||||
@@ -33,6 +117,17 @@ app.registerExtension({
|
||||
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)) {
|
||||
@@ -44,6 +139,10 @@ app.registerExtension({
|
||||
// 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;
|
||||
@@ -103,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;
|
||||
};
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -352,7 +492,15 @@ function setupUseExternalToggleHandler(node) {
|
||||
const isLlmConnected = llmInputConnection && llmInputConnection.link != null;
|
||||
|
||||
if (value && isLlmConnected) {
|
||||
// Using LLM and it's connected - disable text widget and show LLM value
|
||||
// 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;
|
||||
}
|
||||
|
||||
// Try to show LLM value if available
|
||||
const graph = app.graph;
|
||||
const link = graph.links[llmInputConnection.link];
|
||||
if (link) {
|
||||
@@ -371,19 +519,11 @@ function setupUseExternalToggleHandler(node) {
|
||||
}
|
||||
}
|
||||
}
|
||||
textWidget.disabled = true;
|
||||
} else {
|
||||
// Using internal text - enable widget and revert to selected prompt
|
||||
// Using internal text - enable widget but keep current text (which may be LLM output)
|
||||
textWidget.disabled = false;
|
||||
|
||||
// Revert to the currently selected prompt from the node's prompt library
|
||||
if (categoryWidget && promptWidget && node.prompts) {
|
||||
const category = categoryWidget.value;
|
||||
const promptName = promptWidget.value;
|
||||
if (node.prompts[category] && node.prompts[category][promptName]) {
|
||||
const promptData = node.prompts[category][promptName];
|
||||
textWidget.value = promptData?.prompt || "";
|
||||
}
|
||||
if (textWidget.inputEl) {
|
||||
textWidget.inputEl.readOnly = false;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -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
File diff suppressed because it is too large
Load Diff
@@ -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"
|
||||
}
|
||||
+20
-13
@@ -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()
|
||||
@@ -36,7 +37,7 @@ class PromptManagerNode:
|
||||
"text": ("STRING", {"multiline": True, "default": first_prompt_text, "placeholder": "Enter prompt text", "dynamicPrompts": False, "tooltip": "Enter prompt text directly"}),
|
||||
},
|
||||
"optional": {
|
||||
"llm_input": ("STRING", {"multiline": True, "forceInput": True, "tooltip": "Connect LLM text input here"}),
|
||||
"llm_input": ("STRING", {"multiline": True, "forceInput": True, "lazy": True, "tooltip": "Connect LLM text input here"}),
|
||||
},
|
||||
"hidden": {
|
||||
"unique_id": "UNIQUE_ID",
|
||||
@@ -107,7 +108,7 @@ class PromptManagerNode:
|
||||
|
||||
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
|
||||
@@ -124,12 +125,18 @@ class PromptManagerNode:
|
||||
})
|
||||
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}")
|
||||
@@ -146,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()}
|
||||
@@ -154,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:
|
||||
@@ -174,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] = {}
|
||||
@@ -191,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:
|
||||
@@ -209,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:
|
||||
@@ -234,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
@@ -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.1.0"
|
||||
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"
|
||||
|
||||
@@ -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
|
||||
Reference in New Issue
Block a user