Metadata-Version: 2.4
Name: swarm-bee
Version: 1.0.2
Summary: Python client for the Swarm Bee API. Functional parity with bee-js / bee-go / bee-rs.
Project-URL: Homepage, https://github.com/ethswarm-tools/bee-py
Project-URL: Repository, https://github.com/ethswarm-tools/bee-py
Project-URL: Issues, https://github.com/ethswarm-tools/bee-py/issues
Project-URL: Changelog, https://github.com/ethswarm-tools/bee-py/blob/main/CHANGELOG.md
Author: Calin Martinconi
License: MIT License
        
        Copyright (c) 2026 Calin Martinconi
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Keywords: bee,decentralised,ethereum,storage,swarm
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: coincurve>=20.0
Requires-Dist: eth-hash[pycryptodome]>=0.7
Requires-Dist: httpx>=0.27
Requires-Dist: typing-extensions>=4.12; python_version < '3.11'
Requires-Dist: websockets>=13.0
Description-Content-Type: text/markdown

# bee-py

Python client for the [Swarm](https://www.ethswarm.org/) Bee API.
Async-first (`httpx`), Python 3.10+, fully type-checked (`mypy --strict`).

The functional target is parity with [bee-js] (canonical TypeScript
client), [bee-go] (typed Go port), and [bee-rs] (Rust port). bee-go is
the primary reference for shape and behavior; bee-js is the source of
truth for wire-format edge cases.

> **Status:** stable (`1.0`). Functional parity with bee-js, bee-go,
> and bee-rs at Bee API `8.0.0`. 407 tests, mypy --strict clean,
> 42 example apps in `examples/`.

## Install

```bash
pip install swarm-bee
# or
uv add swarm-bee
```

The PyPI distribution name is `swarm-bee` (the natural `bee-py` was
blocked by PyPI's typosquat protection — too close to the unrelated
`beepy` project). The GitHub repo is still `ethswarm-tools/bee-py` to
match the bee-go / bee-rs sibling naming, and the import name is
`bee`:

```python
from bee import Bee, AsyncBee
```

## Quick start (async)

```python
import asyncio
from bee import AsyncBee

async def main() -> None:
    async with AsyncBee("http://localhost:1633") as client:
        health = await client.debug.health()
        print(f"bee {health.version} api {health.api_version}")

asyncio.run(main())
```

## Quick start (sync)

```python
from bee import Bee

with Bee("http://localhost:1633") as client:
    health = client.debug.health()
    print(f"bee {health.version} api {health.api_version}")
```

Both clients share the same surface — `Bee` wraps `AsyncBee` with
`httpx.Client` instead of `httpx.AsyncClient`. Choose whichever fits
your codebase.

## Layout

| Module           | bee-go counterpart  | Scope                                                |
| ---------------- | ------------------- | ---------------------------------------------------- |
| `bee.swarm`      | `pkg/swarm`         | Typed bytes, BMT, SOC, BZZ/DAI, Duration, Size, errs |
| `bee.api`        | `pkg/api`           | Upload/download options, pin, tag, grantee, envelope |
| `bee.file`       | `pkg/file`          | Data/file/chunk/SOC/feed/collection uploads          |
| `bee.postage`    | `pkg/postage`       | Batch CRUD, pure stamp math                          |
| `bee.debug`      | `pkg/debug`         | Health, versions, accounting, chequebook, stake      |
| `bee.pss`        | `pkg/pss`           | PSS send/subscribe/receive (websocket)               |
| `bee.gsoc`       | `pkg/gsoc`          | GSOC send/subscribe + offline SOC address            |
| `bee.manifest`   | `pkg/manifest`      | Mantaray trie, v0.2 wire format, `ResourceLocator`   |
| `bee.storage`    | _bee-js only_       | High-level `buy_storage` / `extend_storage_*`        |
| `bee.dev`        | _bee-js only_       | `BeeDev` newtype around `Bee`                        |

## Bearer auth

```python
async with AsyncBee.with_token("http://localhost:1633", "abc123") as client:
    await client.debug.health()
```

Returns a client whose underlying `httpx` instance has
`Authorization: Bearer abc123` baked in. Sync mirror: `Bee.with_token`.

## Latency probe

```python
elapsed = await client.ping()  # round-trip /health, returns seconds
```

Useful for connection-status indicators in dashboards / TUIs. Mirrors
bee-rs `Client::ping` / bee-go `Client.Ping`.

## Logging

Subscribe to the `bee.http` logger to see structured request/response
events (one per HTTP call):

```python
import logging
logging.basicConfig(level=logging.DEBUG)
logging.getLogger("bee.http").setLevel(logging.DEBUG)
```

Each record carries `method`, `url`, `status`, and `elapsed_ms`
extras. Mirrors the bee-rs `tracing` target `bee::http`.

## Examples

The `examples/` directory contains 42 ready-to-run scripts mirroring
bee-rs / bee-go (basic_usage, quickstart, status, key_gen,
upload_picture, download_picture, encrypted_upload, redundant_upload,
feed_update, feed_history, feed_manifest, soc_write_read, pss_send_receive,
gsoc_mined_pubsub, manifest_add_file, manifest_move_file, ens_locator,
stamp_cost{,_live}, stamp_utilization, list_batches, buy_batch,
pinning_workflow, tag_upload_progress, stamper_client_side, act_share,
swarm_paste, swarm_chat, swarm_blog, swarm_share, swarm_vault,
swarm_pinner, swarm_relay, swarm_deploy, swarm_fs, swarm_keyring,
swarm_feed_rss, swarm_cost_monitor, encrypted_folder_walk,
upload_directory, …) plus an end-to-end `integration_check.py`.

### AI / ML starter examples

Six additional examples target the AI workflow surface — content
addressing fits ML datasets, feed manifests fit prompt versioning, and
SOCs fit deterministic embedding caches:

- `swarm_dataset` — pin a dataset file or HF-style folder; the
  reference IS the integrity check.
- `swarm_prompt_registry` — feed-versioned prompt store; a stable
  manifest URL lets production hot-swap prompts without redeploy.
  Includes a LangChain `PromptTemplate` integration sketch.
- `swarm_mcp_bridge` — MCP server (Anthropic Model Context Protocol)
  exposing Bee primitives as tools, so an MCP client can use Swarm
  as a content-addressed store. Optional dep: `uv add 'mcp[cli]>=1.0'`.
- `swarm_embedding_cache` — `keccak256(text)` → embedding bytes via
  SOC. The cache address is deterministic from `(text, owner)` —
  no index lookup needed. Includes a numpy round-trip example.
- `swarm_agent_memory` — append-only chat history per agent ID via
  feeds. JSON `{role, text, ts}` payloads, OpenAI-style roles.
- `swarm_rag_corpus` — pin a docs folder; walk the manifest to
  enumerate paths; fetch one doc by path. Includes a LangChain
  `DocumentLoader` integration sketch.

### Running examples

Run any example with `uv run python examples/<name>.py`. Most need
`BEE_BATCH_ID` (a usable postage batch); some also need
`BEE_SIGNER_HEX` (a 32-byte hex private key).

## Stack

- `httpx` (async + sync HTTP), `websockets` for live subscriptions
  (TBD)
- `coincurve` (libsecp256k1 C bindings) for ECDSA — same C-bindings
  perf story as bee-rs v1.2.0
- `eth-hash[pycryptodome]` for keccak256
- Standard-library `dataclasses`, `enum`, `tarfile` for structured
  payloads — no `pydantic` dependency

## Bee version compatibility

This client targets Bee `2.7.2-rc1` / API `8.0.0` (the values pinned
in `bee.debug.SUPPORTED_BEE_VERSION_EXACT` and
`bee.debug.SUPPORTED_API_VERSION`). At startup, prefer
`client.debug.is_supported_api_version()` for a major-compatible check
or `client.debug.is_supported_exact_version()` for a strict pin.
Older or newer Bee instances usually work — unknown response fields
are ignored — but new endpoints will return 404 and breaking
wire-format changes will surface as `BeeJsonError`.

## Roadmap

| Milestone | Scope                                                                            |
| --------- | -------------------------------------------------------------------------------- |
| `0.1.x`   | Primitives (typed bytes, BMT, SOC), client plumbing, `debug.health/versions` ✅  |
| `0.2.x`   | Bytes / file upload + download (CAC, SOC, plain reference) ✅                   |
| `0.3.x`   | Postage batches, stamp math, `Stamper` ✅                                       |
| `0.4.x`   | Mantaray manifest, collection upload/download, `ResourceLocator`                 |
| `0.5.x`   | Feeds, GSOC, PSS                                                                 |
| `0.6.x`   | Full `bee.api` (pin, tag, grantee, envelope, stewardship)                        |
| `0.7.x`   | `bee.debug` (accounting, chequebook, stake, transactions, topology) ✅          |
| `0.8.x`   | Value primitives (`Bzz`/`Dai`/`Duration`/`Size`/`FileChunker`/`Cid`) ✅          |
| `0.9.x`   | High-level glue (`storage` helpers, `AsyncChunkStream`, `stream_directory`) ✅  |
| `1.0.0`   | Functional parity with bee-js / bee-go / bee-rs at API `8.0.0`; with_token, ping, `bee.http` logging, `bee.dev` ✅ |

## Development

bee-py is `uv`-managed. Install [uv] once:

```bash
curl -LsSf https://astral.sh/uv/install.sh | sh
```

Then in this repo:

```bash
uv sync                    # create venv + install deps
uv run pytest              # run tests
uv run ruff check          # lint
uv run ruff format --check # format check
uv run mypy                # type check
```

## License

MIT — see [LICENSE](./LICENSE).

[bee-js]: https://github.com/ethersphere/bee-js
[bee-go]: https://github.com/ethswarm-tools/bee-go
[bee-rs]: https://github.com/ethswarm-tools/bee-rs
[uv]: https://github.com/astral-sh/uv
