PotionUI Docs v0.3.0

Contributing Auto-organize facts and actions

Auto-organize lets each user write rules that file their own generations, Library uploads and models: "when a new image is made with Krea-2 at 1344 x 768, add it to Landscapes". A rule has one subject, a list of conditions (a fact, an operator and a value) matched with all or any, and a list of actions. A plugin adds facts and actions of its own; they appear in the rule builder with no frontend work, because the builder picks its control from the fact's kind.

On this page
yaml
organize_facts:
  - key: tagger.labels            # must be namespaced: <plugin>.<name>
    label: Image contains
    subjects: [generation, upload]
    kind: tag_list                # model_ref | enum | size | number | text | tag_list | bool | attribute
    operators: [has, has_not]     # optional, a subset of the kind's operators
    handler: organize.labels      # module.function, like hook handlers
    sql_handler: organize.labels_sql          # optional, makes previews exact and fast
    options_handler: organize.label_options   # optional, feeds the picker's autocomplete
    options: []                   # optional static choices: [{value, label}]
    picker: {}                    # optional hints for the control (see below)
    triggers: [item_created, tags_changed]

organize_actions:
  - key: tagger.notify
    label: Tell my webhook
    subjects: [generation]
    requires_admin: true          # anything that reaches outside the app
    handler: organize.notify
    undo_handler: organize.undo_notify       # optional
    config_schema:
      - {key: channel, kind: text, label: Channel, required: true}
    scope: user
    notes: []
    needs: []
    done_label: ""
    paced: false

scope is user (the default) or instance, notes are lines the editor shows in one info box, needs is [digest] to wait for a model's file hash, done_label is the summary of a finished run and paced marks an action that reaches an outside service; the last four are explained under "Instance actions".

Import only from src.plugin_api.organize. The reference implementation used by the tests lives at tests/fixtures/organize_example_plugin/.

Kinds, operators and values#

kindoperatorsvalue the rule storescontrol the builder showspicker keys
model_refis, is_any_of, is_nota model id, or a list for is_any_ofthe model pickermodel_types
enumis, is_any_of, is_nota string, or a list for is_any_ofchips or a select; autocomplete when there is an options_handlermulti
sizeis, at_least, at_most{"width": 1344, "height": 768}resolution presets + custompresets
numberis, at_least, at_mosta numbersteppermin, max, step, unit
textcontains, not_contains, starts_with, ends_with, is, is_nota string, matched case-insensitively; a core fact such as a model's name can also store ignore_separators: true on the condition to compare without - and _text inputplaceholder
tag_listhas (every listed value), has_not (none of them)a list of stringstag autocomplete-
boolistrue / falsetoggle-
attributeper attribute type, see below{"key", "type", "label", "value"}attribute picker, then the type's operators and controloperators_by_type

compare(kind, operator, actual, expected) is the exact function the evaluator uses, so a plugin can test its handler against it. When a fact returns a list (one value per output of a multi-file generation), a condition matches when any value matches. not_contains and is_not match when no value matches, so an item without the value matches them.

The attribute kind#

An attribute fact is a set of named, typed values on each item, such as the custom attributes admins define for models. The user picks one attribute, then compares its value with the operators of the attribute's type:

typeoperatorsvaluematching
numberis, at_least, at_mosta numbera [low, high] range counts as an interval: is means inside it, at_least compares high, at_most compares low
textthe text operatorsa stringa list of strings (tags) matches like a multi-value text fact
boolistrue / falsea missing value counts as false
enumis, is_any_of, is_nota string, or a list for is_any_ofcase-insensitive

ATTRIBUTE_VALUE_OPERATORS in src.plugin_api.organize holds this table. An attribute fact must have an options_handler, and it lists the attributes rather than values: each entry is {"value": key, "label": label, "meta": {...}}, where meta has type (one of the four above), type_label (shown next to the name in the picker), model_types (the model types it applies to, empty for every type), choices ([{value, label}], for enum) and optional min, max, step (for number). The host calls it when a rule is saved or previewed: the condition's key must be listed, and the stored type and label come from the listing, not from the client. The handler gets the caller's user_id, so leave out attributes the caller may not see.

The fact handler returns a dict of attribute key to that item's value. The sql_handler receives the whole {"key", "type", "label", "value"} dict as value. Set picker: {operators_by_type: {...}} only to narrow the operators per type.

The handlers#

  • Fact handler(item) -> value receives an OrganizeItem (subject, item_id, user_id, read-only data) and returns the value for its kind. It must be pure and fast: no network, no writes. item.data holds, for generations: preset_id, mode, backend_id, form_data, model_ids, files (file_type, width, height, duration_seconds, mime_type, is_final) and tags; for uploads: media_type, mime_type, width, height, duration_seconds, original_filename and tags; for models: filename, model_type, family, sha256, tags, file_size (bytes), description, custom_name (the rule owner's own name for it), provider_names, provider_descriptions, sources (local, cloud or provider ids such as civitai) and attributes (each attribute's value for the rule owner: their own value for a per-user attribute, else the shared value, else the default). Reading your own plugin tables with from src.plugin_api import db inside the handler is fine.
  • Fact sql_handler(operator, value, alias) -> (clause, params) | None returns a SQL predicate over the subject's table, aliased per SQL_ALIASES (g = generations, u = uploads, m = models). viewer.user_id is the rule owner's id, for per-user data. It turns the preview count into one query. Without it, previews evaluate items one by one and say "about" past 5,000 items.
  • Fact options_handler(user_id, subject, query) -> list returns strings or {value, label} dicts, plus an optional meta dict that reaches the client as is. It is called with a 2 second budget.
  • Action handler(item, config, user_id) -> list[OrganizeChange] does the work for one matching item and returns what it changed (target_type, target_id, target_name, data). Return only what is new, and make it idempotent: the same item can be offered again after a restart. The list is recorded so the Activity tab can show it and undo it. Raise OrganizeActionBlocked(code, message) to stop the rule and pause it with a notice.
  • Action undo_handler(item, change, user_id) -> bool reverses one recorded change. Without it, undoing a run leaves that plugin's changes in place and counts them as skipped.
  • Outcomes. A handler that returns normally has done its job (an empty list means there was nothing new). It can say more by raising: OrganizeActionBlocked(code, message) stops the rule and pauses it with a notice; OrganizeActionSkipped(code, message) is permanent for this item: the item counts as done, the other actions of the rule still run, and the run lists the item as skipped with the message; OrganizeActionRetry(code, message, after_s=None) is transient: the item is not done, the rule's remaining actions are not run for it, and the run lists it as waiting. The host tries a waiting item again after 5, 15, 60 and 240 minutes (or after_s seconds), and after five attempts turns it into a skip with the code gave_up. Any other exception counts as a retry with the code error; it never marks the item done.

Instance actions#

scope: instance makes an action part of the instance-wide rules admins keep under Admin, Models, Auto-organize (/api/admin/organize/instance/...). Such a rule belongs to nobody: the handler gets user_id=None, runs as the system, and the run records which admin started it. An instance action is never offered to users, and a user action is never offered to instance rules. Instance actions are for the model subject only.

  • needs: [digest] makes the host call the handler only once the model's sha256 is known. Until then the model is recorded as waiting (unverified) and the host runs the action when model_index.after_digests reports the file; the host never hashes a file to satisfy it.
  • paced: true marks an action that calls an outside service. Such a rule is exempt from the hourly "filed N items" pause, and a run applies it in small steps so progress moves per item. Keep the handler idempotent and raise OrganizeActionRetry for outages.
  • notes and done_label are text for the editor and the run summary.

triggers says when the fact's value can first be known: item_created, or also tags_changed for a value that arrives later (an auto-tagger), or metadata_changed for a model value that changes when its description, attributes, provider info or a user's own name for it is edited (model_index.after_update_metadata), or detected_tags_changed for a generation value written by Media Tagging (media_index.after_tags_written). Rules using such a fact are evaluated again on those changes, for items the rule has not filed yet. A fact whose triggers leave out item_created, like the built-in Detected tags, is not evaluated when the item is created: a rule using it first runs when its event arrives, so a "does not have" test cannot file an item before its tags exist.

What the host guarantees#

  • A rule only ever reads its owner's items and writes to its owner's collections and tags. Plugin actions receive the owner's user_id and must hold to the same rule.
  • An action with requires_admin: true is hidden from non-admins and refused when a non-admin saves a rule with it.
  • Disabling the plugin removes its facts and actions. Rules that use them stay, marked "needs attention", and run again when the plugin is back.
  • A rule files each item at most once, and a live rule that files more than the hourly limit (200 by default) is paused with a notice.