Skip to content

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.

51.1 KB
Raw Blame
from contextlib import ExitStack
from copy import deepcopy
from dataclasses import dataclass, field
from pathlib import Path
from typing import IO, TYPE_CHECKING, Any, Callable, Optional, Union

from dynamicprompts.wildcards import WildcardManager
from PIL.Image import Image
from pydantic.networks import AnyHttpUrl
from torch import Tensor

from invokeai.app.invocations.constants import IMAGE_MODES
from invokeai.app.invocations.fields import MetadataField, WithBoard, WithMetadata
from invokeai.app.services.board_access.board_access_common import (
    BoardAccessDeniedError,
    BoardAction,
    BoardViewer,
    ItemAccessDeniedError,
    ItemAction,
    queue_viewer,
)
from invokeai.app.services.board_records.board_records_common import BoardRecordNotFoundException, BoardRecordOrderBy
from invokeai.app.services.boards.boards_common import BoardDTO
from invokeai.app.services.config.config_default import InvokeAIAppConfig
from invokeai.app.services.files.files_common import FileDTO
from invokeai.app.services.image_records.image_records_common import ImageCategory, ResourceOrigin
from invokeai.app.services.images.images_common import ImageDTO
from invokeai.app.services.invocation_services import InvocationServices
from invokeai.app.services.model_records.model_records_base import UnknownModelException
from invokeai.app.services.session_processor.session_processor_common import ProgressImage
from invokeai.app.services.shared.execution_effects import ExecutionEffectsRecorder, ExecutionInterface
from invokeai.app.services.shared.pagination import SQLiteDirection
from invokeai.app.services.videos.videos_common import VideoDTO
from invokeai.app.services.wildcard_records.wildcard_records_common import build_wildcard_manager
from invokeai.app.util.step_callback import PreviewRender, diffusion_step_callback
from invokeai.app.util.tiny_autoencoder_previews import TinyAutoencoderPreviews
from invokeai.backend.model_manager.configs.base import Config_Base
from invokeai.backend.model_manager.configs.factory import AnyModelConfig
from invokeai.backend.model_manager.configs.roles import serves_as, view_as
from invokeai.backend.model_manager.load.load_base import LoadedModel, LoadedModelWithoutConfig
from invokeai.backend.model_manager.load.model_cache.model_cache import MODEL_LOAD_LOCK
from invokeai.backend.model_manager.taxonomy import AnyModel, BaseModelType, ModelFormat, ModelType, SubModelType
from invokeai.backend.stable_diffusion.diffusers_pipeline import PipelineIntermediateState
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import ConditioningFieldData
from invokeai.backend.util.devices import TorchDevice

if TYPE_CHECKING:
    from invokeai.app.invocations.baseinvocation import BaseInvocation
    from invokeai.app.invocations.model import ModelIdentifierField
    from invokeai.app.services.files.files_base import FileServiceBase
    from invokeai.app.services.session_queue.session_queue_common import SessionQueueItem
    from invokeai.app.services.shared.execution_engine.child import ChildExecutionCapability

"""
The InvocationContext provides access to various services and data about the current invocation.

We do not provide the invocation services directly, as their methods are both dangerous and
inconvenient to use.

For example:
- The `images` service allows nodes to delete or unsafely modify existing images.
- The `configuration` service allows nodes to change the app's config at runtime.
- The `events` service allows nodes to emit arbitrary events.

Wrapping these services provides a simpler and safer interface for nodes to use.

When a node executes, a fresh `InvocationContext` is built for it, ensuring nodes cannot interfere
with each other.

Many of the wrappers have the same signature as the methods they wrap. This allows us to write
user-facing docstrings and not need to go and update the internal services to match.

Note: The docstrings are in weird places, but that's where they must be to get IDEs to see them.
"""


@dataclass
class InvocationContextData:
    queue_item: "SessionQueueItem"
    """The queue item that is being executed."""
    invocation: "BaseInvocation"
    """The invocation that is being executed."""
    source_invocation_id: str
    """The ID of the invocation from which the currently executing invocation was prepared."""
    execution_frame: tuple[int, ...] = ()
    """The active prepared execution node's loop iteration path."""
    execution_state_id: str | None = None
    """The owning graph execution-state identity for effect ownership validation."""
    execution_frame_id: str | None = None
    """The durable frame identity for effect ownership validation."""
    execution_workflow_call_depth: int = 0
    """The active workflow-call depth for effect ownership validation."""
    execution_child_capability: "ChildExecutionCapability | None" = None
    """Engine-issued authority for lifecycle effects in this invocation frame."""
    execution_workflow_authorizer: Callable[[str], Any] | None = None
    """Engine-owned saved-workflow authorization callback, when enabled."""
    execution_workflow_inputs: dict[str, Any] | None = None
    """Resolved saved-workflow inputs supplied by the execution adapter."""
    invocation_resources: ExitStack = field(default_factory=ExitStack)
    """What the context holds for this run of the invocation, such as a Tiny AutoEncoder locked for previews.

    Whoever runs the invocation closes it once the invocation returns or raises."""


class InvocationContextInterface:
    def __init__(self, services: InvocationServices, data: InvocationContextData) -> None:
        self._services = services
        self._data = data

    def _viewer(self, refusal: str) -> BoardViewer:
        """The queue user, as the boards API sees a caller (see `queue_viewer`); a deleted or deactivated account is
        refused."""
        viewer = queue_viewer(
            self._data.queue_item.user_id,
            multiuser=self._services.configuration.multiuser,
            users=self._services.users,
        )
        if viewer is None:
            raise PermissionError(refusal)
        return viewer

    def _get_workflow_json(self) -> str | None:
        queue_item = self._data.queue_item
        if not queue_item._workflow_json_loaded:
            if queue_item.workflow is not None:
                queue_item._workflow_json_snapshot = queue_item.workflow.model_dump_json()
            elif queue_item.root_item_id is not None:
                queue_item._workflow_json_snapshot = self._services.session_queue.get_queue_item_workflow_json(
                    queue_item.root_item_id
                )
            queue_item._workflow_json_loaded = True
        return queue_item._workflow_json_snapshot


def _build_execution_effects(data: InvocationContextData) -> ExecutionEffectsRecorder:
    return ExecutionEffectsRecorder(
        source_node_id=getattr(data.invocation, "id", None) or data.source_invocation_id or "context",
        frame_path=data.execution_frame,
        state_id=data.execution_state_id,
        frame_id=data.execution_frame_id,
        workflow_call_depth=data.execution_workflow_call_depth,
        allow_lifecycle_effects=data.execution_child_capability is not None,
        child_capability=data.execution_child_capability,
    )


class BoardsInterface(InvocationContextInterface):
    def _require(self, board_id: str, viewer: BoardViewer, action: BoardAction, refusal: str) -> None:
        try:
            self._services.board_access.require(board_id, viewer.user_id, viewer.is_admin, action)
        except BoardAccessDeniedError:
            raise PermissionError(refusal)

    def create(self, board_name: str) -> BoardDTO:
        """Creates a board for the current user.

        Args:
            board_name: The name of the board to create.

        Returns:
            The created board DTO.
        """
        viewer = self._viewer("Queue user is not authorized to create boards")
        return self._services.boards.create(board_name, viewer.user_id, viewer=viewer)

    def get_dto(self, board_id: str) -> BoardDTO:
        """Gets a board DTO.

        Args:
            board_id: The ID of the board to get.

        Returns:
            The board DTO.
        """
        refusal = "Queue user is not authorized to access this board"
        viewer = self._viewer(refusal)
        self._require(board_id, viewer, BoardAction.Read, refusal)
        return self._services.boards.get_dto(board_id, viewer=viewer)

    def get_all(self) -> list[BoardDTO]:
        """Gets all boards accessible to the current user.

        Returns:
            A list of all boards accessible to the current user.
        """
        viewer = self._viewer("Queue user is not authorized to list boards")
        return self._services.boards.get_all(
            viewer.user_id, viewer.is_admin, order_by=BoardRecordOrderBy.CreatedAt, direction=SQLiteDirection.Descending
        )

    def add_image_to_board(self, board_id: str, image_name: str) -> None:
        """Adds an image to a board.

        Args:
            board_id: The ID of the board to add the image to.
            image_name: The name of the image to add to the board.
        """
        refusal = "Queue user is not authorized to add this image to this board"
        viewer = self._viewer(refusal)
        self._require(board_id, viewer, BoardAction.AddMedia, refusal)
        # Only an image's owner may put it on a board, as through the boards API.
        try:
            self._services.board_access.require_image(image_name, viewer.user_id, viewer.is_admin, ItemAction.Edit)
        except ItemAccessDeniedError:
            raise PermissionError(refusal)
        return self._services.board_images.add_image_to_board(board_id, image_name)

    def get_all_image_names_for_board(self, board_id: str) -> list[str]:
        """Gets all image names for a board.

        Args:
            board_id: The ID of the board to get the image names for.

        Returns:
            A list of all image names for the board.
        """
        refusal = "Queue user is not authorized to access this board"
        viewer = self._viewer(refusal)
        self._require(board_id, viewer, BoardAction.Read, refusal)
        return self._services.board_images.get_all_board_image_names_for_board(
            board_id,
            categories=None,
            is_intermediate=None,
        )


class LoggerInterface(InvocationContextInterface):
    def debug(self, message: str) -> None:
        """Logs a debug message.

        Args:
            message: The message to log.
        """
        self._services.logger.debug(message)

    def info(self, message: str) -> None:
        """Logs an info message.

        Args:
            message: The message to log.
        """
        self._services.logger.info(message)

    def warning(self, message: str) -> None:
        """Logs a warning message.

        Args:
            message: The message to log.
        """
        self._services.logger.warning(message)

    def error(self, message: str) -> None:
        """Logs an error message.

        Args:
            message: The message to log.
        """
        self._services.logger.error(message)


class FilesInterface(InvocationContextInterface):
    def get_dto(self, file_id: str) -> FileDTO:
        """Gets metadata for a managed file.

        Args:
            file_id: The managed file ID.

        Returns:
            The file DTO.
        """
        return self._get_files_service().get_dto(file_id, user_id=self._data.queue_item.user_id)

    def get_path(self, file_id: str) -> Path:
        """Gets the server-side path to a managed file.

        Args:
            file_id: The managed file ID.

        Returns:
            The path to the managed file on the InvokeAI server.
        """
        return self._get_files_service().get_path(file_id, user_id=self._data.queue_item.user_id)

    def open(self, file_id: str, mode: str = "rb") -> IO[Any]:
        """Opens a managed file for reading.

        Args:
            file_id: The managed file ID.
            mode: The read mode to use. Supported values are "rb" and "r".

        Returns:
            A readable file object.
        """
        return self._get_files_service().open(file_id, mode=mode, user_id=self._data.queue_item.user_id)

    def _get_files_service(self) -> "FileServiceBase":
        if self._services.files is None:
            raise RuntimeError("The managed files service is not available.")
        return self._services.files


class ImagesInterface(InvocationContextInterface):
    def __init__(self, services: InvocationServices, data: InvocationContextData, util: "UtilInterface") -> None:
        super().__init__(services, data)
        self._util = util

    def _assert_read_access(self, image_name: str) -> None:
        # Single-user mode reads any image: the queue runs as the one account.
        if not self._services.configuration.multiuser:
            return
        refusal = "Queue user is not authorized to access this image"
        viewer = self._viewer(refusal)
        try:
            self._services.board_access.require_image(image_name, viewer.user_id, viewer.is_admin, ItemAction.Read)
        except ItemAccessDeniedError:
            raise PermissionError(refusal)

    def save(
        self,
        image: Image,
        board_id: Optional[str] = None,
        image_category: ImageCategory = ImageCategory.GENERAL,
        metadata: Optional[MetadataField] = None,
    ) -> ImageDTO:
        """Saves an image, returning its DTO.

        If the current queue item has a workflow or metadata, it is automatically saved with the image.

        Args:
            image: The image to save, as a PIL image.
            board_id: The board ID to add the image to, if it should be added. It the invocation \
            inherits from `WithBoard`, that board will be used automatically. **Use this only if \
            you want to override or provide a board manually!**
            image_category: The category of the image. Only the GENERAL category is added \
            to the gallery.
            metadata: The metadata to save with the image, if it should have any. If the \
            invocation inherits from `WithMetadata`, that metadata will be used automatically. \
            **Use this only if you want to override or provide metadata manually!**

        Returns:
            The saved image DTO.
        """

        self._util.signal_progress("Saving image")

        # If `metadata` is provided directly, use that. Else, use the metadata provided by `WithMetadata`, falling back to None.
        metadata_ = None
        if metadata:
            metadata_ = metadata.model_dump_json()
        elif isinstance(self._data.invocation, WithMetadata) and self._data.invocation.metadata:
            metadata_ = self._data.invocation.metadata.model_dump_json()

        # If `board_id` is provided directly, use that. Else, use the board provided by `WithBoard`, falling back to None.
        board_id_ = None
        if board_id:
            board_id_ = board_id
        elif isinstance(self._data.invocation, WithBoard) and self._data.invocation.board:
            board_id_ = self._data.invocation.board.board_id

        # Single-user mode saves to any board: the queue runs as the one account.
        if self._services.configuration.multiuser:
            # A deactivated or deleted account must not save outputs, even uncategorized ones.
            viewer = self._viewer("Queue user is not authorized to save images")
            if board_id_ is not None:
                # Checked when the output is saved, against the role the user has now.
                try:
                    self._services.board_access.require(
                        board_id_, viewer.user_id, viewer.is_admin, BoardAction.AddMedia
                    )
                except (BoardAccessDeniedError, BoardRecordNotFoundException):
                    raise PermissionError("Queue user is not authorized to save images to this board")

        workflow_ = self._get_workflow_json()

        graph_ = None
        resolved_inputs = None
        if self._data.queue_item.session.graph:
            # The editor's graph-only fallback needs the complete authoring graph.
            graph_ = self._data.queue_item.session.graph.model_dump_json()
            # Record resolved inputs for this image, without expanding metadata with sibling iterations.
            resolved_inputs = self._data.queue_item.session.execution_graph._get_invocation_input_graph(
                self._data.invocation
            ).model_dump_json()

        return self._services.images.create(
            image=image,
            is_intermediate=self._data.invocation.is_intermediate,
            image_category=image_category,
            board_id=board_id_,
            metadata=metadata_,
            image_origin=ResourceOrigin.INTERNAL,
            workflow=workflow_,
            graph=graph_,
            resolved_inputs=resolved_inputs,
            session_id=self._data.queue_item.session_id,
            node_id=self._data.invocation.id,
            user_id=self._data.queue_item.user_id,
            project_id=self._data.queue_item.project_id,
        )

    def get_pil(self, image_name: str, mode: IMAGE_MODES | None = None) -> Image:
        """Gets an image as a PIL Image object. This method returns a copy of the image.

        Args:
            image_name: The name of the image to get.
            mode: The color mode to convert the image to. If None, the original mode is used.

        Returns:
            The image as a PIL Image object.
        """
        self._assert_read_access(image_name)
        image = self._services.images.get_pil_image(image_name)
        if mode and mode != image.mode:
            try:
                # convert makes a copy!
                image = image.convert(mode)
            except ValueError:
                self._services.logger.warning(
                    f"Could not convert image from {image.mode} to {mode}. Using original mode instead."
                )
                # the service hands out its cached object: the fallback must not return it
                image = image.copy()
        else:
            # copy the image to prevent the user from modifying the original
            image = image.copy()
        return image

    def get_metadata(self, image_name: str) -> Optional[MetadataField]:
        """Gets an image's metadata, if it has any.

        Args:
            image_name: The name of the image to get the metadata for.

        Returns:
            The image's metadata, if it has any.
        """
        self._assert_read_access(image_name)
        return self._services.images.get_metadata(image_name)

    def get_dto(self, image_name: str) -> ImageDTO:
        """Gets an image as an ImageDTO object.

        Args:
            image_name: The name of the image to get.

        Returns:
            The image as an ImageDTO object.
        """
        self._assert_read_access(image_name)
        return self._services.images.get_dto(image_name)

    def get_path(self, image_name: str, thumbnail: bool = False) -> Path:
        """Gets the internal path to an image or thumbnail.

        Args:
            image_name: The name of the image to get the path of.
            thumbnail: Get the path of the thumbnail instead of the full image

        Returns:
            The local path of the image or thumbnail.
        """
        self._assert_read_access(image_name)
        return Path(self._services.images.get_path(image_name, thumbnail))


class VideosInterface(InvocationContextInterface):
    """Save and look up videos produced by invocations.

    Mirrors :class:`ImagesInterface` but consumes a path to an already-encoded
    MP4 (or other supported container) rather than an in-memory PIL image —
    video encoding is the caller's responsibility (e.g. the
    ``wan_latents_to_video`` node uses ``imageio[ffmpeg]``).
    """

    def __init__(self, services: InvocationServices, data: InvocationContextData, util: "UtilInterface") -> None:
        super().__init__(services, data)
        self._util = util

    def _assert_read_access(self, video_name: str) -> None:
        # See ImagesInterface._assert_read_access.
        if not self._services.configuration.multiuser:
            return
        refusal = "Queue user is not authorized to access this video"
        viewer = self._viewer(refusal)
        try:
            self._services.board_access.require_video(video_name, viewer.user_id, viewer.is_admin, ItemAction.Read)
        except ItemAccessDeniedError:
            raise PermissionError(refusal)

    def save(
        self,
        source_path: Path,
        width: int,
        height: int,
        duration: float,
        fps: Optional[float] = None,
        board_id: Optional[str] = None,
        image_category: ImageCategory = ImageCategory.GENERAL,
        metadata: Optional[MetadataField] = None,
    ) -> VideoDTO:
        """Save a video produced by an invocation. The file at ``source_path`` is moved into
        the videos output folder; the caller should treat the path as consumed after this
        returns.

        ``board_id`` falls back to the invocation's :class:`WithBoard` mixin if unset, and
        ``metadata`` falls back to the :class:`WithMetadata` mixin. Both can be overridden
        explicitly. ``image_category`` reuses the image enum since the gallery's category
        filter is shared between kinds.
        """

        self._util.signal_progress("Saving video")

        metadata_ = None
        if metadata:
            metadata_ = metadata.model_dump_json()
        elif isinstance(self._data.invocation, WithMetadata) and self._data.invocation.metadata:
            metadata_ = self._data.invocation.metadata.model_dump_json()

        board_id_ = None
        if board_id:
            board_id_ = board_id
        elif isinstance(self._data.invocation, WithBoard) and self._data.invocation.board:
            board_id_ = self._data.invocation.board.board_id

        # See ImagesInterface.save.
        if self._services.configuration.multiuser:
            viewer = self._viewer("Queue user is not authorized to save videos")
            if board_id_ is not None:
                # Checked when the output is saved, against the role the user has now.
                try:
                    self._services.board_access.require(
                        board_id_, viewer.user_id, viewer.is_admin, BoardAction.AddMedia
                    )
                except (BoardAccessDeniedError, BoardRecordNotFoundException):
                    raise PermissionError("Queue user is not authorized to save videos to this board")

        workflow_ = self._get_workflow_json()

        graph_ = None
        if self._data.queue_item.session.graph:
            graph_ = self._data.queue_item.session.graph.model_dump_json()

        return self._services.videos.create(
            source_path=source_path,
            width=width,
            height=height,
            duration=duration,
            fps=fps,
            is_intermediate=self._data.invocation.is_intermediate,
            video_category=image_category,
            board_id=board_id_,
            metadata=metadata_,
            video_origin=ResourceOrigin.INTERNAL,
            workflow=workflow_,
            graph=graph_,
            session_id=self._data.queue_item.session_id,
            node_id=self._data.invocation.id,
            user_id=self._data.queue_item.user_id,
            project_id=self._data.queue_item.project_id,
        )

    def get_dto(self, video_name: str) -> VideoDTO:
        """Get a video DTO by name."""
        self._assert_read_access(video_name)
        return self._services.videos.get_dto(video_name)

    def get_path(self, video_name: str, thumbnail: bool = False) -> Path:
        """Get the on-disk path to a video file or its WebP thumbnail."""
        self._assert_read_access(video_name)
        return Path(self._services.videos.get_path(video_name, thumbnail=thumbnail))


class TensorsInterface(InvocationContextInterface):
    def save(self, tensor: Tensor) -> str:
        """Saves a tensor, returning its name.

        Args:
            tensor: The tensor to save.

        Returns:
            The name of the saved tensor.
        """

        name = self._services.tensors.save(obj=tensor)
        return name

    def load(self, name: str) -> Tensor:
        """Loads a tensor by name. This method returns a copy of the tensor.

        Args:
            name: The name of the tensor to load.

        Returns:
            The tensor.
        """
        return self._services.tensors.load(name).clone()


class ConditioningInterface(InvocationContextInterface):
    def save(self, conditioning_data: ConditioningFieldData) -> str:
        """Saves a conditioning data object, returning its name.

        Args:
            conditioning_data: The conditioning data to save.

        Returns:
            The name of the saved conditioning data.
        """

        name = self._services.conditioning.save(obj=conditioning_data)
        return name

    def load(self, name: str) -> ConditioningFieldData:
        """Loads conditioning data by name. This method returns a copy of the conditioning data.

        Args:
            name: The name of the conditioning data to load.

        Returns:
            The conditioning data.
        """

        return deepcopy(self._services.conditioning.load(name))


class ModelsInterface(InvocationContextInterface):
    """Common API for loading, downloading and managing models."""

    def __init__(self, services: InvocationServices, data: InvocationContextData, util: "UtilInterface") -> None:
        super().__init__(services, data)
        self._util = util

    def _resolve(self, identifier: Union[str, "ModelIdentifierField"]) -> AnyModelConfig:
        """The record an identifier names, or its view in the role the identifier asks for.

        A key names the stored record. A field names the type the model is asked for in: when that is not the record's
        own type but one it serves as, the result is the record's view in that role. Any other type returns the record
        unchanged, so the node's own validation sees a mismatch.
        """
        if isinstance(identifier, str):
            return self._services.model_manager.store.get_model(identifier)
        config = self._services.model_manager.store.get_model(identifier.key)
        if identifier.type != config.type and serves_as(config, identifier.type):
            return view_as(config, identifier.type)
        return config

    def exists(self, identifier: Union[str, "ModelIdentifierField"]) -> bool:
        """Check if a model exists.

        Args:
            identifier: The key or ModelField representing the model.

        Returns:
            True if the model exists, False if not.
        """
        if isinstance(identifier, str):
            return self._services.model_manager.store.exists(identifier)
        else:
            return self._services.model_manager.store.exists(identifier.key)

    def load(
        self, identifier: Union[str, "ModelIdentifierField"], submodel_type: Optional[SubModelType] = None
    ) -> LoadedModel:
        """Load a model.

        Args:
            identifier: The key or ModelField representing the model. A ModelField's `type` is the type the model is
                loaded as, its own type or a role it serves as (see `Config_Base.roles`).
            submodel_type: The submodel of the model to get.

        Returns:
            An object representing the loaded model.
        """

        # The model manager emits events as it loads the model. It needs the context data to build
        # the event payloads.

        if not isinstance(identifier, str):
            submodel_type = submodel_type or identifier.submodel_type
        model = self._resolve(identifier)

        self._raise_if_external(model)

        message = f"Loading model {model.name}"
        if submodel_type:
            message += f" ({submodel_type.value})"
        self._util.signal_progress(message)
        return self._services.model_manager.load.load_model(model, submodel_type, user_id=self._data.queue_item.user_id)

    def load_by_attrs(
        self, name: str, base: BaseModelType, type: ModelType, submodel_type: Optional[SubModelType] = None
    ) -> LoadedModel:
        """Load a model by its attributes.

        Args:
            name: Name of the model.
            base: The models' base type, e.g. `BaseModelType.StableDiffusion1`, `BaseModelType.StableDiffusionXL`, etc.
            type: Type of the model, e.g. `ModelType.Main`, `ModelType.Vae`, etc.
            submodel_type: The type of submodel to load, e.g. `SubModelType.UNet`, `SubModelType.TextEncoder`, etc. Only main
            models have submodels.

        Returns:
            An object representing the loaded model.
        """

        configs = self._services.model_manager.store.search_by_attr(model_name=name, base_model=base, model_type=type)
        if len(configs) == 0:
            raise UnknownModelException(f"No model found with name {name}, base {base}, and type {type}")

        if len(configs) > 1:
            raise ValueError(f"More than one model found with name {name}, base {base}, and type {type}")

        self._raise_if_external(configs[0])
        message = f"Loading model {name}"
        if submodel_type:
            message += f" ({submodel_type.value})"
        self._util.signal_progress(message)
        return self._services.model_manager.load.load_model(
            configs[0], submodel_type, user_id=self._data.queue_item.user_id
        )

    def offload_from_vram(self, identifier: Union[str, "ModelIdentifierField"]) -> int:
        """Move a model (and all of its submodels) from VRAM to RAM, freeing its VRAM but keeping it cached.

        Use this when an invocation is done with a model for the rest of the run - e.g. a one-shot text encoder -
        so the next, larger load does not have to compete with it for VRAM. The model stays in the RAM cache, so
        a subsequent load only re-streams it back to VRAM rather than rebuilding it from disk.

        The caller must not hold `MODEL_LOAD_LOCK`; this method acquires its read lock.

        Args:
            identifier: The key or ModelField representing the model to offload.

        Returns:
            The number of VRAM bytes freed.
        """
        key = identifier if isinstance(identifier, str) else identifier.key
        with MODEL_LOAD_LOCK.read_lock():
            return self._services.model_manager.load.ram_cache.offload_model_from_vram(key)

    def make_room_in_vram(self, vram_bytes_needed: int) -> int:
        """Offload unlocked cached models from VRAM until `vram_bytes_needed` bytes are free on this thread's
        execution device.

        Use this before placing a model on the GPU *outside* the model cache (e.g. a BitsAndBytes-quantized model
        that cannot be moved between devices). Loads that go through `load()` never need this - the cache makes room
        for them itself when they are locked - but an out-of-cache load competes with the cached models for VRAM
        and would otherwise only get whatever they happened to leave free. The configured working-memory reserve
        is kept free on top of the request.

        The caller must not hold `MODEL_LOAD_LOCK`; this method acquires its read lock.

        Args:
            vram_bytes_needed: The VRAM footprint the caller is about to allocate.

        Returns:
            The VRAM available after offloading, less the working-memory reserve (so it may be negative). Locked
            (in-use) models are never offloaded, so the request is not guaranteed: compare the result with
            `vram_bytes_needed` before allocating.
        """
        with MODEL_LOAD_LOCK.read_lock():
            return self._services.model_manager.load.ram_cache.make_room_in_vram(vram_bytes_needed)

    @staticmethod
    def _raise_if_external(model: AnyModelConfig) -> None:
        if model.base == BaseModelType.External or model.format == ModelFormat.ExternalApi:
            raise ValueError("External API models cannot be loaded from disk")

    def get_config(self, identifier: Union[str, "ModelIdentifierField"]) -> AnyModelConfig:
        """Get a model's config.

        Args:
            identifier: The key or ModelField representing the model. A ModelField's `type` selects the role. The
                config is the record's view in that type when it serves as it (see `Config_Base.roles`), else the
                stored record.

        Returns:
            The model's config.
        """
        return self._resolve(identifier)

    def search_by_path(self, path: Path) -> list[AnyModelConfig]:
        """Search for models by path.

        Args:
            path: The path to search for.

        Returns:
            A list of models that match the path.
        """
        return self._services.model_manager.store.search_by_path(path)

    def search_by_attrs(
        self,
        name: Optional[str] = None,
        base: Optional[BaseModelType] = None,
        type: Optional[ModelType] = None,
        format: Optional[ModelFormat] = None,
    ) -> list[AnyModelConfig]:
        """Search for models by attributes.

        Args:
            name: The name to search for (exact match).
            base: The base to search for, e.g. `BaseModelType.StableDiffusion1`, `BaseModelType.StableDiffusionXL`, etc.
            type: Type type of model to search for, e.g. `ModelType.Main`, `ModelType.Vae`, etc.
            format: The format of model to search for, e.g. `ModelFormat.Checkpoint`, `ModelFormat.Diffusers`, etc.

        Returns:
            A list of models that match the attributes.
        """

        return self._services.model_manager.store.search_by_attr(
            model_name=name,
            base_model=base,
            model_type=type,
            model_format=format,
        )

    def download_and_cache_model(
        self,
        source: str | AnyHttpUrl,
    ) -> Path:
        """
        Download the model file located at source to the models cache and return its Path.

        This can be used to single-file install models and other resources of arbitrary types
        which should not get registered with the database. If the model is already
        installed, the cached path will be returned. Otherwise it will be downloaded.

        Args:
            source: A URL that points to the model, or a huggingface repo_id.

        Returns:
            Path to the downloaded model
        """
        self._util.signal_progress(f"Downloading model {source}")
        return self._services.model_manager.install.download_and_cache_model(source=source)

    def load_local_model(
        self,
        model_path: Path,
        loader: Optional[Callable[[Path], AnyModel]] = None,
    ) -> LoadedModelWithoutConfig:
        """
        Load the model file located at the indicated path

        If a loader callable is provided, it will be invoked to load the model. Otherwise,
        `safetensors.torch.load_file()` or `torch.load()` will be called to load the model.

        Be aware that the LoadedModelWithoutConfig object has no `config` attribute

        Args:
            path: A model Path
            loader: A Callable that expects a Path and returns a dict[str|int, Any]

        Returns:
            A LoadedModelWithoutConfig object.
        """

        self._util.signal_progress(f"Loading model {model_path.name}")
        return self._services.model_manager.load.load_model_from_path(model_path=model_path, loader=loader)

    def load_remote_model(
        self,
        source: str | AnyHttpUrl,
        loader: Optional[Callable[[Path], AnyModel]] = None,
    ) -> LoadedModelWithoutConfig:
        """
        Download, cache, and load the model file located at the indicated URL or repo_id.

        If the model is already downloaded, it will be loaded from the cache.

        If the a loader callable is provided, it will be invoked to load the model. Otherwise,
        `safetensors.torch.load_file()` or `torch.load()` will be called to load the model.

        Be aware that the LoadedModelWithoutConfig object has no `config` attribute

        Args:
            source: A URL or huggingface repoid.
            loader: A Callable that expects a Path and returns a dict[str|int, Any]

        Returns:
            A LoadedModelWithoutConfig object.
        """
        model_path = self._services.model_manager.install.download_and_cache_model(source=str(source))

        self._util.signal_progress(f"Loading model {source}")
        return self._services.model_manager.load.load_model_from_path(model_path=model_path, loader=loader)

    def get_absolute_path(self, config_or_path: AnyModelConfig | Path | str) -> Path:
        """Gets the absolute path for a given model config or path.

        For example, if the model's path is `flux/main/FLUX Dev.safetensors`, and the models path is
        `/home/username/InvokeAI/models`, this method will return
        `/home/username/InvokeAI/models/flux/main/FLUX Dev.safetensors`.

        Args:
            config_or_path: The model config or path.

        Returns:
            The absolute path to the model.
        """

        model_path = Path(config_or_path.path) if isinstance(config_or_path, Config_Base) else Path(config_or_path)

        if model_path.is_absolute():
            return model_path.resolve()

        base_models_path = self._services.configuration.models_path
        joined_path = base_models_path / model_path
        resolved_path = joined_path.resolve()
        return resolved_path


class ConfigInterface(InvocationContextInterface):
    def get(self) -> InvokeAIAppConfig:
        """Gets the app's config.

        Returns:
            The app's config.
        """

        return self._services.configuration


class UtilInterface(InvocationContextInterface):
    def __init__(
        self, services: InvocationServices, data: InvocationContextData, is_canceled: Callable[[], bool]
    ) -> None:
        super().__init__(services, data)
        self._is_canceled = is_canceled
        self._previews: TinyAutoencoderPreviews | None = None

    def is_canceled(self) -> bool:
        """Checks if the current session has been canceled.

        Returns:
            True if the current session has been canceled, False if not.
        """
        return self._is_canceled()

    def sd_step_callback(self, intermediate_state: PipelineIntermediateState, base_model: BaseModelType) -> None:
        """
        The step callback emits a progress event with the current step, the total number of
        steps, a preview image, and some other internal metadata.

        This should be called after each denoising step.

        Args:
            intermediate_state: The intermediate state of the diffusion pipeline.
            base_model: The base model for the current denoising step.
        """

        diffusion_step_callback(
            signal_preview=self._signal_preview,
            intermediate_state=intermediate_state,
            base_model=base_model,
            is_canceled=self.is_canceled,
            render=self._get_previews().render,
        )

    def flux_step_callback(self, intermediate_state: PipelineIntermediateState) -> None:
        """
        The step callback emits a progress event with the current step, the total number of
        steps, a preview image, and some other internal metadata.

        This should be called after each denoising step.

        Args:
            intermediate_state: The intermediate state of the diffusion pipeline.
        """

        diffusion_step_callback(
            signal_preview=self._signal_preview,
            intermediate_state=intermediate_state,
            base_model=BaseModelType.Flux,
            is_canceled=self.is_canceled,
            render=self._get_previews().render,
        )

    def flux2_step_callback(self, intermediate_state: PipelineIntermediateState) -> None:
        """
        The step callback for FLUX.2 Klein models (32-channel VAE).

        Args:
            intermediate_state: The intermediate state of the diffusion pipeline.
        """

        diffusion_step_callback(
            signal_preview=self._signal_preview,
            intermediate_state=intermediate_state,
            base_model=BaseModelType.Flux2,
            is_canceled=self.is_canceled,
            render=self._get_previews().render,
        )

    def signal_progress(
        self,
        message: str,
        percentage: float | None = None,
        image: Image | None = None,
        image_size: tuple[int, int] | None = None,
    ) -> None:
        """Signals the progress of some long-running invocation. The progress is displayed in the UI.

        If a percentage is provided, the UI will display a progress bar and automatically append the percentage to the
        message. You should not include the percentage in the message.

        Example:
            ```py
            total_steps = 10
            for i in range(total_steps):
                percentage = i / (total_steps - 1)
                context.util.signal_progress("Doing something cool", percentage)
            ```

        If an image is provided, the UI will display it. If your image should be displayed at a different size, provide
        a tuple of `(width, height)` for the `image_size` parameter. The image will be displayed at the specified size
        in the UI.

        For example, SD denoising progress images are 1/8 the size of the original image, so you'd do this to ensure the
        image is displayed at the correct size:
            ```py
            # Calculate the output size of the image (8x the progress image's size)
            width = progress_image.width * 8
            height = progress_image.height * 8
            # Signal the progress with the image and output size
            signal_progress("Denoising", percentage, progress_image, (width, height))
            ```

        If your progress image is very large, consider downscaling it to reduce the payload size and provide the original
        size to the `image_size` parameter. The PIL `thumbnail` method is useful for this, as it maintains the aspect
        ratio of the image:
            ```py
            # `thumbnail` modifies the image in-place, so we need to first make a copy
            thumbnail_image = progress_image.copy()
            # Resize the image to a maximum of 256x256 pixels, maintaining the aspect ratio
            thumbnail_image.thumbnail((256, 256))
            # Signal the progress with the thumbnail, passing the original size
            signal_progress("Denoising", percentage, thumbnail, progress_image.size)
            ```

        Args:
            message: A message describing the current status. Do not include the percentage in this message.
            percentage: The current percentage completion for the process. Omit for indeterminate progress.
            image: An optional image to display.
            image_size: The optional size of the image to display. If omitted, the image will be displayed at its
                original size.
        """

        if image is not None:
            self._signal_preview(message, percentage, lambda: (image, image_size))
            return

        # See _signal_preview: imageless progress is a step boundary too.
        TorchDevice.flush_deferred_empty_cache()
        self._services.events.emit_invocation_progress(
            queue_item=self._data.queue_item,
            invocation=self._data.invocation,
            message=message,
            percentage=percentage,
        )

    def _signal_preview(self, message: str, percentage: float | None, render: PreviewRender) -> None:
        """Signal an image-bearing progress frame, rendering the image only if the frame is emitted."""

        # Every denoise loop reports here once per step, so this is where a busy worker reaches a
        # natural boundary in its own GPU work. If a peer deferred a process-global empty_cache
        # (skipped so as not to stall THIS worker mid-step), run it now, from this thread, where
        # the driver-level free costs this device at most a re-allocation of its cached working
        # blocks. A flag test when nothing is pending.
        TorchDevice.flush_deferred_empty_cache()

        # Image-bearing frames are revisioned and throttled by the preview store, and the emitted
        # event is retained there so a reconnecting client can be given the latest frame instead
        # of waiting for the next step. Throttled frames are dropped before the render and the
        # JPEG encode. A Tiny AutoEncoder's frames are expensive enough to widen the interval.
        queue_item = self._data.queue_item
        previews = self._services.progress_previews
        renderer = self._get_previews()
        revision = previews.reserve_revision(
            queue_item.item_id, queue_item.session_id, percentage, min_interval_s=renderer.min_frame_interval_s
        )
        if revision is None:
            return
        with renderer.measure_frame():
            image, image_size = render()
            progress_image = ProgressImage.build(image, image_size)
        event = self._services.events.emit_invocation_progress(
            queue_item=queue_item,
            invocation=self._data.invocation,
            message=message,
            percentage=percentage,
            image=progress_image,
            revision=revision,
        )
        previews.record(event)

    def _get_previews(self) -> TinyAutoencoderPreviews:
        """What renders and paces this invocation's preview frames, created on the first one.

        With `tiny_autoencoder_previews` off, it renders every frame linearly at the store's interval.
        """
        if self._previews is None:
            self._previews = TinyAutoencoderPreviews(
                self._services,
                user_id=self._data.queue_item.user_id,
                enabled=self._services.configuration.tiny_autoencoder_previews,
            )
            # A TAE stays locked from the first preview until the invocation's runner closes this.
            self._data.invocation_resources.callback(self._previews.close)
        return self._previews


class WildcardsInterface(InvocationContextInterface):
    def get_manager(self) -> WildcardManager:
        """Builds the wildcard manager that resolves `__name__` for the queue item's owner.

        Wildcards are per-user records, so an invocation resolves them against whoever queued it.
        """
        wildcards = self._services.wildcard_records.get_many(user_id=self._data.queue_item.user_id)
        return build_wildcard_manager(wildcards)


class InvocationContext:
    """Provides access to various services and data for the current invocation.

    Attributes:
        images (ImagesInterface): Methods to save, get and update images and their metadata.
        tensors (TensorsInterface): Methods to save and get tensors, including image, noise, masks, and masked images.
        conditioning (ConditioningInterface): Methods to save and get conditioning data.
        models (ModelsInterface): Methods to check if a model exists, get a model, and get a model's info.
        logger (LoggerInterface): The app logger.
        config (ConfigInterface): The app config.
        util (UtilInterface): Utility methods, including a method to check if an invocation was canceled and step callbacks.
        boards (BoardsInterface): Methods to interact with boards.
        files (FilesInterface): Methods to read managed files uploaded for node inputs.
        wildcards (WildcardsInterface): Access to the queueing user's wildcards.
    """

    def __init__(
        self,
        images: ImagesInterface,
        videos: VideosInterface,
        tensors: TensorsInterface,
        conditioning: ConditioningInterface,
        models: ModelsInterface,
        logger: LoggerInterface,
        config: ConfigInterface,
        util: UtilInterface,
        boards: BoardsInterface,
        files: FilesInterface,
        wildcards: WildcardsInterface,
        data: InvocationContextData,
        services: InvocationServices,
        execution_effects: Optional[ExecutionEffectsRecorder] = None,
    ) -> None:
        self.images = images
        """Methods to save, get and update images and their metadata."""
        self.videos = videos
        """Methods to save and get videos produced by invocations."""
        self.tensors = tensors
        """Methods to save and get tensors, including image, noise, masks, and masked images."""
        self.conditioning = conditioning
        """Methods to save and get conditioning data."""
        self.models = models
        """Methods to check if a model exists, get a model, and get a model's info."""
        self.logger = logger
        """The app logger."""
        self.config = config
        """The app config."""
        self.util = util
        """Utility methods, including a method to check if an invocation was canceled and step callbacks."""
        self.boards = boards
        """Methods to interact with boards."""
        self.files = files
        """Methods to read managed files uploaded for node inputs."""
        self.wildcards = wildcards
        """Access to the queueing user's wildcards."""
        self._data = data
        """An internal API providing access to data about the current queue item and invocation. You probably shouldn't use this. It may change without warning."""
        self._services = services
        """An internal API providing access to all application services. You probably shouldn't use this. It may change without warning."""
        self.execution_effects = execution_effects or _build_execution_effects(data)
        """Effects recorded during the current invocation run."""
        self.effects = self.execution_effects
        """Alias for :attr:`execution_effects`."""
        self.execution = ExecutionInterface(
            self.execution_effects,
            authorize_workflow=data.execution_workflow_authorizer,
        )
        """Restricted execution-effect recorder facade."""
        self._skip_invocation_cache = False


def build_invocation_context(
    services: InvocationServices,
    data: InvocationContextData,
    is_canceled: Callable[[], bool],
    execution_effects: Optional[ExecutionEffectsRecorder] = None,
) -> InvocationContext:
    """Builds the invocation context for a specific invocation execution.

    Args:
        services: The invocation services to wrap.
        data: The invocation context data.

    Returns:
        The invocation context.
    """

    logger = LoggerInterface(services=services, data=data)
    tensors = TensorsInterface(services=services, data=data)
    config = ConfigInterface(services=services, data=data)
    util = UtilInterface(services=services, data=data, is_canceled=is_canceled)
    conditioning = ConditioningInterface(services=services, data=data)
    models = ModelsInterface(services=services, data=data, util=util)
    images = ImagesInterface(services=services, data=data, util=util)
    videos = VideosInterface(services=services, data=data, util=util)
    boards = BoardsInterface(services=services, data=data)
    files = FilesInterface(services=services, data=data)
    wildcards = WildcardsInterface(services=services, data=data)

    if execution_effects is None:
        execution_effects = _build_execution_effects(data)

    ctx = InvocationContext(
        images=images,
        videos=videos,
        logger=logger,
        config=config,
        tensors=tensors,
        models=models,
        data=data,
        util=util,
        conditioning=conditioning,
        services=services,
        boards=boards,
        files=files,
        wildcards=wildcards,
        execution_effects=execution_effects,
    )

    return ctx