Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3cb7776855 | ||
|
|
f520e8cee6 | ||
|
|
78b93801f6 | ||
|
|
b9612aa18a | ||
|
|
b6d4f0beb4 |
@@ -1,4 +1,5 @@
|
||||
__pycache__
|
||||
AGENTS.md
|
||||
|
||||
# Nutzerspezifische Konfigurationsdateien – nicht durch Updates überschreiben
|
||||
ta_discord_link.json
|
||||
|
||||
@@ -40,6 +40,13 @@ This project was inspired by or builds upon the following open-source works:
|
||||
- ComfyUI: 0.38.0
|
||||
|
||||
## Changelog
|
||||
**v2.2.4 cleaned example workflow (`TA-FLEXMOD-LLM v2.90.json`)**
|
||||
- removed leftover example prompt texts from `TA-FLEXMOD-LLM v2.90.json`
|
||||
|
||||
**v2.2.3 added ta_film_grain.py v1.0**
|
||||
- added self-contained `TAFilmGrain` node (`🎞️ TA Film Grain`, RGB/RGBA, 1:1 parameter-compatible with `ProPostFilmGrain`)
|
||||
- updated example workflow to `TA-FLEXMOD-LLM v2.90.json` using `TAFilmGrain`
|
||||
|
||||
**v2.2.2 changed ta_sageattention_toggler.py to v2.2**
|
||||
- added kitchen_enable Toggle (comfy-kitchen int8_attention)
|
||||
|
||||
@@ -126,6 +133,9 @@ Extends ComfyUI's built-in SaveImage with optional companion `.txt` files contai
|
||||
### 🎬 TA SeedVR2 Gate
|
||||
Enable/disable gate for the SeedVR2 upscaler pipeline using lazy evaluation. When disabled, all upstream nodes (including the ~14 GB model loaders) are skipped entirely.
|
||||
|
||||
### 🎞️ TA Film Grain
|
||||
Self-contained film grain node for RGB and RGBA `IMAGE` tensors (alpha preserved untouched) with shadow/highlight response, gamma shaping, grayscale option, and post-grain sharpening. 1:1 parameter-compatible with `ProPostFilmGrain` without external `filmgrainer` dependencies.
|
||||
|
||||
### 💬 TA Discord Link
|
||||
Displays a clickable Discord invite link directly inside the ComfyUI graph. URL and button label are configurable via a browser-based editor.
|
||||
|
||||
|
||||
+5
-2
@@ -2,8 +2,8 @@
|
||||
TA ComfyUI Nodes Pack
|
||||
© Thomas Möhrling (thomo.ART)
|
||||
Erstelldatum: 2026-03-02
|
||||
Änderungsdatum: 2026-03-13
|
||||
Version: v4.0 - TADiscordLink hinzugefügt
|
||||
Änderungsdatum: 2026-11-15
|
||||
Version: v4.1 - TAFilmGrain hinzugefügt
|
||||
"""
|
||||
|
||||
print("\n" + "="*60)
|
||||
@@ -34,6 +34,7 @@ from .ta_cleanup_switch import TACleanupSwitch
|
||||
from .ta_help_link import TAHelpLink
|
||||
from .ta_discord_link import TADiscordLink
|
||||
from .ta_fastlaplaciansharpen import TAFastLaplacianSharpen
|
||||
from .ta_film_grain import TAFilmGrain
|
||||
|
||||
# Erweiterte Mappings (alt + neu)
|
||||
NODE_CLASS_MAPPINGS.update({
|
||||
@@ -57,6 +58,7 @@ NODE_CLASS_MAPPINGS.update({
|
||||
"TAHelpLink": TAHelpLink,
|
||||
"TADiscordLink": TADiscordLink,
|
||||
"TAFastLaplacianSharpen": TAFastLaplacianSharpen,
|
||||
"TAFilmGrain": TAFilmGrain,
|
||||
})
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS.update({
|
||||
@@ -80,6 +82,7 @@ NODE_DISPLAY_NAME_MAPPINGS.update({
|
||||
"TAHelpLink": "🔗 TA Help Link",
|
||||
"TADiscordLink": "💬 TA Discord Link",
|
||||
"TAFastLaplacianSharpen": "🌀 TA Fast Laplacian Sharpen",
|
||||
"TAFilmGrain": "🎞️ TA Film Grain",
|
||||
})
|
||||
|
||||
WEB_DIRECTORY = "./web/js"
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
"name": "TA-ComfyUI-Nodes-Pack",
|
||||
"author": "tmode-1960",
|
||||
"description": "Custom ComfyUI nodes for advanced AI image workflows. Includes smart model loaders (FLUX, SDXL, ZImage, Qwen), LM Studio/Ollama integration, sampler presets, VRAM/RAM cleanup, and prompt utilities.",
|
||||
"version": "2.2.1",
|
||||
"version": "2.2.5",
|
||||
"repository": "https://github.com/tmode-1960/TA-ComfyUI-Nodes-Pack",
|
||||
"license": "Apache 2.0"
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1
-1
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "TA-ComfyUI-Nodes-Pack"
|
||||
version = "2.2.1"
|
||||
version = "2.2.5"
|
||||
description = "Custom ComfyUI nodes for advanced AI image workflows. Includes smart model loaders (FLUX, SDXL, ZImage, Qwen), LM Studio/Ollama integration, sampler presets, VRAM/RAM cleanup, and prompt utilities."
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.8"
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
================================================================================
|
||||
Node Name : TA Directory Captioning
|
||||
Created : 2025
|
||||
Modified : 2026-03-11
|
||||
Modified : 2026-11-17
|
||||
Copyright : © 2026, Thomas Möhrling (thomo.ART)
|
||||
Version : 2.0
|
||||
Version : 2.1
|
||||
--------------------------------------------------------------------------------
|
||||
Part of ComfyUI-TA-Nodes-Pack
|
||||
License : Apache 2.0
|
||||
@@ -13,6 +13,9 @@ Description:
|
||||
Iterates through a directory, sends images to LM Studio or Ollama Vision
|
||||
Models and saves the generated captions as .txt files alongside each image.
|
||||
Uses TASmartLLM model detection logic (LMStudio + Ollama, Vision tagging).
|
||||
|
||||
Changelog:
|
||||
2.1 2026-11-17 Filter TASmartLLM model list to local LMStudio/Ollama backends
|
||||
================================================================================
|
||||
"""
|
||||
|
||||
@@ -137,7 +140,7 @@ class TACaptioning:
|
||||
Returns:
|
||||
dict: ComfyUI INPUT_TYPES dictionary with all required inputs.
|
||||
"""
|
||||
models = TASmartLLM.get_models()
|
||||
models = [m for m in TASmartLLM.get_models() if m.startswith(("LMStudio/", "Ollama/"))] or ["No Backend"]
|
||||
|
||||
vision_models = [m for m in models if "[Vision]" in m]
|
||||
default_model = vision_models[0] if vision_models else (models[0] if models else "No Backend")
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
"""
|
||||
================================================================================
|
||||
Node Name : TAFilmGrain
|
||||
Created : 2026-11-13
|
||||
Modified : 2026-11-13
|
||||
Copyright : © 2026, Thomas Möhrling (thomo.ART)
|
||||
Version : 1.0
|
||||
--------------------------------------------------------------------------------
|
||||
Part of ComfyUI-TA-Nodes-Pack
|
||||
License : Apache 2.0
|
||||
Description:
|
||||
Self-contained Film Grain node for IMAGE tensors (RGB or RGBA).
|
||||
1:1 parameter-compatible with ProPostFilmGrain without external
|
||||
filmgrainer package imports (avoids namespace collisions). Alpha channel
|
||||
is preserved untouched.
|
||||
Changelog:
|
||||
1.0 2026-11-13 Initial implementation
|
||||
================================================================================
|
||||
"""
|
||||
|
||||
from typing import Tuple
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from PIL import Image, ImageFilter
|
||||
|
||||
|
||||
GRAIN_PROFILES = {
|
||||
"Fine": (0.80, 0.25),
|
||||
"Fine Simple": (1.00, 0.18),
|
||||
"Coarse": (1.60, 0.30),
|
||||
"Coarser": (2.40, 0.36),
|
||||
}
|
||||
|
||||
|
||||
class TAFilmGrain:
|
||||
"""
|
||||
Self-contained Film Grain node for ComfyUI IMAGE tensors.
|
||||
|
||||
Applies organic luminance/chrominance film grain with shadow/highlight
|
||||
response, gamma shaping, optional grayscale conversion, and optional
|
||||
post-grain sharpening. Supports 3-channel (RGB) and 4-channel (RGBA)
|
||||
tensors; alpha is preserved unchanged.
|
||||
"""
|
||||
|
||||
CATEGORY = "TA Nodes/Enhancement"
|
||||
FUNCTION = "apply_filmgrain"
|
||||
RETURN_TYPES = ("IMAGE",)
|
||||
RETURN_NAMES = ("IMAGE",)
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"image": ("IMAGE",),
|
||||
"gray_scale": ("BOOLEAN", {"default": False}),
|
||||
"grain_type": (["Fine", "Fine Simple", "Coarse", "Coarser"],),
|
||||
"grain_sat": ("FLOAT", {"default": 0.15, "min": 0.0, "max": 1.0, "step": 0.01}),
|
||||
"grain_power": ("FLOAT", {"default": 0.40, "min": 0.0, "max": 1.0, "step": 0.01}),
|
||||
"shadows": ("FLOAT", {"default": 0.20, "min": 0.0, "max": 1.0, "step": 0.01}),
|
||||
"highs": ("FLOAT", {"default": 0.20, "min": 0.0, "max": 1.0, "step": 0.01}),
|
||||
"scale": ("FLOAT", {"default": 0.65, "min": 0.0, "max": 10.0, "step": 0.01}),
|
||||
"sharpen": ("INT", {"default": 0, "min": 0, "max": 10}),
|
||||
"src_gamma": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
|
||||
"seed": ("INT", {"default": 1, "min": 1, "max": 18446744073709551615}),
|
||||
},
|
||||
}
|
||||
|
||||
def apply_filmgrain(
|
||||
self,
|
||||
image: torch.Tensor,
|
||||
gray_scale: bool,
|
||||
grain_type: str,
|
||||
grain_sat: float,
|
||||
grain_power: float,
|
||||
shadows: float,
|
||||
highs: float,
|
||||
scale: float,
|
||||
sharpen: int,
|
||||
src_gamma: float,
|
||||
seed: int,
|
||||
) -> Tuple[torch.Tensor]:
|
||||
"""
|
||||
Apply film grain to a batch of IMAGE tensors.
|
||||
|
||||
Args:
|
||||
image : ComfyUI IMAGE tensor, shape (B, H, W, C) with C in {3, 4}.
|
||||
gray_scale : Convert RGB to grayscale before adding grain.
|
||||
grain_type : Grain profile ("Fine", "Fine Simple", "Coarse", "Coarser").
|
||||
grain_sat : Color saturation of the grain (0.0 = monochrome, 1.0 = full RGB).
|
||||
grain_power : Overall grain intensity [0..1].
|
||||
shadows : Grain response in shadow areas [0..1].
|
||||
highs : Grain response in highlight areas [0..1].
|
||||
scale : Grain size scale factor.
|
||||
sharpen : Optional post-grain sharpen passes [0..10].
|
||||
src_gamma : Source gamma curve applied to luminance response.
|
||||
seed : Base random seed (incremented per batch item).
|
||||
|
||||
Returns:
|
||||
Tuple[torch.Tensor]: (grained_IMAGE_tensor,).
|
||||
"""
|
||||
channels = image.shape[-1]
|
||||
if channels not in (3, 4):
|
||||
raise ValueError(
|
||||
f"TAFilmGrain erwartet RGB oder RGBA, bekommen: {channels} Kanale"
|
||||
)
|
||||
|
||||
src = image.cpu() if image.is_cuda else image
|
||||
img_np = src.contiguous().numpy().astype(np.float32)
|
||||
batch_size, height, width, _ = img_np.shape
|
||||
out_np = np.empty_like(img_np)
|
||||
|
||||
grain_size_mult, profile_amp = GRAIN_PROFILES.get(grain_type, (1.0, 0.25))
|
||||
eff_scale = max(0.25, float(scale) * grain_size_mult)
|
||||
gamma_val = max(0.05, float(src_gamma))
|
||||
|
||||
for b in range(batch_size):
|
||||
frame = np.clip(img_np[b], 0.0, 1.0)
|
||||
if channels == 4:
|
||||
rgb = frame[..., :3]
|
||||
alpha = frame[..., 3:4]
|
||||
else:
|
||||
rgb = frame
|
||||
alpha = None
|
||||
|
||||
if gray_scale:
|
||||
luma = (0.299 * rgb[..., 0] + 0.587 * rgb[..., 1] + 0.114 * rgb[..., 2])[..., None]
|
||||
rgb = np.repeat(luma, 3, axis=-1)
|
||||
|
||||
if grain_power > 0.0:
|
||||
rng = np.random.default_rng((int(seed) + b) & 0xFFFFFFFFFFFFFFFF)
|
||||
noise_w = max(1, int(round(width / eff_scale)))
|
||||
noise_h = max(1, int(round(height / eff_scale)))
|
||||
|
||||
mono_noise = rng.normal(0.0, 1.0, (noise_h, noise_w, 1)).astype(np.float32)
|
||||
color_noise = rng.normal(0.0, 1.0, (noise_h, noise_w, 3)).astype(np.float32)
|
||||
sat = float(np.clip(grain_sat, 0.0, 1.0))
|
||||
raw_noise = (1.0 - sat) * mono_noise + sat * color_noise
|
||||
|
||||
if noise_w != width or noise_h != height:
|
||||
resized_ch = []
|
||||
for c in range(3):
|
||||
ch_img = Image.fromarray(raw_noise[..., c], mode="F")
|
||||
ch_res = ch_img.resize((width, height), resample=Image.BILINEAR)
|
||||
resized_ch.append(np.asarray(ch_res, dtype=np.float32))
|
||||
noise = np.stack(resized_ch, axis=-1)
|
||||
else:
|
||||
noise = raw_noise
|
||||
|
||||
lum = 0.299 * rgb[..., 0] + 0.587 * rgb[..., 1] + 0.114 * rgb[..., 2]
|
||||
if abs(gamma_val - 1.0) > 1e-4:
|
||||
lum_g = np.power(np.clip(lum, 0.0, 1.0), 1.0 / gamma_val)
|
||||
else:
|
||||
lum_g = lum
|
||||
|
||||
mid_weight = 4.0 * lum_g * (1.0 - lum_g)
|
||||
shadow_weight = (1.0 - lum_g) ** 2 * float(shadows) * 2.0
|
||||
high_weight = (lum_g ** 2) * float(highs) * 2.0
|
||||
mask = np.clip(mid_weight + shadow_weight + high_weight, 0.0, 1.5)[..., None]
|
||||
|
||||
amp = float(grain_power) * profile_amp
|
||||
rgb = np.clip(rgb + noise * amp * mask, 0.0, 1.0)
|
||||
|
||||
if sharpen > 0:
|
||||
pil_rgb = Image.fromarray((rgb * 255.0).astype(np.uint8), mode="RGB")
|
||||
for _ in range(int(sharpen)):
|
||||
pil_rgb = pil_rgb.filter(ImageFilter.SHARPEN)
|
||||
rgb = np.asarray(pil_rgb, dtype=np.float32) / 255.0
|
||||
|
||||
if alpha is not None:
|
||||
out_np[b] = np.concatenate((rgb, alpha), axis=-1)
|
||||
else:
|
||||
out_np[b] = rgb
|
||||
|
||||
return (torch.from_numpy(out_np),)
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"TAFilmGrain": TAFilmGrain,
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"TAFilmGrain": "🎞️ TA Film Grain",
|
||||
}
|
||||
+230
-77
@@ -2,19 +2,24 @@
|
||||
================================================================================
|
||||
Node Name : TA Smart LLM
|
||||
Created : 2025
|
||||
Modified : 2026-04-05
|
||||
Modified : 2026-11-24
|
||||
Copyright : © 2026, Thomas Möhrling (thomo.ART)
|
||||
Version : 3.8
|
||||
Version : 4.0
|
||||
--------------------------------------------------------------------------------
|
||||
Part of ComfyUI-TA-Nodes-Pack
|
||||
License : Apache 2.0
|
||||
|
||||
|
||||
Description:
|
||||
Smart LLM integration for LM Studio and Ollama backends with VRAM management.
|
||||
Auto-detects vision models (tags with [Vision]), supports image input for
|
||||
multimodal prompts, optional pre/post model unloading, and model caching.
|
||||
Returns generated prompt text and execution status.
|
||||
Smart LLM integration for LM Studio, Ollama, and optional external
|
||||
OpenAI-compatible cloud providers (via environment variables) with VRAM
|
||||
management. Auto-detects vision models (tags with [Vision]), supports
|
||||
image input for multimodal prompts, optional pre/post model unloading,
|
||||
and model caching. Returns generated prompt text and execution status.
|
||||
|
||||
Changelog:
|
||||
4.0 2026-11-24 Add huihui-qwen3.8-27b-abliterated to VISION_MANUAL and pass thinking_mode to LM Studio/Ollama
|
||||
3.9 2026-11-17 Add optional cloud LLM providers (Gemini, OpenAI, OpenRouter, Groq) via env vars
|
||||
================================================================================
|
||||
"""
|
||||
|
||||
@@ -36,13 +41,69 @@ VISION_KEYWORDS = ["llava", "vision", "-vl-", "_vl_", "vl-", "vl_", "moondream",
|
||||
# Manual additions (exact model names without backend prefix, lowercase)
|
||||
# Example: VISION_MANUAL = {"my-vision-model-7b", "another-model-13b"}
|
||||
# VISION_MANUAL = set()
|
||||
VISION_MANUAL = {"qwen3.5-9b-uncensored-hauhaucs-aggressive"}
|
||||
VISION_MANUAL = {
|
||||
"qwen3.5-9b-uncensored-hauhaucs-aggressive",
|
||||
"huihui-qwen3.8-27b-abliterated",
|
||||
}
|
||||
|
||||
# Cloud model prefixes that support multimodal image input
|
||||
CLOUD_VISION_PREFIXES = ("gemini-", "gpt-4o", "gpt-4.1", "gpt-5", "claude-3", "claude-4", "pixtral")
|
||||
|
||||
# Non-chat model substrings to skip when listing cloud provider models
|
||||
CLOUD_SKIP_MODEL_SUBSTRINGS = ("embedding", "imagen", "veo", "tts", "aqa")
|
||||
|
||||
# Optional OpenAI-compatible cloud providers (activated only when env var is set)
|
||||
CLOUD_PROVIDERS = {
|
||||
"Gemini": {
|
||||
"env_var": "GEMINI_API_KEY",
|
||||
"base_url": "https://generativelanguage.googleapis.com/v1beta/openai",
|
||||
"fallback_models": ["gemini-3.8-flash", "gemini-3-flash-preview", "gemini-3.5-flash-lite"],
|
||||
"supports_reasoning_effort": True,
|
||||
},
|
||||
"OpenAI": {
|
||||
"env_var": "OPENAI_API_KEY",
|
||||
"base_url": "https://api.openai.com/v1",
|
||||
"fallback_models": ["gpt-4o", "gpt-4o-mini"],
|
||||
"supports_reasoning_effort": False,
|
||||
},
|
||||
"OpenRouter": {
|
||||
"env_var": "OPENROUTER_API_KEY",
|
||||
"base_url": "https://openrouter.ai/api/v1",
|
||||
"fallback_models": ["openrouter/free"],
|
||||
"supports_reasoning_effort": False,
|
||||
},
|
||||
"Groq": {
|
||||
"env_var": "GROQ_API_KEY",
|
||||
"base_url": "https://api.groq.com/openai/v1",
|
||||
"fallback_models": ["llama-3.3-70b-versatile"],
|
||||
"supports_reasoning_effort": False,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _get_cloud_api_key(provider: str) -> str:
|
||||
"""Returns the trimmed API key for a cloud provider from environment variables."""
|
||||
cfg = CLOUD_PROVIDERS.get(provider)
|
||||
if not cfg:
|
||||
return ""
|
||||
return os.environ.get(cfg["env_var"], "").strip()
|
||||
|
||||
|
||||
def _sanitize_error(message: str, secret: str = "") -> str:
|
||||
"""Ensures an API key is never leaked in logs or status outputs."""
|
||||
if secret and secret in message:
|
||||
return message.replace(secret, "***")
|
||||
return message
|
||||
|
||||
|
||||
def is_vision_model(model_id: str) -> bool:
|
||||
lower = model_id.lower()
|
||||
if any(kw in lower for kw in VISION_KEYWORDS):
|
||||
return True
|
||||
if any(lower.startswith(prefix) for prefix in CLOUD_VISION_PREFIXES) and not any(
|
||||
skip in lower for skip in CLOUD_SKIP_MODEL_SUBSTRINGS
|
||||
):
|
||||
return True
|
||||
if lower in VISION_MANUAL:
|
||||
return True
|
||||
return False
|
||||
@@ -94,27 +155,63 @@ class TASmartLLM:
|
||||
except:
|
||||
pass
|
||||
|
||||
@classmethod
|
||||
def _discover_cloud_models(cls, provider, known_provider_models):
|
||||
"""
|
||||
Discovers available models for a configured cloud provider.
|
||||
Returns (known_set, active_set) for that provider.
|
||||
"""
|
||||
api_key = _get_cloud_api_key(provider)
|
||||
if not api_key:
|
||||
return known_provider_models, set()
|
||||
|
||||
cfg = CLOUD_PROVIDERS[provider]
|
||||
url = f"{cfg['base_url']}/models"
|
||||
headers = {"Authorization": f"Bearer {api_key}"}
|
||||
|
||||
try:
|
||||
r = requests.get(url, headers=headers, timeout=2.0)
|
||||
if r.status_code == 200:
|
||||
discovered = set()
|
||||
for m in r.json().get("data", []):
|
||||
m_id = (m.get("id") or "").strip()
|
||||
if not m_id:
|
||||
continue
|
||||
if m_id.startswith("models/"):
|
||||
m_id = m_id[len("models/"):]
|
||||
if any(skip in m_id.lower() for skip in CLOUD_SKIP_MODEL_SUBSTRINGS):
|
||||
continue
|
||||
discovered.add(f"{provider}/{m_id}")
|
||||
if discovered:
|
||||
return discovered, discovered
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if known_provider_models:
|
||||
return known_provider_models, set()
|
||||
|
||||
fallback = {f"{provider}/{m_id}" for m_id in cfg.get("fallback_models", [])}
|
||||
return fallback, set()
|
||||
|
||||
@classmethod
|
||||
def get_models(cls):
|
||||
"""
|
||||
Discovers and caches available models from LM Studio (port 1234) and
|
||||
Ollama (port 11434). Tags vision-capable models with [Vision] suffix.
|
||||
|
||||
Display logic:
|
||||
- All known models are always shown (prevents validation errors).
|
||||
- Active models appear at the top of the list, offline models below.
|
||||
- No prefix is added to model names so stored values remain stable
|
||||
across restarts regardless of which backend is active.
|
||||
- Per-backend cache is updated on each call if the backend responds,
|
||||
so added/removed models are reflected immediately.
|
||||
Discovers and caches available models from LM Studio (port 1234),
|
||||
Ollama (port 11434), and configured cloud providers (when API key env
|
||||
vars are set). Tags vision-capable models with [Vision] suffix.
|
||||
"""
|
||||
known = cls._load_cached_models()
|
||||
|
||||
known_lmstudio = {m for m in known if m.startswith("LMStudio/")}
|
||||
known_ollama = {m for m in known if m.startswith("Ollama/")}
|
||||
known_cloud = {
|
||||
p: {m for m in known if m.startswith(f"{p}/")}
|
||||
for p in CLOUD_PROVIDERS
|
||||
}
|
||||
|
||||
active_lmstudio = set()
|
||||
active_ollama = set()
|
||||
active_cloud = set()
|
||||
|
||||
# Query LM Studio — replace cache if reachable
|
||||
try:
|
||||
@@ -134,10 +231,23 @@ class TASmartLLM:
|
||||
except:
|
||||
pass
|
||||
|
||||
cls._save_cached_models(known_lmstudio | known_ollama)
|
||||
# Query configured cloud providers (only when env var is set)
|
||||
visible_cloud_known = set()
|
||||
all_cloud_known = set()
|
||||
for provider in CLOUD_PROVIDERS:
|
||||
p_known, p_active = cls._discover_cloud_models(provider, known_cloud[provider])
|
||||
all_cloud_known |= p_known
|
||||
if _get_cloud_api_key(provider):
|
||||
visible_cloud_known |= p_known
|
||||
active_cloud |= p_active
|
||||
|
||||
active = sorted(active_lmstudio | active_ollama)
|
||||
offline = sorted((known_lmstudio | known_ollama) - (active_lmstudio | active_ollama))
|
||||
cls._save_cached_models(known_lmstudio | known_ollama | all_cloud_known)
|
||||
|
||||
active_all = active_lmstudio | active_ollama | active_cloud
|
||||
visible_all = known_lmstudio | known_ollama | visible_cloud_known
|
||||
|
||||
active = sorted(active_all)
|
||||
offline = sorted(visible_all - active_all)
|
||||
|
||||
# Active models first, offline models after — no prefix in stored value
|
||||
result = [tag_model(m) for m in active] + [tag_model(m) for m in offline]
|
||||
@@ -251,24 +361,26 @@ class TASmartLLM:
|
||||
img.save(buffer, 'PNG')
|
||||
return base64.b64encode(buffer.getvalue()).decode('utf-8')
|
||||
|
||||
def _post_with_retry(self, url, payload, is_lmstudio, max_retries=3, retry_delay=1.5, timeout=120):
|
||||
def _post_with_retry(self, url, payload, is_openai, headers=None, max_retries=3, retry_delay=1.5, timeout=120):
|
||||
"""
|
||||
Posts to LLM API with retry logic for transient errors.
|
||||
For LM Studio returns the full message dict; for Ollama returns the response string.
|
||||
Posts to LLM API with retry logic for transient errors (including 429 rate limits).
|
||||
For OpenAI-compatible APIs returns the full message dict; for Ollama returns the response string.
|
||||
"""
|
||||
last_error = None
|
||||
for attempt in range(1, max_retries + 1):
|
||||
try:
|
||||
r = requests.post(url, json=payload, timeout=timeout)
|
||||
r = requests.post(url, json=payload, headers=headers, timeout=timeout)
|
||||
r.raise_for_status()
|
||||
if is_lmstudio:
|
||||
if is_openai:
|
||||
return r.json()['choices'][0]['message'] # Return full message dict
|
||||
else:
|
||||
return r.json()['response']
|
||||
except requests.exceptions.HTTPError as e:
|
||||
last_error = e
|
||||
if e.response is not None and e.response.status_code in (400, 500, 502, 503) and attempt < max_retries:
|
||||
time.sleep(retry_delay)
|
||||
status_code = e.response.status_code if e.response is not None else None
|
||||
if status_code in (400, 429, 500, 502, 503) and attempt < max_retries:
|
||||
delay = retry_delay * attempt if status_code == 429 else retry_delay
|
||||
time.sleep(delay)
|
||||
continue
|
||||
raise
|
||||
except requests.exceptions.RequestException as e:
|
||||
@@ -279,6 +391,47 @@ class TASmartLLM:
|
||||
raise
|
||||
raise last_error
|
||||
|
||||
def _build_openai_payload(self, model_name, system_prompt, full_prompt, img_b64,
|
||||
temperature, max_tokens, extra_params=None):
|
||||
"""Builds a standard OpenAI-compatible /chat/completions payload."""
|
||||
if img_b64:
|
||||
user_content = [
|
||||
{"type": "text", "text": full_prompt},
|
||||
{"type": "image_url", "image_url": {"url": f"data:image/png;base64,{img_b64}"}}
|
||||
]
|
||||
else:
|
||||
user_content = full_prompt
|
||||
|
||||
payload = {
|
||||
"model": model_name,
|
||||
"messages": [
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": user_content}
|
||||
],
|
||||
"temperature": temperature,
|
||||
"max_tokens": max_tokens
|
||||
}
|
||||
if extra_params:
|
||||
payload.update(extra_params)
|
||||
return payload
|
||||
|
||||
def _extract_openai_response(self, message, thinking_mode):
|
||||
"""Extracts (result, reasoning) from an OpenAI-compatible message dict."""
|
||||
content = (message.get('content') or '').strip()
|
||||
reasoning = (message.get('reasoning_content') or '').strip()
|
||||
|
||||
if thinking_mode:
|
||||
# Thinking ON -> return full content including thinking
|
||||
result = content if content else reasoning
|
||||
else:
|
||||
# Thinking OFF -> return only the final answer, strip thinking
|
||||
if content:
|
||||
result = content.split("</think>", 1)[-1].strip() if "</think>" in content else content
|
||||
else:
|
||||
result = reasoning.split("</think>", 1)[-1].strip() if "</think>" in reasoning else ""
|
||||
|
||||
return result, reasoning
|
||||
|
||||
def generate(self, llm_enable, model, user_prompt, system_prompt,
|
||||
temperature=0.7, max_tokens=1024, request_timeout=120,
|
||||
thinking_mode=False,
|
||||
@@ -288,19 +441,19 @@ class TASmartLLM:
|
||||
Main generation method. Queries the selected LLM and returns prompt + status.
|
||||
|
||||
Workflow:
|
||||
1. Skip if disabled or backend unreachable.
|
||||
1. Skip if disabled or backend unreachable / API key missing.
|
||||
2. Optionally unload ComfyUI models for VRAM.
|
||||
3. Build payload (text + optional image b64).
|
||||
4. Send request to LM Studio/Ollama with retries.
|
||||
5. Optionally unload LLM model after.
|
||||
|
||||
4. Send request to LM Studio, Ollama, or configured cloud provider with retries.
|
||||
5. Optionally unload local LLM model after.
|
||||
|
||||
Args:
|
||||
llm_enable (bool): Master enable toggle.
|
||||
model (str): Selected model (tagged).
|
||||
user_prompt (str): User input.
|
||||
system_prompt (str): System instruction.
|
||||
unload_image_models_first (bool): Free VRAM before.
|
||||
unload_llm_after (bool): Free VRAM after.
|
||||
unload_llm_after (bool): Free VRAM after (local backends only).
|
||||
image: Optional IMAGE for vision models.
|
||||
|
||||
Returns:
|
||||
@@ -312,10 +465,18 @@ class TASmartLLM:
|
||||
clean_model = strip_vision_tag(model)
|
||||
backend = clean_model.split('/')[0]
|
||||
model_name = '/'.join(clean_model.split('/')[1:])
|
||||
port = 1234 if "LMStudio" in backend else 11434
|
||||
is_cloud = backend in CLOUD_PROVIDERS
|
||||
api_key = ""
|
||||
|
||||
if not self._backend_reachable(backend, port):
|
||||
return ("", f"SKIPPED - {backend} not reachable", "")
|
||||
if is_cloud:
|
||||
api_key = _get_cloud_api_key(backend)
|
||||
if not api_key:
|
||||
env_var = CLOUD_PROVIDERS[backend]["env_var"]
|
||||
return ("", f"SKIPPED - {backend} API key ({env_var}) not set", "")
|
||||
else:
|
||||
port = 1234 if "LMStudio" in backend else 11434
|
||||
if not self._backend_reachable(backend, port):
|
||||
return ("", f"SKIPPED - {backend} not reachable", "")
|
||||
|
||||
print(f"[TA Smart LLM] Loading model: {clean_model}")
|
||||
|
||||
@@ -324,49 +485,40 @@ class TASmartLLM:
|
||||
self._unload_comfyui_models()
|
||||
|
||||
full_prompt = user_prompt.strip()
|
||||
|
||||
img_b64 = self._build_image_b64(image) if image is not None else None
|
||||
|
||||
try:
|
||||
if "LMStudio" in backend:
|
||||
if is_cloud:
|
||||
cfg = CLOUD_PROVIDERS[backend]
|
||||
url = f"{cfg['base_url']}/chat/completions"
|
||||
headers = {"Authorization": f"Bearer {api_key}"}
|
||||
extra_params = None
|
||||
if cfg.get("supports_reasoning_effort") and not thinking_mode:
|
||||
extra_params = {"reasoning_effort": "none"}
|
||||
|
||||
payload = self._build_openai_payload(
|
||||
model_name, system_prompt, full_prompt, img_b64,
|
||||
temperature, max_tokens, extra_params=extra_params
|
||||
)
|
||||
message = self._post_with_retry(
|
||||
url, payload, is_openai=True, headers=headers, timeout=request_timeout
|
||||
)
|
||||
result, reasoning = self._extract_openai_response(message, thinking_mode)
|
||||
|
||||
elif "LMStudio" in backend:
|
||||
url = f"http://127.0.0.1:{port}/v1/chat/completions"
|
||||
if img_b64:
|
||||
user_content = [
|
||||
{"type": "text", "text": full_prompt},
|
||||
{"type": "image_url", "image_url": {"url": f"data:image/png;base64,{img_b64}"}}
|
||||
]
|
||||
else:
|
||||
user_content = full_prompt
|
||||
payload = {
|
||||
"model": model_name,
|
||||
"messages": [
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": user_content}
|
||||
],
|
||||
"temperature": temperature,
|
||||
"max_tokens": max_tokens
|
||||
}
|
||||
|
||||
message = self._post_with_retry(url, payload, is_lmstudio=True, timeout=request_timeout)
|
||||
|
||||
content = (message.get('content') or '').strip()
|
||||
reasoning = (message.get('reasoning_content') or '').strip()
|
||||
|
||||
if thinking_mode:
|
||||
# Thinking ON → return full content including thinking
|
||||
result = content if content else reasoning
|
||||
else:
|
||||
# Thinking OFF → return only the final answer, strip thinking
|
||||
if content:
|
||||
if "</think>" in content:
|
||||
result = content.split("</think>", 1)[-1].strip()
|
||||
else:
|
||||
result = content
|
||||
else:
|
||||
if "</think>" in reasoning:
|
||||
result = reasoning.split("</think>", 1)[-1].strip()
|
||||
else:
|
||||
result = "" # Pure thinking block, no answer
|
||||
extra_params = (
|
||||
{"chat_template_kwargs": {"enable_thinking": False}}
|
||||
if not thinking_mode else None
|
||||
)
|
||||
payload = self._build_openai_payload(
|
||||
model_name, system_prompt, full_prompt, img_b64,
|
||||
temperature, max_tokens, extra_params=extra_params
|
||||
)
|
||||
message = self._post_with_retry(
|
||||
url, payload, is_openai=True, timeout=request_timeout
|
||||
)
|
||||
result, reasoning = self._extract_openai_response(message, thinking_mode)
|
||||
|
||||
# Unload LM Studio model after request
|
||||
if unload_llm_after:
|
||||
@@ -378,6 +530,7 @@ class TASmartLLM:
|
||||
"model": model_name,
|
||||
"prompt": f"{system_prompt}\n\n{full_prompt}".strip(),
|
||||
"stream": False,
|
||||
"think": bool(thinking_mode),
|
||||
"options": {
|
||||
"temperature": temperature,
|
||||
"num_predict": max_tokens
|
||||
@@ -386,7 +539,7 @@ class TASmartLLM:
|
||||
|
||||
if img_b64:
|
||||
payload["images"] = [img_b64]
|
||||
result = self._post_with_retry(url, payload, is_lmstudio=False, timeout=request_timeout)
|
||||
result = self._post_with_retry(url, payload, is_openai=False, timeout=request_timeout)
|
||||
reasoning = ""
|
||||
|
||||
# Ollama: strip <think> tags if thinking is OFF
|
||||
@@ -404,8 +557,8 @@ class TASmartLLM:
|
||||
return ("", f"WARNING: {clean_model} returned empty response", reasoning)
|
||||
|
||||
except Exception as e:
|
||||
return (f"ERROR: {str(e)}", clean_model, "")
|
||||
return (f"ERROR: {_sanitize_error(str(e), api_key)}", clean_model, "")
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {"TASmartLLM": TASmartLLM}
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {"TASmartLLM": "TA Smart LLM v3.8"}
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {"TASmartLLM": "TA Smart LLM v3.9"}
|
||||
|
||||
Reference in New Issue
Block a user