Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
import torch
from invokeai.app.invocations.baseinvocation import BaseInvocation, Classification, invocation
from invokeai.app.invocations.fields import FieldDescriptions, InputField, SystemPromptField, UIComponent
from invokeai.app.invocations.model import ModelIdentifierField
from invokeai.app.invocations.primitives import StringOutput
from invokeai.app.services.shared.invocation_context import InvocationContext
from invokeai.app.services.system_prompt_records.system_prompt_records_common import (
EXPAND_PROMPT_MAX_TOKENS_DEFAULT,
EXPAND_PROMPT_MAX_TOKENS_MAX,
EXPAND_PROMPT_MAX_TOKENS_MIN,
SystemPromptNotFoundError,
SystemPromptRecordDTO,
)
from invokeai.app.util.misc import SEED_MAX
from invokeai.backend.model_manager.taxonomy import ModelType
from invokeai.backend.text_llm_pipeline import (
DEFAULT_SYSTEM_PROMPT,
TextLLMPipeline,
load_text_llm_tokenizer_and_processor,
)
from invokeai.backend.util.devices import TorchDevice
def _run_text_llm(
context: InvocationContext,
text_llm_model: ModelIdentifierField,
prompt: str,
system_prompt: str,
max_tokens: int,
seed: int,
) -> str:
"""Shared LLM invocation body used by every text-LLM node in this module."""
# Asked for as a Text LLM: a Qwen3.5 encoder record whose whole-model file serves as one is offered in these fields.
text_llm_model = text_llm_model.model_copy(update={"type": ModelType.TextLLM})
tokenizer, _ = load_text_llm_tokenizer_and_processor(
lambda submodel: context.models.load(text_llm_model, submodel), with_processor=False
)
with context.models.load(text_llm_model).model_on_device() as (_, model):
pipeline = TextLLMPipeline(model, tokenizer)
model_device = next(model.parameters()).device
return pipeline.run(
prompt=prompt,
system_prompt=system_prompt,
max_new_tokens=max_tokens,
seed=seed,
device=model_device,
dtype=TorchDevice.choose_torch_dtype(),
)
@invocation(
"text_llm",
title="Text LLM",
tags=["llm", "text", "prompt"],
category="llm",
version="1.1.0",
classification=Classification.Beta,
)
class TextLLMInvocation(BaseInvocation):
"""Run a text language model to generate or expand text (e.g. for prompt expansion)."""
prompt: str = InputField(
default="",
description="Input text prompt.",
ui_component=UIComponent.Textarea,
)
system_prompt: str = InputField(
default=DEFAULT_SYSTEM_PROMPT,
description="System prompt that guides the model's behavior.",
ui_component=UIComponent.Textarea,
)
text_llm_model: ModelIdentifierField = InputField(
title="Text LLM Model",
description=FieldDescriptions.text_llm_model,
ui_model_type=ModelType.TextLLM,
)
max_tokens: int = InputField(
default=EXPAND_PROMPT_MAX_TOKENS_DEFAULT,
ge=EXPAND_PROMPT_MAX_TOKENS_MIN,
le=EXPAND_PROMPT_MAX_TOKENS_MAX,
description="Maximum number of tokens to generate.",
)
seed: int = InputField(default=0, ge=0, le=SEED_MAX, description=FieldDescriptions.seed)
@torch.no_grad()
def invoke(self, context: InvocationContext) -> StringOutput:
output = _run_text_llm(
context=context,
text_llm_model=self.text_llm_model,
prompt=self.prompt,
system_prompt=self.system_prompt,
max_tokens=self.max_tokens,
seed=self.seed,
)
return StringOutput(value=output)
@invocation(
"text_llm_with_preset",
title="Text LLM (with System Prompt Preset)",
tags=["llm", "text", "prompt", "preset", "template"],
category="llm",
version="1.2.0",
classification=Classification.Beta,
)
class TextLLMWithPresetInvocation(BaseInvocation):
"""Run a text language model using a saved system prompt from the System Prompts library.
Behaves identically to the Text LLM node, but the system prompt is selected from a
DB-backed preset instead of being typed inline. Useful when you maintain a curated
library of expansion strategies and want to reuse them across workflows.
Note: the field stores the preset's id, not its text. A workflow exported from one install
only resolves on another if that install has a prompt with the same id -- true for the
seeded defaults (fixed UUIDs), not for user-created prompts. `StylePresetField` has the
same limitation.
"""
prompt: str = InputField(
default="",
description="Input text prompt.",
ui_component=UIComponent.Textarea,
)
system_prompt: SystemPromptField = InputField(
description="The saved system prompt to use as the LLM's instruction.",
)
text_llm_model: ModelIdentifierField = InputField(
title="Text LLM Model",
description=FieldDescriptions.text_llm_model,
ui_model_type=ModelType.TextLLM,
)
max_tokens: int = InputField(
# 0 rather than None as the "defer to the preset" sentinel, matching `tile_size` elsewhere
# in this package. An `int | None` field serialises its bounds into an OpenAPI `anyOf`,
# where the editors' field-template builders cannot see them: the node would render with
# a 0 default they reject, and with no min/max at all.
default=0,
ge=0,
le=EXPAND_PROMPT_MAX_TOKENS_MAX,
description="Maximum number of tokens to generate. 0 uses the preset's own cap, "
f"or {EXPAND_PROMPT_MAX_TOKENS_DEFAULT} if it does not set one.",
)
seed: int = InputField(default=0, ge=0, le=SEED_MAX, description=FieldDescriptions.seed)
def _resolve_system_prompt(self, context: InvocationContext) -> SystemPromptRecordDTO:
"""Resolve the referenced preset, enforcing the same access rules as the REST API.
The record store is unscoped, so without this check a user could read another user's
private prompt by enqueueing a graph that references its id -- the content becomes the
LLM's system message and is recoverable from the node's output.
The rule is deliberately identical to `routers/system_prompts.get_system_prompt`: owner,
public, or admin. Note there is no "owned by the 'system' user" clause, even though the
seeded defaults are owned by it -- `SYSTEM_PROMPT_DEFAULT_USER_ID` is also the synthetic
id every request carries in single-user mode (`auth_dependencies.get_current_user`), so
such a clause would make every prompt created before an install switched to multiuser
un-privatizable here while the REST layer still 403s on it. The seeded defaults are
`is_public=TRUE`, so `record.is_public` already covers them.
(`call_saved_workflow` can keep its default-category clause: workflow `category=default`
is a real column value, not an overloaded owner id.)
"""
system_prompt_id = self.system_prompt.system_prompt_id
try:
record = context._services.system_prompt_records.get(system_prompt_id)
except SystemPromptNotFoundError as e:
raise ValueError(f"The selected system prompt '{system_prompt_id}' could not be found.") from e
config = context._services.configuration
if config.multiuser:
queue_user_id = context._data.queue_item.user_id
user = context._services.users.get(queue_user_id)
is_admin = bool(user and user.is_admin)
is_owner = record.user_id == queue_user_id
if not (is_owner or record.is_public or is_admin):
raise ValueError(f"The selected system prompt '{system_prompt_id}' is not accessible to this user.")
return record
@torch.no_grad()
def invoke(self, context: InvocationContext) -> StringOutput:
record = self._resolve_system_prompt(context)
output = _run_text_llm(
context=context,
text_llm_model=self.text_llm_model,
prompt=self.prompt,
system_prompt=record.content,
# The preset carries its own output-length cap (structured prompts need more room
# than the default), so the 0 default defers to it rather than to a fixed number.
# Any non-zero field value still wins -- it is the node author overriding the preset.
max_tokens=self._resolve_max_tokens(record),
seed=self.seed,
)
return StringOutput(value=output)
def _resolve_max_tokens(self, record: SystemPromptRecordDTO) -> int:
if self.max_tokens:
return self.max_tokens
if record.max_tokens is not None:
return record.max_tokens
return EXPAND_PROMPT_MAX_TOKENS_DEFAULT