PotionUI Docs v0.3.0

What's importable

Every name below can be imported directly from src.plugin_api. They are also grouped into modules (src.plugin_api.providers, .chat, .backends, …) if you prefer to import from those — the names are identical, so it is purely a matter of taste.

GroupModuleExports
Identity — who is calling, and signing them in.identityUser, AccountType, get_current_active_user, ApiScope, key_access, key_scope, SESSION_ONLY (see API keys on plugin routes), authenticate_websocket and the deprecated authenticate_websocket_token (see WebSocket authentication), get_user (a user by id, or None, for background work that acts as a known user), register_login_provider, unregister_login_provider, sign_in_external, ExternalSession, ExternalLoginError
Hooks and runtime — reacting to the app, reaching its managers.hooksHookContext, HookResult, HookSpec, hooks_registry, PluginRegistry, get_container, get_app_loop, run_on_app_loop, get_global_plugin_registry, get_global_tool_registry, ModelLifecycle
Providers — talking to a model marketplace.providersMarketplaceProviderBase, ProviderCapability, ProviderMetadata, ProviderModelInfo, ProviderSearchResult, ProviderPromptItem, ProviderError, ProviderConnectionError, ProviderRateLimitError, ProviderNotFoundError, get_provider_registry, ModelInfo, aiohttp_connector, client_ssl_context, is_certificate_error, certificate_failure_message, HttpMarketplaceProvider, register_provider, retry_after_from_headers
Chat — extending the assistant.chatBaseTool, ToolContext, ToolResult, ToolSource, PreChatAction
LLM — contributing an LLM configuration type.llmAdapter, HttpAdapter, OpenAIChatAdapter, RenderRequest, WireRequest, CapabilityProfile, ProfileLayer, Settings, ToolSpec, the message parts, stream events and provider errors, LLMConfig, DiscoveredModel, DiscoveredWindow
Backends — contributing an engine, and reading the enabled ones.backendsInProcessBackend, BaseBackendConfig, BackendStatus, BackendHealth, BackendModel, ModelListingNotSupported, deduplicate, list_backends() (every enabled backend, highest priority first: what GET /api/backends/enabled returns for it, credentials redacted, plus execution_device ("this_host_gpu", "no_gpu", "remote" or "unestablished"), max_concurrent_runs and vram_total_gb / vram_free_gb; the VRAM is known only for a local native backend on the GPU this process monitors and is None otherwise; a backend that is enabled but not running reports "unestablished" and a None capacity; not user-scoped: it returns what GET /api/backends/enabled returns to any signed-in user)
Cloud — contributing a hosted-model provider, reading the enabled models and pricing a run.cloud, .cloud_testingestimate_cloud_cost(user, model_id, shots, driver=None) (what a run of shots on an enabled cloud model would cost, the answer of POST /api/cloud/models/{model_id}/estimate; each shot is the route's {"task", "params"}; administrators only, PermissionError for anyone else; ModelNotFoundException for a model that is not an enabled cloud model), DirectorEstimateError (a ValueError: the shots it cannot price), enabled_cloud_models(backend_id) (the CloudCatalogEntry of each model turned on in a cloud backend's catalog, by slug: model_id, label, provider_model_id, tasks, outputs and its spec), resolve_cloud_model(model_id) (a ResolvedCloudModel: the backend_id, driver and catalog entry of an enabled cloud model, with its spec; None when no enabled cloud backend offers it), CloudCatalogEntry, ResolvedCloudModel (none of these reads carries a backend credential; the two catalog reads are unscoped: they do not check that a given user may reach a model, which submit_generation does and visible_model_ids(user_id) lists), and the provider kit: register_cloud_provider, CloudProvider, CloudBackendConfig, CloudHttp, CloudModelSpec, ParamSpec, MediaInputSpec, PriceLine, CloudRequest, CloudJob, CloudStatus, CloudResult, CloudArtifact, CloudCost, CloudHealth, CloudError, LocalMedia, CANONICAL_PARAMS, MEDIA_ROLES, TASK_KINDS, CLOUD_BLOCKS, spec_problems, valid_specs, load_catalog_file, encode_media, decode_inline, default_error_mapper, and (from .cloud_testing) FakeCloudProvider, FakeCloudConfig, FakeBehaviour, FakeClock, ContractCase, run_contract, CONTRACT_CHECKS, fake_director_specs, fake_video_bytes, TINY_PNG, bind_plugin_backend
Pipes — contributing a pipeline step.pipesBasePipe, PipeInput, PipeOutput, PipeInputSpec, PipeOutputSpec, PipeConfigSpec, IOType, GenerationOutput, ImageGenerationOutput, VideoGenerationOutput, MeshGenerationOutput, GalleryGenerationOutput, ProgressGenerationOutput, TextGenerationOutput, TextArtifactAction, ComfyUIWorkflowGenerationOutput, GenerationExecutionError, Icon, Progress, logger, OutputTypeSpec, SerializeContext, output_type_registry, DuplicateOutputTypeError, PreEncodedReference (an already VAE-encoded reference a pipe hands to a reference_latents input), MAX_BUNDLE_COPIES (the most copies a prompt resource bundle row may ask for)
Native engine — driving generation through the in-process engine directly.nativeConditioning, GeneratorContext, GeneratorKrea2Pipe, NativeGeneratorHandle, ProgressEmitter, native_step_hooks, load_native_component(path, kind) (one component file, such as a vae, loaded on the CPU by the engine's own loader and returned as its wrapper: .module, move_to(device), unload())
Presets — finding a preset, starting a generation.presetsPresetCollaborators, preset_operations, FilePresetRepository, GenerationRequest, PromptPair, PresetMedia, GalleryItem, lint_preset_dir, PRESET_MEDIA_MAX_BYTES and PRESET_COVER_VIDEO_MAX_BYTES (the byte budgets the preset linter warns above for any preset media file and for a video cover), downscale_and_save_webp, preset_template(preset_id) (a deep copy of a loaded preset as its loader built it, a PresetTemplate whose fields follow the loader and are not yet a stable contract, or None), resolve_preset_path(preset_id, reference) (a path the preset names, with its {{ paths.preset }} and {{ paths._shared }} variables filled and resolved; None unless it stays inside the preset's folder or the shared presets folder), preset_install_state(preset_id) (a PresetInstallState: whether the preset is installed and assigned to anyone), describe_preset (a loaded preset's name, vars and modes, each with its default form and every form's fields as type + required + multi, and its engine, category and requires; None when no preset with that id is loaded, installed or not), list_presets(user) (a PresetDescription of each installed preset the user may run, the only one of these preset reads scoped to a user: describe_preset, preset_template, resolve_preset_path and preset_install_state take no user; see Reading presets), PresetDescription, ModeDescription, FieldDescription, bind_director_media(request, role, media, segment_id=None, promote=False, *, at=None, capabilities=None, field=None) (puts a resolved image, from resolve_media_ref or extract_frame, into the request's Video Director document, keeping the rest of it. A single-shot document takes it as its first or last frame; with promote=True a first frame turns a text-only shot into a start-image shot and a last frame turns a start-image shot into a first-and-last shot. A director document takes first or last on segment_id, or a keyframe at at seconds from the start of that segment, as the preset's director mode allows: see media in docs/video-director.md. Role reference adds one media or a list of them (images, videos, audio tracks) to the reference pool of the preset mode, the form field field or the first of its reference_fields, and with segment_id cites them in that segment's prompt: see references. capabilities defaults to the preset's vars.video_director for the request's mode, read from the running application: a director document or a reference bound before the application has started, such as in a plugin's own unit tests, raises the container's RuntimeError unless capabilities is given. Raises DirectorBindingError with a code), RequirementBackendInfo (the resolved backend a RequirementContext carries: id, engine, driver, config)
Forms — the field types core ships.formscore_field_type_names() (the names of every core non-container field type, e.g. to validate a field_type a form-building tool is handed)
Generation — submitting, previewing, following and reading generations.generationsubmit_generation, preview_memory, cancel_generation, generation_state, generation_record, generation_failure (administrators only), generation_active, list_generation_files, resolve_media_ref, get_session, get_session_snapshot, GenerationRequest, MediaRefError, SessionNotFoundError, IdempotencyKeyConflict, and the errors submit_generation and preview_memory let through, to catch by type: FormBindingError (a ValueError: the form does not bind), FormNotFoundException (no form of that name), NoBackendForEngineError and NoEligibleBackendError (both RuntimeError: no backend can run the request)
Compute — renting GPU compute for a Remote Native worker.computeComputeProvisioner, ComputeProvisionerError, ComputeStatus, ProvisionRequest, ProvisionResult, ProvisionProgress, ProgressReporter, ComputeFieldDescriptorV1, ComputeFieldOptionV1, COMPUTE_STATES, STATE_*, STAGE_*, COMPUTE_HOOKS
Storage — keeping data.storagedb, generate_ulid, plugin_settings, Settings, SettingRepository, PluginRepository
Testing — running your plugin's tests against a scratch database.testingscratch_database(path, *, core_schema=True) (a new database in the file path, created on the spot: FileExistsError when the file already exists, ValueError for the application's own database file even before it exists; it carries the tables of every core migration, or no table at all with core_schema=False, and it is not the application's database until use_database makes it so), use_database(database) (a with block during which db and every repository behind this API read and write database; the database in place before comes back when the block ends, even when it raises). Both are loaded the first time a test asks for them, never by importing src.plugin_api. See Testing your plugin against a scratch database
Media.mediaconvert_image_to_base64, BackgroundMattingModel, probe_video (a VideoProbe from ffprobe, or None), transcode_video(src, dest, TranscodeSpec(...), max_bytes=None) (ffmpeg re-encode to webm VP9 or mp4 H.264: constant frame rate, even dimensions, no audio unless keep_audio; steps down a quality ladder to fit max_bytes; raises VideoTranscodeError, or FfmpegUnavailableError before writing anything when ffmpeg is missing), find_ffmpeg, TranscodeSpec, VideoProbe, StreamingMp4Writer(out_path, width, height, fps) (pipes RGB uint8 frames to ffmpeg into a video-only MP4; write, close, abort, or a with block; raises FFmpegNotFoundError when ffmpeg is missing), has_audio_stream(path), mux_audio_from_source(video_only, source, out_path) (video of one file plus audio of another, stream-copied or AAC; returns False and leaves no partial file when there is no audio or ffmpeg fails), the frame schedule of frame interpolation, the one interpolator/rife uses: source_per_output(src_fps, factor=2, target_fps=0.0) (source frames per output frame, an exact Fraction: 1/factor, or src_fps/target_fps with both rates as fractions), output_fps(src_fps, factor=2, target_fps=0.0), output_count(n_source, ratio) (output frames for n_source source frames, the duration kept) and slot(index, ratio) (a Slot: output frame index lies between source frames left and left + 1 at t in [0, 1), t snapped to 0 within 1e-3), so two interpolators given the same clip place the same frames, NTSC rates on long clips included; extract_frame(user, ref, at="last", purpose="user_upload") and save_user_media(user, path, purpose="user_upload") (async; one frame of a video the user may see, or a file the plugin wrote, stored as the user's upload and returned as a StoredMedia; see Working with the user's media), media_local_path(user, ref) (the path on this server of the file of a media the user may see, or None when the storage keeps it elsewhere), copy_media_file(user, ref, target) (streams that file into a file of the plugin), upload_formats() (the file extensions the Library takes, by media_type), StoredMedia, and the media reference names of .generation: resolve_media_ref, MediaRefError, HistoryMediaRef, LibraryMediaRef, ResolvedMedia; and the image models of the application, for images the plugin holds: image_embedder() and embed_images(images) (SigLIP vectors, L2-normalized), face_detector() and detect_faces(images, min_score=0.5) (YuNet face boxes with five landmarks), face_embedder() and embed_faces(faces) (AuraFace identity vectors of faces given with their landmarks; see Image vectors and faces)
Models — model metadata fields, provider links, resolving a model's file/folder across roots, and acting on catalog models.modelsWellKnownModelMetadataField, get_model_provider_info, ModelFileUnavailable (raised by resolve_model_file when the model's file is not reachable), model_type_dirs, model_write_dir, resolve_model_file, model_for_path(path, admin=False), model_for_sha256(sha256, *, size=None, hash_candidates="background", admin=False) (the indexed model with that hash, or None; pass the file's size in bytes and a local copy that has not been hashed yet but has exactly that size can match as well: "background" queues at most eight of those candidates per call at the normal, rate-capped priority and answers None until they are done, "paced" verifies at most two of them through the rate-capped pool, waiting up to 15 minutes, "inline" hashes up to eight of them before answering at full speed, "never" only looks; ValueError for any other mode; unscoped; both leave out the operational fields - location, file size, hash - unless admin=True, for a caller that has checked the user is an admin), the hook model_index.after_digests (payload model_ids, at most once every 5 seconds: files finished being hashed, so a model's sha256 is now known), visible_model_ids(user_id) (the models assigned to a user, directly or through their groups), assign_model_to_user(model_id, user_id) (True when newly assigned; fires model_index.before_assign / after_assign; raises ModelAssignmentException), update_model_metadata(model_id, values) (sets some shared attribute values, validated against the type's definitions; raises InvalidModelMetadataException, ModelNotFoundException), run_provider_fetch(provider, model_ids) (async; hashes any model that has no digest yet, one after another, then fills empty description, triggers, tags and previews from a provider plugin; {"successful", "failed", "errors"}; raises ProviderFetchException for an unknown or uninitialised provider, or a model_index.before_fetch_info veto), ProviderFetchException, directory_aliases(), type_for_folder_name, model_types() (the registered model types, plugin types included, read at call time), HeaderView, TensorInfo, FamilyMatch, model_classifier_registry (read-only)
Downloads — queueing a download and following it.downloadsqueue_model_download(url, *, filename=None, model_type=None, subdir=None, tags=None, checksum_sha256=None, provider_id=None, created_by=None, destination_backend_id=None) (async; the queued download as a dict; raises DownloadQueueException, or its UnsafeFilenameException and DownloadDestinationInvalid subtypes - the latter when the subfolder, directory or remote backend cannot be used, as opposed to a queue that is blocked), get_download(download_id) (the download's current state, or None), DownloadNotFoundException. Declare the download.after_complete hook to be told when a download has landed (download_id, created_by ...; model_id or duplicate_of only for a plain local model download, the one kind indexed on completion)
User groups — groups, membership, and the NSFW policy a user gets.groupslist_groups(), get_user_groups(user_id), group_member_ids(group_id) (groups are {"id", "name", "is_system", "content_policy"} dicts), effective_content_policy(user_id) ("allowed", "blur" or "blocked": the instance setting made stricter by the user's groups), assign_models_to_group(group_id, model_ids, acting_user) (the ids newly assigned, through the group operation and its hooks in that admin's name; ValueError for a non-admin actor or an unknown group)
Notifications — telling users something happened.notificationsnotify(*, source, title, message="", user_id=None, type="", level="info", category="plugin", metadata=None, transient=False, show_toast=True) (how many users received it; user_id=None broadcasts; a registered type respects each user's preferences), register_notification_types(registry, specs) (from a notification_type.register handler; returns the keys it added), NotificationTypeSpec, NotificationTypeRegistry, DuplicateNotificationTypeError. The notification_type.register hook runs at startup for the enabled plugins and, for a plugin an admin enables while the app runs, at that enable, so its types (and their admin_only) apply without a restart. It runs once per plugin and process: types are never unregistered, so a disabled plugin's types stay declared, and a re-enable does not run it again; types a plugin update adds are declared at the next restart
Auto-organize — contributing rule conditions and actions.organizeOrganizeItem, OrganizeChange, OrganizeActionBlocked, OrganizeActionSkipped, OrganizeActionRetry, compare, FACT_KINDS, OPERATOR_LABELS, CONFIG_FIELD_KINDS, FACT_TRIGGERS, SQL_ALIASES, SUBJECTS
Limits — contributing a plan limit kind, and reading where a user stands.limitsLimitKind, Usage, Refusal, MeasureContext, RefusalContext, AdmissionRequest, LimitEvents (record(user_id, kind, units=1, ref_id=None), refund(ref_id)), LimitEventsView, LimitExceeded, limit_status(user_id, kind) (a LimitStatus: limit (None when nothing limits the user for that kind), used in the current window, exempt, resets_at, contact_line, plus limited and remaining; for a plugin that admits its own operations against a kind it measures itself)
Phrasebook — contributing a batch tool to Find & replace.phrasebookPhrasebookBatchOperation, PhrasebookBatchContext, BatchOutcome, BatchPreview, BatchOperationError
Sampling — contributing a step algorithm or a sigma schedule.samplingSamplerDefinition, ScheduleDefinition, ScheduleContext, OptionSpec, GuidanceStrategy, SamplingCancelled, run_hooks, sample_euler, sampler_registry, schedule_registry
Filters — contributing a photo filter op with a Python counterpart.filtersColourOp, SpatialOp, apply_filter, compile_lut, parse_cube, validate_steps, Cube, CubeError
Setup — telling admins what to do after enabling the plugin.setupSetupCheck, SetupCheckContext, SetupCheckResult

Each module's docstring explains what its exports are for; this table is the index.