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
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: falsescope 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#
| kind | operators | value the rule stores | control the builder shows | picker keys |
|---|---|---|---|---|
model_ref | is, is_any_of, is_not | a model id, or a list for is_any_of | the model picker | model_types |
enum | is, is_any_of, is_not | a string, or a list for is_any_of | chips or a select; autocomplete when there is an options_handler | multi |
size | is, at_least, at_most | {"width": 1344, "height": 768} | resolution presets + custom | presets |
number | is, at_least, at_most | a number | stepper | min, max, step, unit |
text | contains, not_contains, starts_with, ends_with, is, is_not | a 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 input | placeholder |
tag_list | has (every listed value), has_not (none of them) | a list of strings | tag autocomplete | - |
bool | is | true / false | toggle | - |
attribute | per attribute type, see below | {"key", "type", "label", "value"} | attribute picker, then the type's operators and control | operators_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:
| type | operators | value | matching |
|---|---|---|---|
number | is, at_least, at_most | a number | a [low, high] range counts as an interval: is means inside it, at_least compares high, at_most compares low |
text | the text operators | a string | a list of strings (tags) matches like a multi-value text fact |
bool | is | true / false | a missing value counts as false |
enum | is, is_any_of, is_not | a string, or a list for is_any_of | case-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) -> valuereceives anOrganizeItem(subject,item_id,user_id, read-onlydata) and returns the value for its kind. It must be pure and fast: no network, no writes.item.dataholds, for generations:preset_id,mode,backend_id,form_data,model_ids,files(file_type,width,height,duration_seconds,mime_type,is_final) andtags; for uploads:media_type,mime_type,width,height,duration_seconds,original_filenameandtags; 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,cloudor provider ids such ascivitai) andattributes(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 withfrom src.plugin_api import dbinside the handler is fine. - Fact
sql_handler(operator, value, alias) -> (clause, params) | Nonereturns a SQL predicate over the subject's table, aliased perSQL_ALIASES(g=generations,u=uploads,m=models).viewer.user_idis 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) -> listreturns strings or{value, label}dicts, plus an optionalmetadict 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. RaiseOrganizeActionBlocked(code, message)to stop the rule and pause it with a notice. - Action
undo_handler(item, change, user_id) -> boolreverses 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 (orafter_sseconds), and after five attempts turns it into a skip with the codegave_up. Any other exception counts as a retry with the codeerror; 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'ssha256is known. Until then the model is recorded as waiting (unverified) and the host runs the action whenmodel_index.after_digestsreports the file; the host never hashes a file to satisfy it.paced: truemarks 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 raiseOrganizeActionRetryfor outages.notesanddone_labelare 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_idand must hold to the same rule. - An action with
requires_admin: trueis 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.