Upload 6 files
Browse files
custom_nodes/openai_prompt/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .nodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS
|
| 2 |
+
|
| 3 |
+
try:
|
| 4 |
+
from server import PromptServer
|
| 5 |
+
|
| 6 |
+
from .api import setup_routes
|
| 7 |
+
|
| 8 |
+
setup_routes(PromptServer.instance.routes)
|
| 9 |
+
except Exception as exc: # pragma: no cover - depends on ComfyUI runtime
|
| 10 |
+
print(f"[OpenAIPrompt] Could not register API routes: {exc}")
|
| 11 |
+
|
| 12 |
+
WEB_DIRECTORY = "./js"
|
| 13 |
+
|
| 14 |
+
__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"]
|
custom_nodes/openai_prompt/api.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Lightweight API route for the OpenAI Prompt Generator node.
|
| 3 |
+
|
| 4 |
+
Exposes GET /openai_prompt/config so the "Reload from config" button in the
|
| 5 |
+
node can pull fresh values from the JSON config file. The api key is never
|
| 6 |
+
returned to the browser — only a boolean saying whether one is available —
|
| 7 |
+
so the secret stays server-side.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import os
|
| 11 |
+
|
| 12 |
+
from aiohttp import web
|
| 13 |
+
|
| 14 |
+
from .nodes import _DEFAULTS, _load_config
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def setup_routes(routes):
|
| 18 |
+
@routes.get("/openai_prompt/config")
|
| 19 |
+
async def get_config(request):
|
| 20 |
+
config_file = request.query.get("file", "")
|
| 21 |
+
config, path = _load_config(config_file)
|
| 22 |
+
|
| 23 |
+
api_key_set = bool(
|
| 24 |
+
str(config.get("api_key", "")).strip()
|
| 25 |
+
or os.environ.get("OPENAI_API_KEY")
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
# Strip the secret before sending anything to the browser.
|
| 29 |
+
safe_config = {k: v for k, v in config.items() if k != "api_key"}
|
| 30 |
+
|
| 31 |
+
return web.json_response(
|
| 32 |
+
{
|
| 33 |
+
"found": bool(path and safe_config),
|
| 34 |
+
"path": path,
|
| 35 |
+
"config": safe_config,
|
| 36 |
+
"defaults": _DEFAULTS,
|
| 37 |
+
"api_key_set": api_key_set,
|
| 38 |
+
}
|
| 39 |
+
)
|
custom_nodes/openai_prompt/js/preview.js
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* OpenAI Prompt Generator / Text Preview — read-only preview widget.
|
| 3 |
+
*
|
| 4 |
+
* Shows every value passed through the node and keeps a running history of
|
| 5 |
+
* previous runs so you can review everything that has been passed. The history
|
| 6 |
+
* is saved with the workflow and restored on reload. A "Clear history" button
|
| 7 |
+
* resets it.
|
| 8 |
+
*/
|
| 9 |
+
|
| 10 |
+
import { app } from "../../scripts/app.js";
|
| 11 |
+
import { api } from "../../scripts/api.js";
|
| 12 |
+
import { ComfyWidgets } from "../../scripts/widgets.js";
|
| 13 |
+
|
| 14 |
+
const NODE_NAMES = ["OpenAIPromptGenerator", "TextPreview"];
|
| 15 |
+
const PREVIEW_NAME = "preview";
|
| 16 |
+
const MAX_RUNS = 50; // cap history so it can't grow unbounded
|
| 17 |
+
|
| 18 |
+
function tstamp() {
|
| 19 |
+
const d = new Date();
|
| 20 |
+
return d.toLocaleTimeString();
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
function render(history) {
|
| 24 |
+
if (!history || history.length === 0) return "";
|
| 25 |
+
// Newest run first so the latest output is at the top.
|
| 26 |
+
return history
|
| 27 |
+
.slice()
|
| 28 |
+
.reverse()
|
| 29 |
+
.map((run) => {
|
| 30 |
+
const head = `── Run ${run.n} · ${run.items.length} item(s) · ${run.time} ──`;
|
| 31 |
+
const body = run.items
|
| 32 |
+
.map((t, i) => `[${i + 1}] ${t}`)
|
| 33 |
+
.join("\n");
|
| 34 |
+
return `${head}\n${body}`;
|
| 35 |
+
})
|
| 36 |
+
.join("\n\n");
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
app.registerExtension({
|
| 40 |
+
name: "OpenAIPrompt.Preview",
|
| 41 |
+
async beforeRegisterNodeDef(nodeType, nodeData) {
|
| 42 |
+
if (!NODE_NAMES.includes(nodeData.name)) return;
|
| 43 |
+
|
| 44 |
+
function ensureWidget() {
|
| 45 |
+
let w = this.widgets?.find((x) => x.name === PREVIEW_NAME);
|
| 46 |
+
if (!w) {
|
| 47 |
+
w = ComfyWidgets["STRING"](
|
| 48 |
+
this,
|
| 49 |
+
PREVIEW_NAME,
|
| 50 |
+
["STRING", { multiline: true }],
|
| 51 |
+
app,
|
| 52 |
+
).widget;
|
| 53 |
+
w.inputEl.readOnly = true;
|
| 54 |
+
w.inputEl.style.opacity = "0.8";
|
| 55 |
+
// We manage this value ourselves; don't let it round-trip as an input.
|
| 56 |
+
w.serializeValue = () => "";
|
| 57 |
+
}
|
| 58 |
+
return w;
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
function refresh() {
|
| 62 |
+
const w = ensureWidget.call(this);
|
| 63 |
+
w.value = render(this._previewHistory);
|
| 64 |
+
requestAnimationFrame(() => {
|
| 65 |
+
const sz = this.computeSize();
|
| 66 |
+
if (sz[1] > this.size[1]) this.onResize?.(sz);
|
| 67 |
+
app.graph.setDirtyCanvas(true, false);
|
| 68 |
+
});
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
// ── lifecycle ────────────────────────────────────────────────────────
|
| 72 |
+
const onNodeCreated = nodeType.prototype.onNodeCreated;
|
| 73 |
+
nodeType.prototype.onNodeCreated = function () {
|
| 74 |
+
onNodeCreated?.apply(this, arguments);
|
| 75 |
+
if (!this._previewHistory) this._previewHistory = [];
|
| 76 |
+
this._previewRun = 0;
|
| 77 |
+
|
| 78 |
+
ensureWidget.call(this);
|
| 79 |
+
this.addWidget("button", "Clear history", null, () => {
|
| 80 |
+
this._previewHistory = [];
|
| 81 |
+
this._previewRun = 0;
|
| 82 |
+
refresh.call(this);
|
| 83 |
+
});
|
| 84 |
+
refresh.call(this);
|
| 85 |
+
};
|
| 86 |
+
|
| 87 |
+
const onExecuted = nodeType.prototype.onExecuted;
|
| 88 |
+
nodeType.prototype.onExecuted = function (message) {
|
| 89 |
+
onExecuted?.apply(this, arguments);
|
| 90 |
+
if (!message?.text) return;
|
| 91 |
+
const items = (Array.isArray(message.text) ? message.text : [message.text])
|
| 92 |
+
.map((t) => (t == null ? "" : String(t)));
|
| 93 |
+
|
| 94 |
+
if (!this._previewHistory) this._previewHistory = [];
|
| 95 |
+
this._previewRun = (this._previewRun || 0) + 1;
|
| 96 |
+
this._previewHistory.push({
|
| 97 |
+
n: this._previewRun,
|
| 98 |
+
time: tstamp(),
|
| 99 |
+
items,
|
| 100 |
+
});
|
| 101 |
+
if (this._previewHistory.length > MAX_RUNS) {
|
| 102 |
+
this._previewHistory.splice(0, this._previewHistory.length - MAX_RUNS);
|
| 103 |
+
}
|
| 104 |
+
refresh.call(this);
|
| 105 |
+
};
|
| 106 |
+
|
| 107 |
+
// ── persistence (saved inside the workflow json) ─────────────────────
|
| 108 |
+
const onSerialize = nodeType.prototype.onSerialize;
|
| 109 |
+
nodeType.prototype.onSerialize = function (o) {
|
| 110 |
+
onSerialize?.apply(this, arguments);
|
| 111 |
+
o.preview_history = this._previewHistory || [];
|
| 112 |
+
o.preview_run = this._previewRun || 0;
|
| 113 |
+
};
|
| 114 |
+
|
| 115 |
+
const onConfigure = nodeType.prototype.onConfigure;
|
| 116 |
+
nodeType.prototype.onConfigure = function (o) {
|
| 117 |
+
onConfigure?.apply(this, arguments);
|
| 118 |
+
if (Array.isArray(o.preview_history)) {
|
| 119 |
+
this._previewHistory = o.preview_history;
|
| 120 |
+
this._previewRun =
|
| 121 |
+
o.preview_run || o.preview_history.length || 0;
|
| 122 |
+
refresh.call(this);
|
| 123 |
+
}
|
| 124 |
+
};
|
| 125 |
+
},
|
| 126 |
+
});
|
| 127 |
+
|
| 128 |
+
// ── Mask the API key + "Reload from config" button ──────────────────────────
|
| 129 |
+
app.registerExtension({
|
| 130 |
+
name: "OpenAIPrompt.MaskApiKey",
|
| 131 |
+
async beforeRegisterNodeDef(nodeType, nodeData) {
|
| 132 |
+
if (nodeData.name !== "OpenAIPromptGenerator") return;
|
| 133 |
+
|
| 134 |
+
function setWidget(node, name, value) {
|
| 135 |
+
const w = node.widgets?.find((x) => x.name === name);
|
| 136 |
+
if (!w || value === undefined || value === null) return;
|
| 137 |
+
w.value = value;
|
| 138 |
+
w.callback?.(value);
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
async function reloadFromConfig() {
|
| 142 |
+
const fileW = this.widgets?.find((x) => x.name === "config_file");
|
| 143 |
+
const file = fileW ? fileW.value || "" : "";
|
| 144 |
+
let data;
|
| 145 |
+
try {
|
| 146 |
+
const resp = await api.fetchApi(
|
| 147 |
+
`/openai_prompt/config?file=${encodeURIComponent(file)}`,
|
| 148 |
+
);
|
| 149 |
+
data = await resp.json();
|
| 150 |
+
} catch (err) {
|
| 151 |
+
console.error("[OpenAIPrompt] reload failed", err);
|
| 152 |
+
return;
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
// Start from built-in defaults, then overlay whatever the config file
|
| 156 |
+
// provided. If nothing was found we simply end up with the defaults.
|
| 157 |
+
const values = Object.assign({}, data.defaults || {}, data.config || {});
|
| 158 |
+
for (const [k, v] of Object.entries(values)) {
|
| 159 |
+
setWidget(this, k, v);
|
| 160 |
+
}
|
| 161 |
+
// The api key is never sent to the browser; clear the field so it falls
|
| 162 |
+
// back to the config/env value at runtime, keeping the secret hidden.
|
| 163 |
+
setWidget(this, "api_key", "");
|
| 164 |
+
|
| 165 |
+
const where = data.found ? `config (${data.path})` : "built-in defaults";
|
| 166 |
+
console.log(`[OpenAIPrompt] Reloaded values from ${where}.`);
|
| 167 |
+
app.graph.setDirtyCanvas(true, true);
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
function maskWidget() {
|
| 171 |
+
const w = this.widgets?.find((x) => x.name === "api_key");
|
| 172 |
+
if (!w || w._masked) return;
|
| 173 |
+
w._masked = true;
|
| 174 |
+
|
| 175 |
+
// Mask the value drawn on the node canvas without altering the stored
|
| 176 |
+
// value. We swap in dots just for the duration of the draw call.
|
| 177 |
+
const origDraw = w.draw;
|
| 178 |
+
if (origDraw) {
|
| 179 |
+
w.draw = function (ctx, node, width, y, height) {
|
| 180 |
+
const real = this.value;
|
| 181 |
+
const len = real ? String(real).length : 0;
|
| 182 |
+
this.value = len ? "•".repeat(Math.min(len, 24)) : "";
|
| 183 |
+
const r = origDraw.call(this, ctx, node, width, y, height);
|
| 184 |
+
this.value = real;
|
| 185 |
+
return r;
|
| 186 |
+
};
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
// If the widget uses a DOM input (multiline/newer frontend), turn it
|
| 190 |
+
// into a real password field.
|
| 191 |
+
if (w.inputEl) {
|
| 192 |
+
w.inputEl.type = "password";
|
| 193 |
+
w.inputEl.autocomplete = "off";
|
| 194 |
+
}
|
| 195 |
+
}
|
| 196 |
+
|
| 197 |
+
const onNodeCreated = nodeType.prototype.onNodeCreated;
|
| 198 |
+
nodeType.prototype.onNodeCreated = function () {
|
| 199 |
+
onNodeCreated?.apply(this, arguments);
|
| 200 |
+
maskWidget.call(this);
|
| 201 |
+
this.addWidget("button", "Reload from config", null, () =>
|
| 202 |
+
reloadFromConfig.call(this),
|
| 203 |
+
);
|
| 204 |
+
};
|
| 205 |
+
|
| 206 |
+
const onConfigure = nodeType.prototype.onConfigure;
|
| 207 |
+
nodeType.prototype.onConfigure = function () {
|
| 208 |
+
onConfigure?.apply(this, arguments);
|
| 209 |
+
maskWidget.call(this);
|
| 210 |
+
};
|
| 211 |
+
},
|
| 212 |
+
});
|
custom_nodes/openai_prompt/nodes.py
ADDED
|
@@ -0,0 +1,661 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
OpenAI-compatible LLM prompt generator node for ComfyUI.
|
| 3 |
+
|
| 4 |
+
Uses the official `openai` python SDK so it works with any OpenAI-compatible
|
| 5 |
+
endpoint (OpenAI, OpenRouter, LM Studio, Ollama, vLLM, etc.) by letting the
|
| 6 |
+
user configure the base URL and API key.
|
| 7 |
+
|
| 8 |
+
Two modes:
|
| 9 |
+
* Plain text -> outputs a single string.
|
| 10 |
+
* Structured -> asks the model for a JSON array of strings and outputs the
|
| 11 |
+
list. With OUTPUT_IS_LIST the downstream graph runs once per
|
| 12 |
+
item, so "make 3 prompts" feeds each prompt through the graph
|
| 13 |
+
one after another.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import json
|
| 17 |
+
import os
|
| 18 |
+
import re
|
| 19 |
+
|
| 20 |
+
# Fields that may be supplied by the JSON config file.
|
| 21 |
+
_CONFIG_FIELDS = (
|
| 22 |
+
"base_url",
|
| 23 |
+
"api_key",
|
| 24 |
+
"model",
|
| 25 |
+
"system_prompt",
|
| 26 |
+
"instruction",
|
| 27 |
+
"structured_output",
|
| 28 |
+
"count",
|
| 29 |
+
"temperature",
|
| 30 |
+
"max_tokens",
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
# Default name searched for when the user gives just a filename.
|
| 34 |
+
_DEFAULT_CONFIG_NAME = "openai_prompt_config.json"
|
| 35 |
+
|
| 36 |
+
# Built-in fallback values used when no config file is found. Shared by
|
| 37 |
+
# INPUT_TYPES (widget defaults) and the /openai_prompt/config API route so the
|
| 38 |
+
# "Reload from config" button can revert to these.
|
| 39 |
+
_DEFAULTS = {
|
| 40 |
+
"base_url": "https://api.openai.com/v1",
|
| 41 |
+
"model": "gpt-4o-mini",
|
| 42 |
+
"system_prompt": (
|
| 43 |
+
"You are a helpful assistant that writes vivid, detailed "
|
| 44 |
+
"image-generation prompts."
|
| 45 |
+
),
|
| 46 |
+
"instruction": "Make prompts for an anime girl.",
|
| 47 |
+
"structured_output": False,
|
| 48 |
+
"count": 3,
|
| 49 |
+
"temperature": 0.9,
|
| 50 |
+
"max_tokens": 1024,
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def _comfy_base_path():
|
| 55 |
+
"""Best-effort path to the ComfyUI install directory."""
|
| 56 |
+
try:
|
| 57 |
+
import folder_paths # provided by ComfyUI at runtime
|
| 58 |
+
|
| 59 |
+
return getattr(folder_paths, "base_path", None)
|
| 60 |
+
except Exception:
|
| 61 |
+
return None
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _config_search_dirs():
|
| 65 |
+
"""
|
| 66 |
+
Ordered list of directories to look in for the config file.
|
| 67 |
+
|
| 68 |
+
Covers: an env-var directory, the ComfyUI install dir and its parent,
|
| 69 |
+
this custom node's folder and a few parents, plus the current dir.
|
| 70 |
+
"""
|
| 71 |
+
dirs = []
|
| 72 |
+
|
| 73 |
+
env_dir = os.environ.get("OPENAI_PROMPT_CONFIG_DIR")
|
| 74 |
+
if env_dir:
|
| 75 |
+
dirs.append(env_dir)
|
| 76 |
+
|
| 77 |
+
base = _comfy_base_path()
|
| 78 |
+
if base:
|
| 79 |
+
dirs.append(base)
|
| 80 |
+
dirs.append(os.path.dirname(base.rstrip("/\\")))
|
| 81 |
+
|
| 82 |
+
here = os.path.dirname(os.path.abspath(__file__))
|
| 83 |
+
node_dir = here
|
| 84 |
+
for _ in range(4): # this node folder + a few parents (e.g. custom_nodes, ComfyUI, parent)
|
| 85 |
+
dirs.append(node_dir)
|
| 86 |
+
parent = os.path.dirname(node_dir)
|
| 87 |
+
if parent == node_dir:
|
| 88 |
+
break
|
| 89 |
+
node_dir = parent
|
| 90 |
+
|
| 91 |
+
dirs.append(os.getcwd())
|
| 92 |
+
|
| 93 |
+
# De-duplicate while preserving order.
|
| 94 |
+
seen, unique = set(), []
|
| 95 |
+
for d in dirs:
|
| 96 |
+
if d and d not in seen:
|
| 97 |
+
seen.add(d)
|
| 98 |
+
unique.append(d)
|
| 99 |
+
return unique
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def _resolve_config_path(config_file):
|
| 103 |
+
"""Turn the user's config_file setting into an existing file path, or None."""
|
| 104 |
+
# 1. Explicit override via environment variable (full path).
|
| 105 |
+
env_path = os.environ.get("OPENAI_PROMPT_CONFIG")
|
| 106 |
+
candidates = []
|
| 107 |
+
if env_path:
|
| 108 |
+
candidates.append(env_path)
|
| 109 |
+
|
| 110 |
+
name = (config_file or "").strip() or _DEFAULT_CONFIG_NAME
|
| 111 |
+
expanded = os.path.expanduser(name)
|
| 112 |
+
|
| 113 |
+
if os.path.isabs(expanded):
|
| 114 |
+
candidates.append(expanded)
|
| 115 |
+
elif os.sep in expanded or (os.altsep and os.altsep in expanded):
|
| 116 |
+
# Relative path with directories: resolve against each search dir.
|
| 117 |
+
candidates.append(os.path.abspath(expanded))
|
| 118 |
+
for d in _config_search_dirs():
|
| 119 |
+
candidates.append(os.path.join(d, expanded))
|
| 120 |
+
else:
|
| 121 |
+
# Bare filename: search each candidate directory.
|
| 122 |
+
for d in _config_search_dirs():
|
| 123 |
+
candidates.append(os.path.join(d, expanded))
|
| 124 |
+
|
| 125 |
+
for path in candidates:
|
| 126 |
+
if path and os.path.isfile(path):
|
| 127 |
+
return path
|
| 128 |
+
return None
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def _load_config(config_file):
|
| 132 |
+
"""
|
| 133 |
+
Load config from JSON. Returns (config_dict, path).
|
| 134 |
+
|
| 135 |
+
Accepts either a flat object with the known fields, or an object nested
|
| 136 |
+
under a "prompt_generator" / "openai_prompt" key.
|
| 137 |
+
"""
|
| 138 |
+
path = _resolve_config_path(config_file)
|
| 139 |
+
if not path:
|
| 140 |
+
return {}, None
|
| 141 |
+
try:
|
| 142 |
+
with open(path, "r", encoding="utf-8") as fh:
|
| 143 |
+
data = json.load(fh)
|
| 144 |
+
except Exception as exc:
|
| 145 |
+
print(f"[OpenAIPrompt] Failed to read config '{path}': {exc}")
|
| 146 |
+
return {}, path
|
| 147 |
+
|
| 148 |
+
if not isinstance(data, dict):
|
| 149 |
+
print(f"[OpenAIPrompt] Config '{path}' must be a JSON object.")
|
| 150 |
+
return {}, path
|
| 151 |
+
|
| 152 |
+
# Unwrap a nested section if present.
|
| 153 |
+
for section in ("prompt_generator", "openai_prompt", "OpenAIPromptGenerator"):
|
| 154 |
+
if isinstance(data.get(section), dict):
|
| 155 |
+
merged = dict(data)
|
| 156 |
+
merged.update(data[section])
|
| 157 |
+
data = merged
|
| 158 |
+
break
|
| 159 |
+
|
| 160 |
+
config = {k: data[k] for k in _CONFIG_FIELDS if k in data}
|
| 161 |
+
return config, path
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def _strip_code_fence(text: str) -> str:
|
| 166 |
+
"""Remove a leading/trailing markdown code fence if present."""
|
| 167 |
+
text = text.strip()
|
| 168 |
+
if text.startswith("```"):
|
| 169 |
+
text = re.sub(r"^```[a-zA-Z0-9]*\n?", "", text)
|
| 170 |
+
text = re.sub(r"\n?```\s*$", "", text)
|
| 171 |
+
return text.strip()
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def _coerce_to_list(value) -> list:
|
| 175 |
+
"""Turn whatever JSON we parsed into a flat list of strings."""
|
| 176 |
+
items = []
|
| 177 |
+
|
| 178 |
+
def _push(v):
|
| 179 |
+
if v is None:
|
| 180 |
+
return
|
| 181 |
+
if isinstance(v, str):
|
| 182 |
+
s = v.strip()
|
| 183 |
+
if s:
|
| 184 |
+
items.append(s)
|
| 185 |
+
elif isinstance(v, (int, float, bool)):
|
| 186 |
+
items.append(str(v))
|
| 187 |
+
elif isinstance(v, dict):
|
| 188 |
+
# Prefer common text-carrying keys, else serialise.
|
| 189 |
+
for key in ("prompt", "text", "value", "content", "description"):
|
| 190 |
+
if key in v and isinstance(v[key], str):
|
| 191 |
+
_push(v[key])
|
| 192 |
+
return
|
| 193 |
+
items.append(json.dumps(v, ensure_ascii=False))
|
| 194 |
+
elif isinstance(v, (list, tuple)):
|
| 195 |
+
for sub in v:
|
| 196 |
+
_push(sub)
|
| 197 |
+
|
| 198 |
+
_push(value)
|
| 199 |
+
return items
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def _parse_structured(content: str) -> list:
|
| 203 |
+
"""Best-effort extraction of a list of strings from the model output."""
|
| 204 |
+
cleaned = _strip_code_fence(content)
|
| 205 |
+
|
| 206 |
+
# 1. Try to parse the whole thing as JSON.
|
| 207 |
+
parsed = None
|
| 208 |
+
try:
|
| 209 |
+
parsed = json.loads(cleaned)
|
| 210 |
+
except Exception:
|
| 211 |
+
# 2. Fall back to grabbing the first JSON array or object in the text.
|
| 212 |
+
for pattern in (r"\[.*\]", r"\{.*\}"):
|
| 213 |
+
match = re.search(pattern, cleaned, re.DOTALL)
|
| 214 |
+
if match:
|
| 215 |
+
try:
|
| 216 |
+
parsed = json.loads(match.group(0))
|
| 217 |
+
break
|
| 218 |
+
except Exception:
|
| 219 |
+
continue
|
| 220 |
+
|
| 221 |
+
if parsed is None:
|
| 222 |
+
# 3. Non-JSON output: split into separate prompts.
|
| 223 |
+
return _split_plaintext(cleaned)
|
| 224 |
+
|
| 225 |
+
# If it's a dict, look for the first list value it contains.
|
| 226 |
+
if isinstance(parsed, dict):
|
| 227 |
+
for val in parsed.values():
|
| 228 |
+
if isinstance(val, list):
|
| 229 |
+
parsed = val
|
| 230 |
+
break
|
| 231 |
+
|
| 232 |
+
return _coerce_to_list(parsed)
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def _split_plaintext(text: str) -> list:
|
| 236 |
+
"""
|
| 237 |
+
Split model prose into individual prompts when it did not return JSON.
|
| 238 |
+
|
| 239 |
+
Strategy (most reliable first):
|
| 240 |
+
1. Numbered / bulleted items ("1.", "1)", "- ", "* ") — supports
|
| 241 |
+
multi-line prompts belonging to the same number.
|
| 242 |
+
2. Blank-line separated paragraphs.
|
| 243 |
+
3. The whole thing as a single item.
|
| 244 |
+
"""
|
| 245 |
+
text = text.strip()
|
| 246 |
+
if not text:
|
| 247 |
+
return []
|
| 248 |
+
|
| 249 |
+
# 1. Numbered or bulleted list. Split at the start of each marker.
|
| 250 |
+
marker = re.compile(r"(?m)^\s*(?:\d+[.)]|[-*•])\s+")
|
| 251 |
+
if len(marker.findall(text)) >= 2:
|
| 252 |
+
parts = marker.split(text)
|
| 253 |
+
items = [p.strip() for p in parts if p.strip()]
|
| 254 |
+
if items:
|
| 255 |
+
return [re.sub(r"^(?:prompt|option|result)\s*\d*\s*[:.-]\s*",
|
| 256 |
+
"", it, flags=re.IGNORECASE).strip()
|
| 257 |
+
for it in items]
|
| 258 |
+
|
| 259 |
+
# 2. Blank-line separated paragraphs.
|
| 260 |
+
paragraphs = [p.strip() for p in re.split(r"\n\s*\n", text) if p.strip()]
|
| 261 |
+
if len(paragraphs) >= 2:
|
| 262 |
+
return paragraphs
|
| 263 |
+
|
| 264 |
+
# 3. Single value.
|
| 265 |
+
return [text]
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def _adaptive_call(call, kwargs, max_attempts=6):
|
| 269 |
+
"""
|
| 270 |
+
Call the API, progressively dropping/renaming parameters that a given
|
| 271 |
+
model or endpoint rejects (e.g. newer reasoning models deprecate
|
| 272 |
+
`temperature` and require `max_completion_tokens` instead of `max_tokens`).
|
| 273 |
+
"""
|
| 274 |
+
kwargs = dict(kwargs)
|
| 275 |
+
last_error = None
|
| 276 |
+
|
| 277 |
+
for _ in range(max_attempts):
|
| 278 |
+
try:
|
| 279 |
+
return call(kwargs)
|
| 280 |
+
except Exception as exc: # noqa: BLE001 - inspect message to adapt
|
| 281 |
+
last_error = exc
|
| 282 |
+
msg = str(getattr(exc, "message", "") or exc).lower()
|
| 283 |
+
changed = False
|
| 284 |
+
|
| 285 |
+
# Parameter deprecated / unsupported / bad value -> drop it.
|
| 286 |
+
for param in ("temperature", "top_p", "seed", "response_format",
|
| 287 |
+
"frequency_penalty", "presence_penalty"):
|
| 288 |
+
if param in kwargs and param in msg and (
|
| 289 |
+
"deprecat" in msg
|
| 290 |
+
or "unsupported" in msg
|
| 291 |
+
or "not support" in msg
|
| 292 |
+
or "does not support" in msg
|
| 293 |
+
or "unknown" in msg
|
| 294 |
+
):
|
| 295 |
+
kwargs.pop(param, None)
|
| 296 |
+
changed = True
|
| 297 |
+
|
| 298 |
+
# Some models want max_completion_tokens instead of max_tokens.
|
| 299 |
+
if "max_tokens" in kwargs and (
|
| 300 |
+
"max_completion_tokens" in msg or "max_tokens" in msg
|
| 301 |
+
):
|
| 302 |
+
kwargs["max_completion_tokens"] = kwargs.pop("max_tokens")
|
| 303 |
+
changed = True
|
| 304 |
+
|
| 305 |
+
# If we couldn't figure out what to strip, try removing the usual
|
| 306 |
+
# optional suspects one at a time before giving up.
|
| 307 |
+
if not changed:
|
| 308 |
+
for param in ("response_format", "temperature", "top_p",
|
| 309 |
+
"seed", "max_tokens"):
|
| 310 |
+
if param in kwargs:
|
| 311 |
+
kwargs.pop(param)
|
| 312 |
+
changed = True
|
| 313 |
+
break
|
| 314 |
+
|
| 315 |
+
if not changed:
|
| 316 |
+
break
|
| 317 |
+
|
| 318 |
+
raise last_error
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def _tensor_to_data_uris(image, max_images=4):
|
| 322 |
+
"""
|
| 323 |
+
Convert a ComfyUI IMAGE tensor into a list of PNG data URIs suitable for
|
| 324 |
+
the OpenAI vision message format.
|
| 325 |
+
|
| 326 |
+
ComfyUI images are float tensors shaped [batch, height, width, channels]
|
| 327 |
+
with values in the 0..1 range.
|
| 328 |
+
"""
|
| 329 |
+
import base64
|
| 330 |
+
import io
|
| 331 |
+
|
| 332 |
+
import numpy as np
|
| 333 |
+
from PIL import Image
|
| 334 |
+
|
| 335 |
+
arr = image
|
| 336 |
+
if hasattr(arr, "cpu"): # torch tensor
|
| 337 |
+
arr = arr.cpu().numpy()
|
| 338 |
+
arr = np.asarray(arr)
|
| 339 |
+
if arr.ndim == 3: # single image -> add batch dim
|
| 340 |
+
arr = arr[None, ...]
|
| 341 |
+
|
| 342 |
+
uris = []
|
| 343 |
+
for frame in arr[:max_images]:
|
| 344 |
+
pixels = np.clip(frame * 255.0, 0, 255).astype(np.uint8)
|
| 345 |
+
# Normalise channel dimension so PIL can infer the mode itself.
|
| 346 |
+
if pixels.ndim == 3:
|
| 347 |
+
if pixels.shape[-1] == 1: # single channel -> grayscale
|
| 348 |
+
pixels = pixels[..., 0]
|
| 349 |
+
elif pixels.shape[-1] > 4: # keep RGB, drop extras
|
| 350 |
+
pixels = pixels[..., :3]
|
| 351 |
+
buf = io.BytesIO()
|
| 352 |
+
Image.fromarray(pixels).save(buf, format="PNG")
|
| 353 |
+
b64 = base64.b64encode(buf.getvalue()).decode("ascii")
|
| 354 |
+
uris.append(f"data:image/png;base64,{b64}")
|
| 355 |
+
return uris
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
class OpenAIPromptGenerator:
|
| 359 |
+
"""
|
| 360 |
+
Generate text (or a list of prompts) from any OpenAI-compatible LLM.
|
| 361 |
+
|
| 362 |
+
Connect the `text` output to any node that accepts a string (e.g. a
|
| 363 |
+
CLIP Text Encode). In structured mode the output is a list, so ComfyUI
|
| 364 |
+
executes the rest of the graph once for each generated prompt.
|
| 365 |
+
"""
|
| 366 |
+
|
| 367 |
+
@classmethod
|
| 368 |
+
def INPUT_TYPES(cls):
|
| 369 |
+
# Load the config once at registration so its values become the
|
| 370 |
+
# visible defaults for a freshly added node. (Restart ComfyUI to pick
|
| 371 |
+
# up edits to the config file.) The api key is intentionally NOT
|
| 372 |
+
# embedded as a default so the secret never ends up in object_info or
|
| 373 |
+
# saved workflows — it is pulled from the config/env at runtime.
|
| 374 |
+
cfg, _ = _load_config(_DEFAULT_CONFIG_NAME)
|
| 375 |
+
|
| 376 |
+
def d(key, fallback):
|
| 377 |
+
return cfg.get(key, fallback)
|
| 378 |
+
|
| 379 |
+
return {
|
| 380 |
+
"required": {
|
| 381 |
+
"config_file": (
|
| 382 |
+
"STRING",
|
| 383 |
+
{"default": _DEFAULT_CONFIG_NAME, "multiline": False},
|
| 384 |
+
),
|
| 385 |
+
"use_config": ("BOOLEAN", {"default": True}),
|
| 386 |
+
"base_url": (
|
| 387 |
+
"STRING",
|
| 388 |
+
{
|
| 389 |
+
"default": d("base_url", "https://api.openai.com/v1"),
|
| 390 |
+
"multiline": False,
|
| 391 |
+
},
|
| 392 |
+
),
|
| 393 |
+
"api_key": (
|
| 394 |
+
"STRING",
|
| 395 |
+
{
|
| 396 |
+
"default": "",
|
| 397 |
+
"multiline": False,
|
| 398 |
+
# Hints for frontends that support masked inputs; the
|
| 399 |
+
# bundled JS also masks it on the node canvas.
|
| 400 |
+
"password": True,
|
| 401 |
+
"sensitive": True,
|
| 402 |
+
"placeholder": "loaded from config file",
|
| 403 |
+
},
|
| 404 |
+
),
|
| 405 |
+
"model": (
|
| 406 |
+
"STRING",
|
| 407 |
+
{"default": d("model", "gpt-4o-mini"), "multiline": False},
|
| 408 |
+
),
|
| 409 |
+
"system_prompt": (
|
| 410 |
+
"STRING",
|
| 411 |
+
{
|
| 412 |
+
"default": d(
|
| 413 |
+
"system_prompt",
|
| 414 |
+
"You are a helpful assistant that writes vivid, "
|
| 415 |
+
"detailed image-generation prompts.",
|
| 416 |
+
),
|
| 417 |
+
"multiline": True,
|
| 418 |
+
},
|
| 419 |
+
),
|
| 420 |
+
"instruction": (
|
| 421 |
+
"STRING",
|
| 422 |
+
{
|
| 423 |
+
"default": d(
|
| 424 |
+
"instruction", "Make prompts for an anime girl."
|
| 425 |
+
),
|
| 426 |
+
"multiline": True,
|
| 427 |
+
},
|
| 428 |
+
),
|
| 429 |
+
"structured_output": (
|
| 430 |
+
"BOOLEAN",
|
| 431 |
+
{"default": bool(d("structured_output", False))},
|
| 432 |
+
),
|
| 433 |
+
"count": (
|
| 434 |
+
"INT",
|
| 435 |
+
{
|
| 436 |
+
"default": int(d("count", 1)),
|
| 437 |
+
"min": 1,
|
| 438 |
+
"max": 1000,
|
| 439 |
+
"step": 1,
|
| 440 |
+
},
|
| 441 |
+
),
|
| 442 |
+
"temperature": (
|
| 443 |
+
"FLOAT",
|
| 444 |
+
{
|
| 445 |
+
"default": float(d("temperature", 0.9)),
|
| 446 |
+
"min": 0.0,
|
| 447 |
+
"max": 2.0,
|
| 448 |
+
"step": 0.05,
|
| 449 |
+
},
|
| 450 |
+
),
|
| 451 |
+
"max_tokens": (
|
| 452 |
+
"INT",
|
| 453 |
+
{
|
| 454 |
+
"default": int(d("max_tokens", 1024)),
|
| 455 |
+
"min": 1,
|
| 456 |
+
"max": 32768,
|
| 457 |
+
"step": 1,
|
| 458 |
+
},
|
| 459 |
+
),
|
| 460 |
+
"seed": (
|
| 461 |
+
"INT",
|
| 462 |
+
{"default": 0, "min": 0, "max": 0xFFFFFFFFFFFFFFFF},
|
| 463 |
+
),
|
| 464 |
+
},
|
| 465 |
+
"optional": {
|
| 466 |
+
# Connect Load Image (or Batch Images) nodes here to use the
|
| 467 |
+
# picture(s) as input for a vision-capable model. Each input
|
| 468 |
+
# may itself be a batch; all supplied images are sent.
|
| 469 |
+
"image": ("IMAGE",),
|
| 470 |
+
},
|
| 471 |
+
}
|
| 472 |
+
|
| 473 |
+
RETURN_TYPES = ("STRING",)
|
| 474 |
+
RETURN_NAMES = ("text",)
|
| 475 |
+
OUTPUT_IS_LIST = (True,)
|
| 476 |
+
FUNCTION = "generate"
|
| 477 |
+
CATEGORY = "LLM"
|
| 478 |
+
OUTPUT_NODE = True
|
| 479 |
+
|
| 480 |
+
def generate(
|
| 481 |
+
self,
|
| 482 |
+
config_file,
|
| 483 |
+
use_config,
|
| 484 |
+
base_url,
|
| 485 |
+
api_key,
|
| 486 |
+
model,
|
| 487 |
+
system_prompt,
|
| 488 |
+
instruction,
|
| 489 |
+
structured_output,
|
| 490 |
+
count,
|
| 491 |
+
temperature,
|
| 492 |
+
max_tokens,
|
| 493 |
+
seed,
|
| 494 |
+
image=None,
|
| 495 |
+
):
|
| 496 |
+
# Config already seeds the widget defaults at registration. At runtime
|
| 497 |
+
# we only *fill in* fields the user left blank (most importantly the
|
| 498 |
+
# api key, which is never embedded), so manual edits are respected.
|
| 499 |
+
config = {}
|
| 500 |
+
if use_config:
|
| 501 |
+
config, path = _load_config(config_file)
|
| 502 |
+
if path and config:
|
| 503 |
+
print(f"[OpenAIPrompt] Config available at '{path}'.")
|
| 504 |
+
elif config_file.strip():
|
| 505 |
+
print(
|
| 506 |
+
f"[OpenAIPrompt] No usable config found for '{config_file}' "
|
| 507 |
+
f"(searched ComfyUI dir, its parent, and the node folder)."
|
| 508 |
+
)
|
| 509 |
+
|
| 510 |
+
def _fill(key, current):
|
| 511 |
+
if isinstance(current, str) and current.strip() == "" and key in config:
|
| 512 |
+
return config[key]
|
| 513 |
+
return current
|
| 514 |
+
|
| 515 |
+
base_url = _fill("base_url", base_url)
|
| 516 |
+
api_key = _fill("api_key", api_key)
|
| 517 |
+
model = _fill("model", model)
|
| 518 |
+
system_prompt = _fill("system_prompt", system_prompt)
|
| 519 |
+
instruction = _fill("instruction", instruction)
|
| 520 |
+
structured_output = bool(structured_output)
|
| 521 |
+
count = int(count)
|
| 522 |
+
temperature = float(temperature)
|
| 523 |
+
max_tokens = int(max_tokens)
|
| 524 |
+
|
| 525 |
+
try:
|
| 526 |
+
from openai import OpenAI
|
| 527 |
+
except ImportError as exc:
|
| 528 |
+
raise RuntimeError(
|
| 529 |
+
"The `openai` package is required. Install it with "
|
| 530 |
+
"`pip install openai` (or `bun`-equivalent in your env)."
|
| 531 |
+
) from exc
|
| 532 |
+
|
| 533 |
+
# Allow an env var fallback so the key need not live in the workflow file.
|
| 534 |
+
key = api_key.strip() or os.environ.get("OPENAI_API_KEY", "")
|
| 535 |
+
if not key:
|
| 536 |
+
# Many local servers (Ollama/LM Studio) ignore the key but the SDK
|
| 537 |
+
# still requires a non-empty value.
|
| 538 |
+
key = "not-needed"
|
| 539 |
+
|
| 540 |
+
client = OpenAI(base_url=base_url.strip() or None, api_key=key)
|
| 541 |
+
|
| 542 |
+
user_content = instruction
|
| 543 |
+
request_kwargs = {
|
| 544 |
+
"model": model,
|
| 545 |
+
"temperature": float(temperature),
|
| 546 |
+
"max_tokens": int(max_tokens),
|
| 547 |
+
}
|
| 548 |
+
if int(seed) > 0:
|
| 549 |
+
request_kwargs["seed"] = int(seed)
|
| 550 |
+
|
| 551 |
+
if structured_output:
|
| 552 |
+
# Ask explicitly for a JSON array so we can split the results.
|
| 553 |
+
# The explicit count must win over any number the user wrote in the
|
| 554 |
+
# instruction (e.g. "make 3 prompts"), so state it firmly.
|
| 555 |
+
n = int(count)
|
| 556 |
+
noun = "result" if n == 1 else "results"
|
| 557 |
+
example = '["only one"]' if n == 1 else '["first", "second"]'
|
| 558 |
+
user_content = (
|
| 559 |
+
f"{instruction}\n\n"
|
| 560 |
+
f"IMPORTANT: Produce EXACTLY {n} {noun}, no more and no fewer. "
|
| 561 |
+
f"This overrides any other quantity mentioned above. "
|
| 562 |
+
f"Return them as a JSON array of {n} string(s), "
|
| 563 |
+
f"e.g. {example}. "
|
| 564 |
+
f"Output only the JSON array, no extra commentary."
|
| 565 |
+
)
|
| 566 |
+
# Nudge servers that support it toward JSON output. Wrapped in a
|
| 567 |
+
# try since not every endpoint accepts response_format.
|
| 568 |
+
request_kwargs["response_format"] = {"type": "json_object"}
|
| 569 |
+
|
| 570 |
+
# Build the user message. When one or more images are connected, send
|
| 571 |
+
# them as a multimodal message so vision-capable models can see them.
|
| 572 |
+
user_message = {"role": "user", "content": user_content}
|
| 573 |
+
total_image_cap = 16
|
| 574 |
+
uris = []
|
| 575 |
+
for tensor in (image):
|
| 576 |
+
if tensor is None or len(uris) >= total_image_cap:
|
| 577 |
+
continue
|
| 578 |
+
try:
|
| 579 |
+
uris.extend(
|
| 580 |
+
_tensor_to_data_uris(
|
| 581 |
+
tensor, max_images=total_image_cap - len(uris)
|
| 582 |
+
)
|
| 583 |
+
)
|
| 584 |
+
except Exception as exc: # noqa: BLE001
|
| 585 |
+
print(f"[OpenAIPrompt] Could not encode an image, skipping: {exc}")
|
| 586 |
+
|
| 587 |
+
if uris:
|
| 588 |
+
parts = [{"type": "text", "text": user_content}]
|
| 589 |
+
for uri in uris:
|
| 590 |
+
parts.append({"type": "image_url", "image_url": {"url": uri}})
|
| 591 |
+
user_message = {"role": "user", "content": parts}
|
| 592 |
+
|
| 593 |
+
messages = [
|
| 594 |
+
{"role": "system", "content": system_prompt},
|
| 595 |
+
user_message,
|
| 596 |
+
]
|
| 597 |
+
|
| 598 |
+
def _call(kwargs):
|
| 599 |
+
resp = client.chat.completions.create(messages=messages, **kwargs)
|
| 600 |
+
return resp.choices[0].message.content or ""
|
| 601 |
+
|
| 602 |
+
content = _adaptive_call(_call, request_kwargs)
|
| 603 |
+
|
| 604 |
+
if structured_output:
|
| 605 |
+
results = _parse_structured(content)
|
| 606 |
+
if not results:
|
| 607 |
+
results = [content.strip()]
|
| 608 |
+
# Enforce the requested count so the widget is authoritative even
|
| 609 |
+
# if the model returns more items than asked (e.g. the instruction
|
| 610 |
+
# text mentions a different number).
|
| 611 |
+
if count >= 1 and len(results) > count:
|
| 612 |
+
results = results[:count]
|
| 613 |
+
else:
|
| 614 |
+
results = [content.strip()]
|
| 615 |
+
|
| 616 |
+
return {"ui": {"text": results}, "result": (results,)}
|
| 617 |
+
|
| 618 |
+
|
| 619 |
+
class TextPreview:
|
| 620 |
+
"""
|
| 621 |
+
Preview one or more text values.
|
| 622 |
+
|
| 623 |
+
Accepts a single string or a list (e.g. the list produced by the
|
| 624 |
+
OpenAI Prompt Generator in structured mode) and displays every item on
|
| 625 |
+
the node. It also passes the text straight through, so you can insert it
|
| 626 |
+
inline between nodes without breaking the connection.
|
| 627 |
+
"""
|
| 628 |
+
|
| 629 |
+
@classmethod
|
| 630 |
+
def INPUT_TYPES(cls):
|
| 631 |
+
return {
|
| 632 |
+
"required": {
|
| 633 |
+
"text": ("STRING", {"forceInput": True}),
|
| 634 |
+
},
|
| 635 |
+
}
|
| 636 |
+
|
| 637 |
+
INPUT_IS_LIST = True
|
| 638 |
+
RETURN_TYPES = ("STRING",)
|
| 639 |
+
RETURN_NAMES = ("text",)
|
| 640 |
+
OUTPUT_IS_LIST = (True,)
|
| 641 |
+
FUNCTION = "preview"
|
| 642 |
+
CATEGORY = "LLM"
|
| 643 |
+
OUTPUT_NODE = True
|
| 644 |
+
|
| 645 |
+
def preview(self, text):
|
| 646 |
+
# With INPUT_IS_LIST every input arrives as a list; flatten to strings.
|
| 647 |
+
if not isinstance(text, list):
|
| 648 |
+
text = [text]
|
| 649 |
+
items = ["" if t is None else str(t) for t in text]
|
| 650 |
+
return {"ui": {"text": items}, "result": (items,)}
|
| 651 |
+
|
| 652 |
+
|
| 653 |
+
NODE_CLASS_MAPPINGS = {
|
| 654 |
+
"OpenAIPromptGenerator": OpenAIPromptGenerator,
|
| 655 |
+
"TextPreview": TextPreview,
|
| 656 |
+
}
|
| 657 |
+
|
| 658 |
+
NODE_DISPLAY_NAME_MAPPINGS = {
|
| 659 |
+
"OpenAIPromptGenerator": "OpenAI Prompt Generator",
|
| 660 |
+
"TextPreview": "Text Preview",
|
| 661 |
+
}
|
custom_nodes/openai_prompt/openai_prompt_config.example.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"base_url": "https://api.openai.com/v1",
|
| 3 |
+
"api_key": "sk-your-key-here",
|
| 4 |
+
"model": "gpt-4o-mini",
|
| 5 |
+
"system_prompt": "You are a helpful assistant that writes vivid, detailed image-generation prompts.",
|
| 6 |
+
"structured_output": true,
|
| 7 |
+
"count": 3,
|
| 8 |
+
"temperature": 0.9,
|
| 9 |
+
"max_tokens": 1024
|
| 10 |
+
}
|
custom_nodes/openai_prompt/requirements.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
openai
|