Skip to content

The most powerful and modular diffusion model GUI, api and backend with a graph/nodes interface. The fastest local inference engine in the world.

TextGenerate: Add system_prompt input and separate thinking output (CORE-460) (#16442)

Jukka Seppänen9498c42baac7
diff --git a/comfy/text_encoders/flux.py b/comfy/text_encoders/flux.py
index fbdb1d13a..300ac5c11 100644
--- a/comfy/text_encoders/flux.py
+++ b/comfy/text_encoders/flux.py
@@ -160,11 +160,13 @@ class KleinTokenizer(sd1_clip.SD1Tokenizer):
super().__init__(embedding_directory=embedding_directory, tokenizer_data=tokenizer_data, name=name, tokenizer=tokenizer)
self.llama_template = "<|im_start|>user\n{}<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
- def tokenize_with_weights(self, text, return_word_ids=False, llama_template=None, **kwargs):
+ def tokenize_with_weights(self, text, return_word_ids=False, llama_template=None, system_prompt="", **kwargs):
if llama_template is None:
llama_text = self.llama_template.format(text)
else:
llama_text = llama_template.format(text)
+ if system_prompt:
+ llama_text = "<|im_start|>system\n" + system_prompt + "<|im_end|>\n" + llama_text
tokens = super().tokenize_with_weights(llama_text, return_word_ids=return_word_ids, disable_weights=True, **kwargs)
return tokens
diff --git a/comfy/text_encoders/gemma4.py b/comfy/text_encoders/gemma4.py
index 07cd45aed..bba11b183 100644
--- a/comfy/text_encoders/gemma4.py
+++ b/comfy/text_encoders/gemma4.py
@@ -1468,7 +1468,7 @@ class Gemma4_Tokenizer():
up_slopes = slopes[:, 2:] / filter_diff[1:]
return np.maximum(np.zeros(1), np.minimum(down_slopes, up_slopes))
- def tokenize_with_weights(self, text, return_word_ids=False, image=None, audio=None, video=None, llama_template=None, skip_template=True, thinking=False, **kwargs):
+ def tokenize_with_weights(self, text, return_word_ids=False, image=None, audio=None, video=None, llama_template=None, skip_template=True, thinking=False, system_prompt="", **kwargs):
# Process audio
audio_features = []
@@ -1521,7 +1521,8 @@ class Gemma4_Tokenizer():
llama_text = llama_template.format(text)
else:
# Build template from modalities present
- system = "<|turn>system\n<|think|>\n<turn|>\n" if thinking else ""
+ think = "<|think|>\n" if thinking else ""
+ system = f"<|turn>system\n{think}{system_prompt}<turn|>\n" if thinking or system_prompt else ""
media = ""
if len(images) > 0:
if is_video:
diff --git a/comfy/text_encoders/lt.py b/comfy/text_encoders/lt.py
index 2579e1b15..d362fe073 100644
--- a/comfy/text_encoders/lt.py
+++ b/comfy/text_encoders/lt.py
@@ -27,7 +27,7 @@ class Gemma3_Tokenizer():
def state_dict(self):
return {"spiece_model": self.tokenizer.serialize_model()}
- def tokenize_with_weights(self, text, return_word_ids=False, image=None, llama_template=None, skip_template=True, **kwargs):
+ def tokenize_with_weights(self, text, return_word_ids=False, image=None, llama_template=None, skip_template=True, system_prompt="", **kwargs):
self.llama_template = "<start_of_turn>system\nYou are a helpful assistant.<end_of_turn>\n<start_of_turn>user\n{}<end_of_turn>\n<start_of_turn>model\n"
self.llama_template_images = "<start_of_turn>system\nYou are a helpful assistant.<end_of_turn>\n<start_of_turn>user\n\n<image_soft_token>{}<end_of_turn>\n\n<start_of_turn>model\n"
@@ -57,6 +57,8 @@ class Gemma3_Tokenizer():
llama_text = self.llama_template.format(text)
else:
llama_text = llama_template.format(text)
+ if system_prompt: # replaces the default system turn
+ llama_text = "<start_of_turn>system\n" + system_prompt + "<end_of_turn>\n" + llama_text[llama_text.index("<start_of_turn>user"):]
text_tokens = super().tokenize_with_weights(llama_text, return_word_ids)
diff --git a/comfy/text_encoders/qwen35.py b/comfy/text_encoders/qwen35.py
index 29b5d469d..29ce136ef 100644
--- a/comfy/text_encoders/qwen35.py
+++ b/comfy/text_encoders/qwen35.py
@@ -1037,7 +1037,7 @@ class Qwen35ImageTokenizer(sd1_clip.SD1Tokenizer):
self.llama_template = "<|im_start|>user\n{}<|im_end|>\n<|im_start|>assistant\n"
self.llama_template_images = "<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>{}<|im_end|>\n<|im_start|>assistant\n"
- def tokenize_with_weights(self, text, return_word_ids=False, llama_template=None, images=[], prevent_empty_text=False, thinking=False, **kwargs):
+ def tokenize_with_weights(self, text, return_word_ids=False, llama_template=None, images=[], prevent_empty_text=False, thinking=False, system_prompt="", **kwargs):
image = kwargs.get("image", None)
if image is not None and len(images) == 0:
images = [image[i:i + 1] for i in range(image.shape[0])]
@@ -1061,6 +1061,8 @@ class Qwen35ImageTokenizer(sd1_clip.SD1Tokenizer):
vision_block = "<|vision_start|><|image_pad|><|vision_end|>"
template = template.replace(vision_block, vision_block * len(images), 1)
llama_text = template.format(text)
+ if system_prompt:
+ llama_text = "<|im_start|>system\n" + system_prompt + "<|im_end|>\n" + llama_text
if not thinking:
llama_text += "<think>\n</think>\n"
diff --git a/comfy/text_encoders/qwen3vl.py b/comfy/text_encoders/qwen3vl.py
index f16b2a7e4..050e76270 100644
--- a/comfy/text_encoders/qwen3vl.py
+++ b/comfy/text_encoders/qwen3vl.py
@@ -159,7 +159,7 @@ class Qwen3VLTokenizer(sd1_clip.SD1Tokenizer):
self.llama_template = "<|im_start|>user\n{}<|im_end|>\n<|im_start|>assistant\n"
self.llama_template_images = "<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>{}<|im_end|>\n<|im_start|>assistant\n"
- def tokenize_with_weights(self, text, return_word_ids=False, llama_template=None, images=[], prevent_empty_text=False, thinking=False, skip_template=False, **kwargs):
+ def tokenize_with_weights(self, text, return_word_ids=False, llama_template=None, images=[], prevent_empty_text=False, thinking=False, skip_template=False, system_prompt="", **kwargs):
image = kwargs.get("image", None)
if image is not None and len(images) == 0:
images = [image[i:i + 1] for i in range(image.shape[0])]
@@ -181,6 +181,8 @@ class Qwen3VLTokenizer(sd1_clip.SD1Tokenizer):
vision_block = "<|vision_start|><|image_pad|><|vision_end|>"
template = template.replace(vision_block, vision_block * len(images), 1)
llama_text = template.format(text)
+ if system_prompt: # replaces any system turn the template carries
+ llama_text = "<|im_start|>system\n" + system_prompt + "<|im_end|>\n" + llama_text[llama_text.index("<|im_start|>user"):]
if not thinking: # Qwen3 convention: empty think block suppresses reasoning
llama_text += "<think>\n\n</think>\n\n"
diff --git a/comfy/text_encoders/z_image.py b/comfy/text_encoders/z_image.py
index 33b7cf594..498882d6e 100644
--- a/comfy/text_encoders/z_image.py
+++ b/comfy/text_encoders/z_image.py
@@ -14,11 +14,13 @@ class ZImageTokenizer(sd1_clip.SD1Tokenizer):
super().__init__(embedding_directory=embedding_directory, tokenizer_data=tokenizer_data, name="qwen3_4b", tokenizer=Qwen3Tokenizer)
self.llama_template = "<|im_start|>user\n{}<|im_end|>\n<|im_start|>assistant\n"
- def tokenize_with_weights(self, text, return_word_ids=False, llama_template=None, **kwargs):
+ def tokenize_with_weights(self, text, return_word_ids=False, llama_template=None, system_prompt="", **kwargs):
if llama_template is None:
llama_text = self.llama_template.format(text)
else:
llama_text = llama_template.format(text)
+ if system_prompt:
+ llama_text = "<|im_start|>system\n" + system_prompt + "<|im_end|>\n" + llama_text
tokens = super().tokenize_with_weights(llama_text, return_word_ids=return_word_ids, disable_weights=True, **kwargs)
return tokens
diff --git a/comfy_extras/nodes_textgen.py b/comfy_extras/nodes_textgen.py
index 243834cef..ae1ead89b 100644
--- a/comfy_extras/nodes_textgen.py
+++ b/comfy_extras/nodes_textgen.py
@@ -1,4 +1,3 @@
-import re
from comfy_api.latest import ComfyExtension, io
from typing_extensions import override
@@ -41,18 +40,20 @@ class TextGenerate(io.ComfyNode):
io.Boolean.Input("thinking", optional=True, default=False, tooltip="Operate in thinking mode if the model supports it."),
io.Boolean.Input("use_default_template", optional=True, default=True, tooltip="Use the built in system prompt/template if the model has one.", advanced=True),
io.Combo.Input("mtp", options=["auto", "off", "2", "3", "4", "5"], default="auto", optional=True, tooltip="Speculative decoding with the checkpoint's multi-token-prediction head. No effect without MTP weights. auto adapts the draft depth; 2-5 pins it. Sampled output stays correctly distributed but differs from non-MTP output for the same seed."),
+ io.String.Input("system_prompt", force_input=True, optional=True, tooltip="Replaces the system prompt in the model's chat template. Ignored when the default template is not used."),
],
outputs=[
io.String.Output(display_name="generated_text"),
+ io.String.Output(display_name="thinking"),
],
)
@classmethod
- def execute(cls, clip, prompt, max_length, sampling_mode, image=None, thinking=False, use_default_template=True, video=None, audio=None, mtp="auto") -> io.NodeOutput:
+ def execute(cls, clip, prompt, max_length, sampling_mode, image=None, thinking=False, use_default_template=True, video=None, audio=None, mtp="auto", system_prompt="") -> io.NodeOutput:
mtp = False if mtp == "off" else (True if mtp == "auto" else int(mtp))
- tokens = clip.tokenize(prompt, image=image, skip_template=not use_default_template, min_length=1, thinking=thinking, video=video, audio=audio)
+ tokens = clip.tokenize(prompt, image=image, skip_template=not use_default_template, min_length=1, thinking=thinking, video=video, audio=audio, system_prompt=system_prompt if use_default_template else "")
# Get sampling parameters from dynamic combo
do_sample = sampling_mode.get("sampling_mode") == "on"
@@ -80,7 +81,12 @@ class TextGenerate(io.ComfyNode):
generated_text = clip.decode(generated_ids)
- return io.NodeOutput(generated_text)
+ # Reasoning opens in the generated text or at the end of a raw prompt, and has no close when max_length cut it short.
+ reasoning, _, text = generated_text.partition("</think>")
+ if not reasoning.lstrip().startswith("<think>") and not prompt.rstrip().endswith("<think>"):
+ reasoning, text = "", generated_text
+
+ return io.NodeOutput(text.strip(), reasoning.replace("<think>", "", 1).strip())
LTX2_T2V_SYSTEM_PROMPT = """You are a Creative Assistant. Given a user's raw input prompt describing a scene or concept, expand it into a detailed video generation prompt with specific visuals and integrated audio to guide a text-to-video model.
@@ -229,17 +235,17 @@ class TextGenerateLTX2Prompt(TextGenerate):
)
@classmethod
- def execute(cls, clip, prompt, max_length, sampling_mode, image=None, thinking=False, use_default_template=True, video=None, audio=None, mtp="auto") -> io.NodeOutput:
+ def execute(cls, clip, prompt, max_length, sampling_mode, image=None, thinking=False, use_default_template=True, video=None, audio=None, mtp="auto", system_prompt="") -> io.NodeOutput:
# Gemma 3 and Gemma 4 use different chat-turn markers and image tokens.
# The Gemma 4 text encoder is the LTX 2.4 path; Gemma 3 is LTX 2.0.
is_gemma4 = "gemma4" in getattr(clip.tokenizer, "clip_name", "")
if is_gemma4:
if image is not None:
- system = LTX24_I2V_SYSTEM_PROMPT.strip()
+ system = system_prompt.strip() or LTX24_I2V_SYSTEM_PROMPT.strip()
user_text = f"User Raw Input Prompt: {prompt}."
else:
- system = LTX24_T2V_SYSTEM_PROMPT.strip()
+ system = system_prompt.strip() or LTX24_T2V_SYSTEM_PROMPT.strip()
user_text = f"user prompt: {prompt}"
think_prefix = "<|think|>\n" if thinking else ""
model_open = "" if thinking else "<|channel>final\n"
@@ -250,7 +256,7 @@ class TextGenerateLTX2Prompt(TextGenerate):
f"<|turn>model\n{model_open}"
)
else:
- system = (LTX2_I2V_SYSTEM_PROMPT if image is not None else LTX2_T2V_SYSTEM_PROMPT).strip()
+ system = system_prompt.strip() or (LTX2_I2V_SYSTEM_PROMPT if image is not None else LTX2_T2V_SYSTEM_PROMPT).strip()
media = "\n<image_soft_token>\n" if image is not None else ""
formatted_prompt = (
f"<start_of_turn>system\n{system}<end_of_turn>\n"
@@ -260,10 +266,8 @@ class TextGenerateLTX2Prompt(TextGenerate):
out = super().execute(clip, formatted_prompt, max_length, sampling_mode, image=image, thinking=thinking, use_default_template=use_default_template, video=video, audio=audio, mtp=mtp)
- # Drop reasoning, including a block left unclosed by max_length. Both system prompts ask
- # for the original prompt back when there is nothing to give; empty conditions on nothing.
- text = re.sub(r"<think>.*?(?:</think>|$)", "", out.args[0], flags=re.DOTALL).strip()
- return io.NodeOutput(text or prompt)
+ # Both system prompts ask for the original prompt back when there is nothing to give; empty conditions on nothing.
+ return io.NodeOutput(out.args[0] or prompt, out.args[1])
class TextgenExtension(ComfyExtension):