2.26.5.43. pycsamt.agents.plugins#

Plugin interfaces for the pyCSAMT agent loop.

The agent loop (router, orchestrator, provenance) depends on three domain-specific pieces. This module names them as typing.Protocol classes so another package can supply its own domain without forking pycsamt.agents:

  • WorkflowRegistry - which workflows exist, how free text is classified into one, and which agent steps run for it;

  • PlanValidator - which plans are blocked, which need human review, and the deterministic route cross-check;

  • RecordWriter - the run record (events, snapshot, persistence) and the retrieval-corpus manifest hook.

A DomainPlugin bundles one of each. Plugins are registered with register_plugin() or advertised through the entry-point group pycsamt.agent_plugins and found by discover_plugins(). get_plugin() returns one by name; with no name it returns the built-in "pycsamt" plugin, whose adapters delegate to the existing tables and functions, so the default agent behaviour is unchanged.

The module itself uses the standard library only; the built-in adapters import pycsamt.agents internals lazily, at call time, so that patching those module attributes (as the test-suite does) keeps working.

Writing a plugin#

Implement the three protocols with plain classes (no inheritance is needed; the protocols are structural), bundle them, and register:

>>> from pycsamt.agents.plugins import (
...     DomainPlugin, get_plugin, register_plugin)
>>> base = get_plugin()
>>> demo = DomainPlugin(
...     name="demo", registry=base.registry,
...     validator=base.validator,
...     record_factory=base.record_factory)
>>> register_plugin(demo, replace=True) is demo
True
>>> get_plugin("demo").name
'demo'

To ship it from another distribution, declare an entry point that resolves to a DomainPlugin instance or to a zero-argument callable returning one:

[project.entry-points."pycsamt.agent_plugins"]
mtpy = "my_package.agent_plugin:make_plugin"

See examples/agent_plugins/mtpy_example in the repository for a complete plugin.

Module Attributes

ENTRY_POINT_GROUP

Entry-point group scanned by discover_plugins().

DEFAULT_PLUGIN

Name of the built-in plugin returned by get_plugin().

Step

One dispatch step: (step_name, agent_class_name, input_fn, description[, required]), the tuple shape the orchestrator runs.

Functions

available_plugins()

Return registered plugin names mapped to their descriptions.

discover_plugins()

Load plugins advertised in ENTRY_POINT_GROUP.

get_plugin([name])

Return the plugin called name (built-in when None).

register_plugin(plugin, *[, replace])

Register plugin under plugin.name.

Classes

DomainPlugin(name, registry, validator, ...)

Bundle of the three pieces one domain supplies.

PlanValidator(*args, **kwargs)

Gate that decides whether a plan may run.

RecordWriter(*args, **kwargs)

Append-only run record written next to the outputs.

WorkflowRegistry(*args, **kwargs)

Catalogue of workflows a domain offers to the agent loop.

pycsamt.agents.plugins.ENTRY_POINT_GROUP = 'pycsamt.agent_plugins'

Entry-point group scanned by discover_plugins().

pycsamt.agents.plugins.DEFAULT_PLUGIN = 'pycsamt'

Name of the built-in plugin returned by get_plugin().

class pycsamt.agents.plugins.WorkflowRegistry(*args, **kwargs)[source]

Bases: Protocol

Catalogue of workflows a domain offers to the agent loop.

Variables:
  • name (str) – Short identifier of the registry (normally the plugin name).

  • descriptions (Mapping[str, str]) – Every known workflow id mapped to a one-line description. Ids absent from this mapping are unknown and get blocked.

  • valid_workflows (frozenset of str) – Ids that go through the plan gate (validation and review). Known ids outside this set are dispatched on other paths (plots, tools) without a plan.

  • dispatchable (frozenset of str) – Ids that have a step chain, i.e. for which steps() returns a sequence.

Notes

Implementations must be deterministic: the same text always classifies to the same id, because the cross-check and the paper’s offline router rows rely on it.

name: str
property descriptions: Mapping[str, str][source]
property valid_workflows: frozenset[str][source]
property dispatchable: frozenset[str][source]
classify(text, *, default=None)[source]

Return the workflow id text asks for, or default.

Parameters:
  • text (str)

  • default (str | None)

Return type:

str | None

family(workflow)[source]

Return the analysis family of workflow (None in).

Parameters:

workflow (str | None)

Return type:

str | None

normalise(workflow)[source]

Return the canonical id for an alias or spelling.

Parameters:

workflow (str)

Return type:

str

steps(workflow)[source]

Return the dispatch steps of workflow, or None.

Parameters:

workflow (str)

Return type:

Sequence[tuple] | None

class pycsamt.agents.plugins.PlanValidator(*args, **kwargs)[source]

Bases: Protocol

Gate that decides whether a plan may run.

The orchestrator calls errors() first (any error blocks execution), then needs_review() (True requires the caller to approve the exact plan hash).

errors(plan)[source]

Return human-readable validation errors (empty = valid).

Parameters:

plan (Any)

Return type:

list[str]

needs_review(plan)[source]

Return True when the plan needs human approval.

Parameters:

plan (Any)

Return type:

bool

cross_check(text, intent, workflow)[source]

Router-level check of an LLM route against a keyword route.

Returns a reason string when the two routes disagree, else None.

Parameters:
  • text (str)

  • intent (str)

  • workflow (str | None)

Return type:

str | None

route_flags(text, workflow)[source]

Orchestrator-level cross-check, as plan risk flags.

Any returned flag is added to the plan’s risk_flags and therefore sends the plan to the review gate.

Parameters:
Return type:

list[str]

class pycsamt.agents.plugins.RecordWriter(*args, **kwargs)[source]

Bases: Protocol

Append-only run record written next to the outputs.

emit(event, **fields)[source]

Append one event with JSON-serialisable fields.

Parameters:
Return type:

None

snapshot()[source]

Return the record as a redacted, JSON-ready dictionary.

Return type:

dict[str, Any]

persist(path)[source]

Write the snapshot to path (and keep it updated).

Parameters:

path (str | Path)

Return type:

None

corpus_manifest()[source]

Return the manifest of the retrieval index, or None.

Return type:

Any

class pycsamt.agents.plugins.DomainPlugin(name, registry, validator, record_factory, description='')[source]

Bases: object

Bundle of the three pieces one domain supplies.

Parameters:
  • name (str) – Registry key, e.g. "pycsamt" or "mtpy_example".

  • registry (WorkflowRegistry) – Workflow catalogue and dispatch steps.

  • validator (PlanValidator) – Plan gate and cross-check.

  • record_factory (callable) – record_factory(payload) -> RecordWriter; payload is the request dictionary the run started from.

  • description (str, default "") – One-line summary shown by available_plugins().

Raises:

TypeError – If a member does not satisfy its protocol.

name: str
registry: WorkflowRegistry
validator: PlanValidator
record_factory: Callable[[dict], RecordWriter]
description: str = ''
pycsamt.agents.plugins.register_plugin(plugin, *, replace=False)[source]

Register plugin under plugin.name.

Parameters:
  • plugin (DomainPlugin) – The bundle to register.

  • replace (bool, default False) – Overwrite an existing plugin of the same name.

Returns:

plugin, so the call can be used as an expression.

Return type:

DomainPlugin

Raises:
  • TypeError – If plugin is not a DomainPlugin.

  • ValueError – If the name is taken and replace is false, or if the name is the built-in "pycsamt".

Examples

>>> from pycsamt.agents.plugins import get_plugin, register_plugin
>>> register_plugin(get_plugin())
Traceback (most recent call last):
...
ValueError: The built-in 'pycsamt' plugin cannot be replaced.
pycsamt.agents.plugins.get_plugin(name=None)[source]

Return the plugin called name (built-in when None).

Parameters:

name (str or None, default None) – Plugin name. None returns the built-in "pycsamt" plugin. An unknown name triggers discover_plugins() once before failing.

Return type:

DomainPlugin

Raises:

KeyError – If no plugin of that name is registered or discoverable.

Examples

>>> from pycsamt.agents.plugins import get_plugin
>>> p = get_plugin()
>>> p.name, p.registry.normalise("PINN")
('pycsamt', 'pinn_inversion')
pycsamt.agents.plugins.available_plugins()[source]

Return registered plugin names mapped to their descriptions.

Return type:

dict[str, str]

pycsamt.agents.plugins.discover_plugins()[source]

Load plugins advertised in ENTRY_POINT_GROUP.

Each entry point must resolve to a DomainPlugin or to a zero-argument callable returning one. Already-registered names are left alone. Discovery runs once per process; later calls only report.

Returns:

Entry-point name mapped to "loaded", "skipped" (name already registered) or the error message of a failed load. Failures are also logged at WARNING level; they never stop the agent loop.

Return type:

dict of str to str