Metadata-Version: 2.4
Name: pyspokes
Version: 0.1.0a7
Summary: Type-based spoke discovery and resolution for Python applications
Keywords: plugin,plugins,plugin-system,discovery,dependency-injection,hub,spokes
Author: AI Helpers
Author-email: AI Helpers <vasseur.corentin@gmail.com>
License-Expression: MIT
License-File: LICENSE.txt
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Dist: pyyaml>=6.0.1,<7
Requires-Dist: typer>=0.20.0,<0.21 ; extra == 'cli'
Requires-Dist: rich>=13.0.0,<16 ; extra == 'cli'
Requires-Python: >=3.13
Project-URL: Homepage, https://github.com/ai-helpers/pyspokes
Project-URL: Documentation, https://ai-helpers.github.io/pyspokes
Project-URL: Repository, https://github.com/ai-helpers/pyspokes
Project-URL: Issues, https://github.com/ai-helpers/pyspokes/issues
Project-URL: Changelog, https://github.com/ai-helpers/pyspokes/blob/main/CHANGELOG.md
Provides-Extra: cli
Description-Content-Type: text/markdown

![Tests](docs/_static/badges/test-badge.svg)
![Coverage](docs/_static/badges/coverage-badge.svg)

# pyspokes

pyspokes is a plugin system built around one idea: your application is the hub, and every implementation it can plug in is a spoke.
Packages declare their spokes in a `spokes.yaml` file, and the application asks the hub for the interface it needs.

See the full documentation at <https://ai-helpers.github.io/pyspokes>

## Table of Contents (ToC)

- [pyspokes](#pyspokes)
  - [Table of Contents (ToC)](#table-of-contents-toc)
  - [Usage](#usage)
  - [Concrete examples](#concrete-examples)
    - [A model gateway with local overrides](#a-model-gateway-with-local-overrides)
    - [One bucket, three clouds](#one-bucket-three-clouds)
  - [Getting Started](#getting-started)
    - [Prerequisites](#prerequisites)
    - [Install dependencies](#install-dependencies)
    - [Common tasks](#common-tasks)
    - [Build the documentation](#build-the-documentation)
  - [Contributing](#contributing)

## Usage

A package declares its spokes in a `spokes.yaml` file at its root:

```yaml
# notify_app/spokes.yaml
- path: channels.EmailNotifier
  name: email

- path: channels.SlackNotifier
  name: slack
  priority: 5
```

```python
# notify_app/channels.py
from notify_app.notifier import Notifier


class EmailNotifier(Notifier):
    def send(self, recipient: str, message: str) -> str:
        return f"email to {recipient}: {message}"


class SlackNotifier(Notifier):
    def send(self, recipient: str, message: str) -> str:
        return f"slack DM to {recipient}: {message}"
```

Once the package is installed, the application asks the hub for the interface and never imports
an implementation:

```python
from notify_app.notifier import Notifier
from pyspokes import get_spoke, get_spokes

notifier = get_spoke(Notifier)                 # highest priority: SlackNotifier
print(notifier.send("ada", "build finished"))  # slack DM to ada: build finished

email = get_spoke(Notifier, name="email")      # pick one by name
channels = get_spokes(Notifier)                # all of them, highest priority first
```

Adding a channel means installing a package that ships a `spokes.yaml`; the code above does not
change. The [quickstart](https://ai-helpers.github.io/pyspokes/quickstart.html) walks through the
whole example.

## Concrete examples

### A model gateway with local overrides

A platform team provides a chat model for the whole company. The catalog team must use a model
hosted on premises, and wants a cheaper one for summarising reviews. Neither team edits the
other's code, and the application is the same script throughout.

```text
platform/                      catalog/
├── pyproject.toml             ├── pyproject.toml
└── llm_platform/              └── catalog_llm/
    ├── __init__.py                ├── __init__.py
    ├── chat.py                    ├── models.py
    └── spokes.yaml                └── spokes.yaml
```

**The platform package** owns the interface and a default implementation:

```python
# llm_platform/chat.py
from abc import ABC, abstractmethod


class ChatModel(ABC):
    """Answer a prompt."""

    @abstractmethod
    def complete(self, prompt: str) -> str: ...


class HostedChat(ChatModel):
    def complete(self, prompt: str) -> str:
        return f"[hosted model] {prompt}"
```

```yaml
# llm_platform/spokes.yaml
- path: chat.HostedChat
```

`spokes.yaml` has to ship inside the package. With setuptools:

```toml
# platform/pyproject.toml
[build-system]
requires = ["setuptools>=77"]
build-backend = "setuptools.build_meta"

[project]
name = "llm-platform"
version = "0.1.0"
requires-python = ">=3.13"
dependencies = ["pyspokes"]

[tool.setuptools]
packages = ["llm_platform"]

[tool.setuptools.package-data]
llm_platform = ["spokes.yaml"]
```

**The catalog package** adds two models. One outranks the platform default; the other has the
default priority and is picked by name:

```python
# catalog_llm/models.py
from llm_platform.chat import ChatModel


class OnPremChat(ChatModel):
    def complete(self, prompt: str) -> str:
        return f"[on-prem model] {prompt}"


class SmallChat(ChatModel):
    def complete(self, prompt: str) -> str:
        return f"[small model] {prompt}"
```

```yaml
# catalog_llm/spokes.yaml
- path: models.OnPremChat
  priority: 10

- path: models.SmallChat
  name: reviews
```

Its `pyproject.toml` is the same with `catalog-llm` / `catalog_llm` as the names and
`dependencies = ["llm-platform"]`.

**The application** imports the interface only, and lets configuration pick a name:

```python
# describe_product.py
import os

from llm_platform.chat import ChatModel
from pyspokes import get_spoke

model = get_spoke(ChatModel, name=os.getenv("CHAT_MODEL"), required=True)
print(model.complete("Describe a steel water bottle"))
```

With only the platform package installed, the hub finds one `ChatModel`:

```text
$ pip install ./platform
$ python describe_product.py
[hosted model] Describe a steel water bottle
```

Install the catalog package and the same script changes behaviour:

```text
$ pip install ./catalog
$ python describe_product.py
[on-prem model] Describe a steel water bottle

$ CHAT_MODEL=reviews python describe_product.py
[small model] Describe a steel water bottle

$ CHAT_MODEL=legacy python describe_product.py
pyspokes.exceptions.SpokeNotFoundError: No spoke found for required type <class 'llm_platform.chat.ChatModel'> named 'legacy'.
```

`priority: 10` beats the default of 1, `name` narrows the candidates, and `required=True` turns
a typo into an error at startup instead of a silent fallback. More situations like this one are
in the [examples](https://ai-helpers.github.io/pyspokes/examples.html).

### One bucket, three clouds

An application saves reports to a bucket. Depending on the deployment, that bucket is on AWS,
Google Cloud or Azure. The application code is the same everywhere: each cloud is one package,
and switching means installing a different one.

A core package owns the interface and has no spokes:

```python
# storage_core/store.py
from abc import ABC, abstractmethod


class ObjectStore(ABC):
    """Keep files in a bucket."""

    @abstractmethod
    def put(self, key: str, data: bytes) -> str:
        """Store ``data`` under ``key`` and return where it went."""
```

Each cloud package implements it with its own SDK and declares one named spoke. The hub builds
spokes with no arguments, so each class reads its settings from the environment:

```python
# storage_aws/s3.py
import os

import boto3
from storage_core.store import ObjectStore


class S3Store(ObjectStore):
    def __init__(self) -> None:
        self.bucket = os.environ["REPORTS_BUCKET"]
        self.client = boto3.client("s3")

    def put(self, key: str, data: bytes) -> str:
        self.client.put_object(Bucket=self.bucket, Key=key, Body=data)
        return f"s3://{self.bucket}/{key}"
```

```python
# storage_gcp/gcs.py
import os

from google.cloud import storage
from storage_core.store import ObjectStore


class GcsStore(ObjectStore):
    def __init__(self) -> None:
        self.bucket = storage.Client().bucket(os.environ["REPORTS_BUCKET"])

    def put(self, key: str, data: bytes) -> str:
        self.bucket.blob(key).upload_from_string(data)
        return f"gs://{self.bucket.name}/{key}"
```

```python
# storage_azure/blob.py
import os

from azure.storage.blob import BlobServiceClient
from storage_core.store import ObjectStore


class AzureBlobStore(ObjectStore):
    def __init__(self) -> None:
        service = BlobServiceClient.from_connection_string(os.environ["AZURE_STORAGE_CONNECTION_STRING"])
        self.container = service.get_container_client(os.environ["REPORTS_BUCKET"])

    def put(self, key: str, data: bytes) -> str:
        blob = self.container.upload_blob(key, data, overwrite=True)
        return blob.url
```

```yaml
# storage_aws/spokes.yaml      # storage_gcp/spokes.yaml      # storage_azure/spokes.yaml
- path: s3.S3Store             - path: gcs.GcsStore           - path: blob.AzureBlobStore
  name: aws                      name: gcp                      name: azure
```

The application imports no SDK and names no cloud:

```python
# save_report.py
import os

from pyspokes import get_spoke
from storage_core.store import ObjectStore

store = get_spoke(ObjectStore, name=os.getenv("STORAGE_BACKEND"), required=True)
print(store.put("2026/11/sales.csv", b"store,total\nparis,1280\n"))
```

**Switch by installing.** Each deployment installs the package for its cloud, and only that
cloud's SDK comes with it:

```text
$ pip install ./storage-aws        # the AWS deployment
$ python save_report.py
s3://acme-reports/2026/11/sales.csv

$ pip uninstall storage-aws && pip install ./storage-gcp        # the Google Cloud deployment
$ python save_report.py
gs://acme-reports/2026/11/sales.csv
```

**Switch by configuration.** With several of them installed in one image, the name picks the
cloud at run time:

```text
$ STORAGE_BACKEND=aws python save_report.py
s3://acme-reports/2026/11/sales.csv

$ STORAGE_BACKEND=gcp python save_report.py
gs://acme-reports/2026/11/sales.csv

$ STORAGE_BACKEND=azure python save_report.py
https://acmereports.blob.core.windows.net/acme-reports/2026/11/sales.csv
```

When several stores are installed, always give a name (or distinct priorities): the three above
share the default priority, so without one the winner depends on discovery order. With none
installed, `required=True` stops the script with a `SpokeNotFoundError`.

The same split works for a database: an interface such as `OrderRepository` in the core package,
and one package per managed PostgreSQL (Amazon RDS, Cloud SQL, Azure Database for PostgreSQL),
each carrying its own driver settings and authentication.

## Getting Started

### Prerequisites

- Python 3.13+
- [uv](https://docs.astral.sh/uv/)

### Install dependencies

```bash
uv sync --all-groups
```

### Common tasks

Day-to-day commands are exposed as make tasks (run `make help` to list them all):

```bash
make check-tests     # run the unit tests with pytest
make checkers        # run all the checkers (lock, format, quality, types, coverage)
make formatters      # format the sources and tests with ruff
make badges          # regenerate the test and coverage badges shown above
make documenters     # build the documentation
```

### Build the documentation

The documentation is built with [Sphinx](https://www.sphinx-doc.org/) and the
[furo](https://github.com/pradyunsg/furo) theme, and is deployed to GitHub Pages
on every push to `main`.

```bash
make documenters
```

## Contributing

Contributions are welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for the development setup,
the checks to run before pushing, and the coding conventions.
