A high-performance inference engine for AI models
Bindings: Python (#369)
Aleksei Savind409ba3437d4
diff --git a/.github/actions/setup/action.yml b/.github/actions/setup/action.ymlindex 47738470b..e2f33440f 100644--- a/.github/actions/setup/action.yml+++ b/.github/actions/setup/action.yml@@ -22,12 +22,16 @@ inputs:description: "Additional Rust target to install"required: falsedefault: ''- node:- description: "Install Node + pnpm"+ bindings-napi:+ description: "Install requirements for bindings-napi"required: falsedefault: 'false'- swift:- description: "Install cargo-swift CLI"+ bindings-uniffi:+ description: "Install requirements for bindings-uniffi"+ required: false+ default: 'false'+ bindings-pyo3:+ description: "Install requirements for bindings-pyo3"required: falsedefault: 'false'@@ -70,7 +74,7 @@ runs:- if: inputs.nextest == 'true'uses: taiki-e/install-action@nextest- - if: inputs.test_data == 'true'+ - if: inputs.test_data == 'true' || inputs.bindings-pyo3 == 'true'uses: astral-sh/setup-uv@v7with:enable-cache: true@@ -90,18 +94,23 @@ runs:uv run export tokenizersshell: bash- - if: inputs.node == 'true'+ - if: inputs.bindings-napi == 'true'uses: actions/setup-node@v4with:node-version: "20"- - if: inputs.node == 'true'+ - if: inputs.bindings-napi == 'true'uses: pnpm/action-setup@v4with:version: 10.33.0# Please make sure to use compatible versions of the cargo-swift / uniffi pair.# See: https://github.com/antoniusnaumann/cargo-swift?tab=readme-ov-file#installing-for-a-different-uniffi-version- - if: inputs.swift == 'true'+ - if: inputs.bindings-uniffi == 'true'run: cargo install [email protected] -fshell: bash++ - if: inputs.bindings-pyo3 == 'true'+ run: |+ uv tool install maturin+ shell: bash\ No newline at end of filediff --git a/.github/workflows/tests.yml b/.github/workflows/tests.ymlindex 2de9c444e..435af8458 100644--- a/.github/workflows/tests.yml+++ b/.github/workflows/tests.yml@@ -111,8 +111,9 @@ jobs:- uses: ./.github/actions/setupwith:metal: true- node: true- swift: true+ bindings-napi: true+ bindings-uniffi: true+ bindings-pyo3: true- name: Prepare bindingsrun: cargo run -p cli-release prepare-bindingsdiff --git a/Cargo.lock b/Cargo.lockindex 74d5f3d24..9c1c9f498 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -840,6 +840,25 @@ dependencies = ["syn 2.0.117",]+[[package]]+name = "bindings-types"+version = "0.1.9"+dependencies = [+ "inventory",+ "napi",+ "napi-build",+ "napi-derive",+ "pyo3",+ "pyo3-async-runtimes",+ "pyo3-build-config",+ "pyo3-stub-gen",+ "serde-wasm-bindgen",+ "tsify",+ "uniffi",+ "wasm-bindgen",+ "wasm-bindgen-futures",+]+[[package]]name = "bit-set"version = "0.5.3"@@ -2762,6 +2781,15 @@ dependencies = ["version_check",]+[[package]]+name = "getopts"+version = "0.2.24"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cfe4fbac503b8d1f88e6676011885f34b7174f46e59956bba534ba83abded4df"+dependencies = [+ "unicode-width 0.2.2",+]+[[package]]name = "getrandom"version = "0.2.17"@@ -3554,6 +3582,18 @@ dependencies = ["serde",]+[[package]]+name = "is-macro"+version = "0.3.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d57a3e447e24c22647738e4607f1df1e0ec6f72e16182c4cd199f647cdfb0e4"+dependencies = [+ "heck",+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]+[[package]]name = "is-terminal"version = "0.4.17"@@ -3598,6 +3638,15 @@ dependencies = ["either",]+[[package]]+name = "itertools"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57"+dependencies = [+ "either",+]+[[package]]name = "itertools"version = "0.13.0"@@ -3767,6 +3816,12 @@ version = "0.11.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "bf36173d4167ed999940f804952e6b08197cae5ad5d572eb4db150ce8ad5d58f"+[[package]]+name = "lalrpop-util"+version = "0.20.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "507460a910eb7b32ee961886ff48539633b788a36b65692b95f225b844c82553"+[[package]]name = "lazy_static"version = "1.5.0"@@ -4025,6 +4080,12 @@ version = "0.2.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "670fdfda89751bc4a84ac13eaa63e205cf0fd22b4c9a5fbfa085b63c1f1d3a30"+[[package]]+name = "maplit"+version = "1.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3e2e65a1a2e43cfcb47a895c4c8b10d1f4a61097f9f254f183aee60cad9c651d"+[[package]]name = "matchers"version = "0.2.0"@@ -4275,13 +4336,18 @@ name = "nagare"version = "0.1.9"dependencies = ["bindings",+ "bindings-types","futures","hanashi","indexmap 2.14.0",+ "inventory","napi","napi-build","napi-derive","pyo3",+ "pyo3-async-runtimes",+ "pyo3-build-config",+ "pyo3-stub-gen","reqwest 0.13.2","serde","serde-wasm-bindgen",@@ -4605,6 +4671,22 @@ dependencies = ["libc",]+[[package]]+name = "numpy"+version = "0.28.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "778da78c64ddc928ebf5ad9df5edf0789410ff3bdbf3619aed51cd789a6af1e2"+dependencies = [+ "libc",+ "ndarray",+ "num-complex",+ "num-integer",+ "num-traits",+ "pyo3",+ "pyo3-build-config",+ "rustc-hash 2.1.2",+]+[[package]]name = "numtoa"version = "0.3.1"@@ -4820,6 +4902,15 @@ dependencies = ["num-traits",]+[[package]]+name = "ordered-float"+version = "5.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b7d950ca161dc355eaf28f82b11345ed76c6e1f6eb1f4f4479e0323b9e2fbd0e"+dependencies = [+ "num-traits",+]+[[package]]name = "ordered-stream"version = "0.2.0"@@ -5292,6 +5383,20 @@ dependencies = ["pyo3-macros",]+[[package]]+name = "pyo3-async-runtimes"+version = "0.28.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9e7364a95bf00e8377bbf9b0f09d7ff9715a29d8fcf93b47d1a967363b973178"+dependencies = [+ "futures-channel",+ "futures-util",+ "once_cell",+ "pin-project-lite",+ "pyo3",+ "tokio",+]+[[package]]name = "pyo3-build-config"version = "0.28.3"@@ -5336,6 +5441,46 @@ dependencies = ["syn 2.0.117",]+[[package]]+name = "pyo3-stub-gen"+version = "0.22.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8933f5816871707ba1379189c9fe3ae3511403fc9564914fb085b7686160529f"+dependencies = [+ "anyhow",+ "chrono",+ "either",+ "indexmap 2.14.0",+ "inventory",+ "itertools 0.14.0",+ "log",+ "maplit",+ "num-complex",+ "numpy",+ "ordered-float 5.3.0",+ "pyo3",+ "pyo3-stub-gen-derive",+ "rustpython-parser",+ "serde",+ "serde_json",+ "time",+ "toml 1.1.2+spec-1.1.0",+]++[[package]]+name = "pyo3-stub-gen-derive"+version = "0.22.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d085a7cb2c2a8aa9b660abfbdbb456b2e0872090158398d0524a3a2ae38f0ab0"+dependencies = [+ "heck",+ "indexmap 2.14.0",+ "proc-macro2",+ "quote",+ "rustpython-parser",+ "syn 2.0.117",+]+[[package]]name = "qoi"version = "0.4.1"@@ -6194,6 +6339,63 @@ dependencies = ["untrusted",]+[[package]]+name = "rustpython-ast"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4cdaf8ee5c1473b993b398c174641d3aa9da847af36e8d5eb8291930b72f31a5"+dependencies = [+ "is-macro",+ "num-bigint",+ "rustpython-parser-core",+ "static_assertions",+]++[[package]]+name = "rustpython-parser"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "868f724daac0caf9bd36d38caf45819905193a901e8f1c983345a68e18fb2abb"+dependencies = [+ "anyhow",+ "is-macro",+ "itertools 0.11.0",+ "lalrpop-util",+ "log",+ "num-bigint",+ "num-traits",+ "phf",+ "phf_codegen",+ "rustc-hash 1.1.0",+ "rustpython-ast",+ "rustpython-parser-core",+ "tiny-keccak",+ "unic-emoji-char",+ "unic-ucd-ident",+ "unicode_names2",+]++[[package]]+name = "rustpython-parser-core"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b4b6c12fa273825edc7bccd9a734f0ad5ba4b8a2f4da5ff7efe946f066d0f4ad"+dependencies = [+ "is-macro",+ "memchr",+ "rustpython-parser-vendored",+]++[[package]]+name = "rustpython-parser-vendored"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "04fcea49a4630a3a5d940f4d514dc4f575ed63c14c3e3ed07146634aed7f67a6"+dependencies = [+ "memchr",+ "once_cell",+]+[[package]]name = "rustversion"version = "1.0.22"@@ -6583,13 +6785,18 @@ name = "shoji"version = "0.1.9"dependencies = ["bindings",+ "bindings-types","futures","hound","indexmap 2.14.0",+ "inventory","napi","napi-build","napi-derive","pyo3",+ "pyo3-async-runtimes",+ "pyo3-build-config",+ "pyo3-stub-gen","serde","serde-wasm-bindgen","serde_json",@@ -6947,7 +7154,7 @@ dependencies = ["nix 0.29.0","num-derive","num-traits",- "ordered-float",+ "ordered-float 4.6.0","pest","pest_derive","phf",@@ -7286,6 +7493,21 @@ dependencies = ["winnow 0.7.15",]+[[package]]+name = "toml"+version = "1.1.2+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "81f3d15e84cbcd896376e6730314d59fb5a87f31e4b038454184435cd57defee"+dependencies = [+ "indexmap 2.14.0",+ "serde_core",+ "serde_spanned 1.1.1",+ "toml_datetime 1.1.1+spec-1.1.0",+ "toml_parser",+ "toml_writer",+ "winnow 1.0.2",+]+[[package]]name = "toml_datetime"version = "0.6.11"@@ -7581,6 +7803,58 @@ dependencies = ["version_check",]+[[package]]+name = "unic-char-property"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a8c57a407d9b6fa02b4795eb81c5b6652060a15a7903ea981f3d723e6c0be221"+dependencies = [+ "unic-char-range",+]++[[package]]+name = "unic-char-range"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0398022d5f700414f6b899e10b8348231abf9173fa93144cbc1a43b9793c1fbc"++[[package]]+name = "unic-common"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "80d7ff825a6a654ee85a63e80f92f054f904f21e7d12da4e22f9834a4aaa35bc"++[[package]]+name = "unic-emoji-char"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b07221e68897210270a38bde4babb655869637af0f69407f96053a34f76494d"+dependencies = [+ "unic-char-property",+ "unic-char-range",+ "unic-ucd-version",+]++[[package]]+name = "unic-ucd-ident"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e230a37c0381caa9219d67cf063aa3a375ffed5bf541a452db16e744bdab6987"+dependencies = [+ "unic-char-property",+ "unic-char-range",+ "unic-ucd-version",+]++[[package]]+name = "unic-ucd-version"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "96bd2f2237fe450fcd0a1d2f5f4e91711124f7857ba2e964247776ebeeb7b0c4"+dependencies = [+ "unic-common",+]+[[package]]name = "unicase"version = "2.9.0"@@ -7649,6 +7923,28 @@ version = "0.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "39ec24b3121d976906ece63c9daad25b85969647682eee313cb5779fdd69e14e"+[[package]]+name = "unicode_names2"+version = "1.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d1673eca9782c84de5f81b82e4109dcfb3611c8ba0d52930ec4a9478f547b2dd"+dependencies = [+ "phf",+ "unicode_names2_generator",+]++[[package]]+name = "unicode_names2_generator"+version = "1.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b91e5b84611016120197efd7dc93ef76774f4e084cd73c9fb3ea4a86c570c56e"+dependencies = [+ "getopts",+ "log",+ "phf_codegen",+ "rand 0.8.6",+]+[[package]]name = "uniffi"version = "0.31.1"@@ -7878,6 +8174,7 @@ dependencies = ["backend-remote","backend-uzu","bindings",+ "bindings-types","chrono","dirs","dotenvy",@@ -7887,6 +8184,7 @@ dependencies = ["futures-util","indexmap 2.14.0","indicatif",+ "inventory","keyring","nagare","napi",@@ -7896,7 +8194,11 @@ dependencies = ["objc2-foundation","objc2-security","pyo3",+ "pyo3-async-runtimes",+ "pyo3-build-config",+ "pyo3-stub-gen","reqwest 0.13.2",+ "schemars 1.2.1","serde","serde-wasm-bindgen","serde_json",@@ -8230,7 +8532,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5f2ab60e120fd6eaa68d9567f3226e876684639d22a4219b313ff69ec0ccd5ac"dependencies = ["log",- "ordered-float",+ "ordered-float 4.6.0","strsim","thiserror 1.0.69","wezterm-dynamic-derive",diff --git a/Cargo.toml b/Cargo.tomlindex a39829fc4..a85a08eeb 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -1,6 +1,7 @@[workspace]members = ["crates/dsl",+ "crates/bindings-types","crates/bindings","crates/shoji","crates/backend-uzu",@@ -28,6 +29,7 @@ repository = "https://github.com/trymirai/uzu"[workspace.dependencies]dsl = { path = "crates/dsl" }+bindings-types = { path = "crates/bindings-types", default-features = false }bindings = { path = "crates/bindings", default-features = false }shoji = { path = "crates/shoji", default-features = false }backend-uzu = { path = "crates/backend-uzu", default-features = false }@@ -138,12 +140,16 @@ napi = { version = "3.8.3", features = [] }napi-derive = "3.5.2"napi-build = "2.3.1"-pyo3 = { version = "0.28.2", features = [+pyo3 = { version = "0.28.3", features = ["extension-module",- "abi3-py38",+ "abi3-py312","experimental-async","multiple-pymethods",] }+pyo3-build-config = "0.28.3"+pyo3-async-runtimes = { version = "0.28.0", features = ["tokio-runtime"] }+pyo3-stub-gen = "0.22.1"+inventory = "0.3.24"wasm-bindgen = { version = "0.2.114", features = ["serde-serialize"] }serde-wasm-bindgen = "0.6.5"wasm-bindgen-futures = "0.4.64"diff --git a/bindings/python/.gitignore b/bindings/python/.gitignorenew file mode 100644index 000000000..64d49ae3b--- /dev/null+++ b/bindings/python/.gitignore@@ -0,0 +1,216 @@+# Byte-compiled / optimized / DLL files+__pycache__/+*.py[codz]+*$py.class++# C extensions+*.so++# Distribution / packaging+.Python+build/+develop-eggs/+dist/+downloads/+eggs/+.eggs/+lib/+lib64/+parts/+sdist/+var/+wheels/+share/python-wheels/+*.egg-info/+.installed.cfg+*.egg+MANIFEST++# PyInstaller+# Usually these files are written by a python script from a template+# before PyInstaller builds the exe, so as to inject date/other infos into it.+*.manifest+*.spec++# Installer logs+pip-log.txt+pip-delete-this-directory.txt++# Unit test / coverage reports+htmlcov/+.tox/+.nox/+.coverage+.coverage.*+.cache+nosetests.xml+coverage.xml+*.cover+*.py.cover+.hypothesis/+.pytest_cache/+cover/++# Translations+*.mo+*.pot++# Django stuff:+*.log+local_settings.py+db.sqlite3+db.sqlite3-journal++# Flask stuff:+instance/+.webassets-cache++# Scrapy stuff:+.scrapy++# Sphinx documentation+docs/_build/++# PyBuilder+.pybuilder/+target/++# Jupyter Notebook+.ipynb_checkpoints++# IPython+profile_default/+ipython_config.py++# pyenv+# For a library or package, you might want to ignore these files since the code is+# intended to run in multiple environments; otherwise, check them in:+# .python-version++# pipenv+# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.+# However, in case of collaboration, if having platform-specific dependencies or dependencies+# having no cross-platform support, pipenv may install dependencies that don't work, or not+# install all needed dependencies.+# Pipfile.lock++# UV+# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.+# This is especially recommended for binary packages to ensure reproducibility, and is more+# commonly ignored for libraries.+# uv.lock++# poetry+# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.+# This is especially recommended for binary packages to ensure reproducibility, and is more+# commonly ignored for libraries.+# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control+# poetry.lock+# poetry.toml++# pdm+# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.+# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.+# https://pdm-project.org/en/latest/usage/project/#working-with-version-control+# pdm.lock+# pdm.toml+.pdm-python+.pdm-build/++# pixi+# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.+# pixi.lock+# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one+# in the .venv directory. It is recommended not to include this directory in version control.+.pixi++# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm+__pypackages__/++# Celery stuff+celerybeat-schedule+celerybeat.pid++# Redis+*.rdb+*.aof+*.pid++# RabbitMQ+mnesia/+rabbitmq/+rabbitmq-data/++# ActiveMQ+activemq-data/++# SageMath parsed files+*.sage.py++# Environments+.env+.envrc+.venv+env/+venv/+ENV/+env.bak/+venv.bak/++# Spyder project settings+.spyderproject+.spyproject++# Rope project settings+.ropeproject++# mkdocs documentation+/site++# mypy+.mypy_cache/+.dmypy.json+dmypy.json++# Pyre type checker+.pyre/++# pytype static type analyzer+.pytype/++# Cython debug symbols+cython_debug/++# PyCharm+# JetBrains specific template is maintained in a separate JetBrains.gitignore that can+# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore+# and can be added to the global gitignore or merged into this file. For a more nuclear+# option (not recommended) you can uncomment the following to ignore the entire idea folder.+# .idea/++# Abstra+# Abstra is an AI-powered process automation framework.+# Ignore directories containing user credentials, local state, and settings.+# Learn more at https://abstra.io/docs+.abstra/++# Visual Studio Code+# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore+# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore+# and can be added to the global gitignore or merged into this file. However, if you prefer,+# you could uncomment the following to ignore the entire vscode folder+# .vscode/++# Ruff stuff:+.ruff_cache/++# PyPI configuration file+.pypirc++# Marimo+marimo/_static/+marimo/_lsp/+__marimo__/++# Streamlit+.streamlit/secrets.toml\ No newline at end of filediff --git a/bindings/python/.vscode/settings.json b/bindings/python/.vscode/settings.jsonnew file mode 100644index 000000000..132b6d2cf--- /dev/null+++ b/bindings/python/.vscode/settings.json@@ -0,0 +1,4 @@+{+ "python.defaultInterpreterPath": "${workspaceFolder}/bindings/python/.venv/bin/python",+ "ruff.path": ["${workspaceFolder}/bindings/python/.venv/bin/ruff"]+}diff --git a/bindings/python/README.md b/bindings/python/README.mdnew file mode 100644index 000000000..e69de29bbdiff --git a/bindings/python/examples/__init__.py b/bindings/python/examples/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/bindings/python/examples/chat.py b/bindings/python/examples/chat.pynew file mode 100644index 000000000..273cf75fc--- /dev/null+++ b/bindings/python/examples/chat.py@@ -0,0 +1,45 @@+import asyncio++from uzu import (+ ChatConfig,+ ChatMessage,+ ChatReplyConfig,+ ChatSessionStreamChunk,+ Engine,+ EngineConfig,+)+++async def main() -> None:+ engine_config = EngineConfig.create()+ engine = await Engine.create(engine_config)++ model = await engine.model("Qwen/Qwen3-0.6B")+ if model is None:+ raise RuntimeError("Model not found")+ async for update in (await engine.download(model)).iterator():+ print(f"Download progress: {update.progress}")++ messages = [+ ChatMessage.system().with_text("You are a helpful assistant"),+ ChatMessage.user().with_text("Tell me a short, funny story about a robot"),+ ]+ session = await engine.chat(model, ChatConfig.create())+ stream = await session.reply_with_stream(messages, ChatReplyConfig.create())+ message: ChatMessage | None = None+ async for chunk in stream.iterator():+ if isinstance(chunk, ChatSessionStreamChunk.Replies):+ replies = chunk.replies+ if replies:+ reply = replies[0]+ message = reply.message+ print(f"Generated tokens: {reply.stats.tokens_count_output}")+ elif isinstance(chunk, ChatSessionStreamChunk.Error):+ print(f"Error: {chunk.error}")+ if message is not None:+ print(f"Reasoning: {message.reasoning}")+ print(f"Text: {message.text}")+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/bindings/python/examples/chat_for_classification.py b/bindings/python/examples/chat_for_classification.pynew file mode 100644index 000000000..2be88e865--- /dev/null+++ b/bindings/python/examples/chat_for_classification.py@@ -0,0 +1,53 @@+import asyncio++from uzu import (+ ChatConfig,+ ChatMessage,+ ChatReplyConfig,+ ChatSpeculationPreset,+ Engine,+ EngineConfig,+ Feature,+ ReasoningEffort,+ SamplingMethod,+)+++async def main() -> None:+ engine_config = EngineConfig.create()+ engine = await Engine.create(engine_config)++ model = await engine.model("Qwen/Qwen3-0.6B")+ if model is None:+ raise RuntimeError("Model not found")+ async for update in (await engine.download(model)).iterator():+ print(f"Download progress: {update.progress}")++ feature = Feature(+ "sentiment",+ ["Happy", "Sad", "Angry", "Fearful", "Surprised", "Disgusted"],+ )+ chat_config = ChatConfig.create().with_speculation_preset(ChatSpeculationPreset.Classification(feature))+ session = await engine.chat(model, chat_config)++ text_to_detect_feature = "Today's been awesome! Everything just feels right, and I can't stop smiling."+ prompt = (+ f'Text is: "{text_to_detect_feature}". '+ f"Choose {feature.name} from the list: {', '.join(feature.values)}. "+ "Answer with one word. Don't add a dot at the end."+ )+ messages = [+ ChatMessage.system().with_reasoning_effort(ReasoningEffort.Disabled),+ ChatMessage.user().with_text(prompt),+ ]++ chat_reply_config = ChatReplyConfig.create().with_token_limit(32).with_sampling_method(SamplingMethod.Greedy())+ replies = await session.reply(messages, chat_reply_config)+ if replies:+ reply = replies[0]+ print(f"Prediction: {reply.message.text}")+ print(f"Generated tokens: {reply.stats.tokens_count_output}")+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/bindings/python/examples/chat_for_summarization.py b/bindings/python/examples/chat_for_summarization.pynew file mode 100644index 000000000..a99e57ba8--- /dev/null+++ b/bindings/python/examples/chat_for_summarization.py@@ -0,0 +1,54 @@+import asyncio++from uzu import (+ ChatConfig,+ ChatMessage,+ ChatReplyConfig,+ ChatSpeculationPreset,+ Engine,+ EngineConfig,+ ReasoningEffort,+ SamplingMethod,+)+++async def main() -> None:+ engine_config = EngineConfig.create()+ engine = await Engine.create(engine_config)++ model = await engine.model("Qwen/Qwen3-0.6B")+ if model is None:+ raise RuntimeError("Model not found")+ async for update in (await engine.download(model)).iterator():+ print(f"Download progress: {update.progress}")++ text_to_summarize = (+ "A Large Language Model (LLM) is a type of artificial intelligence that processes and generates human-like text. "+ "It is trained on vast datasets containing books, articles, and web content, allowing it to understand and predict language patterns. "+ "LLMs use deep learning, particularly transformer-based architectures, to analyze text, recognize context, and generate coherent responses. "+ "These models have a wide range of applications, including chatbots, content creation, translation, and code generation. "+ "One of the key strengths of LLMs is their ability to generate contextually relevant text based on prompts. "+ "They utilize self-attention mechanisms to weigh the importance of words within a sentence, improving accuracy and fluency. "+ "Examples of popular LLMs include OpenAI's GPT series, Google's BERT, and Meta's LLaMA. "+ "As these models grow in size and sophistication, they continue to enhance human-computer interactions, "+ "making AI-powered communication more natural and effective."+ )+ prompt = f'Text is: "{text_to_summarize}". Write only summary itself.'+ messages = [+ ChatMessage.system().with_reasoning_effort(ReasoningEffort.Disabled),+ ChatMessage.user().with_text(prompt),+ ]++ chat_config = ChatConfig.create().with_speculation_preset(ChatSpeculationPreset.Summarization())+ session = await engine.chat(model, chat_config)++ chat_reply_config = ChatReplyConfig.create().with_token_limit(256).with_sampling_method(SamplingMethod.Greedy())+ replies = await session.reply(messages, chat_reply_config)+ if replies:+ reply = replies[0]+ print(f"Summary: {reply.message.text}")+ print(f"Generation t/s: {reply.stats.generate_tokens_per_second}")+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/bindings/python/examples/classifier.py b/bindings/python/examples/classifier.pynew file mode 100644index 000000000..2dc0a9b38--- /dev/null+++ b/bindings/python/examples/classifier.py@@ -0,0 +1,24 @@+import asyncio++from uzu import ClassificationMessage, Engine, EngineConfig+++async def main() -> None:+ engine_config = EngineConfig.create()+ engine = await Engine.create(engine_config)++ model = await engine.model("trymirai/chat-moderation-router")+ if model is None:+ raise RuntimeError("Model not found")+ async for update in (await engine.download(model)).iterator():+ print(f"Download progress: {update.progress}")++ messages = [ClassificationMessage.user("Hi")]++ session = await engine.classification(model)+ output = await session.classify(messages)+ print(f"Output: {output.probabilities.values}")+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/bindings/python/examples/cloud.py b/bindings/python/examples/cloud.pynew file mode 100644index 000000000..f7ba51e55--- /dev/null+++ b/bindings/python/examples/cloud.py@@ -0,0 +1,28 @@+import asyncio++from uzu import ChatConfig, ChatMessage, ChatReplyConfig, Engine, EngineConfig, ReasoningEffort+++async def main() -> None:+ engine_config = EngineConfig.create().with_openai_api_key("OPENAI_API_KEY")+ engine = await Engine.create(engine_config)++ model = await engine.model("gpt-5")+ if model is None:+ raise RuntimeError("Model not found")++ messages = [+ ChatMessage.system().with_reasoning_effort(ReasoningEffort.Low),+ ChatMessage.user().with_text("How LLMs work"),+ ]++ session = await engine.chat(model, ChatConfig.create())+ replies = await session.reply(messages, ChatReplyConfig.create())+ if replies:+ message = replies[0].message+ print(f"Reasoning: {message.reasoning}")+ print(f"Text: {message.text}")+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/bindings/python/examples/quick_start.py b/bindings/python/examples/quick_start.pynew file mode 100644index 000000000..9ac17880c--- /dev/null+++ b/bindings/python/examples/quick_start.py@@ -0,0 +1,34 @@+import asyncio++from uzu import ChatConfig, ChatMessage, ChatReplyConfig, Engine, EngineConfig+++async def main() -> None:+ engine_config = EngineConfig.create()+ engine = await Engine.create(engine_config)++ model = await engine.model("Qwen/Qwen3-0.6B")+ if model is None:+ return++ async for update in (await engine.download(model)).iterator():+ print(f"Download progress: {update.progress}")++ session = await engine.chat(model, ChatConfig.create())++ messages = [+ ChatMessage.system().with_text("You are a helpful assistant"),+ ChatMessage.user().with_text("Tell me a short, funny story about a robot"),+ ]++ replies = await session.reply(messages, ChatReplyConfig.create())+ if not replies:+ return++ message = replies[-1].message+ print(f"Reasoning: {message.reasoning}")+ print(f"Text: {message.text}")+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/bindings/python/examples/snippets.py b/bindings/python/examples/snippets.pynew file mode 100644index 000000000..158c74d16--- /dev/null+++ b/bindings/python/examples/snippets.py@@ -0,0 +1,176 @@+import asyncio++from uzu import (+ ChatConfig,+ ChatMessage,+ ChatReplyConfig,+ ChatSpeculationPreset,+ Engine,+ EngineConfig,+ Feature,+ ReasoningEffort,+ SamplingMethod,+)+++async def quick_start_example() -> None:+ # snippet:quick-start+ engine_config = EngineConfig.create()+ engine = await Engine.create(engine_config)++ model = await engine.model("Qwen/Qwen3-0.6B")+ if model is None:+ raise RuntimeError("Model not found")+ async for update in (await engine.download(model)).iterator():+ print(f"Download progress: {update.progress}")++ messages = [+ ChatMessage.system().with_text("You are a helpful assistant"),+ ChatMessage.user().with_text("Tell me a short, funny story about a robot"),+ ]++ session = await engine.chat(model, ChatConfig.create())+ replies = await session.reply(messages, ChatReplyConfig.create())+ message = replies[0].message if replies else None+ # endsnippet:quick-start++ if message is not None:+ print(f"Reasoning: {message.reasoning}")+ print(f"Text: {message.text}")+++async def chat_example() -> None:+ # snippet:engine-create+ engine_config = EngineConfig.create()+ engine = await Engine.create(engine_config)+ # endsnippet:engine-create++ # snippet:model-choose+ model = await engine.model("Qwen/Qwen3-0.6B")+ if model is None:+ raise RuntimeError("Model not found")+ # endsnippet:model-choose++ # snippet:model-download+ async for update in (await engine.download(model)).iterator():+ print(f"Download progress: {update.progress}")+ # endsnippet:model-download++ # snippet:session-create-general+ session = await engine.chat(model, ChatConfig.create())+ # endsnippet:session-create-general++ # snippet:session-input-general+ messages = [+ ChatMessage.system().with_text("You are a helpful assistant"),+ ChatMessage.user().with_text("Tell me a short, funny story about a robot"),+ ]+ # endsnippet:session-input-general++ # snippet:session-run-general+ replies = await session.reply(messages, ChatReplyConfig.create())+ message = replies[0].message if replies else None+ # endsnippet:session-run-general++ if message is not None:+ print(f"Reasoning: {message.reasoning}")+ print(f"Text: {message.text}")+++async def summarization_example() -> None:+ engine_config = EngineConfig.create()+ engine = await Engine.create(engine_config)++ model = await engine.model("Qwen/Qwen3-0.6B")+ if model is None:+ raise RuntimeError("Model not found")+ async for update in (await engine.download(model)).iterator():+ print(f"Download progress: {update.progress}")++ # snippet:session-input-summarization+ text_to_summarize = (+ "A Large Language Model (LLM) is a type of artificial intelligence that processes and generates human-like text. "+ "It is trained on vast datasets containing books, articles, and web content, allowing it to understand and predict language patterns. "+ "LLMs use deep learning, particularly transformer-based architectures, to analyze text, recognize context, and generate coherent responses. "+ "These models have a wide range of applications, including chatbots, content creation, translation, and code generation. "+ "One of the key strengths of LLMs is their ability to generate contextually relevant text based on prompts. "+ "They utilize self-attention mechanisms to weigh the importance of words within a sentence, improving accuracy and fluency. "+ "Examples of popular LLMs include OpenAI's GPT series, Google's BERT, and Meta's LLaMA. "+ "As these models grow in size and sophistication, they continue to enhance human-computer interactions, "+ "making AI-powered communication more natural and effective."+ )+ prompt = f'Text is: "{text_to_summarize}". Write only summary itself.'+ messages = [+ ChatMessage.system().with_reasoning_effort(ReasoningEffort.Disabled),+ ChatMessage.user().with_text(prompt),+ ]+ # endsnippet:session-input-summarization++ # snippet:session-create-summarization+ chat_config = ChatConfig.create().with_speculation_preset(ChatSpeculationPreset.Summarization())+ session = await engine.chat(model, chat_config)+ # endsnippet:session-create-summarization++ # snippet:session-run-summarization+ chat_reply_config = ChatReplyConfig.create().with_token_limit(256).with_sampling_method(SamplingMethod.Greedy())+ replies = await session.reply(messages, chat_reply_config)+ reply = replies[0] if replies else None+ # endsnippet:session-run-summarization++ if reply is not None:+ print(f"Summary: {reply.message.text}")+ print(f"Generation t/s: {reply.stats.generate_tokens_per_second}")+++async def classification_example() -> None:+ engine_config = EngineConfig.create()+ engine = await Engine.create(engine_config)++ model = await engine.model("Qwen/Qwen3-0.6B")+ if model is None:+ raise RuntimeError("Model not found")+ async for update in (await engine.download(model)).iterator():+ print(f"Download progress: {update.progress}")++ # snippet:session-create-classification+ feature = Feature(+ "sentiment",+ ["Happy", "Sad", "Angry", "Fearful", "Surprised", "Disgusted"],+ )+ chat_config = ChatConfig.create().with_speculation_preset(ChatSpeculationPreset.Classification(feature))+ session = await engine.chat(model, chat_config)+ # endsnippet:session-create-classification++ # snippet:session-input-classification+ text_to_detect_feature = "Today's been awesome! Everything just feels right, and I can't stop smiling."+ prompt = (+ f'Text is: "{text_to_detect_feature}". '+ f"Choose {feature.name} from the list: {', '.join(feature.values)}. "+ "Answer with one word. Don't add a dot at the end."+ )+ messages = [+ ChatMessage.system().with_reasoning_effort(ReasoningEffort.Disabled),+ ChatMessage.user().with_text(prompt),+ ]+ # endsnippet:session-input-classification++ # snippet:session-run-classification+ chat_reply_config = ChatReplyConfig.create().with_token_limit(32).with_sampling_method(SamplingMethod.Greedy())+ replies = await session.reply(messages, chat_reply_config)+ reply = replies[0] if replies else None+ # endsnippet:session-run-classification++ if reply is not None:+ print(f"Prediction: {reply.message.text}")+ print(f"Generated tokens: {reply.stats.tokens_count_output}")+++async def main() -> None:+ await quick_start_example()+ await chat_example()+ await summarization_example()+ await classification_example()+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/bindings/python/examples/ssm.py b/bindings/python/examples/ssm.pynew file mode 100644index 000000000..736a5b068--- /dev/null+++ b/bindings/python/examples/ssm.py@@ -0,0 +1,28 @@+import asyncio++from uzu import ChatConfig, ChatMessage, ChatReplyConfig, Engine, EngineConfig+++async def main() -> None:+ engine_config = EngineConfig.create()+ engine = await Engine.create(engine_config)++ model = await engine.model("cartesia-ai/Llamba-1B-4bit-mlx")+ if model is None:+ raise RuntimeError("Model not found")+ async for update in (await engine.download(model)).iterator():+ print(f"Download progress: {update.progress}")++ messages = [+ ChatMessage.user().with_text("Tell me a short, funny story about a robot"),+ ]++ session = await engine.chat(model, ChatConfig.create())+ replies = await session.reply(messages, ChatReplyConfig.create())+ if replies:+ message = replies[0].message+ print(f"Text: {message.text}")+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/bindings/python/examples/structured_output.py b/bindings/python/examples/structured_output.pynew file mode 100644index 000000000..a1d6c1917--- /dev/null+++ b/bindings/python/examples/structured_output.py@@ -0,0 +1,61 @@+import asyncio+import json++from pydantic import BaseModel++from uzu import (+ ChatConfig,+ ChatMessage,+ ChatReplyConfig,+ Engine,+ EngineConfig,+ Grammar,+ ReasoningEffort,+)+++class Country(BaseModel):+ name: str+ capital: str+++class CountryList(BaseModel):+ countries: list[Country]+++def structured_response(response: str | None, model_type: type[BaseModel]) -> BaseModel | None:+ if not response:+ return None+ return model_type.model_validate_json(response)+++async def main() -> None:+ engine_config = EngineConfig.create()+ engine = await Engine.create(engine_config)++ model = await engine.model("Qwen/Qwen3-0.6B")+ if model is None:+ raise RuntimeError("Model not found")+ async for update in (await engine.download(model)).iterator():+ print(f"Download progress: {update.progress}")++ schema_string = json.dumps(CountryList.model_json_schema())+ messages = [+ ChatMessage.system().with_reasoning_effort(ReasoningEffort.Disabled),+ ChatMessage.user().with_text(+ "Give me a JSON object containing a list of 3 countries, where each country has name and capital fields"+ ),+ ]++ session = await engine.chat(model, ChatConfig.create())+ replies = await session.reply(+ messages,+ ChatReplyConfig.create().with_grammar(Grammar.JsonSchema(schema_string)),+ )+ if replies:+ countries = structured_response(replies[0].message.text, CountryList)+ print(countries)+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/bindings/python/examples/text_to_speech.py b/bindings/python/examples/text_to_speech.pynew file mode 100644index 000000000..cd1cfadf9--- /dev/null+++ b/bindings/python/examples/text_to_speech.py@@ -0,0 +1,32 @@+import asyncio+from pathlib import Path++from uzu import Engine, EngineConfig+++async def main() -> None:+ engine_config = EngineConfig.create()+ engine = await Engine.create(engine_config)++ model = await engine.model("fishaudio/s1-mini")+ if model is None:+ raise RuntimeError("Model not found")+ async for update in (await engine.download(model)).iterator():+ print(f"Download progress: {update.progress}")++ text = (+ "London is the capital of United Kingdom and one of the world's most influential cities, "+ "known for its rich history, cultural diversity, and global significance in finance, politics, and the arts. "+ "Situated along the River Thames, the city blends historic landmarks like Tower of London and Buckingham Palace "+ "with modern architecture such as The Shard. London is also home to renowned institutions including the British Museum "+ "and vibrant areas like Covent Garden, offering a mix of history, entertainment, and innovation that attracts millions of visitors each year."+ )+ output_path = Path.home() / "Desktop" / "output.wav"+ session = await engine.text_to_speech(model)+ pcm_batch = await session.synthesize(text)+ pcm_batch.save_as_wav(str(output_path))+ print(f"Output saved to: {output_path}")+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/bindings/python/pyproject.toml b/bindings/python/pyproject.tomlnew file mode 100644index 000000000..8c850cd61--- /dev/null+++ b/bindings/python/pyproject.toml@@ -0,0 +1,88 @@+[build-system]+requires = ["maturin>=1.8,<2.0"]+build-backend = "maturin"++[project]+name = "uzu"+description = "A high-performance inference engine for AI models"+readme = "README.md"+requires-python = ">=3.12"+license = "MIT"+authors = [{ name = "Mirai Tech Inc.", email = "[email protected]" }]+keywords = ["llm", "inference", "ai", "rust", "pyo3"]+classifiers = [+ "License :: OSI Approved :: MIT License",+ "Operating System :: MacOS",+ "Programming Language :: Rust",+ "Programming Language :: Python :: 3",+ "Programming Language :: Python :: 3.12",+ "Programming Language :: Python :: Implementation :: CPython",+ "Programming Language :: Python :: Implementation :: PyPy",+ "Topic :: Scientific/Engineering :: Artificial Intelligence",+]+dynamic = ["version"]++[project.urls]+Homepage = "https://trymirai.com"+Repository = "https://github.com/trymirai/uzu-python"+Issues = "https://github.com/trymirai/uzu-python/issues"++[project.optional-dependencies]+dev = ["pytest>=8.3.4", "ruff>=0.14.0"]+examples = ["pydantic>=2.13.3"]++[tool.maturin]+features = ["bindings-pyo3"]+module-name = "uzu"+bindings = "pyo3"+strip = true+manifest-path = "../../crates/uzu/Cargo.toml"+python-source = "."++[tool.pytest.ini_options]+testpaths = ["tests"]+asyncio_mode = "auto"++[tool.ruff]+target-version = "py312"+line-length = 119++[tool.ruff.lint]+select = ["ALL"]+ignore = [+ "C408",+ "C901",+ "D",+ "EM101",+ "EM102",+ "ERA001",+ "FIX002",+ "F722",+ "FBT001",+ "FBT002",+ "N812",+ "PD008",+ "PGH003",+ "PLC0415",+ "PLR0904",+ "PLR0912",+ "PLR0913",+ "PLR0915",+ "PLR0917",+ "PLR2004",+ "PLR6301",+ "PLW0108",+ "PT",+ "PTH123",+ "RET503",+ "RET504",+ "RUF005",+ "S",+ "SIM108",+ "T20",+ "TD003",+ "TRY003",+ "CPY001",+ "COM812",+ "TC003",+]diff --git a/bindings/python/uv.lock b/bindings/python/uv.locknew file mode 100644index 000000000..23e45458d--- /dev/null+++ b/bindings/python/uv.lock@@ -0,0 +1,230 @@+version = 1+revision = 3+requires-python = ">=3.12"++[[package]]+name = "annotated-types"+version = "0.7.0"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/ee/67/531ea369ba64dcff5ec9c3402f9f51bf748cec26dde048a2f973a4eea7f5/annotated_types-0.7.0.tar.gz", hash = "sha256:aff07c09a53a08bc8cfccb9c85b05f1aa9a2a6f23728d790723543408344ce89", size = 16081, upload-time = "2024-05-20T21:33:25.928Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/78/b6/6307fbef88d9b5ee7421e68d78a9f162e0da4900bc5f5793f6d3d0e34fb8/annotated_types-0.7.0-py3-none-any.whl", hash = "sha256:1f02e8b43a8fbbc3f3e0d4f0f4bfc8131bcb4eebe8849b8e5c773f3a1c582a53", size = 13643, upload-time = "2024-05-20T21:33:24.1Z" },+]++[[package]]+name = "colorama"+version = "0.4.6"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" },+]++[[package]]+name = "iniconfig"+version = "2.3.0"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/72/34/14ca021ce8e5dfedc35312d08ba8bf51fdd999c576889fc2c24cb97f4f10/iniconfig-2.3.0.tar.gz", hash = "sha256:c76315c77db068650d49c5b56314774a7804df16fee4402c1f19d6d15d8c4730", size = 20503, upload-time = "2025-10-18T21:55:43.219Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" },+]++[[package]]+name = "packaging"+version = "26.2"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/d7/f1/e7a6dd94a8d4a5626c03e4e99c87f241ba9e350cd9e6d75123f992427270/packaging-26.2.tar.gz", hash = "sha256:ff452ff5a3e828ce110190feff1178bb1f2ea2281fa2075aadb987c2fb221661", size = 228134, upload-time = "2026-04-24T20:15:23.917Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/df/b2/87e62e8c3e2f4b32e5fe99e0b86d576da1312593b39f47d8ceef365e95ed/packaging-26.2-py3-none-any.whl", hash = "sha256:5fc45236b9446107ff2415ce77c807cee2862cb6fac22b8a73826d0693b0980e", size = 100195, upload-time = "2026-04-24T20:15:22.081Z" },+]++[[package]]+name = "pluggy"+version = "1.6.0"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/f9/e2/3e91f31a7d2b083fe6ef3fa267035b518369d9511ffab804f839851d2779/pluggy-1.6.0.tar.gz", hash = "sha256:7dcc130b76258d33b90f61b658791dede3486c3e6bfb003ee5c9bfb396dd22f3", size = 69412, upload-time = "2025-05-15T12:30:07.975Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" },+]++[[package]]+name = "pydantic"+version = "2.13.3"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "annotated-types" },+ { name = "pydantic-core" },+ { name = "typing-extensions" },+ { name = "typing-inspection" },+]+sdist = { url = "https://files.pythonhosted.org/packages/d9/e4/40d09941a2cebcb20609b86a559817d5b9291c49dd6f8c87e5feffbe703a/pydantic-2.13.3.tar.gz", hash = "sha256:af09e9d1d09f4e7fe37145c1f577e1d61ceb9a41924bf0094a36506285d0a84d", size = 844068, upload-time = "2026-04-20T14:46:43.632Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/f3/0a/fd7d723f8f8153418fb40cf9c940e82004fce7e987026b08a68a36dd3fe7/pydantic-2.13.3-py3-none-any.whl", hash = "sha256:6db14ac8dfc9a1e57f87ea2c0de670c251240f43cb0c30a5130e9720dc612927", size = 471981, upload-time = "2026-04-20T14:46:41.402Z" },+]++[[package]]+name = "pydantic-core"+version = "2.46.3"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "typing-extensions" },+]+sdist = { url = "https://files.pythonhosted.org/packages/2a/ef/f7abb56c49382a246fd2ce9c799691e3c3e7175ec74b14d99e798bcddb1a/pydantic_core-2.46.3.tar.gz", hash = "sha256:41c178f65b8c29807239d47e6050262eb6bf84eb695e41101e62e38df4a5bc2c", size = 471412, upload-time = "2026-04-20T14:40:56.672Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/4b/cb/5b47425556ecc1f3fe18ed2a0083188aa46e1dd812b06e406475b3a5d536/pydantic_core-2.46.3-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:b11b59b3eee90a80a36701ddb4576d9ae31f93f05cb9e277ceaa09e6bf074a67", size = 2101946, upload-time = "2026-04-20T14:40:52.581Z" },+ { url = "https://files.pythonhosted.org/packages/a1/4f/2fb62c2267cae99b815bbf4a7b9283812c88ca3153ef29f7707200f1d4e5/pydantic_core-2.46.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:af8653713055ea18a3abc1537fe2ebc42f5b0bbb768d1eb79fd74eb47c0ac089", size = 1951612, upload-time = "2026-04-20T14:42:42.996Z" },+ { url = "https://files.pythonhosted.org/packages/50/6e/b7348fd30d6556d132cddd5bd79f37f96f2601fe0608afac4f5fb01ec0b3/pydantic_core-2.46.3-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:75a519dab6d63c514f3a81053e5266c549679e4aa88f6ec57f2b7b854aceb1b0", size = 1977027, upload-time = "2026-04-20T14:42:02.001Z" },+ { url = "https://files.pythonhosted.org/packages/82/11/31d60ee2b45540d3fb0b29302a393dbc01cd771c473f5b5147bcd353e593/pydantic_core-2.46.3-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:a6cd87cb1575b1ad05ba98894c5b5c96411ef678fa2f6ed2576607095b8d9789", size = 2063008, upload-time = "2026-04-20T14:44:17.952Z" },+ { url = "https://files.pythonhosted.org/packages/8a/db/3a9d1957181b59258f44a2300ab0f0be9d1e12d662a4f57bb31250455c52/pydantic_core-2.46.3-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:f80a55484b8d843c8ada81ebf70a682f3f00a3d40e378c06cf17ecb44d280d7d", size = 2233082, upload-time = "2026-04-20T14:40:57.934Z" },+ { url = "https://files.pythonhosted.org/packages/9c/e1/3277c38792aeb5cfb18c2f0c5785a221d9ff4e149abbe1184d53d5f72273/pydantic_core-2.46.3-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:3861f1731b90c50a3266316b9044f5c9b405eecb8e299b0a7120596334e4fe9c", size = 2304615, upload-time = "2026-04-20T14:42:12.584Z" },+ { url = "https://files.pythonhosted.org/packages/5e/d5/e3d9717c9eba10855325650afd2a9cba8e607321697f18953af9d562da2f/pydantic_core-2.46.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fb528e295ed31570ac3dcc9bfdd6e0150bc11ce6168ac87a8082055cf1a67395", size = 2094380, upload-time = "2026-04-20T14:43:05.522Z" },+ { url = "https://files.pythonhosted.org/packages/a1/20/abac35dedcbfd66c6f0b03e4e3564511771d6c9b7ede10a362d03e110d9b/pydantic_core-2.46.3-cp312-cp312-manylinux_2_31_riscv64.whl", hash = "sha256:367508faa4973b992b271ba1494acaab36eb7e8739d1e47be5035fb1ea225396", size = 2135429, upload-time = "2026-04-20T14:41:55.549Z" },+ { url = "https://files.pythonhosted.org/packages/6c/a5/41bfd1df69afad71b5cf0535055bccc73022715ad362edbc124bc1e021d7/pydantic_core-2.46.3-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:5ad3c826fe523e4becf4fe39baa44286cff85ef137c729a2c5e269afbfd0905d", size = 2174582, upload-time = "2026-04-20T14:41:45.96Z" },+ { url = "https://files.pythonhosted.org/packages/79/65/38d86ea056b29b2b10734eb23329b7a7672ca604df4f2b6e9c02d4ee22fe/pydantic_core-2.46.3-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:ec638c5d194ef8af27db69f16c954a09797c0dc25015ad6123eb2c73a4d271ca", size = 2187533, upload-time = "2026-04-20T14:40:55.367Z" },+ { url = "https://files.pythonhosted.org/packages/b6/55/a1129141678a2026badc539ad1dee0a71d06f54c2f06a4bd68c030ac781b/pydantic_core-2.46.3-cp312-cp312-musllinux_1_1_armv7l.whl", hash = "sha256:28ed528c45446062ee66edb1d33df5d88828ae167de76e773a3c7f64bd14e976", size = 2332985, upload-time = "2026-04-20T14:44:13.05Z" },+ { url = "https://files.pythonhosted.org/packages/d7/60/cb26f4077719f709e54819f4e8e1d43f4091f94e285eb6bd21e1190a7b7c/pydantic_core-2.46.3-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:aed19d0c783886d5bd86d80ae5030006b45e28464218747dcf83dabfdd092c7b", size = 2373670, upload-time = "2026-04-20T14:41:53.421Z" },+ { url = "https://files.pythonhosted.org/packages/6b/7e/c3f21882bdf1d8d086876f81b5e296206c69c6082551d776895de7801fa0/pydantic_core-2.46.3-cp312-cp312-win32.whl", hash = "sha256:06d5d8820cbbdb4147578c1fe7ffcd5b83f34508cb9f9ab76e807be7db6ff0a4", size = 1966722, upload-time = "2026-04-20T14:44:30.588Z" },+ { url = "https://files.pythonhosted.org/packages/57/be/6b5e757b859013ebfbd7adba02f23b428f37c86dcbf78b5bb0b4ffd36e99/pydantic_core-2.46.3-cp312-cp312-win_amd64.whl", hash = "sha256:c3212fda0ee959c1dd04c60b601ec31097aaa893573a3a1abd0a47bcac2968c1", size = 2072970, upload-time = "2026-04-20T14:42:54.248Z" },+ { url = "https://files.pythonhosted.org/packages/bf/f8/a989b21cc75e9a32d24192ef700eea606521221a89faa40c919ce884f2b1/pydantic_core-2.46.3-cp312-cp312-win_arm64.whl", hash = "sha256:f1f8338dd7a7f31761f1f1a3c47503a9a3b34eea3c8b01fa6ee96408affb5e72", size = 2035963, upload-time = "2026-04-20T14:44:20.4Z" },+ { url = "https://files.pythonhosted.org/packages/9b/3c/9b5e8eb9821936d065439c3b0fb1490ffa64163bfe7e1595985a47896073/pydantic_core-2.46.3-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:12bc98de041458b80c86c56b24df1d23832f3e166cbaff011f25d187f5c62c37", size = 2102109, upload-time = "2026-04-20T14:41:24.219Z" },+ { url = "https://files.pythonhosted.org/packages/91/97/1c41d1f5a19f241d8069f1e249853bcce378cdb76eec8ab636d7bc426280/pydantic_core-2.46.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:85348b8f89d2c3508b65b16c3c33a4da22b8215138d8b996912bb1532868885f", size = 1951820, upload-time = "2026-04-20T14:42:14.236Z" },+ { url = "https://files.pythonhosted.org/packages/30/b4/d03a7ae14571bc2b6b3c7b122441154720619afe9a336fa3a95434df5e2f/pydantic_core-2.46.3-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1105677a6df914b1fb71a81b96c8cce7726857e1717d86001f29be06a25ee6f8", size = 1977785, upload-time = "2026-04-20T14:42:31.648Z" },+ { url = "https://files.pythonhosted.org/packages/ae/0c/4086f808834b59e3c8f1aa26df8f4b6d998cdcf354a143d18ef41529d1fe/pydantic_core-2.46.3-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:87082cd65669a33adeba5470769e9704c7cf026cc30afb9cc77fd865578ebaad", size = 2062761, upload-time = "2026-04-20T14:40:37.093Z" },+ { url = "https://files.pythonhosted.org/packages/fa/71/a649be5a5064c2df0db06e0a512c2281134ed2fcc981f52a657936a7527c/pydantic_core-2.46.3-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:60e5f66e12c4f5212d08522963380eaaeac5ebd795826cfd19b2dfb0c7a52b9c", size = 2232989, upload-time = "2026-04-20T14:42:59.254Z" },+ { url = "https://files.pythonhosted.org/packages/a2/84/7756e75763e810b3a710f4724441d1ecc5883b94aacb07ca71c5fb5cfb69/pydantic_core-2.46.3-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:b6cdf19bf84128d5e7c37e8a73a0c5c10d51103a650ac585d42dd6ae233f2b7f", size = 2303975, upload-time = "2026-04-20T14:41:32.287Z" },+ { url = "https://files.pythonhosted.org/packages/6c/35/68a762e0c1e31f35fa0dac733cbd9f5b118042853698de9509c8e5bf128b/pydantic_core-2.46.3-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:031bb17f4885a43773c8c763089499f242aee2ea85cf17154168775dccdecf35", size = 2095325, upload-time = "2026-04-20T14:42:47.685Z" },+ { url = "https://files.pythonhosted.org/packages/77/bf/1bf8c9a8e91836c926eae5e3e51dce009bf495a60ca56060689d3df3f340/pydantic_core-2.46.3-cp313-cp313-manylinux_2_31_riscv64.whl", hash = "sha256:bcf2a8b2982a6673693eae7348ef3d8cf3979c1d63b54fca7c397a635cc68687", size = 2133368, upload-time = "2026-04-20T14:41:22.766Z" },+ { url = "https://files.pythonhosted.org/packages/e5/50/87d818d6bab915984995157ceb2380f5aac4e563dddbed6b56f0ed057aba/pydantic_core-2.46.3-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:28e8cf2f52d72ced402a137145923a762cbb5081e48b34312f7a0c8f55928ec3", size = 2173908, upload-time = "2026-04-20T14:42:52.044Z" },+ { url = "https://files.pythonhosted.org/packages/91/88/a311fb306d0bd6185db41fa14ae888fb81d0baf648a761ae760d30819d33/pydantic_core-2.46.3-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:17eaface65d9fc5abb940003020309c1bf7a211f5f608d7870297c367e6f9022", size = 2186422, upload-time = "2026-04-20T14:43:29.55Z" },+ { url = "https://files.pythonhosted.org/packages/8f/79/28fd0d81508525ab2054fef7c77a638c8b5b0afcbbaeee493cf7c3fef7e1/pydantic_core-2.46.3-cp313-cp313-musllinux_1_1_armv7l.whl", hash = "sha256:93fd339f23408a07e98950a89644f92c54d8729719a40b30c0a30bb9ebc55d23", size = 2332709, upload-time = "2026-04-20T14:42:16.134Z" },+ { url = "https://files.pythonhosted.org/packages/b3/21/795bf5fe5c0f379308b8ef19c50dedab2e7711dbc8d0c2acf08f1c7daa05/pydantic_core-2.46.3-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:23cbdb3aaa74dfe0837975dbf69b469753bbde8eacace524519ffdb6b6e89eb7", size = 2372428, upload-time = "2026-04-20T14:41:10.974Z" },+ { url = "https://files.pythonhosted.org/packages/45/b3/ed14c659cbe7605e3ef063077680a64680aec81eb1a04763a05190d49b7f/pydantic_core-2.46.3-cp313-cp313-win32.whl", hash = "sha256:610eda2e3838f401105e6326ca304f5da1e15393ae25dacae5c5c63f2c275b13", size = 1965601, upload-time = "2026-04-20T14:41:42.128Z" },+ { url = "https://files.pythonhosted.org/packages/ef/bb/adb70d9a762ddd002d723fbf1bd492244d37da41e3af7b74ad212609027e/pydantic_core-2.46.3-cp313-cp313-win_amd64.whl", hash = "sha256:68cc7866ed863db34351294187f9b729964c371ba33e31c26f478471c52e1ed0", size = 2071517, upload-time = "2026-04-20T14:43:36.096Z" },+ { url = "https://files.pythonhosted.org/packages/52/eb/66faefabebfe68bd7788339c9c9127231e680b11906368c67ce112fdb47f/pydantic_core-2.46.3-cp313-cp313-win_arm64.whl", hash = "sha256:f64b5537ac62b231572879cd08ec05600308636a5d63bcbdb15063a466977bec", size = 2035802, upload-time = "2026-04-20T14:43:38.507Z" },+ { url = "https://files.pythonhosted.org/packages/7f/db/a7bcb4940183fda36022cd18ba8dd12f2dff40740ec7b58ce7457befa416/pydantic_core-2.46.3-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:afa3aa644f74e290cdede48a7b0bee37d1c35e71b05105f6b340d484af536d9b", size = 2097614, upload-time = "2026-04-20T14:44:38.374Z" },+ { url = "https://files.pythonhosted.org/packages/24/35/e4066358a22e3e99519db370494c7528f5a2aa1367370e80e27e20283543/pydantic_core-2.46.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:ced3310e51aa425f7f77da8bbbb5212616655bedbe82c70944320bc1dbe5e018", size = 1951896, upload-time = "2026-04-20T14:40:53.996Z" },+ { url = "https://files.pythonhosted.org/packages/87/92/37cf4049d1636996e4b888c05a501f40a43ff218983a551d57f9d5e14f0d/pydantic_core-2.46.3-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e29908922ce9da1a30b4da490bd1d3d82c01dcfdf864d2a74aacee674d0bfa34", size = 1979314, upload-time = "2026-04-20T14:41:49.446Z" },+ { url = "https://files.pythonhosted.org/packages/d8/36/9ff4d676dfbdfb2d591cf43f3d90ded01e15b1404fd101180ed2d62a2fd3/pydantic_core-2.46.3-cp314-cp314-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:0c9ff69140423eea8ed2d5477df3ba037f671f5e897d206d921bc9fdc39613e7", size = 2056133, upload-time = "2026-04-20T14:42:23.574Z" },+ { url = "https://files.pythonhosted.org/packages/bc/f0/405b442a4d7ba855b06eec8b2bf9c617d43b8432d099dfdc7bf999293495/pydantic_core-2.46.3-cp314-cp314-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:b675ab0a0d5b1c8fdb81195dc5bcefea3f3c240871cdd7ff9a2de8aa50772eb2", size = 2228726, upload-time = "2026-04-20T14:44:22.816Z" },+ { url = "https://files.pythonhosted.org/packages/e7/f8/65cd92dd5a0bd89ba277a98ecbfaf6fc36bbd3300973c7a4b826d6ab1391/pydantic_core-2.46.3-cp314-cp314-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:0087084960f209a9a4af50ecd1fb063d9ad3658c07bb81a7a53f452dacbfb2ba", size = 2301214, upload-time = "2026-04-20T14:44:48.792Z" },+ { url = "https://files.pythonhosted.org/packages/fd/86/ef96a4c6e79e7a2d0410826a68fbc0eccc0fd44aa733be199d5fcac3bb87/pydantic_core-2.46.3-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ed42e6cc8e1b0e2b9b96e2276bad70ae625d10d6d524aed0c93de974ae029f9f", size = 2099927, upload-time = "2026-04-20T14:41:40.196Z" },+ { url = "https://files.pythonhosted.org/packages/6d/53/269caf30e0096e0a8a8f929d1982a27b3879872cca2d917d17c2f9fdf4fe/pydantic_core-2.46.3-cp314-cp314-manylinux_2_31_riscv64.whl", hash = "sha256:f1771ce258afb3e4201e67d154edbbae712a76a6081079fe247c2f53c6322c22", size = 2128789, upload-time = "2026-04-20T14:41:15.868Z" },+ { url = "https://files.pythonhosted.org/packages/00/b0/1a6d9b6a587e118482910c244a1c5acf4d192604174132efd12bf0ac486f/pydantic_core-2.46.3-cp314-cp314-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:a7610b6a5242a6c736d8ad47fd5fff87fcfe8f833b281b1c409c3d6835d9227f", size = 2173815, upload-time = "2026-04-20T14:44:25.152Z" },+ { url = "https://files.pythonhosted.org/packages/87/56/e7e00d4041a7e62b5a40815590114db3b535bf3ca0bf4dca9f16cef25246/pydantic_core-2.46.3-cp314-cp314-musllinux_1_1_aarch64.whl", hash = "sha256:ff5e7783bcc5476e1db448bf268f11cb257b1c276d3e89f00b5727be86dd0127", size = 2181608, upload-time = "2026-04-20T14:41:28.933Z" },+ { url = "https://files.pythonhosted.org/packages/e8/22/4bd23c3d41f7c185d60808a1de83c76cf5aeabf792f6c636a55c3b1ec7f9/pydantic_core-2.46.3-cp314-cp314-musllinux_1_1_armv7l.whl", hash = "sha256:9d2e32edcc143bc01e95300671915d9ca052d4f745aa0a49c48d4803f8a85f2c", size = 2326968, upload-time = "2026-04-20T14:42:03.962Z" },+ { url = "https://files.pythonhosted.org/packages/24/ac/66cd45129e3915e5ade3b292cb3bc7fd537f58f8f8dbdaba6170f7cabb74/pydantic_core-2.46.3-cp314-cp314-musllinux_1_1_x86_64.whl", hash = "sha256:6e42d83d1c6b87fa56b521479cff237e626a292f3b31b6345c15a99121b454c1", size = 2369842, upload-time = "2026-04-20T14:41:35.52Z" },+ { url = "https://files.pythonhosted.org/packages/a2/51/dd4248abb84113615473aa20d5545b7c4cd73c8644003b5259686f93996c/pydantic_core-2.46.3-cp314-cp314-win32.whl", hash = "sha256:07bc6d2a28c3adb4f7c6ae46aa4f2d2929af127f587ed44057af50bf1ce0f505", size = 1959661, upload-time = "2026-04-20T14:41:00.042Z" },+ { url = "https://files.pythonhosted.org/packages/20/eb/59980e5f1ae54a3b86372bd9f0fa373ea2d402e8cdcd3459334430f91e91/pydantic_core-2.46.3-cp314-cp314-win_amd64.whl", hash = "sha256:8940562319bc621da30714617e6a7eaa6b98c84e8c685bcdc02d7ed5e7c7c44e", size = 2071686, upload-time = "2026-04-20T14:43:16.471Z" },+ { url = "https://files.pythonhosted.org/packages/8c/db/1cf77e5247047dfee34bc01fa9bca134854f528c8eb053e144298893d370/pydantic_core-2.46.3-cp314-cp314-win_arm64.whl", hash = "sha256:5dcbbcf4d22210ced8f837c96db941bdb078f419543472aca5d9a0bb7cddc7df", size = 2026907, upload-time = "2026-04-20T14:43:31.732Z" },+ { url = "https://files.pythonhosted.org/packages/57/c0/b3df9f6a543276eadba0a48487b082ca1f201745329d97dbfa287034a230/pydantic_core-2.46.3-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:d0fe3dce1e836e418f912c1ad91c73357d03e556a4d286f441bf34fed2dbeecf", size = 2095047, upload-time = "2026-04-20T14:42:37.982Z" },+ { url = "https://files.pythonhosted.org/packages/66/57/886a938073b97556c168fd99e1a7305bb363cd30a6d2c76086bf0587b32a/pydantic_core-2.46.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:9ce92e58abc722dac1bf835a6798a60b294e48eb0e625ec9fd994b932ac5feee", size = 1934329, upload-time = "2026-04-20T14:43:49.655Z" },+ { url = "https://files.pythonhosted.org/packages/0b/7c/b42eaa5c34b13b07ecb51da21761297a9b8eb43044c864a035999998f328/pydantic_core-2.46.3-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a03e6467f0f5ab796a486146d1b887b2dc5e5f9b3288898c1b1c3ad974e53e4a", size = 1974847, upload-time = "2026-04-20T14:42:10.737Z" },+ { url = "https://files.pythonhosted.org/packages/e6/9b/92b42db6543e7de4f99ae977101a2967b63122d4b6cf7773812da2d7d5b5/pydantic_core-2.46.3-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:2798b6ba041b9d70acfb9071a2ea13c8456dd1e6a5555798e41ba7b0790e329c", size = 2041742, upload-time = "2026-04-20T14:40:44.262Z" },+ { url = "https://files.pythonhosted.org/packages/0f/19/46fbe1efabb5aa2834b43b9454e70f9a83ad9c338c1291e48bdc4fecf167/pydantic_core-2.46.3-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:9be3e221bdc6d69abf294dcf7aff6af19c31a5cdcc8f0aa3b14be29df4bd03b1", size = 2236235, upload-time = "2026-04-20T14:41:27.307Z" },+ { url = "https://files.pythonhosted.org/packages/77/da/b3f95bc009ad60ec53120f5d16c6faa8cabdbe8a20d83849a1f2b8728148/pydantic_core-2.46.3-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f13936129ce841f2a5ddf6f126fea3c43cd128807b5a59588c37cf10178c2e64", size = 2282633, upload-time = "2026-04-20T14:44:33.271Z" },+ { url = "https://files.pythonhosted.org/packages/cc/6e/401336117722e28f32fb8220df676769d28ebdf08f2f4469646d404c43a3/pydantic_core-2.46.3-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:28b5f2ef03416facccb1c6ef744c69793175fd27e44ef15669201601cf423acb", size = 2109679, upload-time = "2026-04-20T14:44:41.065Z" },+ { url = "https://files.pythonhosted.org/packages/fc/53/b289f9bc8756a32fe718c46f55afaeaf8d489ee18d1a1e7be1db73f42cc4/pydantic_core-2.46.3-cp314-cp314t-manylinux_2_31_riscv64.whl", hash = "sha256:830d1247d77ad23852314f069e9d7ddafeec5f684baf9d7e7065ed46a049c4e6", size = 2108342, upload-time = "2026-04-20T14:42:50.144Z" },+ { url = "https://files.pythonhosted.org/packages/10/5b/8292fc7c1f9111f1b2b7c1b0dcf1179edcd014fc3ea4517499f50b829d71/pydantic_core-2.46.3-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:d0793c90c1a3c74966e7975eaef3ed30ebdff3260a0f815a62a22adc17e4c01c", size = 2157208, upload-time = "2026-04-20T14:42:08.133Z" },+ { url = "https://files.pythonhosted.org/packages/2b/9e/f80044e9ec07580f057a89fc131f78dda7a58751ddf52bbe05eaf31db50f/pydantic_core-2.46.3-cp314-cp314t-musllinux_1_1_aarch64.whl", hash = "sha256:d2d0aead851b66f5245ec0c4fb2612ef457f8bbafefdf65a2bf9d6bac6140f47", size = 2167237, upload-time = "2026-04-20T14:42:25.412Z" },+ { url = "https://files.pythonhosted.org/packages/f8/84/6781a1b037f3b96be9227edbd1101f6d3946746056231bf4ac48cdff1a8d/pydantic_core-2.46.3-cp314-cp314t-musllinux_1_1_armv7l.whl", hash = "sha256:2f40e4246676beb31c5ce77c38a55ca4e465c6b38d11ea1bd935420568e0b1ab", size = 2312540, upload-time = "2026-04-20T14:40:40.313Z" },+ { url = "https://files.pythonhosted.org/packages/3e/db/19c0839feeb728e7df03255581f198dfdf1c2aeb1e174a8420b63c5252e5/pydantic_core-2.46.3-cp314-cp314t-musllinux_1_1_x86_64.whl", hash = "sha256:cf489cf8986c543939aeee17a09c04d6ffb43bfef8ca16fcbcc5cfdcbed24dba", size = 2369556, upload-time = "2026-04-20T14:41:09.427Z" },+ { url = "https://files.pythonhosted.org/packages/e0/15/3228774cb7cd45f5f721ddf1b2242747f4eb834d0c491f0c02d606f09fed/pydantic_core-2.46.3-cp314-cp314t-win32.whl", hash = "sha256:ffe0883b56cfc05798bf994164d2b2ff03efe2d22022a2bb080f3b626176dd56", size = 1949756, upload-time = "2026-04-20T14:41:25.717Z" },+ { url = "https://files.pythonhosted.org/packages/b8/2a/c79cf53fd91e5a87e30d481809f52f9a60dd221e39de66455cf04deaad37/pydantic_core-2.46.3-cp314-cp314t-win_amd64.whl", hash = "sha256:706d9d0ce9cf4593d07270d8e9f53b161f90c57d315aeec4fb4fd7a8b10240d8", size = 2051305, upload-time = "2026-04-20T14:43:18.627Z" },+ { url = "https://files.pythonhosted.org/packages/0b/db/d8182a7f1d9343a032265aae186eb063fe26ca4c40f256b21e8da4498e89/pydantic_core-2.46.3-cp314-cp314t-win_arm64.whl", hash = "sha256:77706aeb41df6a76568434701e0917da10692da28cb69d5fb6919ce5fdb07374", size = 2026310, upload-time = "2026-04-20T14:41:01.778Z" },+ { url = "https://files.pythonhosted.org/packages/34/42/f426db557e8ab2791bc7562052299944a118655496fbff99914e564c0a94/pydantic_core-2.46.3-graalpy312-graalpy250_312_native-macosx_10_12_x86_64.whl", hash = "sha256:b12dd51f1187c2eb489af8e20f880362db98e954b54ab792fa5d92e8bcc6b803", size = 2091877, upload-time = "2026-04-20T14:43:27.091Z" },+ { url = "https://files.pythonhosted.org/packages/5c/4f/86a832a9d14df58e663bfdf4627dc00d3317c2bd583c4fb23390b0f04b8e/pydantic_core-2.46.3-graalpy312-graalpy250_312_native-macosx_11_0_arm64.whl", hash = "sha256:f00a0961b125f1a47af7bcc17f00782e12f4cd056f83416006b30111d941dfa3", size = 1932428, upload-time = "2026-04-20T14:40:45.781Z" },+ { url = "https://files.pythonhosted.org/packages/11/1a/fe857968954d93fb78e0d4b6df5c988c74c4aaa67181c60be7cfe327c0ca/pydantic_core-2.46.3-graalpy312-graalpy250_312_native-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:57697d7c056aca4bbb680200f96563e841a6386ac1129370a0102592f4dddff5", size = 1997550, upload-time = "2026-04-20T14:44:02.425Z" },+ { url = "https://files.pythonhosted.org/packages/17/eb/9d89ad2d9b0ba8cd65393d434471621b98912abb10fbe1df08e480ba57b5/pydantic_core-2.46.3-graalpy312-graalpy250_312_native-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fd35aa21299def8db7ef4fe5c4ff862941a9a158ca7b63d61e66fe67d30416b4", size = 2137657, upload-time = "2026-04-20T14:42:45.149Z" },+]++[[package]]+name = "pygments"+version = "2.20.0"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/c3/b2/bc9c9196916376152d655522fdcebac55e66de6603a76a02bca1b6414f6c/pygments-2.20.0.tar.gz", hash = "sha256:6757cd03768053ff99f3039c1a36d6c0aa0b263438fcab17520b30a303a82b5f", size = 4955991, upload-time = "2026-03-29T13:29:33.898Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/f4/7e/a72dd26f3b0f4f2bf1dd8923c85f7ceb43172af56d63c7383eb62b332364/pygments-2.20.0-py3-none-any.whl", hash = "sha256:81a9e26dd42fd28a23a2d169d86d7ac03b46e2f8b59ed4698fb4785f946d0176", size = 1231151, upload-time = "2026-03-29T13:29:30.038Z" },+]++[[package]]+name = "pytest"+version = "9.0.3"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "colorama", marker = "sys_platform == 'win32'" },+ { name = "iniconfig" },+ { name = "packaging" },+ { name = "pluggy" },+ { name = "pygments" },+]+sdist = { url = "https://files.pythonhosted.org/packages/7d/0d/549bd94f1a0a402dc8cf64563a117c0f3765662e2e668477624baeec44d5/pytest-9.0.3.tar.gz", hash = "sha256:b86ada508af81d19edeb213c681b1d48246c1a91d304c6c81a427674c17eb91c", size = 1572165, upload-time = "2026-04-07T17:16:18.027Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/d4/24/a372aaf5c9b7208e7112038812994107bc65a84cd00e0354a88c2c77a617/pytest-9.0.3-py3-none-any.whl", hash = "sha256:2c5efc453d45394fdd706ade797c0a81091eccd1d6e4bccfcd476e2b8e0ab5d9", size = 375249, upload-time = "2026-04-07T17:16:16.13Z" },+]++[[package]]+name = "ruff"+version = "0.15.12"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/99/43/3291f1cc9106f4c63bdce7a8d0df5047fe8422a75b091c16b5e9355e0b11/ruff-0.15.12.tar.gz", hash = "sha256:ecea26adb26b4232c0c2ca19ccbc0083a68344180bba2a600605538ce51a40a6", size = 4643852, upload-time = "2026-04-24T18:17:14.305Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/c3/6e/e78ffb61d4686f3d96ba3df2c801161843746dcbcbb17a1e927d4829312b/ruff-0.15.12-py3-none-linux_armv6l.whl", hash = "sha256:f86f176e188e94d6bdbc09f09bfd9dc729059ad93d0e7390b5a73efe19f8861c", size = 10640713, upload-time = "2026-04-24T18:17:22.841Z" },+ { url = "https://files.pythonhosted.org/packages/ae/08/a317bc231fb9e7b93e4ef3089501e51922ff88d6936ce5cf870c4fe55419/ruff-0.15.12-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:e3bcd123364c3770b8e1b7baaf343cc99a35f197c5c6e8af79015c666c423a6c", size = 11069267, upload-time = "2026-04-24T18:17:30.105Z" },+ { url = "https://files.pythonhosted.org/packages/aa/a4/f828e9718d3dce1f5f11c39c4f65afd32783c8b2aebb2e3d259e492c47bd/ruff-0.15.12-py3-none-macosx_11_0_arm64.whl", hash = "sha256:fe87510d000220aa1ed530d4448a7c696a0cae1213e5ec30e5874287b66557b5", size = 10397182, upload-time = "2026-04-24T18:17:07.177Z" },+ { url = "https://files.pythonhosted.org/packages/71/e0/3310fc6d1b5e1fdea22bf3b1b807c7e187b581021b0d7d4514cccdb5fb71/ruff-0.15.12-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:84a1630093121375a3e2a95b4a6dc7b59e2b4ee76216e32d81aae550a832d002", size = 10758012, upload-time = "2026-04-24T18:16:55.759Z" },+ { url = "https://files.pythonhosted.org/packages/11/c1/a606911aee04c324ddaa883ae418f3569792fd3c4a10c50e0dd0a2311e1e/ruff-0.15.12-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:fb129f40f114f089ebe0ca56c0d251cf2061b17651d464bb6478dc01e69f11f5", size = 10447479, upload-time = "2026-04-24T18:16:51.677Z" },+ { url = "https://files.pythonhosted.org/packages/9d/68/4201e8444f0894f21ab4aeeaee68aa4f10b51613514a20d80bd628d57e88/ruff-0.15.12-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b0c862b172d695db7598426b8af465e7e9ac00a3ea2a3630ee67eb82e366aaa6", size = 11234040, upload-time = "2026-04-24T18:17:16.529Z" },+ { url = "https://files.pythonhosted.org/packages/34/ff/8a6d6cf4ccc23fd67060874e832c18919d1557a0611ebef03fdb01fff11e/ruff-0.15.12-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:2849ea9f3484c3aca43a82f484210370319e7170df4dfe4843395ddf6c57bc33", size = 12087377, upload-time = "2026-04-24T18:17:04.944Z" },+ { url = "https://files.pythonhosted.org/packages/85/f6/c669cf73f5152f623d34e69866a46d5e6185816b19fcd5b6dd8a2d299922/ruff-0.15.12-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9e77c7e51c07fe396826d5969a5b846d9cd4c402535835fb6e21ce8b28fef847", size = 11367784, upload-time = "2026-04-24T18:17:25.409Z" },+ { url = "https://files.pythonhosted.org/packages/e8/39/c61d193b8a1daaa8977f7dea9e8d8ba866e02ea7b65d32f6861693aa4c12/ruff-0.15.12-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:83b2f4f2f3b1026b5fb449b467d9264bf22067b600f7b6f41fc5958909f449d0", size = 11344088, upload-time = "2026-04-24T18:17:12.258Z" },+ { url = "https://files.pythonhosted.org/packages/c2/8d/49afab3645e31e12c590acb6d3b5b69d7aab5b81926dbaf7461f9441f37a/ruff-0.15.12-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:9ba3b8f1afd7e2e43d8943e55f249e13f9682fde09711644a6e7290eb4f3e339", size = 11271770, upload-time = "2026-04-24T18:17:02.457Z" },+ { url = "https://files.pythonhosted.org/packages/46/06/33f41fe94403e2b755481cdfb9b7ef3e4e0ed031c4581124658d935d52b4/ruff-0.15.12-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:e852ba9fdc890655e1d78f2df1499efbe0e54126bd405362154a75e2bde159c5", size = 10719355, upload-time = "2026-04-24T18:17:27.648Z" },+ { url = "https://files.pythonhosted.org/packages/0d/59/18aa4e014debbf559670e4048e39260a85c7fcee84acfd761ac01e7b8d35/ruff-0.15.12-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:dd8aed930da53780d22fc70bdf84452c843cf64f8cb4eb38984319c24c5cd5fd", size = 10462758, upload-time = "2026-04-24T18:17:32.347Z" },+ { url = "https://files.pythonhosted.org/packages/25/e7/cc9f16fd0f3b5fddcbd7ec3d6ae30c8f3fde1047f32a4093a98d633c6570/ruff-0.15.12-py3-none-musllinux_1_2_i686.whl", hash = "sha256:01da3988d225628b709493d7dc67c3b9b12c0210016b08690ef9bd27970b262b", size = 10953498, upload-time = "2026-04-24T18:17:20.674Z" },+ { url = "https://files.pythonhosted.org/packages/72/7a/a9ba7f98c7a575978698f4230c5e8cc54bbc761af34f560818f933dafa0c/ruff-0.15.12-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:9cae0f92bd5700d1213188b31cd3bdd2b315361296d10b96b8e2337d3d11f53e", size = 11447765, upload-time = "2026-04-24T18:17:09.755Z" },+ { url = "https://files.pythonhosted.org/packages/ea/f9/0ae446942c846b8266059ad8a30702a35afae55f5cdc54c5adf8d7afdc27/ruff-0.15.12-py3-none-win32.whl", hash = "sha256:d0185894e038d7043ba8fd6aee7499ece6462dc0ea9f1e260c7451807c714c20", size = 10657277, upload-time = "2026-04-24T18:17:18.591Z" },+ { url = "https://files.pythonhosted.org/packages/33/f1/9614e03e1cdcbf9437570b5400ced8a720b5db22b28d8e0f1bda429f660d/ruff-0.15.12-py3-none-win_amd64.whl", hash = "sha256:c87a162d61ab3adca47c03f7f717c68672edec7d1b5499e652331780fe74950d", size = 11837758, upload-time = "2026-04-24T18:17:00.113Z" },+ { url = "https://files.pythonhosted.org/packages/c0/98/6beb4b351e472e5f4c4613f7c35a5290b8be2497e183825310c4c3a3984b/ruff-0.15.12-py3-none-win_arm64.whl", hash = "sha256:a538f7a82d061cee7be55542aca1d86d1393d55d81d4fcc314370f4340930d4f", size = 11120821, upload-time = "2026-04-24T18:16:57.979Z" },+]++[[package]]+name = "typing-extensions"+version = "4.15.0"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/72/94/1a15dd82efb362ac84269196e94cf00f187f7ed21c242792a923cdb1c61f/typing_extensions-4.15.0.tar.gz", hash = "sha256:0cea48d173cc12fa28ecabc3b837ea3cf6f38c6d1136f85cbaaf598984861466", size = 109391, upload-time = "2025-08-25T13:49:26.313Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/18/67/36e9267722cc04a6b9f15c7f3441c2363321a3ea07da7ae0c0707beb2a9c/typing_extensions-4.15.0-py3-none-any.whl", hash = "sha256:f0fa19c6845758ab08074a0cfa8b7aecb71c999ca73d62883bc25cc018c4e548", size = 44614, upload-time = "2025-08-25T13:49:24.86Z" },+]++[[package]]+name = "typing-inspection"+version = "0.4.2"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "typing-extensions" },+]+sdist = { url = "https://files.pythonhosted.org/packages/55/e3/70399cb7dd41c10ac53367ae42139cf4b1ca5f36bb3dc6c9d33acdb43655/typing_inspection-0.4.2.tar.gz", hash = "sha256:ba561c48a67c5958007083d386c3295464928b01faa735ab8547c5692e87f464", size = 75949, upload-time = "2025-10-01T02:14:41.687Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/dc/9b/47798a6c91d8bdb567fe2698fe81e0c6b7cb7ef4d13da4114b41d239f65d/typing_inspection-0.4.2-py3-none-any.whl", hash = "sha256:4ed1cacbdc298c220f1bd249ed5287caa16f34d44ef4e9c3d0cbad5b521545e7", size = 14611, upload-time = "2025-10-01T02:14:40.154Z" },+]++[[package]]+name = "uzu"+source = { editable = "." }++[package.optional-dependencies]+dev = [+ { name = "pytest" },+ { name = "ruff" },+]+examples = [+ { name = "pydantic" },+]++[package.metadata]+requires-dist = [+ { name = "pydantic", marker = "extra == 'examples'", specifier = ">=2.13.3" },+ { name = "pytest", marker = "extra == 'dev'", specifier = ">=8.3.4" },+ { name = "ruff", marker = "extra == 'dev'", specifier = ">=0.14.0" },+]+provides-extras = ["dev", "examples"]diff --git a/bindings/python/uzu/__init__.py b/bindings/python/uzu/__init__.pynew file mode 100644index 000000000..90df4cc80--- /dev/null+++ b/bindings/python/uzu/__init__.py@@ -0,0 +1,7 @@+import sys as _sys++from . import uzu+from .uzu import * # noqa: F403++_sys.modules.pop("uzu.uzu", None)+del uzudiff --git a/bindings/python/uzu/__init__.pyi b/bindings/python/uzu/__init__.pyinew file mode 100644index 000000000..a57e65e15--- /dev/null+++ b/bindings/python/uzu/__init__.pyi@@ -0,0 +1,1257 @@+# This file is automatically generated by pyo3_stub_gen+# ruff: noqa: E501, F401, F403, F405++import builtins+import collections.abc+import enum+import typing+__all__ = [+ "CancelToken",+ "ChatConfig",+ "ChatContentBlock",+ "ChatContentBlockType",+ "ChatMessage",+ "ChatMessageMetadata",+ "ChatModelCapabilities",+ "ChatReply",+ "ChatReplyConfig",+ "ChatReplyFinishReason",+ "ChatReplyStats",+ "ChatRole",+ "ChatSession",+ "ChatSessionState",+ "ChatSessionStream",+ "ChatSessionStreamChunk",+ "ChatSpeculationPreset",+ "ClassificationLabel",+ "ClassificationMessage",+ "ClassificationOutput",+ "ClassificationOutputProbabilities",+ "ClassificationRole",+ "ClassificationSession",+ "ClassificationSessionState",+ "ClassificationStats",+ "ContextLength",+ "Device",+ "DownloadPhase",+ "DownloadState",+ "Downloader",+ "DownloaderStream",+ "DownloaderStreamUpdate",+ "Engine",+ "EngineCallback",+ "EngineConfig",+ "Feature",+ "File",+ "Grammar",+ "Hash",+ "HashMethod",+ "Image",+ "ImageFormat",+ "ImageTheme",+ "Keyring",+ "Metadata",+ "Model",+ "ModelAccessibility",+ "ModelBackend",+ "ModelFamily",+ "ModelProperties",+ "ModelQuantization",+ "ModelReference",+ "ModelRegistry",+ "ModelSpecialization",+ "ModelVendor",+ "PcmBatch",+ "ReasoningEffort",+ "Repository",+ "SamplingMethod",+ "SamplingPolicy",+ "SamplingSeed",+ "TextToSpeechSession",+ "TextToSpeechSessionState",+ "TextToSpeechSessionStream",+ "TextToSpeechSessionStreamChunk",+ "TextToSpeechStats",+ "Token",+ "ToolCall",+ "ToolDescription",+ "ToolFunction",+ "ToolNamespace",+ "TranslationPayload",+ "Value",+]++class CancelToken:+ @property+ def is_cancelled(self) -> builtins.bool: ...+ @staticmethod+ def create() -> CancelToken: ...+ def cancel(self) -> None: ...++class ChatConfig:+ @property+ def context_length(self) -> ContextLength: ...+ @property+ def sampling_seed(self) -> SamplingSeed: ...+ @property+ def speculation_preset(self) -> typing.Optional[ChatSpeculationPreset]: ...+ def __new__(cls, context_length: ContextLength, sampling_seed: SamplingSeed, speculation_preset: typing.Optional[ChatSpeculationPreset]) -> ChatConfig: ...+ @staticmethod+ def create() -> ChatConfig: ...+ def with_context_length(self, context_length: ContextLength) -> ChatConfig: ...+ def with_sampling_seed(self, sampling_seed: SamplingSeed) -> ChatConfig: ...+ def with_speculation_preset(self, speculation_preset: typing.Optional[ChatSpeculationPreset]) -> ChatConfig: ...++class ChatContentBlock:+ @typing.final+ class Identity(ChatContentBlock):+ __match_args__ = ("value",)+ @property+ def value(self) -> builtins.str: ...+ def __new__(cls, value: builtins.str) -> ChatContentBlock.Identity: ...++ @typing.final+ class ReasoningEffort(ChatContentBlock):+ __match_args__ = ("value",)+ @property+ def value(self) -> ReasoningEffort: ...+ def __new__(cls, value: ReasoningEffort) -> ChatContentBlock.ReasoningEffort: ...++ @typing.final+ class ConversationStartDate(ChatContentBlock):+ __match_args__ = ("value",)+ @property+ def value(self) -> builtins.str: ...+ def __new__(cls, value: builtins.str) -> ChatContentBlock.ConversationStartDate: ...++ @typing.final+ class KnowledgeCutoff(ChatContentBlock):+ __match_args__ = ("value",)+ @property+ def value(self) -> builtins.str: ...+ def __new__(cls, value: builtins.str) -> ChatContentBlock.KnowledgeCutoff: ...++ @typing.final+ class BuiltinTools(ChatContentBlock):+ __match_args__ = ("names",)+ @property+ def names(self) -> builtins.list[builtins.str]: ...+ def __new__(cls, names: typing.Sequence[builtins.str]) -> ChatContentBlock.BuiltinTools: ...++ @typing.final+ class Tools(ChatContentBlock):+ __match_args__ = ("namespaces",)+ @property+ def namespaces(self) -> builtins.list[ToolNamespace]: ...+ def __new__(cls, namespaces: typing.Sequence[ToolNamespace]) -> ChatContentBlock.Tools: ...++ @typing.final+ class Text(ChatContentBlock):+ __match_args__ = ("value",)+ @property+ def value(self) -> builtins.str: ...+ def __new__(cls, value: builtins.str) -> ChatContentBlock.Text: ...++ @typing.final+ class Image(ChatContentBlock):+ __match_args__ = ("url",)+ @property+ def url(self) -> builtins.str: ...+ def __new__(cls, url: builtins.str) -> ChatContentBlock.Image: ...++ @typing.final+ class Video(ChatContentBlock):+ __match_args__ = ("url",)+ @property+ def url(self) -> builtins.str: ...+ def __new__(cls, url: builtins.str) -> ChatContentBlock.Video: ...++ @typing.final+ class Audio(ChatContentBlock):+ __match_args__ = ("url",)+ @property+ def url(self) -> builtins.str: ...+ def __new__(cls, url: builtins.str) -> ChatContentBlock.Audio: ...++ @typing.final+ class File(ChatContentBlock):+ __match_args__ = ("url",)+ @property+ def url(self) -> builtins.str: ...+ def __new__(cls, url: builtins.str) -> ChatContentBlock.File: ...++ @typing.final+ class Reasoning(ChatContentBlock):+ __match_args__ = ("value",)+ @property+ def value(self) -> builtins.str: ...+ def __new__(cls, value: builtins.str) -> ChatContentBlock.Reasoning: ...++ @typing.final+ class ToolCall(ChatContentBlock):+ __match_args__ = ("value",)+ @property+ def value(self) -> ToolCall: ...+ def __new__(cls, value: ToolCall) -> ChatContentBlock.ToolCall: ...++ @typing.final+ class ToolCallCandidate(ChatContentBlock):+ __match_args__ = ("value",)+ @property+ def value(self) -> Value: ...+ def __new__(cls, value: Value) -> ChatContentBlock.ToolCallCandidate: ...++ @typing.final+ class ToolCallResult(ChatContentBlock):+ __match_args__ = ("identifier", "name", "value",)+ @property+ def identifier(self) -> typing.Optional[builtins.str]: ...+ @property+ def name(self) -> typing.Optional[builtins.str]: ...+ @property+ def value(self) -> Value: ...+ def __new__(cls, identifier: typing.Optional[builtins.str], name: typing.Optional[builtins.str], value: Value) -> ChatContentBlock.ToolCallResult: ...++ @typing.final+ class Translation(ChatContentBlock):+ __match_args__ = ("payload", "source_language_code", "target_language_code",)+ @property+ def payload(self) -> TranslationPayload: ...+ @property+ def source_language_code(self) -> builtins.str: ...+ @property+ def target_language_code(self) -> builtins.str: ...+ def __new__(cls, payload: TranslationPayload, source_language_code: builtins.str, target_language_code: builtins.str) -> ChatContentBlock.Translation: ...++ @typing.final+ class Custom(ChatContentBlock):+ __match_args__ = ("value",)+ @property+ def value(self) -> Value: ...+ def __new__(cls, value: Value) -> ChatContentBlock.Custom: ...++ ...++class ChatMessage:+ @property+ def role(self) -> ChatRole: ...+ @property+ def content(self) -> builtins.list[ChatContentBlock]: ...+ @property+ def metadata(self) -> ChatMessageMetadata: ...+ @property+ def reasoning_effort(self) -> typing.Optional[ReasoningEffort]: ...+ @property+ def text(self) -> typing.Optional[builtins.str]: ...+ @property+ def reasoning(self) -> typing.Optional[builtins.str]: ...+ @property+ def tool_namespaces(self) -> builtins.list[ToolNamespace]: ...+ @property+ def tool_calls(self) -> builtins.list[ToolCall]: ...+ def __new__(cls, role: ChatRole, content: typing.Sequence[ChatContentBlock], metadata: ChatMessageMetadata) -> ChatMessage: ...+ @staticmethod+ def tool() -> ChatMessage: ...+ @staticmethod+ def assistant() -> ChatMessage: ...+ @staticmethod+ def user() -> ChatMessage: ...+ @staticmethod+ def developer() -> ChatMessage: ...+ @staticmethod+ def system() -> ChatMessage: ...+ @staticmethod+ def for_role(role: ChatRole) -> ChatMessage: ...+ def with_block(self, block: ChatContentBlock) -> ChatMessage: ...+ def with_reasoning_effort(self, reasoning_effort: ReasoningEffort) -> ChatMessage: ...+ def with_tool_namespaces(self, tool_namespaces: typing.Sequence[ToolNamespace]) -> ChatMessage: ...+ def with_text(self, text: builtins.str) -> ChatMessage: ...+ def with_reasoning(self, reasoning: builtins.str) -> ChatMessage: ...+ def with_tool_call(self, tool_call: ToolCall) -> ChatMessage: ...+ def with_tool_call_candidate(self, value: Value) -> ChatMessage: ...++class ChatMessageMetadata:+ @property+ def values(self) -> builtins.dict[builtins.str, Value]: ...+ def __new__(cls, values: typing.Mapping[builtins.str, Value]) -> ChatMessageMetadata: ...++class ChatModelCapabilities:+ @property+ def supports_reasoning(self) -> builtins.bool: ...+ @property+ def supports_disable_reasoning(self) -> builtins.bool: ...+ @property+ def supports_tools(self) -> builtins.bool: ...+ @property+ def supports_multiple_tool_calls(self) -> builtins.bool: ...+ @property+ def requires_tools(self) -> builtins.bool: ...+ def __new__(cls, supports_reasoning: builtins.bool, supports_disable_reasoning: builtins.bool, supports_tools: builtins.bool, supports_multiple_tool_calls: builtins.bool, requires_tools: builtins.bool) -> ChatModelCapabilities: ...++class ChatReply:+ @property+ def message(self) -> ChatMessage: ...+ @property+ def stats(self) -> ChatReplyStats: ...+ @property+ def finish_reason(self) -> typing.Optional[ChatReplyFinishReason]: ...+ def __new__(cls, message: ChatMessage, stats: ChatReplyStats, finish_reason: typing.Optional[ChatReplyFinishReason]) -> ChatReply: ...++class ChatReplyConfig:+ @property+ def token_limit(self) -> typing.Optional[builtins.int]: ...+ @property+ def sampling_policy(self) -> SamplingPolicy: ...+ @property+ def grammar(self) -> typing.Optional[Grammar]: ...+ def __new__(cls, token_limit: typing.Optional[builtins.int], sampling_policy: SamplingPolicy, grammar: typing.Optional[Grammar]) -> ChatReplyConfig: ...+ @staticmethod+ def create() -> ChatReplyConfig: ...+ def with_token_limit(self, token_limit: typing.Optional[builtins.int]) -> ChatReplyConfig: ...+ def with_sampling_policy(self, sampling_policy: SamplingPolicy) -> ChatReplyConfig: ...+ def with_sampling_method(self, sampling_method: SamplingMethod) -> ChatReplyConfig: ...+ def with_grammar(self, grammar: typing.Optional[Grammar]) -> ChatReplyConfig: ...++class ChatReplyStats:+ @property+ def duration(self) -> builtins.float: ...+ @property+ def time_to_first_token(self) -> typing.Optional[builtins.float]: ...+ @property+ def prefill_tokens_per_second(self) -> typing.Optional[builtins.float]: ...+ @property+ def generate_tokens_per_second(self) -> typing.Optional[builtins.float]: ...+ @property+ def tokens_count_input(self) -> typing.Optional[builtins.int]: ...+ @property+ def tokens_count_output(self) -> typing.Optional[builtins.int]: ...+ @property+ def tokens_count(self) -> typing.Optional[builtins.int]: ...+ def __new__(cls, duration: builtins.float, time_to_first_token: typing.Optional[builtins.float], prefill_tokens_per_second: typing.Optional[builtins.float], generate_tokens_per_second: typing.Optional[builtins.float], tokens_count_input: typing.Optional[builtins.int], tokens_count_output: typing.Optional[builtins.int]) -> ChatReplyStats: ...++class ChatRole:+ @typing.final+ class User(ChatRole):+ __match_args__ = ()+ def __new__(cls) -> ChatRole.User: ...++ @typing.final+ class Assistant(ChatRole):+ __match_args__ = ()+ def __new__(cls) -> ChatRole.Assistant: ...++ @typing.final+ class System(ChatRole):+ __match_args__ = ()+ def __new__(cls) -> ChatRole.System: ...++ @typing.final+ class Developer(ChatRole):+ __match_args__ = ()+ def __new__(cls) -> ChatRole.Developer: ...++ @typing.final+ class Tool(ChatRole):+ __match_args__ = ()+ def __new__(cls) -> ChatRole.Tool: ...++ @typing.final+ class Custom(ChatRole):+ __match_args__ = ("name",)+ @property+ def name(self) -> builtins.str: ...+ def __new__(cls, name: builtins.str) -> ChatRole.Custom: ...++ ...++class ChatSession:+ def state(self) -> collections.abc.Awaitable[ChatSessionState]: ...+ def messages(self) -> collections.abc.Awaitable[builtins.list[ChatMessage]]: ...+ def reset(self) -> collections.abc.Awaitable[None]: ...+ def reply(self, input: typing.Sequence[ChatMessage], config: ChatReplyConfig) -> collections.abc.Awaitable[builtins.list[ChatReply]]: ...+ def reply_with_stream(self, input: typing.Sequence[ChatMessage], config: ChatReplyConfig) -> collections.abc.Awaitable[ChatSessionStream]: ...++class ChatSessionStream:+ @property+ def cancel_token(self) -> CancelToken: ...+ def next(self) -> collections.abc.Awaitable[ChatSessionStreamChunk | None]: ...+ def __aiter__(self) -> ChatSessionStream: ...+ def __anext__(self) -> collections.abc.Awaitable[ChatSessionStreamChunk]: ...+ def iterator(self) -> ChatSessionStream: ...++class ChatSessionStreamChunk:+ @typing.final+ class Replies(ChatSessionStreamChunk):+ __match_args__ = ("replies",)+ @property+ def replies(self) -> builtins.list[ChatReply]: ...+ def __new__(cls, replies: typing.Sequence[ChatReply]) -> ChatSessionStreamChunk.Replies: ...++ @typing.final+ class Error(ChatSessionStreamChunk):+ __match_args__ = ("error",)+ @property+ def error(self) -> builtins.str: ...+ def __new__(cls, error: builtins.str) -> ChatSessionStreamChunk.Error: ...++ ...++class ChatSpeculationPreset:+ @typing.final+ class GeneralChat(ChatSpeculationPreset):+ __match_args__ = ()+ def __new__(cls) -> ChatSpeculationPreset.GeneralChat: ...++ @typing.final+ class Summarization(ChatSpeculationPreset):+ __match_args__ = ()+ def __new__(cls) -> ChatSpeculationPreset.Summarization: ...++ @typing.final+ class Classification(ChatSpeculationPreset):+ __match_args__ = ("feature",)+ @property+ def feature(self) -> Feature: ...+ def __new__(cls, feature: Feature) -> ChatSpeculationPreset.Classification: ...++ ...++class ClassificationLabel:+ @property+ def index(self) -> builtins.int: ...+ @property+ def label(self) -> builtins.str: ...+ @property+ def title(self) -> builtins.str: ...+ @property+ def description(self) -> builtins.str: ...+ @property+ def recommended_threshold(self) -> builtins.float: ...+ def __new__(cls, index: builtins.int, label: builtins.str, title: builtins.str, description: builtins.str, recommended_threshold: builtins.float) -> ClassificationLabel: ...++class ClassificationMessage:+ @property+ def role(self) -> ClassificationRole: ...+ @property+ def content(self) -> builtins.str: ...+ def __new__(cls, role: ClassificationRole, content: builtins.str) -> ClassificationMessage: ...+ @staticmethod+ def assistant(content: builtins.str) -> ClassificationMessage: ...+ @staticmethod+ def user(content: builtins.str) -> ClassificationMessage: ...++class ClassificationOutput:+ @property+ def logits(self) -> builtins.list[builtins.float]: ...+ @property+ def probabilities(self) -> ClassificationOutputProbabilities: ...+ @property+ def stats(self) -> ClassificationStats: ...+ def __new__(cls, logits: typing.Sequence[builtins.float], probabilities: ClassificationOutputProbabilities, stats: ClassificationStats) -> ClassificationOutput: ...++class ClassificationOutputProbabilities:+ @property+ def values(self) -> builtins.dict[builtins.str, builtins.float]: ...+ def __new__(cls, values: typing.Mapping[builtins.str, builtins.float]) -> ClassificationOutputProbabilities: ...++class ClassificationSession:+ def state(self) -> collections.abc.Awaitable[ClassificationSessionState]: ...+ def classify(self, input: typing.Sequence[ClassificationMessage]) -> collections.abc.Awaitable[ClassificationOutput]: ...++class ClassificationStats:+ @property+ def preprocessing_duration(self) -> builtins.float: ...+ @property+ def forward_pass_duration(self) -> builtins.float: ...+ @property+ def postprocessing_duration(self) -> builtins.float: ...+ @property+ def total_duration(self) -> builtins.float: ...+ @property+ def tokens_count(self) -> builtins.int: ...+ @property+ def tokens_per_second(self) -> builtins.float: ...+ @property+ def predicted_label(self) -> builtins.str: ...+ @property+ def confidence(self) -> builtins.float: ...+ def __new__(cls, preprocessing_duration: builtins.float, forward_pass_duration: builtins.float, postprocessing_duration: builtins.float, total_duration: builtins.float, tokens_count: builtins.int, tokens_per_second: builtins.float, predicted_label: builtins.str, confidence: builtins.float) -> ClassificationStats: ...++class ContextLength:+ @typing.final+ class Default(ContextLength):+ __match_args__ = ()+ def __new__(cls) -> ContextLength.Default: ...++ @typing.final+ class Maximal(ContextLength):+ __match_args__ = ()+ def __new__(cls) -> ContextLength.Maximal: ...++ @typing.final+ class Custom(ContextLength):+ __match_args__ = ("length",)+ @property+ def length(self) -> builtins.int: ...+ def __new__(cls, length: builtins.int) -> ContextLength.Custom: ...++ ...++class Device:+ @property+ def os_name(self) -> typing.Optional[builtins.str]: ...+ @property+ def cpu_name(self) -> typing.Optional[builtins.str]: ...+ @property+ def memory_total(self) -> builtins.int: ...+ @property+ def home_path(self) -> builtins.str: ...+ @property+ def application_identifier(self) -> builtins.str: ...+ @property+ def is_environment_sandboxed(self) -> builtins.bool: ...+ @property+ def is_keyring_available(self) -> builtins.bool: ...+ def __new__(cls, os_name: typing.Optional[builtins.str], cpu_name: typing.Optional[builtins.str], memory_total: builtins.int, home_path: builtins.str, application_identifier: builtins.str, is_environment_sandboxed: builtins.bool, is_keyring_available: builtins.bool) -> Device: ...+ @staticmethod+ def create() -> Device: ...++class DownloadPhase:+ @typing.final+ class NotDownloaded(DownloadPhase):+ __match_args__ = ()+ def __new__(cls) -> DownloadPhase.NotDownloaded: ...++ @typing.final+ class Downloading(DownloadPhase):+ __match_args__ = ()+ def __new__(cls) -> DownloadPhase.Downloading: ...++ @typing.final+ class Paused(DownloadPhase):+ __match_args__ = ()+ def __new__(cls) -> DownloadPhase.Paused: ...++ @typing.final+ class Downloaded(DownloadPhase):+ __match_args__ = ()+ def __new__(cls) -> DownloadPhase.Downloaded: ...++ @typing.final+ class Locked(DownloadPhase):+ __match_args__ = ()+ def __new__(cls) -> DownloadPhase.Locked: ...++ @typing.final+ class Error(DownloadPhase):+ __match_args__ = ("message",)+ @property+ def message(self) -> builtins.str: ...+ def __new__(cls, message: builtins.str) -> DownloadPhase.Error: ...++ ...++class DownloadState:+ @property+ def total_bytes(self) -> builtins.int: ...+ @property+ def downloaded_bytes(self) -> builtins.int: ...+ @property+ def phase(self) -> DownloadPhase: ...+ @property+ def progress(self) -> builtins.float: ...+ @property+ def is_in_progress(self) -> builtins.bool: ...+ @property+ def can_pause(self) -> builtins.bool: ...+ @property+ def can_delete(self) -> builtins.bool: ...+ def __new__(cls, total_bytes: builtins.int, downloaded_bytes: builtins.int, phase: DownloadPhase) -> DownloadState: ...++class Downloader:+ def state(self) -> collections.abc.Awaitable[DownloadState | None]: ...+ def resume(self) -> collections.abc.Awaitable[None]: ...+ def pause(self) -> collections.abc.Awaitable[None]: ...+ def delete(self) -> collections.abc.Awaitable[None]: ...+ def progress(self) -> collections.abc.Awaitable[DownloaderStream]: ...++class DownloaderStream:+ def next(self) -> collections.abc.Awaitable[DownloaderStreamUpdate | None]: ...+ def __aiter__(self) -> DownloaderStream: ...+ def __anext__(self) -> collections.abc.Awaitable[DownloaderStreamUpdate]: ...+ def iterator(self) -> DownloaderStream: ...++class DownloaderStreamUpdate:+ @property+ def bytes_total(self) -> builtins.int: ...+ @property+ def bytes_downloaded(self) -> builtins.int: ...+ @property+ def progress(self) -> builtins.float: ...+ def __new__(cls, bytes_total: builtins.int, bytes_downloaded: builtins.int) -> DownloaderStreamUpdate: ...++class Engine:+ @staticmethod+ def create(config: EngineConfig) -> collections.abc.Awaitable[Engine]: ...+ def register_callback(self, callback: EngineCallback) -> collections.abc.Awaitable[None]: ...+ def remove_registry(self, registry_identifier: builtins.str) -> collections.abc.Awaitable[None]: ...+ def remove_backend(self, identifier: builtins.str) -> collections.abc.Awaitable[None]: ...+ def models(self) -> collections.abc.Awaitable[builtins.list[Model]]: ...+ def models_local(self) -> collections.abc.Awaitable[builtins.list[Model]]: ...+ def models_remote(self) -> collections.abc.Awaitable[builtins.list[Model]]: ...+ def models_downloadable(self) -> collections.abc.Awaitable[builtins.list[Model]]: ...+ def models_for_chat(self) -> collections.abc.Awaitable[builtins.list[Model]]: ...+ def models_for_classification(self) -> collections.abc.Awaitable[builtins.list[Model]]: ...+ def models_for_text_to_speech(self) -> collections.abc.Awaitable[builtins.list[Model]]: ...+ def models_for_translation(self) -> collections.abc.Awaitable[builtins.list[Model]]: ...+ def models_for_speculation(self) -> collections.abc.Awaitable[builtins.list[Model]]: ...+ def model_registries(self) -> collections.abc.Awaitable[builtins.list[ModelRegistry]]: ...+ def model_vendors(self) -> collections.abc.Awaitable[builtins.list[ModelVendor]]: ...+ def models_by_vendor(self, vendor_identifier: builtins.str) -> collections.abc.Awaitable[builtins.list[Model]]: ...+ def model_families(self) -> collections.abc.Awaitable[builtins.list[ModelFamily]]: ...+ def models_by_family(self, family_identifier: builtins.str) -> collections.abc.Awaitable[builtins.list[Model]]: ...+ def model(self, identifier: builtins.str) -> collections.abc.Awaitable[Model | None]: ...+ def model_by_identifier(self, identifier: builtins.str) -> collections.abc.Awaitable[Model | None]: ...+ def model_by_repo_id(self, repo_id: builtins.str) -> collections.abc.Awaitable[Model | None]: ...+ def model_by_path(self, path: builtins.str) -> collections.abc.Awaitable[Model | None]: ...+ def model_path(self, model: Model) -> collections.abc.Awaitable[builtins.str | None]: ...+ def downloader(self, model: Model) -> Downloader: ...+ def download(self, model: Model) -> collections.abc.Awaitable[DownloaderStream]: ...+ def download_state(self, model: Model) -> collections.abc.Awaitable[DownloadState | None]: ...+ def download_states(self) -> collections.abc.Awaitable[builtins.dict[builtins.str, DownloadState]]: ...+ def chat(self, model: Model, config: ChatConfig) -> collections.abc.Awaitable[ChatSession]: ...+ def classification(self, model: Model) -> collections.abc.Awaitable[ClassificationSession]: ...+ def text_to_speech(self, model: Model) -> collections.abc.Awaitable[TextToSpeechSession]: ...++class EngineCallback:+ @staticmethod+ def create(callback: collections.abc.Callable[[], None]) -> EngineCallback: ...++class EngineConfig:+ @property+ def mirai_api_key(self) -> typing.Optional[builtins.str]: ...+ @property+ def lalamo_path(self) -> typing.Optional[builtins.str]: ...+ @property+ def huggingface_api_key(self) -> typing.Optional[builtins.str]: ...+ @property+ def openai_api_key(self) -> typing.Optional[builtins.str]: ...+ @property+ def anthropic_api_key(self) -> typing.Optional[builtins.str]: ...+ @property+ def gemini_api_key(self) -> typing.Optional[builtins.str]: ...+ @property+ def xai_api_key(self) -> typing.Optional[builtins.str]: ...+ @property+ def baseten_api_key(self) -> typing.Optional[builtins.str]: ...+ @property+ def openrouter_api_key(self) -> typing.Optional[builtins.str]: ...+ @property+ def allow_ollama_usage(self) -> builtins.bool: ...+ @property+ def allow_lmstudio_usage(self) -> builtins.bool: ...+ def __new__(cls, mirai_api_key: typing.Optional[builtins.str], lalamo_path: typing.Optional[builtins.str], huggingface_api_key: typing.Optional[builtins.str], openai_api_key: typing.Optional[builtins.str], anthropic_api_key: typing.Optional[builtins.str], gemini_api_key: typing.Optional[builtins.str], xai_api_key: typing.Optional[builtins.str], baseten_api_key: typing.Optional[builtins.str], openrouter_api_key: typing.Optional[builtins.str], allow_ollama_usage: builtins.bool, allow_lmstudio_usage: builtins.bool) -> EngineConfig: ...+ @staticmethod+ def create() -> EngineConfig: ...+ def with_mirai_api_key(self, mirai_api_key: builtins.str) -> EngineConfig: ...+ def with_lalamo_path(self, lalamo_path: builtins.str) -> EngineConfig: ...+ def with_huggingface_api_key(self, huggingface_api_key: builtins.str) -> EngineConfig: ...+ def with_openai_api_key(self, openai_api_key: builtins.str) -> EngineConfig: ...+ def with_anthropic_api_key(self, anthropic_api_key: builtins.str) -> EngineConfig: ...+ def with_gemini_api_key(self, gemini_api_key: builtins.str) -> EngineConfig: ...+ def with_xai_api_key(self, xai_api_key: builtins.str) -> EngineConfig: ...+ def with_baseten_api_key(self, baseten_api_key: builtins.str) -> EngineConfig: ...+ def with_openrouter_api_key(self, openrouter_api_key: builtins.str) -> EngineConfig: ...+ def with_allow_ollama_usage(self, allow_ollama_usage: builtins.bool) -> EngineConfig: ...+ def with_allow_lmstudio_usage(self, allow_lmstudio_usage: builtins.bool) -> EngineConfig: ...++class Feature:+ @property+ def name(self) -> builtins.str: ...+ @property+ def values(self) -> builtins.list[builtins.str]: ...+ def __new__(cls, name: builtins.str, values: typing.Sequence[builtins.str]) -> Feature: ...++class File:+ @property+ def url(self) -> builtins.str: ...+ @property+ def name(self) -> builtins.str: ...+ @property+ def size(self) -> builtins.int: ...+ @property+ def hashes(self) -> builtins.list[Hash]: ...+ @property+ def crc32c(self) -> typing.Optional[builtins.str]: ...+ @property+ def md5(self) -> typing.Optional[builtins.str]: ...+ def __new__(cls, url: builtins.str, name: builtins.str, size: builtins.int, hashes: typing.Sequence[Hash]) -> File: ...++class Grammar:+ @typing.final+ class JsonAny(Grammar):+ __match_args__ = ()+ def __new__(cls) -> Grammar.JsonAny: ...++ @typing.final+ class JsonSchema(Grammar):+ __match_args__ = ("schema",)+ @property+ def schema(self) -> builtins.str: ...+ def __new__(cls, schema: builtins.str) -> Grammar.JsonSchema: ...++ @typing.final+ class Regex(Grammar):+ __match_args__ = ("pattern",)+ @property+ def pattern(self) -> builtins.str: ...+ def __new__(cls, pattern: builtins.str) -> Grammar.Regex: ...++ ...++class Hash:+ @property+ def method(self) -> HashMethod: ...+ @property+ def value(self) -> builtins.str: ...+ def __new__(cls, method: HashMethod, value: builtins.str) -> Hash: ...++class Image:+ @property+ def id(self) -> builtins.str: ...+ @property+ def url(self) -> builtins.str: ...+ @property+ def theme(self) -> ImageTheme: ...+ @property+ def format(self) -> ImageFormat: ...+ @property+ def description(self) -> typing.Optional[builtins.str]: ...+ @property+ def width(self) -> typing.Optional[builtins.int]: ...+ @property+ def height(self) -> typing.Optional[builtins.int]: ...+ def __new__(cls, id: builtins.str, url: builtins.str, theme: ImageTheme, format: ImageFormat, description: typing.Optional[builtins.str], width: typing.Optional[builtins.int], height: typing.Optional[builtins.int]) -> Image: ...++class Keyring:+ @staticmethod+ def create() -> Keyring: ...+ def store(self, key: builtins.str, value: builtins.str) -> None: ...+ def retrieve(self, key: builtins.str) -> typing.Optional[builtins.str]: ...+ def remove(self, key: builtins.str) -> None: ...++class Metadata:+ @property+ def identifier(self) -> builtins.str: ...+ @property+ def name(self) -> builtins.str: ...+ @property+ def description(self) -> typing.Optional[builtins.str]: ...+ @property+ def icons(self) -> builtins.list[Image]: ...+ def __new__(cls, identifier: builtins.str, name: builtins.str, description: typing.Optional[builtins.str], icons: typing.Sequence[Image]) -> Metadata: ...+ @staticmethod+ def external(name: builtins.str) -> Metadata: ...++class Model:+ @property+ def identifier(self) -> builtins.str: ...+ @property+ def registry(self) -> ModelRegistry: ...+ @property+ def backends(self) -> builtins.list[ModelBackend]: ...+ @property+ def family(self) -> typing.Optional[ModelFamily]: ...+ @property+ def properties(self) -> typing.Optional[ModelProperties]: ...+ @property+ def quantization(self) -> typing.Optional[ModelQuantization]: ...+ @property+ def specializations(self) -> builtins.list[ModelSpecialization]: ...+ @property+ def accessibility(self) -> ModelAccessibility: ...+ @property+ def name(self) -> builtins.str: ...+ @property+ def is_local(self) -> builtins.bool: ...+ @property+ def is_remote(self) -> builtins.bool: ...+ @property+ def is_downloadable(self) -> builtins.bool: ...+ @property+ def is_quantized(self) -> builtins.bool: ...+ @property+ def cache_identifier(self) -> builtins.str: ...+ @property+ def repo_ids(self) -> builtins.list[builtins.str]: ...+ @property+ def local_external_path(self) -> typing.Optional[builtins.str]: ...+ @property+ def reference_name(self) -> typing.Optional[builtins.str]: ...+ @property+ def checkpoint_version(self) -> typing.Optional[builtins.str]: ...+ @property+ def is_chat_capable(self) -> builtins.bool: ...+ @property+ def is_classification_capable(self) -> builtins.bool: ...+ @property+ def is_text_to_speech_capable(self) -> builtins.bool: ...+ @property+ def is_translation_capable(self) -> builtins.bool: ...+ @property+ def is_speculation_capable(self) -> builtins.bool: ...+ def __new__(cls, identifier: builtins.str, registry: ModelRegistry, backends: typing.Sequence[ModelBackend], family: typing.Optional[ModelFamily], properties: typing.Optional[ModelProperties], quantization: typing.Optional[ModelQuantization], specializations: typing.Sequence[ModelSpecialization], accessibility: ModelAccessibility) -> Model: ...+ @staticmethod+ def external(identifier: builtins.str, registry_identifier: builtins.str, registry_name: builtins.str, backend_identifier: builtins.str, backend_name: builtins.str, backend_version: builtins.str, specializations: typing.Sequence[ModelSpecialization], accessibility: ModelAccessibility) -> Model: ...++class ModelAccessibility:+ @typing.final+ class Local(ModelAccessibility):+ __match_args__ = ("reference",)+ @property+ def reference(self) -> ModelReference: ...+ def __new__(cls, reference: ModelReference) -> ModelAccessibility.Local: ...++ @typing.final+ class Remote(ModelAccessibility):+ __match_args__ = ("repository",)+ @property+ def repository(self) -> typing.Optional[Repository]: ...+ def __new__(cls, repository: typing.Optional[Repository]) -> ModelAccessibility.Remote: ...++ ...++class ModelBackend:+ @property+ def identifier(self) -> builtins.str: ...+ @property+ def version(self) -> builtins.str: ...+ @property+ def metadata(self) -> Metadata: ...+ @property+ def name(self) -> builtins.str: ...+ def __new__(cls, identifier: builtins.str, version: builtins.str, metadata: Metadata) -> ModelBackend: ...++class ModelFamily:+ @property+ def identifier(self) -> builtins.str: ...+ @property+ def vendor(self) -> ModelVendor: ...+ @property+ def metadata(self) -> Metadata: ...+ @property+ def name(self) -> builtins.str: ...+ def __new__(cls, identifier: builtins.str, vendor: ModelVendor, metadata: Metadata) -> ModelFamily: ...++class ModelProperties:+ @property+ def identifier(self) -> builtins.str: ...+ @property+ def size(self) -> builtins.int: ...+ @property+ def version(self) -> typing.Optional[builtins.str]: ...+ @property+ def metadata(self) -> Metadata: ...+ @property+ def name(self) -> builtins.str: ...+ def __new__(cls, identifier: builtins.str, size: builtins.int, version: typing.Optional[builtins.str], metadata: Metadata) -> ModelProperties: ...++class ModelQuantization:+ @property+ def identifier(self) -> builtins.str: ...+ @property+ def method(self) -> builtins.str: ...+ @property+ def bits_per_weight(self) -> builtins.int: ...+ @property+ def vendor(self) -> ModelVendor: ...+ @property+ def metadata(self) -> Metadata: ...+ @property+ def name(self) -> builtins.str: ...+ def __new__(cls, identifier: builtins.str, method: builtins.str, bits_per_weight: builtins.int, vendor: ModelVendor, metadata: Metadata) -> ModelQuantization: ...++class ModelReference:+ @typing.final+ class Mirai(ModelReference):+ __match_args__ = ("toolchain_version", "repository", "source_repository", "files",)+ @property+ def toolchain_version(self) -> builtins.str: ...+ @property+ def repository(self) -> typing.Optional[Repository]: ...+ @property+ def source_repository(self) -> typing.Optional[Repository]: ...+ @property+ def files(self) -> builtins.list[File]: ...+ def __new__(cls, toolchain_version: builtins.str, repository: typing.Optional[Repository], source_repository: typing.Optional[Repository], files: typing.Sequence[File]) -> ModelReference.Mirai: ...++ @typing.final+ class HuggingFace(ModelReference):+ __match_args__ = ("repository",)+ @property+ def repository(self) -> Repository: ...+ def __new__(cls, repository: Repository) -> ModelReference.HuggingFace: ...++ @typing.final+ class Local(ModelReference):+ __match_args__ = ("path",)+ @property+ def path(self) -> builtins.str: ...+ def __new__(cls, path: builtins.str) -> ModelReference.Local: ...++ ...++class ModelRegistry:+ @property+ def identifier(self) -> builtins.str: ...+ @property+ def metadata(self) -> Metadata: ...+ @property+ def name(self) -> builtins.str: ...+ def __new__(cls, identifier: builtins.str, metadata: Metadata) -> ModelRegistry: ...++class ModelSpecialization:+ @typing.final+ class Chat(ModelSpecialization):+ __match_args__ = ()+ def __new__(cls) -> ModelSpecialization.Chat: ...++ @typing.final+ class Classification(ModelSpecialization):+ __match_args__ = ()+ def __new__(cls) -> ModelSpecialization.Classification: ...++ @typing.final+ class TextToSpeech(ModelSpecialization):+ __match_args__ = ()+ def __new__(cls) -> ModelSpecialization.TextToSpeech: ...++ @typing.final+ class Translation(ModelSpecialization):+ __match_args__ = ()+ def __new__(cls) -> ModelSpecialization.Translation: ...++ @typing.final+ class Speculation(ModelSpecialization):+ __match_args__ = ()+ def __new__(cls) -> ModelSpecialization.Speculation: ...++ ...++class ModelVendor:+ @property+ def identifier(self) -> builtins.str: ...+ @property+ def metadata(self) -> Metadata: ...+ @property+ def name(self) -> builtins.str: ...+ def __new__(cls, identifier: builtins.str, metadata: Metadata) -> ModelVendor: ...++class PcmBatch:+ @property+ def samples(self) -> builtins.list[builtins.float]: ...+ @property+ def sample_rate(self) -> builtins.int: ...+ @property+ def channels(self) -> builtins.int: ...+ @property+ def lengths(self) -> builtins.list[builtins.int]: ...+ @property+ def batch_size(self) -> builtins.int: ...+ @property+ def total_frames(self) -> builtins.int: ...+ def __new__(cls, samples: typing.Sequence[builtins.float], sample_rate: builtins.int, channels: builtins.int, lengths: typing.Sequence[builtins.int]) -> PcmBatch: ...+ def save_as_wav(self, path: builtins.str) -> None: ...++class Repository:+ @property+ def identifier(self) -> builtins.str: ...+ @property+ def commit_hash(self) -> typing.Optional[builtins.str]: ...+ @property+ def paths(self) -> typing.Optional[builtins.list[builtins.str]]: ...+ def __new__(cls, identifier: builtins.str, commit_hash: typing.Optional[builtins.str], paths: typing.Optional[typing.Sequence[builtins.str]]) -> Repository: ...++class SamplingMethod:+ @typing.final+ class Greedy(SamplingMethod):+ __match_args__ = ()+ def __new__(cls) -> SamplingMethod.Greedy: ...++ @typing.final+ class Stochastic(SamplingMethod):+ __match_args__ = ("temperature", "top_k", "top_p", "min_p",)+ @property+ def temperature(self) -> typing.Optional[builtins.float]: ...+ @property+ def top_k(self) -> typing.Optional[builtins.int]: ...+ @property+ def top_p(self) -> typing.Optional[builtins.float]: ...+ @property+ def min_p(self) -> typing.Optional[builtins.float]: ...+ def __new__(cls, temperature: typing.Optional[builtins.float], top_k: typing.Optional[builtins.int], top_p: typing.Optional[builtins.float], min_p: typing.Optional[builtins.float]) -> SamplingMethod.Stochastic: ...++ ...++class SamplingPolicy:+ @typing.final+ class Default(SamplingPolicy):+ __match_args__ = ()+ def __new__(cls) -> SamplingPolicy.Default: ...++ @typing.final+ class Custom(SamplingPolicy):+ __match_args__ = ("method",)+ @property+ def method(self) -> SamplingMethod: ...+ def __new__(cls, method: SamplingMethod) -> SamplingPolicy.Custom: ...++ ...++class SamplingSeed:+ @typing.final+ class Default(SamplingSeed):+ __match_args__ = ()+ def __new__(cls) -> SamplingSeed.Default: ...++ @typing.final+ class Custom(SamplingSeed):+ __match_args__ = ("seed",)+ @property+ def seed(self) -> builtins.int: ...+ def __new__(cls, seed: builtins.int) -> SamplingSeed.Custom: ...++ ...++class TextToSpeechSession:+ def state(self) -> collections.abc.Awaitable[TextToSpeechSessionState]: ...+ def synthesize(self, input: builtins.str) -> collections.abc.Awaitable[PcmBatch]: ...++class TextToSpeechSessionStream:+ @property+ def cancel_token(self) -> CancelToken: ...+ def next(self) -> collections.abc.Awaitable[TextToSpeechSessionStreamChunk | None]: ...+ def __aiter__(self) -> TextToSpeechSessionStream: ...+ def __anext__(self) -> collections.abc.Awaitable[TextToSpeechSessionStreamChunk]: ...+ def iterator(self) -> TextToSpeechSessionStream: ...++class TextToSpeechSessionStreamChunk:+ @typing.final+ class PcmBatch(TextToSpeechSessionStreamChunk):+ __match_args__ = ("batch",)+ @property+ def batch(self) -> PcmBatch: ...+ def __new__(cls, batch: PcmBatch) -> TextToSpeechSessionStreamChunk.PcmBatch: ...++ @typing.final+ class Error(TextToSpeechSessionStreamChunk):+ __match_args__ = ("error",)+ @property+ def error(self) -> builtins.str: ...+ def __new__(cls, error: builtins.str) -> TextToSpeechSessionStreamChunk.Error: ...++ ...++class TextToSpeechStats:+ @property+ def text_length(self) -> builtins.int: ...+ @property+ def first_chunk_seconds(self) -> builtins.float: ...+ @property+ def generation_duration(self) -> builtins.float: ...+ @property+ def audio_duration(self) -> builtins.float: ...+ def __new__(cls, text_length: builtins.int, first_chunk_seconds: builtins.float, generation_duration: builtins.float, audio_duration: builtins.float) -> TextToSpeechStats: ...++class Token:+ @property+ def id(self) -> builtins.int: ...+ @property+ def value(self) -> builtins.str: ...+ @property+ def is_special(self) -> builtins.bool: ...+ def __new__(cls, id: builtins.int, value: builtins.str, is_special: builtins.bool) -> Token: ...++class ToolCall:+ @property+ def identifier(self) -> typing.Optional[builtins.str]: ...+ @property+ def name(self) -> builtins.str: ...+ @property+ def arguments(self) -> Value: ...+ def __new__(cls, identifier: typing.Optional[builtins.str], name: builtins.str, arguments: Value) -> ToolCall: ...++class ToolDescription:+ @typing.final+ class Function(ToolDescription):+ __match_args__ = ("tool_function",)+ @property+ def tool_function(self) -> ToolFunction: ...+ def __new__(cls, tool_function: ToolFunction) -> ToolDescription.Function: ...++ ...++class ToolFunction:+ @property+ def name(self) -> builtins.str: ...+ @property+ def description(self) -> builtins.str: ...+ @property+ def parameters(self) -> typing.Optional[Value]: ...+ @property+ def return_definition(self) -> typing.Optional[Value]: ...+ def __new__(cls, name: builtins.str, description: builtins.str, parameters: typing.Optional[Value], return_definition: typing.Optional[Value]) -> ToolFunction: ...++class ToolNamespace:+ @property+ def name(self) -> builtins.str: ...+ @property+ def description(self) -> typing.Optional[builtins.str]: ...+ @property+ def tools(self) -> builtins.list[ToolDescription]: ...+ def __new__(cls, name: builtins.str, description: typing.Optional[builtins.str], tools: typing.Sequence[ToolDescription]) -> ToolNamespace: ...++class TranslationPayload:+ @typing.final+ class Text(TranslationPayload):+ __match_args__ = ("text",)+ @property+ def text(self) -> builtins.str: ...+ def __new__(cls, text: builtins.str) -> TranslationPayload.Text: ...++ @typing.final+ class Image(TranslationPayload):+ __match_args__ = ("url",)+ @property+ def url(self) -> builtins.str: ...+ def __new__(cls, url: builtins.str) -> TranslationPayload.Image: ...++ ...++class Value:+ @property+ def json(self) -> builtins.str: ...+ def __new__(cls, json: builtins.str) -> Value: ...++class ChatContentBlockType(enum.Enum):+ Identity = ...+ ReasoningEffort = ...+ ConversationStartDate = ...+ KnowledgeCutoff = ...+ BuiltinTools = ...+ Tools = ...+ Text = ...+ Image = ...+ Video = ...+ Audio = ...+ File = ...+ Reasoning = ...+ ToolCall = ...+ ToolCallCandidate = ...+ ToolCallResult = ...+ Translation = ...+ Custom = ...++class ChatReplyFinishReason(enum.Enum):+ Stop = ...+ Length = ...+ Cancelled = ...+ ContextLimitReached = ...+ ToolCalls = ...+ Rejected = ...++class ChatSessionState(enum.Enum):+ Idle = ...+ Generation = ...+ ToolCalling = ...+ Resetting = ...++class ClassificationRole(enum.Enum):+ User = ...+ Assistant = ...++class ClassificationSessionState(enum.Enum):+ Idle = ...+ Classifying = ...++class HashMethod(enum.Enum):+ CRC32C = ...+ MD5 = ...++class ImageFormat(enum.Enum):+ Png = ...+ Webp = ...+ Svg = ...++class ImageTheme(enum.Enum):+ Light = ...+ Dark = ...++class ReasoningEffort(enum.Enum):+ Disabled = ...+ Default = ...+ Low = ...+ Medium = ...+ High = ...++class TextToSpeechSessionState(enum.Enum):+ Idle = ...+ Synthesizing = ...+diff --git a/bindings/python/uzu/py.typed b/bindings/python/uzu/py.typednew file mode 100644index 000000000..e69de29bbdiff --git a/bindings/swift/README.md b/bindings/swift/README.mdindex e505c8f1d..1749151c2 100644--- a/bindings/swift/README.md+++ b/bindings/swift/README.md@@ -43,8 +43,8 @@ Run it using one of the following commands:```bashswift run examples chat-swift run examples summarization-swift run examples classification+swift run examples chat-for-summarization+swift run examples chat-for-classificationswift run examples cloudswift run examples structured-outputswift run examples classifier@@ -66,7 +66,7 @@ Once loaded, the same `ChatSession` can be reused for multiple requests until yoIn this example, we will use the `summarization` preset to generate a summary of the input text:```swift-// include:Sources/Examples/Summarization.swift+// include:Sources/Examples/ChatForSummarization.swift```You will notice that the model’s run count is lower than the actual number of generated tokens due to speculative decoding, which significantly improves generation speed.@@ -76,7 +76,7 @@ You will notice that the model’s run count is lower than the actual number ofIn this example, we will use the `classification` preset to determine the sentiment of the user's input:```swift-// include:Sources/Examples/Classification.swift+// include:Sources/Examples/ChatForClassification.swift```You can view the stats to see that the answer will be ready immediately after the prefill step, and actual generation won’t even start due to speculative decoding, which significantly improves generation speed.diff --git a/bindings/swift/Sources/Examples/CLI.swift b/bindings/swift/Sources/Examples/CLI.swiftindex bfb5f2ede..1279d0b97 100644--- a/bindings/swift/Sources/Examples/CLI.swift+++ b/bindings/swift/Sources/Examples/CLI.swift@@ -12,7 +12,7 @@ struct Example: AsyncParsableCommand {@Argument(help:- "Mode: chat | summarization | classification | quick-start | snippets | cloud | ssm | structured-output | classifier | text-to-speech",+ "Mode: chat | chat-for-summarization | chat-for-classification | quick-start | snippets | cloud | ssm | structured-output | classifier | text-to-speech",transform: { $0.lowercased() })var mode: String = "chat"@@ -20,10 +20,10 @@ struct Example: AsyncParsableCommand {switch mode {case "chat":try await runChat()- case "summarization":- try await runSummarization()- case "classification":- try await runClassification()+ case "chat-for-summarization":+ try await runChatForSummarization()+ case "chat-for-classification":+ try await runChatForClassification()case "quick-start":try await runQuickStart()case "snippets":diff --git a/bindings/swift/Sources/Examples/Classification.swift b/bindings/swift/Sources/Examples/ChatForClassification.swiftsimilarity index 96%rename from bindings/swift/Sources/Examples/Classification.swiftrename to bindings/swift/Sources/Examples/ChatForClassification.swiftindex 893dea15f..ccd219cd7 100644--- a/bindings/swift/Sources/Examples/Classification.swift+++ b/bindings/swift/Sources/Examples/ChatForClassification.swift@@ -1,6 +1,6 @@import Uzu-public func runClassification() async throws {+public func runChatForClassification() async throws {let engineConfig = EngineConfig.create()let engine = try await Engine.create(config: engineConfig)diff --git a/bindings/swift/Sources/Examples/Summarization.swift b/bindings/swift/Sources/Examples/ChatForSummarization.swiftsimilarity index 97%rename from bindings/swift/Sources/Examples/Summarization.swiftrename to bindings/swift/Sources/Examples/ChatForSummarization.swiftindex b761aecc9..1e3bf51dd 100644--- a/bindings/swift/Sources/Examples/Summarization.swift+++ b/bindings/swift/Sources/Examples/ChatForSummarization.swift@@ -1,6 +1,6 @@import Uzu-public func runSummarization() async throws {+public func runChatForSummarization() async throws {let engineConfig = EngineConfig.create()let engine = try await Engine.create(config: engineConfig)diff --git a/bindings/ts/README.md b/bindings/ts/README.mdindex 9b182ada7..42ad72483 100644--- a/bindings/ts/README.md+++ b/bindings/ts/README.md@@ -38,12 +38,18 @@ Everything from model downloading to inference configuration is handled automati## Examples+Install dependencies:++```bash+pnpm i+```+Run it using one of the following commands:```bashpnpm run tsn examples/chat.ts-pnpm run tsn examples/summarization.ts-pnpm run tsn examples/classification.ts+pnpm run tsn examples/chatForSummarization.ts+pnpm run tsn examples/chatForClassification.tspnpm run tsn examples/cloud.tspnpm run tsn examples/structuredOutput.tspnpm run tsn examples/classifier.ts@@ -63,7 +69,7 @@ In this example, we will download a model and get a reply to a specific list ofIn this example, we will use the `summarization` preset to generate a summary of the input text:```ts-// include:examples/summarization.ts+// include:examples/chatForSummarization.ts```You will notice that the model’s run count is lower than the actual number of generated tokens due to speculative decoding, which significantly improves generation speed.@@ -73,7 +79,7 @@ You will notice that the model’s run count is lower than the actual number ofIn this example, we will use the `classification` preset to determine the sentiment of the user's input:```ts-// include:examples/classification.ts+// include:examples/chatForClassification.ts```You can view the stats to see that the answer will be ready immediately after the prefill step, and actual generation won’t even start due to speculative decoding, which significantly improves generation speed.diff --git a/bindings/ts/examples/classification.ts b/bindings/ts/examples/chatForClassification.tssimilarity index 100%rename from bindings/ts/examples/classification.tsrename to bindings/ts/examples/chatForClassification.tsdiff --git a/bindings/ts/examples/summarization.ts b/bindings/ts/examples/chatForSummarization.tssimilarity index 100%rename from bindings/ts/examples/summarization.tsrename to bindings/ts/examples/chatForSummarization.tsdiff --git a/crates/bindings-types/Cargo.toml b/crates/bindings-types/Cargo.tomlnew file mode 100644index 000000000..42c81f766--- /dev/null+++ b/crates/bindings-types/Cargo.toml@@ -0,0 +1,52 @@+[package]+name = "bindings-types"+version.workspace = true+edition.workspace = true+rust-version.workspace = true+license.workspace = true+authors.workspace = true+repository.workspace = true++[lib]+crate-type = ["lib", "cdylib", "staticlib"]++[features]+default = []+bindings = [+ "bindings-uniffi",+ "bindings-napi",+ "bindings-pyo3",+ "bindings-wasm",+]+bindings-uniffi = ["dep:uniffi"]+bindings-napi = ["dep:napi", "dep:napi-derive", "dep:napi-build"]+bindings-pyo3 = [+ "dep:pyo3",+ "dep:pyo3-build-config",+ "dep:pyo3-async-runtimes",+ "dep:pyo3-stub-gen",+ "dep:inventory",+]+bindings-wasm = [+ "dep:wasm-bindgen",+ "dep:serde-wasm-bindgen",+ "dep:wasm-bindgen-futures",+ "dep:tsify",+]++[dependencies]+uniffi = { workspace = true, optional = true }+napi = { workspace = true, optional = true }+napi-derive = { workspace = true, optional = true }+pyo3 = { workspace = true, optional = true }+pyo3-async-runtimes = { workspace = true, optional = true }+pyo3-stub-gen = { workspace = true, optional = true }+inventory = { workspace = true, optional = true }+wasm-bindgen = { workspace = true, optional = true }+serde-wasm-bindgen = { workspace = true, optional = true }+wasm-bindgen-futures = { workspace = true, optional = true }+tsify = { workspace = true, optional = true }++[build-dependencies]+napi-build = { workspace = true, optional = true }+pyo3-build-config = { workspace = true, optional = true }diff --git a/crates/bindings-types/build.rs b/crates/bindings-types/build.rsnew file mode 100644index 000000000..43dd98946--- /dev/null+++ b/crates/bindings-types/build.rs@@ -0,0 +1,6 @@+fn main() {+ #[cfg(feature = "bindings-napi")]+ napi_build::setup();+ #[cfg(feature = "bindings-pyo3")]+ pyo3_build_config::add_extension_module_link_args();+}diff --git a/crates/bindings-types/src/lib.rs b/crates/bindings-types/src/lib.rsnew file mode 100644index 000000000..5f85429af--- /dev/null+++ b/crates/bindings-types/src/lib.rs@@ -0,0 +1,10 @@+#[cfg(feature = "bindings-pyo3")]+extern crate self as bindings_types;++#[cfg(feature = "bindings-pyo3")]+pub struct PyClassRegistration {+ pub register: fn(&::pyo3::Bound<'_, ::pyo3::types::PyModule>) -> ::pyo3::PyResult<()>,+}++#[cfg(feature = "bindings-pyo3")]+::inventory::collect!(PyClassRegistration);diff --git a/crates/bindings/src/backends/mod.rs b/crates/bindings/src/backends/mod.rsnew file mode 100644index 000000000..fe10b835e--- /dev/null+++ b/crates/bindings/src/backends/mod.rs@@ -0,0 +1,79 @@+mod napi;+mod pyo3;+mod rust;+mod uniffi;+mod wasm;++pub use napi::Napi;+use proc_macro2::TokenStream;+pub use pyo3::Pyo3;+use quote::quote;+pub use rust::Rust;+pub use uniffi::Uniffi;+pub use wasm::Wasm;++use crate::contexts::{+ AliasContext, ClassContext, EnumerationContext, ErrorContext, ImplementationContext, MethodMetadata,+ StructureContext,+};++pub trait Backend {+ fn structure_attributes(_context: &StructureContext) -> TokenStream {+ quote! {}+ }++ fn structure_companions(_context: &StructureContext) -> TokenStream {+ quote! {}+ }++ fn class_attributes(_context: &ClassContext) -> TokenStream {+ quote! {}+ }++ fn class_companions(_context: &ClassContext) -> TokenStream {+ quote! {}+ }++ fn enumeration_attributes(_context: &EnumerationContext) -> TokenStream {+ quote! {}+ }++ fn enumeration_companions(_context: &EnumerationContext) -> TokenStream {+ quote! {}+ }++ fn alias_attributes(_context: &AliasContext) -> TokenStream {+ quote! {}+ }++ fn alias_companions(_context: &AliasContext) -> TokenStream {+ quote! {}+ }++ fn implementation_attributes(_context: &ImplementationContext) -> TokenStream {+ quote! {}+ }++ fn implementation_companions(_context: &ImplementationContext) -> TokenStream {+ quote! {}+ }++ fn method_attributes(_metadata: &MethodMetadata) -> TokenStream {+ quote! {}+ }++ fn method_companions(+ _context: &ImplementationContext,+ _metadata: &MethodMetadata,+ ) -> TokenStream {+ quote! {}+ }++ fn error_attributes(_context: &ErrorContext) -> TokenStream {+ quote! {}+ }++ fn error_companions(_context: &ErrorContext) -> TokenStream {+ quote! {}+ }+}diff --git a/crates/bindings/src/napi.rs b/crates/bindings/src/backends/napi.rssimilarity index 71%rename from crates/bindings/src/napi.rsrename to crates/bindings/src/backends/napi.rsindex e8b455a33..71aaa6724 100644--- a/crates/bindings/src/napi.rs+++ b/crates/bindings/src/backends/napi.rs@@ -1,56 +1,133 @@+use proc_macro2::TokenStream;use quote::{format_ident, quote};-use syn::{Attribute, Ident, Token, Variant, parse_quote, punctuated::Punctuated};+use syn::{Ident, Token, Variant, punctuated::Punctuated};++use crate::{+ backends::Backend,+ contexts::{+ AliasContext, ClassContext, EnumerationContext, EnumerationShape, ErrorContext, ErrorShape,+ ImplementationContext, MethodMetadata, StructureContext,+ },+ types::{ClassFlavor, MethodFlavor, StructureFlavor},+};++pub struct Napi;++impl Backend for Napi {+ fn structure_attributes(context: &StructureContext) -> TokenStream {+ match context.flavor {+ StructureFlavor::Plain => quote! {+ #[cfg_attr(feature = "bindings-napi", napi_derive::napi(object))]+ },+ StructureFlavor::Class => quote! {+ #[cfg_attr(feature = "bindings-napi", napi_derive::napi(constructor))]+ },+ }+ }-use crate::{BindingKind, MethodFlavor};+ fn structure_companions(context: &StructureContext) -> TokenStream {+ let type_name = &context.item.ident;+ match context.flavor {+ StructureFlavor::Plain => struct_value_implementations(type_name),+ StructureFlavor::Class => class_value_implementations(type_name),+ }+ }-pub fn attributes(kind: &BindingKind) -> proc_macro2::TokenStream {- match kind {- BindingKind::Enum => quote! {- #[cfg_attr(feature = "bindings-napi", napi_derive::napi(string_enum))]- },- BindingKind::Class => quote! {- #[cfg_attr(feature = "bindings-napi", napi_derive::napi)]- },- BindingKind::ClassCloneable => quote! {- #[cfg_attr(feature = "bindings-napi", napi_derive::napi(constructor))]- },- BindingKind::Stream => quote! {- #[cfg_attr(feature = "bindings-napi", napi_derive::napi(async_iterator))]- },- BindingKind::Struct => quote! {- #[cfg_attr(feature = "bindings-napi", napi_derive::napi(object))]- },- BindingKind::Implementation => quote! {+ fn class_attributes(context: &ClassContext) -> TokenStream {+ match context.flavor {+ ClassFlavor::Plain => quote! {+ #[cfg_attr(feature = "bindings-napi", napi_derive::napi)]+ },+ ClassFlavor::Stream => quote! {+ #[cfg_attr(feature = "bindings-napi", napi_derive::napi(async_iterator))]+ },+ }+ }++ fn enumeration_attributes(context: &EnumerationContext) -> TokenStream {+ match context.shape {+ EnumerationShape::Unit => quote! {+ #[cfg_attr(feature = "bindings-napi", napi_derive::napi(string_enum))]+ },+ EnumerationShape::Data => quote! {},+ }+ }++ fn enumeration_companions(context: &EnumerationContext) -> TokenStream {+ match context.shape {+ EnumerationShape::Unit => quote! {},+ EnumerationShape::Data => enum_variant_classes(&context.item.ident, &context.item.variants),+ }+ }++ fn alias_attributes(_context: &AliasContext) -> TokenStream {+ quote! {#[cfg_attr(feature = "bindings-napi", napi_derive::napi)]- },- BindingKind::Alias => quote! {+ }+ }++ fn implementation_attributes(_context: &ImplementationContext) -> TokenStream {+ quote! {#[cfg_attr(feature = "bindings-napi", napi_derive::napi)]- },- _ => quote! {},+ }}-}-pub fn method_attribute(flavor: &MethodFlavor) -> Attribute {- match flavor {- MethodFlavor::Plain => parse_quote! {- #[cfg_attr(feature = "bindings-napi", napi)]- },- MethodFlavor::Constructor => parse_quote! {- #[cfg_attr(feature = "bindings-napi", napi(constructor))]- },- MethodFlavor::Factory => parse_quote! {- #[cfg_attr(feature = "bindings-napi", napi)]- },- MethodFlavor::Getter => parse_quote! {- #[cfg_attr(feature = "bindings-napi", napi(getter))]- },- MethodFlavor::Setter => parse_quote! {- #[cfg_attr(feature = "bindings-napi", napi(setter))]- },+ fn method_attributes(metadata: &MethodMetadata) -> TokenStream {+ match metadata.flavor {+ MethodFlavor::Plain | MethodFlavor::StreamNext => quote! {+ #[cfg_attr(feature = "bindings-napi", napi)]+ },+ MethodFlavor::Constructor => quote! {+ #[cfg_attr(feature = "bindings-napi", napi(constructor))]+ },+ MethodFlavor::Getter => quote! {+ #[cfg_attr(feature = "bindings-napi", napi(getter))]+ },+ MethodFlavor::Setter => quote! {+ #[cfg_attr(feature = "bindings-napi", napi(setter))]+ },+ MethodFlavor::Factory | MethodFlavor::FactoryWithCallback => quote! {},+ }+ }++ fn method_companions(+ context: &ImplementationContext,+ metadata: &MethodMetadata,+ ) -> TokenStream {+ match metadata.flavor {+ MethodFlavor::Factory => factory_expansion(&context.self_type, metadata),+ MethodFlavor::FactoryWithCallback => factory_with_callback_expansion(&context.self_type, metadata),+ MethodFlavor::StreamNext => stream_next_generator(&context.self_type, &metadata.method),+ _ => quote! {},+ }+ }++ fn error_attributes(context: &ErrorContext) -> TokenStream {+ match context.shape {+ ErrorShape::Unit => quote! {+ #[cfg_attr(feature = "bindings-napi", napi_derive::napi(string_enum))]+ },+ ErrorShape::Data => quote! {+ #[cfg_attr(feature = "bindings-napi", napi_derive::napi)]+ },+ }+ }++ fn error_companions(context: &ErrorContext) -> TokenStream {+ let type_name = &context.item.ident;+ let value_implementations = match context.shape {+ ErrorShape::Unit => quote! {},+ ErrorShape::Data => struct_value_implementations(type_name),+ };+ let error_implementation_block = error_implementations(type_name);+ quote! {+ #value_implementations+ #error_implementation_block+ }}}-pub fn struct_value_implementations(type_name: &Ident) -> proc_macro2::TokenStream {+fn struct_value_implementations(type_name: &Ident) -> TokenStream {quote! {#[cfg(feature = "bindings-napi")]const _: () = {@@ -74,7 +151,7 @@ pub fn struct_value_implementations(type_name: &Ident) -> proc_macro2::TokenStre}}-pub fn class_value_implementations(type_name: &Ident) -> proc_macro2::TokenStream {+fn class_value_implementations(type_name: &Ident) -> TokenStream {quote! {#[cfg(feature = "bindings-napi")]const _: () = {@@ -105,10 +182,10 @@ pub fn class_value_implementations(type_name: &Ident) -> proc_macro2::TokenStrea}}-pub fn enum_variant_classes(+fn enum_variant_classes(enum_ident: &Ident,variants: &Punctuated<Variant, Token![,]>,-) -> proc_macro2::TokenStream {+) -> TokenStream {let union_alias_ident = format_ident!("{}Napi", enum_ident);let variant_count = variants.len();let either_type_ident: Option<Ident> = match variant_count {@@ -118,7 +195,7 @@ pub fn enum_variant_classes(n => {return syn::Error::new_spanned(enum_ident,- format!("bindings::export(Enum) supports up to 26 data variants (found {n})"),+ format!("Bindings::export(Enumeration) supports up to 26 data variants (found {n})"),).to_compile_error();},@@ -127,7 +204,7 @@ pub fn enum_variant_classes((0..variant_count).map(|index| format_ident!("{}", (b'A' + index as u8) as char)).collect();let mut variant_class_items = Vec::new();- let mut from_variant_impls = Vec::new();+ let mut from_variant_implementations = Vec::new();let mut to_napi_match_arms = Vec::new();let mut from_napi_try_branches = Vec::new();let mut union_type_params = Vec::new();@@ -143,7 +220,7 @@ pub fn enum_variant_classes(syn::Fields::Named(named) => &named.named,_ => unreachable!("non-named variants must be rejected before reaching this function"),};- let field_declarations: Vec<proc_macro2::TokenStream> = named_fields+ let field_declarations: Vec<TokenStream> = named_fields.iter().map(|field| {let field_ident = field.ident.as_ref().expect("named field");@@ -154,7 +231,7 @@ pub fn enum_variant_classes(let field_idents: Vec<&Ident> =named_fields.iter().map(|field| field.ident.as_ref().expect("named field")).collect();- let variant_class_value_impls = class_value_implementations(&variant_class_ident);+ let variant_class_value_implementations = class_value_implementations(&variant_class_ident);variant_class_items.push(quote! {#[cfg(feature = "bindings-napi")]#[napi_derive::napi(constructor)]@@ -163,10 +240,10 @@ pub fn enum_variant_classes(#( #field_declarations ),*}- #variant_class_value_impls+ #variant_class_value_implementations});- from_variant_impls.push(quote! {+ from_variant_implementations.push(quote! {#[cfg(feature = "bindings-napi")]impl From<#variant_class_ident> for #enum_ident {fn from(value: #variant_class_ident) -> Self {@@ -242,7 +319,7 @@ pub fn enum_variant_classes(},};- let union_from_impls = if either_type_ident.is_some() {+ let union_from_implementations = if either_type_ident.is_some() {quote! {#[cfg(feature = "bindings-napi")]impl From<#enum_ident> for #union_alias_ident {@@ -268,10 +345,10 @@ pub fn enum_variant_classes(quote! {#( #variant_class_items )*- #( #from_variant_impls )*+ #( #from_variant_implementations )*#union_alias_definition- #union_from_impls+ #union_from_implementations#[cfg(feature = "bindings-napi")]const _: () = {@@ -322,79 +399,18 @@ pub fn enum_variant_classes(}}-pub fn stream_next_generator(- self_type: &syn::Type,- method: &syn::ImplItemFn,-) -> proc_macro2::TokenStream {- let method_ident = &method.sig.ident;- let yield_type = match extract_option_inner_type(&method.sig.output) {- Some(ty) => ty,- None => {- return syn::Error::new_spanned(- &method.sig,- "bindings::export(StreamNext) requires return type `Option<T>`",- )- .to_compile_error();- },- };-- quote! {- #[cfg(feature = "bindings-napi")]- #[napi_derive::napi]- impl napi::bindgen_prelude::AsyncGenerator for #self_type {- type Yield = #yield_type;- type Next = ();- type Return = ();-- fn next(- &mut self,- _value: Option<Self::Next>,- ) -> impl ::core::future::Future<Output = napi::Result<Option<Self::Yield>>>- + Send- + 'static {- let this: Self = ::core::clone::Clone::clone(self);- async move { Ok(this.#method_ident().await) }- }- }- }-}--fn extract_option_inner_type(output: &syn::ReturnType) -> Option<syn::Type> {- let return_type = match output {- syn::ReturnType::Type(_, return_type) => return_type.as_ref(),- syn::ReturnType::Default => return None,- };- let type_path = match return_type {- syn::Type::Path(type_path) => type_path,- _ => return None,- };- let last_segment = type_path.path.segments.last()?;- if last_segment.ident != "Option" {- return None;- }- let generic_arguments = match &last_segment.arguments {- syn::PathArguments::AngleBracketed(angle_bracketed) => &angle_bracketed.args,- _ => return None,- };- for argument in generic_arguments {- if let syn::GenericArgument::Type(inner_type) = argument {- return Some(inner_type.clone());- }- }- None-}--pub fn factory(+fn factory_expansion(self_type: &syn::Type,- method: &syn::ImplItemFn,-) -> proc_macro2::TokenStream {+ metadata: &MethodMetadata,+) -> TokenStream {+ let method = &metadata.method;let method_ident = &method.sig.ident;let method_name = method_ident.to_string();let wrapper_ident = format_ident!("{}_bindings_napi", method_ident);let inputs = &method.sig.inputs;let output = &method.sig.output;let asyncness = &method.sig.asyncness;- let arg_idents = factory_arg_idents(inputs);+ let arg_idents = metadata.arg_idents();let forward_await = asyncness.as_ref().map(|_| quote! { .await });quote! {@@ -409,38 +425,25 @@ pub fn factory(}}-fn factory_arg_idents(inputs: &syn::punctuated::Punctuated<syn::FnArg, syn::Token![,]>) -> Vec<syn::Ident> {- inputs- .iter()- .filter_map(|arg| match arg {- syn::FnArg::Typed(pat_type) => match pat_type.pat.as_ref() {- syn::Pat::Ident(pat_ident) => Some(pat_ident.ident.clone()),- _ => None,- },- syn::FnArg::Receiver(_) => None,- })- .collect()-}--pub fn factory_with_callback(+fn factory_with_callback_expansion(self_type: &syn::Type,- method: &syn::ImplItemFn,-) -> proc_macro2::TokenStream {+ metadata: &MethodMetadata,+) -> TokenStream {+ let method = &metadata.method;let method_ident = &method.sig.ident;let body = &method.block;- let callback_inputs = match extract_callback_inputs(method) {+ let callback_inputs = match metadata.callback_inputs() {Some(inputs) => inputs,None => {return syn::Error::new_spanned(&method.sig,- "bindings::export(FactoryWithCallback) requires a parameter of type \+ "Bindings::export(Method(FactoryWithCallback)) requires a parameter of type \`Box<dyn Fn(..) + Send + Sync>` (return type must be `()`)",).to_compile_error();},};- let synthetic_idents: Vec<syn::Ident> =- (0..callback_inputs.len()).map(|index| format_ident!("arg{index}")).collect();+ let synthetic_idents: Vec<Ident> = (0..callback_inputs.len()).map(|index| format_ident!("arg{index}")).collect();let napi_args_type = napi_args_tuple(&callback_inputs);let napi_call_value = napi_call_tuple(&synthetic_idents);@@ -471,7 +474,7 @@ pub fn factory_with_callback(}}-fn napi_args_tuple(inputs: &[syn::Type]) -> proc_macro2::TokenStream {+fn napi_args_tuple(inputs: &[syn::Type]) -> TokenStream {match inputs.len() {0 => quote! { () },1 => {@@ -482,7 +485,7 @@ fn napi_args_tuple(inputs: &[syn::Type]) -> proc_macro2::TokenStream {}}-fn napi_call_tuple(idents: &[syn::Ident]) -> proc_macro2::TokenStream {+fn napi_call_tuple(idents: &[Ident]) -> TokenStream {match idents.len() {0 => quote! { () },1 => {@@ -493,69 +496,69 @@ fn napi_call_tuple(idents: &[syn::Ident]) -> proc_macro2::TokenStream {}}-pub(crate) fn extract_callback_inputs(method: &syn::ImplItemFn) -> Option<Vec<syn::Type>> {- for input in &method.sig.inputs {- let syn::FnArg::Typed(pat_type) = input else {- continue;- };- if let Some(inputs) = extract_void_fn_inputs(&pat_type.ty) {- return Some(inputs);- }- }- None-}--fn extract_void_fn_inputs(ty: &syn::Type) -> Option<Vec<syn::Type>> {- let inner = extract_box_inner(ty)?;- let syn::Type::TraitObject(trait_object) = inner else {- return None;+fn stream_next_generator(+ self_type: &syn::Type,+ method: &syn::ImplItemFn,+) -> TokenStream {+ let method_ident = &method.sig.ident;+ let yield_type = match extract_option_inner_type(&method.sig.output) {+ Some(ty) => ty,+ None => {+ return syn::Error::new_spanned(+ &method.sig,+ "Bindings::export(Method(StreamNext)) requires return type `Option<T>`",+ )+ .to_compile_error();+ },};- for bound in &trait_object.bounds {- let syn::TypeParamBound::Trait(trait_bound) = bound else {- continue;- };- let segment = trait_bound.path.segments.last()?;- if segment.ident != "Fn" && segment.ident != "FnMut" && segment.ident != "FnOnce" {- continue;- }- let syn::PathArguments::Parenthesized(paren) = &segment.arguments else {- continue;- };- let returns_unit = match &paren.output {- syn::ReturnType::Default => true,- syn::ReturnType::Type(_, ty) => match ty.as_ref() {- syn::Type::Tuple(tuple) => tuple.elems.is_empty(),- _ => false,- },- };- if !returns_unit {- return None;++ quote! {+ #[cfg(feature = "bindings-napi")]+ #[napi_derive::napi]+ impl napi::bindgen_prelude::AsyncGenerator for #self_type {+ type Yield = #yield_type;+ type Next = ();+ type Return = ();++ fn next(+ &mut self,+ _value: Option<Self::Next>,+ ) -> impl ::core::future::Future<Output = napi::Result<Option<Self::Yield>>>+ + Send+ + 'static {+ let this: Self = ::core::clone::Clone::clone(self);+ async move { Ok(this.#method_ident().await) }+ }}- return Some(paren.inputs.iter().cloned().collect());}- None}-fn extract_box_inner(ty: &syn::Type) -> Option<&syn::Type> {- let syn::Type::Path(type_path) = ty else {- return None;+fn extract_option_inner_type(output: &syn::ReturnType) -> Option<syn::Type> {+ let return_type = match output {+ syn::ReturnType::Type(_, return_type) => return_type.as_ref(),+ syn::ReturnType::Default => return None,+ };+ let type_path = match return_type {+ syn::Type::Path(type_path) => type_path,+ _ => return None,};- let segment = type_path.path.segments.last()?;- if segment.ident != "Box" {+ let last_segment = type_path.path.segments.last()?;+ if last_segment.ident != "Option" {return None;}- let syn::PathArguments::AngleBracketed(args) = &segment.arguments else {- return None;+ let generic_arguments = match &last_segment.arguments {+ syn::PathArguments::AngleBracketed(angle_bracketed) => &angle_bracketed.args,+ _ => return None,};- for argument in &args.args {- if let syn::GenericArgument::Type(inner) = argument {- return Some(inner);+ for argument in generic_arguments {+ if let syn::GenericArgument::Type(inner_type) = argument {+ return Some(inner_type.clone());}}None}-pub fn error_implementations(type_name: &Ident) -> proc_macro2::TokenStream {+fn error_implementations(type_name: &Ident) -> TokenStream {quote! {#[cfg(feature = "bindings-napi")]impl From<#type_name> for napi::Error {diff --git a/crates/bindings/src/backends/pyo3.rs b/crates/bindings/src/backends/pyo3.rsnew file mode 100644index 000000000..8605ebb7f--- /dev/null+++ b/crates/bindings/src/backends/pyo3.rs@@ -0,0 +1,666 @@+use proc_macro2::TokenStream;+use quote::{format_ident, quote};+use syn::Ident;++use crate::{+ backends::Backend,+ contexts::{+ ClassContext, EnumerationContext, EnumerationShape, ErrorContext, ImplementationContext, MethodMetadata,+ StructureContext,+ },+ types::MethodFlavor,+};++pub struct Pyo3;++impl Backend for Pyo3 {+ fn structure_attributes(_context: &StructureContext) -> TokenStream {+ quote! {+ #[cfg_attr(feature = "bindings-pyo3", pyo3_stub_gen::derive::gen_stub_pyclass)]+ #[cfg_attr(feature = "bindings-pyo3", pyo3::pyclass(get_all, from_py_object))]+ }+ }++ fn structure_companions(context: &StructureContext) -> TokenStream {+ let registration_block = registration(&context.item.ident);+ let constructor_block = struct_constructor(context.item);+ quote! {+ #registration_block+ #constructor_block+ }+ }++ fn class_attributes(_context: &ClassContext) -> TokenStream {+ quote! {+ #[cfg_attr(feature = "bindings-pyo3", pyo3_stub_gen::derive::gen_stub_pyclass)]+ #[cfg_attr(feature = "bindings-pyo3", pyo3::pyclass(from_py_object))]+ }+ }++ fn class_companions(context: &ClassContext) -> TokenStream {+ registration(&context.item.ident)+ }++ fn enumeration_attributes(context: &EnumerationContext) -> TokenStream {+ let stub_gen_attribute = match context.shape {+ EnumerationShape::Unit => quote! {+ #[cfg_attr(feature = "bindings-pyo3", pyo3_stub_gen::derive::gen_stub_pyclass_enum)]+ },+ EnumerationShape::Data => quote! {+ #[cfg_attr(feature = "bindings-pyo3", pyo3_stub_gen::derive::gen_stub_pyclass_complex_enum)]+ },+ };+ quote! {+ #stub_gen_attribute+ #[cfg_attr(feature = "bindings-pyo3", pyo3::pyclass(eq, from_py_object))]+ }+ }++ fn enumeration_companions(context: &EnumerationContext) -> TokenStream {+ registration(&context.item.ident)+ }++ fn implementation_companions(context: &ImplementationContext) -> TokenStream {+ implementation_expansion(context)+ }++ fn method_attributes(metadata: &MethodMetadata) -> TokenStream {+ match metadata.flavor {+ MethodFlavor::Constructor => quote! {+ #[cfg_attr(feature = "bindings-pyo3", new)]+ },+ MethodFlavor::Factory => quote! {+ #[cfg_attr(feature = "bindings-pyo3", staticmethod)]+ },+ _ => quote! {},+ }+ }++ fn method_companions(+ context: &ImplementationContext,+ metadata: &MethodMetadata,+ ) -> TokenStream {+ match metadata.flavor {+ MethodFlavor::Factory => factory_expansion(&context.self_type, metadata),+ MethodFlavor::FactoryWithCallback => factory_with_callback_expansion(&context.self_type, metadata),+ _ => quote! {},+ }+ }++ fn error_companions(context: &ErrorContext) -> TokenStream {+ error_implementations(&context.item.ident)+ }+}++fn implementation_expansion(context: &ImplementationContext) -> TokenStream {+ let mut wrappers: Vec<TokenStream> = Vec::new();+ for metadata in context.all_methods() {+ if matches!(metadata.flavor, MethodFlavor::Factory | MethodFlavor::FactoryWithCallback) {+ continue;+ }+ wrappers.push(build_method_wrapper(metadata));+ }++ if let Some(metadata) = context.methods_of(MethodFlavor::StreamNext).next() {+ wrappers.push(build_stream_protocol(&metadata.method));+ }++ if wrappers.is_empty() {+ return quote! {};+ }++ let self_type = &context.self_type;+ quote! {+ #[cfg(feature = "bindings-pyo3")]+ const _: () = {+ #[allow(unused_imports)]+ use ::pyo3::prelude::*;+ #[pyo3_stub_gen::derive::gen_stub_pymethods]+ #[pyo3::pymethods]+ impl #self_type {+ #( #wrappers )*+ }+ };+ }+}++fn build_stream_protocol(next_method: &syn::ImplItemFn) -> TokenStream {+ let next_ident = &next_method.sig.ident;+ let item_repr = next_item_type_repr(&next_method.sig.output).unwrap_or_else(|| "typing.Any".to_string());+ let anext_repr = format!("collections.abc.Awaitable[{item_repr}]");++ quote! {+ pub fn __aiter__(slf: ::pyo3::PyRef<'_, Self>) -> ::pyo3::PyRef<'_, Self> {+ slf+ }++ #[gen_stub(override_return_type(type_repr = #anext_repr, imports = ("collections.abc")))]+ pub fn __anext__<'py>(+ &self,+ py: ::pyo3::Python<'py>,+ ) -> ::pyo3::PyResult<::pyo3::Bound<'py, ::pyo3::PyAny>> {+ let __this = ::std::clone::Clone::clone(self);+ ::pyo3_async_runtimes::tokio::future_into_py(py, async move {+ match __this.#next_ident().await {+ ::std::option::Option::Some(value) => ::std::result::Result::Ok(value),+ ::std::option::Option::None => ::std::result::Result::Err(+ ::pyo3::exceptions::PyStopAsyncIteration::new_err("end of stream"),+ ),+ }+ })+ }++ pub fn iterator(slf: ::pyo3::PyRef<'_, Self>) -> ::pyo3::PyRef<'_, Self> {+ slf+ }+ }+}++fn next_item_type_repr(output: &syn::ReturnType) -> Option<String> {+ let return_type = match output {+ syn::ReturnType::Default => return None,+ syn::ReturnType::Type(_, return_type) => return_type.as_ref(),+ };+ let path = match return_type {+ syn::Type::Path(type_path) => &type_path.path,+ _ => return None,+ };+ let last = path.segments.last()?;+ if last.ident != "Option" {+ return None;+ }+ let arguments = match &last.arguments {+ syn::PathArguments::AngleBracketed(angle) => &angle.args,+ _ => return None,+ };+ let inner = arguments.iter().find_map(|argument| match argument {+ syn::GenericArgument::Type(inner_type) => Some(inner_type),+ _ => None,+ })?;+ let inner_path = match inner {+ syn::Type::Path(type_path) => &type_path.path,+ _ => return None,+ };+ Some(inner_path.segments.last()?.ident.to_string())+}++fn build_method_wrapper(metadata: &MethodMetadata) -> TokenStream {+ let method = &metadata.method;+ let flavor = metadata.flavor;+ let original_ident = &method.sig.ident;+ let original_name = original_ident.to_string();+ let wrapper_ident = format_ident!("__pyo3_{}", original_ident);+ let asyncness = metadata.is_async();++ let pyo3_attribute = if asyncness {+ match flavor {+ MethodFlavor::Constructor => quote! { #[new] },+ MethodFlavor::Factory => quote! { #[staticmethod] },+ _ => quote! {},+ }+ } else {+ match flavor {+ MethodFlavor::Constructor => quote! { #[new] },+ MethodFlavor::Factory => quote! { #[staticmethod] },+ MethodFlavor::Getter => quote! { #[getter] },+ MethodFlavor::Setter => quote! { #[setter] },+ MethodFlavor::Plain | MethodFlavor::FactoryWithCallback | MethodFlavor::StreamNext => {+ quote! {}+ },+ }+ };++ let receiver = metadata.receiver();+ let typed_args = metadata.typed_args();+ let arg_idents = metadata.arg_idents();+ let typed_arg_tokens: Vec<TokenStream> = typed_args+ .iter()+ .map(|pat_type| {+ let pattern = &pat_type.pat;+ let owned_type = strip_outer_ref(&pat_type.ty);+ quote! { #pattern: #owned_type }+ })+ .collect();+ let arg_call_tokens: Vec<TokenStream> = typed_args+ .iter()+ .zip(arg_idents.iter())+ .map(|(pat_type, ident)| {+ if matches!(pat_type.ty.as_ref(), syn::Type::Reference(_)) {+ quote! { &#ident }+ } else {+ quote! { #ident }+ }+ })+ .collect();++ let receiver_tokens = match receiver {+ Some(receiver_arg) if receiver_arg.mutability.is_some() => quote! { &mut self },+ Some(_) => quote! { &self },+ None => quote! {},+ };+ let receiver_separator = if receiver.is_some() && !typed_arg_tokens.is_empty() {+ quote! { , }+ } else {+ quote! {}+ };++ let pyo3_name_attribute = match flavor {+ MethodFlavor::Constructor => quote! {},+ _ => quote! { #[pyo3(name = #original_name)] },+ };++ let call_target = if receiver.is_some() {+ quote! { self.#original_ident }+ } else {+ quote! { Self::#original_ident }+ };++ if asyncness {+ let inner_repr = rust_return_to_python_repr(&method.sig.output);+ let awaitable_repr = format!("collections.abc.Awaitable[{inner_repr}]");+ let stub_attribute = quote! {+ #[gen_stub(override_return_type(type_repr = #awaitable_repr, imports = ("collections.abc")))]+ };+ let py_argument = quote! { py: ::pyo3::Python<'py> };+ let inputs_with_py = if receiver.is_some() {+ if typed_arg_tokens.is_empty() {+ quote! { #receiver_tokens, #py_argument }+ } else {+ quote! { #receiver_tokens, #py_argument, #( #typed_arg_tokens ),* }+ }+ } else if typed_arg_tokens.is_empty() {+ quote! { #py_argument }+ } else {+ quote! { #py_argument, #( #typed_arg_tokens ),* }+ };+ let capture = if receiver.is_some() {+ quote! { let __this = ::std::clone::Clone::clone(self); }+ } else {+ quote! {}+ };+ let invocation = if receiver.is_some() {+ quote! { __this.#original_ident( #( #arg_call_tokens ),* ).await }+ } else {+ quote! { Self::#original_ident( #( #arg_call_tokens ),* ).await }+ };+ let body = if metadata.returns_result() {+ quote! {+ let __result = #invocation;+ __result.map_err(::std::convert::Into::into)+ }+ } else {+ quote! {+ let __value = #invocation;+ ::std::result::Result::<_, ::pyo3::PyErr>::Ok(__value)+ }+ };+ quote! {+ #pyo3_attribute+ #pyo3_name_attribute+ #stub_attribute+ pub fn #wrapper_ident<'py>(+ #inputs_with_py+ ) -> ::pyo3::PyResult<::pyo3::Bound<'py, ::pyo3::PyAny>> {+ #capture+ ::pyo3_async_runtimes::tokio::future_into_py(py, async move {+ #body+ })+ }+ }+ } else {+ let output = &method.sig.output;+ let inputs = if receiver.is_some() {+ quote! { #receiver_tokens #receiver_separator #( #typed_arg_tokens ),* }+ } else {+ quote! { #( #typed_arg_tokens ),* }+ };+ quote! {+ #pyo3_attribute+ #pyo3_name_attribute+ pub fn #wrapper_ident( #inputs ) #output {+ #call_target( #( #arg_call_tokens ),* )+ }+ }+ }+}++fn strip_outer_ref(ty: &syn::Type) -> TokenStream {+ if let syn::Type::Reference(reference) = ty {+ let inner = &reference.elem;+ quote! { #inner }+ } else {+ quote! { #ty }+ }+}++fn rust_return_to_python_repr(output: &syn::ReturnType) -> String {+ let return_type = match output {+ syn::ReturnType::Default => return "None".to_string(),+ syn::ReturnType::Type(_, return_type) => return_type.as_ref(),+ };+ rust_type_to_python_repr(unwrap_result(return_type))+}++fn rust_return_to_python_repr_for_self(+ output: &syn::ReturnType,+ self_type: &syn::Type,+) -> String {+ let representation = rust_return_to_python_repr(output);+ let self_name =+ type_path_last_ident(self_type).map(|ident| ident.to_string()).unwrap_or_else(|| "typing.Any".to_string());+ representation.replace("Self", &self_name)+}++fn type_path_last_ident(ty: &syn::Type) -> Option<&Ident> {+ if let syn::Type::Path(type_path) = ty {+ return type_path.path.segments.last().map(|segment| &segment.ident);+ }+ None+}++fn unwrap_result(ty: &syn::Type) -> &syn::Type {+ if let syn::Type::Path(type_path) = ty {+ if let Some(last) = type_path.path.segments.last() {+ if last.ident == "Result" {+ if let syn::PathArguments::AngleBracketed(arguments) = &last.arguments {+ if let Some(syn::GenericArgument::Type(inner)) =+ arguments.args.iter().find(|argument| matches!(argument, syn::GenericArgument::Type(_)))+ {+ return inner;+ }+ }+ }+ }+ }+ ty+}++fn rust_type_to_python_repr(ty: &syn::Type) -> String {+ match ty {+ syn::Type::Path(type_path) => {+ let Some(last) = type_path.path.segments.last() else {+ return "typing.Any".to_string();+ };+ let name = last.ident.to_string();+ match name.as_str() {+ "bool" => "builtins.bool".to_string(),+ "i8" | "i16" | "i32" | "i64" | "i128" | "u8" | "u16" | "u32" | "u64" | "u128" | "isize" | "usize" => {+ "builtins.int".to_string()+ },+ "f32" | "f64" => "builtins.float".to_string(),+ "String" | "str" => "builtins.str".to_string(),+ "Option" => match generic_args(&last.arguments).as_slice() {+ [inner] => format!("{} | None", rust_type_to_python_repr(inner)),+ _ => "typing.Any".to_string(),+ },+ "Vec" => match generic_args(&last.arguments).as_slice() {+ [inner] => format!("builtins.list[{}]", rust_type_to_python_repr(inner)),+ _ => "typing.Any".to_string(),+ },+ "HashMap" | "BTreeMap" | "IndexMap" => match generic_args(&last.arguments).as_slice() {+ [key, value] => {+ format!("builtins.dict[{}, {}]", rust_type_to_python_repr(key), rust_type_to_python_repr(value))+ },+ _ => "typing.Any".to_string(),+ },+ _ => name,+ }+ },+ syn::Type::Tuple(tuple) if tuple.elems.is_empty() => "None".to_string(),+ syn::Type::Reference(reference) => rust_type_to_python_repr(reference.elem.as_ref()),+ _ => "typing.Any".to_string(),+ }+}++fn generic_args(arguments: &syn::PathArguments) -> Vec<&syn::Type> {+ let syn::PathArguments::AngleBracketed(angle) = arguments else {+ return Vec::new();+ };+ angle+ .args+ .iter()+ .filter_map(|argument| match argument {+ syn::GenericArgument::Type(ty) => Some(ty),+ _ => None,+ })+ .collect()+}++fn factory_expansion(+ self_type: &syn::Type,+ metadata: &MethodMetadata,+) -> TokenStream {+ let method = &metadata.method;+ let method_ident = &method.sig.ident;+ let method_name = method_ident.to_string();+ let wrapper_ident = format_ident!("{}_bindings_pyo3", method_ident);+ let inputs = &method.sig.inputs;+ let output = &method.sig.output;+ let asyncness = metadata.is_async();+ let arg_idents = metadata.arg_idents();++ if asyncness {+ let body = if metadata.returns_result() {+ quote! {+ let __result = <#self_type>::#method_ident( #( #arg_idents ),* ).await;+ __result.map_err(::std::convert::Into::into)+ }+ } else {+ quote! {+ let __value = <#self_type>::#method_ident( #( #arg_idents ),* ).await;+ ::std::result::Result::<_, ::pyo3::PyErr>::Ok(__value)+ }+ };+ let inner_repr = rust_return_to_python_repr_for_self(output, self_type);+ let awaitable_repr = format!("collections.abc.Awaitable[{inner_repr}]");+ quote! {+ #[cfg(feature = "bindings-pyo3")]+ const _: () = {+ #[allow(unused_imports)]+ use ::pyo3::prelude::*;+ #[pyo3_stub_gen::derive::gen_stub_pymethods]+ #[pyo3::pymethods]+ impl #self_type {+ #[staticmethod]+ #[pyo3(name = #method_name)]+ #[gen_stub(override_return_type(type_repr = #awaitable_repr, imports = ("collections.abc")))]+ pub fn #wrapper_ident<'py>(+ py: ::pyo3::Python<'py>,+ #inputs+ ) -> ::pyo3::PyResult<::pyo3::Bound<'py, ::pyo3::PyAny>> {+ ::pyo3_async_runtimes::tokio::future_into_py(py, async move {+ #body+ })+ }+ }+ };+ }+ } else {+ quote! {+ #[cfg(feature = "bindings-pyo3")]+ const _: () = {+ #[allow(unused_imports)]+ use ::pyo3::prelude::*;+ #[pyo3_stub_gen::derive::gen_stub_pymethods]+ #[pyo3::pymethods]+ impl #self_type {+ #[staticmethod]+ #[pyo3(name = #method_name)]+ pub fn #wrapper_ident( #inputs ) #output {+ <#self_type>::#method_ident( #( #arg_idents ),* )+ }+ }+ };+ }+ }+}++fn factory_with_callback_expansion(+ self_type: &syn::Type,+ metadata: &MethodMetadata,+) -> TokenStream {+ let method = &metadata.method;+ let method_ident = &method.sig.ident;+ let method_name = method_ident.to_string();+ let body = &method.block;+ let wrapper_ident = format_ident!("{}_bindings_pyo3", method_ident);++ let callback_inputs = match metadata.callback_inputs() {+ Some(inputs) => inputs,+ None => {+ return syn::Error::new_spanned(+ &method.sig,+ "Bindings::export(Method(FactoryWithCallback)) requires a parameter of type \+ `Box<dyn Fn(..) + Send + Sync>` (return type must be `()`)",+ )+ .to_compile_error();+ },+ };+ let synthetic_idents: Vec<Ident> = (0..callback_inputs.len()).map(|index| format_ident!("arg{index}")).collect();+ let py_call_arguments = if synthetic_idents.is_empty() {+ quote! { () }+ } else {+ quote! { ( #( #synthetic_idents ),* , ) }+ };+ let callback_arg_reprs: Vec<String> = callback_inputs.iter().map(rust_type_to_python_repr).collect();+ let callable_repr = format!("collections.abc.Callable[[{}], None]", callback_arg_reprs.join(", "));++ quote! {+ #[cfg(feature = "bindings-pyo3")]+ const _: () = {+ #[allow(unused_imports)]+ use ::pyo3::prelude::*;+ #[pyo3_stub_gen::derive::gen_stub_pymethods]+ #[pyo3::pymethods]+ impl #self_type {+ #[staticmethod]+ #[pyo3(name = #method_name)]+ pub fn #wrapper_ident(+ #[gen_stub(override_type(type_repr = #callable_repr, imports = ("collections.abc")))]+ callback: ::pyo3::Py<::pyo3::PyAny>,+ ) -> ::pyo3::PyResult<Self> {+ let callback: ::std::boxed::Box<+ dyn ::std::ops::Fn( #( #callback_inputs ),* ) + ::std::marker::Send + ::std::marker::Sync,+ > = ::std::boxed::Box::new(+ move | #( #synthetic_idents: #callback_inputs ),* | {+ ::pyo3::Python::attach(|py| {+ let _ = callback.call1(py, #py_call_arguments);+ });+ },+ );+ ::std::result::Result::Ok(#body)+ }+ }+ };+ }+}++fn struct_constructor(item_struct: &syn::ItemStruct) -> TokenStream {+ let type_name = &item_struct.ident;+ let fields = match &item_struct.fields {+ syn::Fields::Named(named) => &named.named,+ _ => return quote! {},+ };+ let public_fields: Vec<&syn::Field> =+ fields.iter().filter(|field| matches!(field.vis, syn::Visibility::Public(_))).collect();+ if public_fields.is_empty() {+ return quote! {};+ }+ let parameters: Vec<TokenStream> = public_fields+ .iter()+ .map(|field| {+ let ident = field.ident.as_ref().unwrap();+ let ty = &field.ty;+ quote! { #ident: #ty }+ })+ .collect();+ let assignments: Vec<TokenStream> = public_fields+ .iter()+ .map(|field| {+ let ident = field.ident.as_ref().unwrap();+ quote! { #ident }+ })+ .collect();+ quote! {+ #[cfg(feature = "bindings-pyo3")]+ const _: () = {+ #[allow(unused_imports)]+ use ::pyo3::prelude::*;+ #[pyo3_stub_gen::derive::gen_stub_pymethods]+ #[pyo3::pymethods]+ impl #type_name {+ #[new]+ fn __pyo3_new(#( #parameters ),*) -> Self {+ Self { #( #assignments ),* }+ }+ }+ };+ }+}++fn registration(type_name: &Ident) -> TokenStream {+ let type_name_string = type_name.to_string();+ quote! {+ #[cfg(feature = "bindings-pyo3")]+ ::inventory::submit! {+ ::bindings_types::PyClassRegistration {+ register: |module| {+ use ::pyo3::types::{PyAnyMethods, PyModuleMethods};+ module.add_class::<#type_name>()?;+ let cls = module.as_any().getattr(#type_name_string)?;+ let module_name: ::std::string::String =+ module.as_any().getattr("__name__")?.extract()?;+ let public_module = module_name+ .rsplit_once('.')+ .map(|(parent, _)| parent.to_owned())+ .unwrap_or(module_name);+ cls.setattr("__module__", public_module)?;+ ::std::result::Result::Ok(())+ },+ }+ }+ }+}++fn error_implementations(type_name: &Ident) -> TokenStream {+ let from_py_message = format!("{} cannot be received from Python", type_name);+ quote! {+ #[cfg(feature = "bindings-pyo3")]+ impl From<#type_name> for ::pyo3::PyErr {+ fn from(error: #type_name) -> Self {+ ::pyo3::exceptions::PyRuntimeError::new_err(error.to_string())+ }+ }++ #[cfg(feature = "bindings-pyo3")]+ impl<'a, 'py> ::pyo3::FromPyObject<'a, 'py> for #type_name {+ type Error = ::pyo3::PyErr;+ fn extract(_obj: ::pyo3::Borrowed<'a, 'py, ::pyo3::PyAny>) -> ::std::result::Result<Self, Self::Error> {+ ::std::result::Result::Err(+ ::pyo3::exceptions::PyTypeError::new_err(#from_py_message),+ )+ }+ }++ #[cfg(feature = "bindings-pyo3")]+ impl<'py> ::pyo3::IntoPyObject<'py> for #type_name {+ type Target = ::pyo3::types::PyString;+ type Output = ::pyo3::Bound<'py, ::pyo3::types::PyString>;+ type Error = ::std::convert::Infallible;++ fn into_pyobject(self, py: ::pyo3::Python<'py>) -> ::std::result::Result<Self::Output, Self::Error> {+ ::std::result::Result::Ok(::pyo3::types::PyString::new(py, &self.to_string()))+ }+ }++ #[cfg(feature = "bindings-pyo3")]+ impl ::pyo3_stub_gen::PyStubType for #type_name {+ fn type_output() -> ::pyo3_stub_gen::TypeInfo {+ ::pyo3_stub_gen::TypeInfo::builtin("str")+ }+ fn type_input() -> ::pyo3_stub_gen::TypeInfo {+ ::pyo3_stub_gen::TypeInfo::builtin("str")+ }+ }+ }+}diff --git a/crates/bindings/src/backends/rust.rs b/crates/bindings/src/backends/rust.rsnew file mode 100644index 000000000..2edc6bff8--- /dev/null+++ b/crates/bindings/src/backends/rust.rs@@ -0,0 +1,30 @@+use proc_macro2::TokenStream;+use quote::quote;++use crate::{+ backends::Backend,+ contexts::{ImplementationContext, MethodMetadata},+ types::MethodFlavor,+};++pub struct Rust;++impl Backend for Rust {+ fn method_companions(+ context: &ImplementationContext,+ metadata: &MethodMetadata,+ ) -> TokenStream {+ match metadata.flavor {+ MethodFlavor::Factory => {+ let self_type = &context.self_type;+ let method = &metadata.method;+ quote! {+ impl #self_type {+ #method+ }+ }+ },+ _ => quote! {},+ }+ }+}diff --git a/crates/bindings/src/uniffi.rs b/crates/bindings/src/backends/uniffi.rssimilarity index 53%rename from crates/bindings/src/uniffi.rsrename to crates/bindings/src/backends/uniffi.rsindex c87e3ee97..bdb1239e3 100644--- a/crates/bindings/src/uniffi.rs+++ b/crates/bindings/src/backends/uniffi.rs@@ -1,67 +1,96 @@+use proc_macro2::TokenStream;use quote::{format_ident, quote};-use syn::{Attribute, Ident, parse_quote};+use syn::Ident;-use crate::{BindingKind, MethodFlavor};+use crate::{+ backends::Backend,+ contexts::{+ ClassContext, EnumerationContext, ErrorContext, ImplementationContext, MethodMetadata, StructureContext,+ },+ types::MethodFlavor,+};-pub fn attributes(kind: &BindingKind) -> proc_macro2::TokenStream {- match kind {- BindingKind::Enum => quote! {- #[cfg_attr(feature = "bindings-uniffi", derive(uniffi::Enum))]- },- BindingKind::Struct => quote! {- #[cfg_attr(feature = "bindings-uniffi", derive(uniffi::Record))]- },- BindingKind::Class | BindingKind::Stream => quote! {- #[cfg_attr(feature = "bindings-uniffi", derive(uniffi::Object))]- },- BindingKind::ClassCloneable => quote! {+pub struct Uniffi;++impl Backend for Uniffi {+ fn structure_attributes(_context: &StructureContext) -> TokenStream {+ quote! {#[cfg_attr(feature = "bindings-uniffi", derive(uniffi::Record))]- },- BindingKind::Implementation => quote! {},- _ => quote! {},+ }}-}-pub fn implementation_attribute(has_async: bool) -> proc_macro2::TokenStream {- if has_async {+ fn class_attributes(_context: &ClassContext) -> TokenStream {quote! {- #[cfg_attr(feature = "bindings-uniffi", uniffi::export(async_runtime = "tokio"))]+ #[cfg_attr(feature = "bindings-uniffi", derive(uniffi::Object))]}- } else {+ }++ fn enumeration_attributes(_context: &EnumerationContext) -> TokenStream {quote! {- #[cfg_attr(feature = "bindings-uniffi", uniffi::export)]+ #[cfg_attr(feature = "bindings-uniffi", derive(uniffi::Enum))]}}-}-pub fn method_attribute(flavor: &MethodFlavor) -> Option<Attribute> {- match flavor {- MethodFlavor::Plain | MethodFlavor::Getter | MethodFlavor::Setter | MethodFlavor::Factory => None,- MethodFlavor::Constructor => Some(parse_quote! {- #[cfg_attr(feature = "bindings-uniffi", uniffi::constructor)]- }),+ fn implementation_attributes(context: &ImplementationContext) -> TokenStream {+ if context.has_async_method() {+ quote! {+ #[cfg_attr(feature = "bindings-uniffi", uniffi::export(async_runtime = "tokio"))]+ }+ } else {+ quote! {+ #[cfg_attr(feature = "bindings-uniffi", uniffi::export)]+ }+ }+ }++ fn method_attributes(metadata: &MethodMetadata) -> TokenStream {+ match metadata.flavor {+ MethodFlavor::Constructor => quote! {+ #[cfg_attr(feature = "bindings-uniffi", uniffi::constructor)]+ },+ _ => quote! {},+ }+ }++ fn method_companions(+ context: &ImplementationContext,+ metadata: &MethodMetadata,+ ) -> TokenStream {+ match metadata.flavor {+ MethodFlavor::Factory => factory_expansion(context, metadata),+ MethodFlavor::FactoryWithCallback => factory_with_callback_expansion(context, metadata),+ _ => quote! {},+ }+ }++ fn error_attributes(_context: &ErrorContext) -> TokenStream {+ quote! {+ #[cfg_attr(feature = "bindings-uniffi", derive(uniffi::Error))]+ }}}-pub fn factory(- self_type: &syn::Type,- method: &syn::ImplItemFn,-) -> proc_macro2::TokenStream {+fn factory_expansion(+ context: &ImplementationContext,+ metadata: &MethodMetadata,+) -> TokenStream {+ let self_type = &context.self_type;+ let method = &metadata.method;let method_ident = &method.sig.ident;- let self_ident = match self_type_ident(self_type) {+ let self_ident = match context.self_type_ident() {Some(ident) => ident,None => {- return syn::Error::new_spanned(self_type, "bindings::export(Factory) requires a named self type")+ return syn::Error::new_spanned(self_type, "Bindings::export(Method(Factory)) requires a named self type").to_compile_error();},};- let fn_name = format_ident!("{}_{}", heck::AsSnakeCase(self_ident.to_string()).to_string(), method_ident,);+ let fn_name = format_ident!("{}_{}", heck::AsSnakeCase(self_ident.to_string()).to_string(), method_ident);let inputs = &method.sig.inputs;let output = replace_self_in_return(&method.sig.output, self_type);let asyncness = &method.sig.asyncness;- let arg_idents = factory_arg_idents(inputs);+ let arg_idents = metadata.arg_idents();let forward_await = asyncness.as_ref().map(|_| quote! { .await });- let export_attr = if asyncness.is_some() {+ let export_attribute = if asyncness.is_some() {quote! { #[uniffi::export(async_runtime = "tokio")] }} else {quote! { #[uniffi::export] }@@ -69,100 +98,45 @@ pub fn factory(quote! {#[cfg(feature = "bindings-uniffi")]- #export_attr+ #export_attributepub #asyncness fn #fn_name( #inputs ) #output {<#self_type>::#method_ident( #( #arg_idents ),* )#forward_await}}}-fn replace_self_in_return(- output: &syn::ReturnType,- self_type: &syn::Type,-) -> syn::ReturnType {- use syn::fold::Fold;- let mut folder = SelfReplacer {- self_type: self_type.clone(),- };- folder.fold_return_type(output.clone())-}--struct SelfReplacer {- self_type: syn::Type,-}--impl syn::fold::Fold for SelfReplacer {- fn fold_type(- &mut self,- ty: syn::Type,- ) -> syn::Type {- if let syn::Type::Path(path) = &ty {- if path.qself.is_none()- && path.path.segments.len() == 1- && path.path.segments[0].ident == "Self"- && path.path.segments[0].arguments.is_empty()- {- return self.self_type.clone();- }- }- syn::fold::fold_type(self, ty)- }-}--fn factory_arg_idents(inputs: &syn::punctuated::Punctuated<syn::FnArg, syn::Token![,]>) -> Vec<syn::Ident> {- inputs- .iter()- .filter_map(|arg| match arg {- syn::FnArg::Typed(pat_type) => match pat_type.pat.as_ref() {- syn::Pat::Ident(pat_ident) => Some(pat_ident.ident.clone()),- _ => None,- },- syn::FnArg::Receiver(_) => None,- })- .collect()-}--pub fn error_attribute() -> proc_macro2::TokenStream {- quote! {- #[cfg_attr(feature = "bindings-uniffi", derive(uniffi::Error))]- }-}--#[allow(dead_code)]-pub fn error_implementations(_type_name: &Ident) -> proc_macro2::TokenStream {- quote! {}-}--pub fn factory_with_callback(- self_type: &syn::Type,- method: &syn::ImplItemFn,-) -> proc_macro2::TokenStream {+fn factory_with_callback_expansion(+ context: &ImplementationContext,+ metadata: &MethodMetadata,+) -> TokenStream {+ let self_type = &context.self_type;+ let method = &metadata.method;let method_ident = &method.sig.ident;let body = &method.block;- let self_ident = match self_type_ident(self_type) {+ let self_ident = match context.self_type_ident() {Some(ident) => ident,None => {return syn::Error::new_spanned(self_type,- "bindings::export(FactoryWithCallback) requires a named self type",+ "Bindings::export(Method(FactoryWithCallback)) requires a named self type",).to_compile_error();},};let handler_ident = format_ident!("{}Handler", self_ident);- let callback_inputs = match crate::napi::extract_callback_inputs(method) {+ let callback_inputs = match metadata.callback_inputs() {Some(inputs) => inputs,None => {return syn::Error::new_spanned(&method.sig,- "bindings::export(FactoryWithCallback) requires a parameter of type \+ "Bindings::export(Method(FactoryWithCallback)) requires a parameter of type \`Box<dyn Fn(..) + Send + Sync>` (return type must be `()`)",).to_compile_error();},};- let arg_idents: Vec<syn::Ident> = (0..callback_inputs.len()).map(|index| format_ident!("arg{index}")).collect();+ let arg_idents: Vec<Ident> = (0..callback_inputs.len()).map(|index| format_ident!("arg{index}")).collect();quote! {#[cfg(feature = "bindings-uniffi")]@@ -187,9 +161,35 @@ pub fn factory_with_callback(}}-fn self_type_ident(self_type: &syn::Type) -> Option<Ident> {- match self_type {- syn::Type::Path(path) => path.path.segments.last().map(|segment| segment.ident.clone()),- _ => None,+fn replace_self_in_return(+ output: &syn::ReturnType,+ self_type: &syn::Type,+) -> syn::ReturnType {+ use syn::fold::Fold;+ let mut folder = SelfReplacer {+ self_type: self_type.clone(),+ };+ folder.fold_return_type(output.clone())+}++struct SelfReplacer {+ self_type: syn::Type,+}++impl syn::fold::Fold for SelfReplacer {+ fn fold_type(+ &mut self,+ ty: syn::Type,+ ) -> syn::Type {+ if let syn::Type::Path(path) = &ty {+ if path.qself.is_none()+ && path.path.segments.len() == 1+ && path.path.segments[0].ident == "Self"+ && path.path.segments[0].arguments.is_empty()+ {+ return self.self_type.clone();+ }+ }+ syn::fold::fold_type(self, ty)}}diff --git a/crates/bindings/src/backends/wasm.rs b/crates/bindings/src/backends/wasm.rsnew file mode 100644index 000000000..94d35f497--- /dev/null+++ b/crates/bindings/src/backends/wasm.rs@@ -0,0 +1,55 @@+use proc_macro2::TokenStream;+use quote::quote;++use crate::{+ backends::Backend,+ contexts::{ClassContext, EnumerationContext, ErrorContext, ImplementationContext, StructureContext},+ types::StructureFlavor,+};++pub struct Wasm;++impl Backend for Wasm {+ fn structure_attributes(context: &StructureContext) -> TokenStream {+ match context.flavor {+ StructureFlavor::Plain => quote! {+ #[cfg_attr(feature = "bindings-wasm", derive(tsify::Tsify))]+ #[cfg_attr(feature = "bindings-wasm", tsify(into_wasm_abi, from_wasm_abi))]+ },+ StructureFlavor::Class => quote! {+ #[cfg_attr(feature = "bindings-wasm", wasm_bindgen::prelude::wasm_bindgen)]+ },+ }+ }++ fn class_attributes(_context: &ClassContext) -> TokenStream {+ quote! {+ #[cfg_attr(feature = "bindings-wasm", wasm_bindgen::prelude::wasm_bindgen)]+ }+ }++ fn enumeration_attributes(_context: &EnumerationContext) -> TokenStream {+ quote! {+ #[cfg_attr(feature = "bindings-wasm", derive(tsify::Tsify))]+ #[cfg_attr(feature = "bindings-wasm", tsify(into_wasm_abi, from_wasm_abi))]+ }+ }++ fn implementation_attributes(_context: &ImplementationContext) -> TokenStream {+ quote! {+ #[cfg_attr(feature = "bindings-wasm", wasm_bindgen::prelude::wasm_bindgen)]+ }+ }++ fn error_companions(context: &ErrorContext) -> TokenStream {+ let type_name = &context.item.ident;+ quote! {+ #[cfg(feature = "bindings-wasm")]+ impl From<#type_name> for wasm_bindgen::JsValue {+ fn from(error: #type_name) -> Self {+ wasm_bindgen::JsValue::from_str(&error.to_string())+ }+ }+ }+ }+}diff --git a/crates/bindings/src/contexts/alias_context.rs b/crates/bindings/src/contexts/alias_context.rsnew file mode 100644index 000000000..bbc9b8121--- /dev/null+++ b/crates/bindings/src/contexts/alias_context.rs@@ -0,0 +1 @@+pub struct AliasContext;diff --git a/crates/bindings/src/contexts/class_context.rs b/crates/bindings/src/contexts/class_context.rsnew file mode 100644index 000000000..053673b3c--- /dev/null+++ b/crates/bindings/src/contexts/class_context.rs@@ -0,0 +1,6 @@+use crate::types::ClassFlavor;++pub struct ClassContext<'item> {+ pub flavor: ClassFlavor,+ pub item: &'item syn::ItemStruct,+}diff --git a/crates/bindings/src/contexts/enumeration_context.rs b/crates/bindings/src/contexts/enumeration_context.rsnew file mode 100644index 000000000..d939b9843--- /dev/null+++ b/crates/bindings/src/contexts/enumeration_context.rs@@ -0,0 +1,51 @@+use syn::{Token, Variant, punctuated::Punctuated};++pub enum EnumerationShape {+ Unit,+ Data,+}++impl EnumerationShape {+ pub fn from_variants(variants: &Punctuated<Variant, Token![,]>) -> syn::Result<Self> {+ let mut has_unit_variant = false;+ let mut has_named_variant = false;+ for variant in variants {+ match variant.fields {+ syn::Fields::Unit => has_unit_variant = true,+ syn::Fields::Named(_) => has_named_variant = true,+ syn::Fields::Unnamed(_) => {+ return Err(syn::Error::new_spanned(+ &variant.fields,+ "Bindings::export(Enumeration) variants must use named fields (use `{}` for empty variants), tuple variants are not supported",+ ));+ },+ }+ }+ if has_unit_variant && has_named_variant {+ return Err(syn::Error::new(+ proc_macro2::Span::call_site(),+ "Bindings::export(Enumeration) variants must all be unit (e.g. `Foo`) or all be named (e.g. `Foo {}`, `Foo { x: i64 }`), mixing is not supported",+ ));+ }+ if has_named_variant {+ Ok(EnumerationShape::Data)+ } else {+ Ok(EnumerationShape::Unit)+ }+ }+}++pub struct EnumerationContext<'item> {+ pub item: &'item syn::ItemEnum,+ pub shape: EnumerationShape,+}++impl<'item> EnumerationContext<'item> {+ pub fn from_item(item: &'item syn::ItemEnum) -> syn::Result<Self> {+ let shape = EnumerationShape::from_variants(&item.variants)?;+ Ok(Self {+ item,+ shape,+ })+ }+}diff --git a/crates/bindings/src/contexts/error_context.rs b/crates/bindings/src/contexts/error_context.rsnew file mode 100644index 000000000..0fdf40c67--- /dev/null+++ b/crates/bindings/src/contexts/error_context.rs@@ -0,0 +1,31 @@+use syn::{Token, Variant, punctuated::Punctuated};++pub enum ErrorShape {+ Unit,+ Data,+}++impl ErrorShape {+ pub fn from_variants(variants: &Punctuated<Variant, Token![,]>) -> Self {+ if variants.iter().all(|variant| matches!(variant.fields, syn::Fields::Unit)) {+ ErrorShape::Unit+ } else {+ ErrorShape::Data+ }+ }+}++pub struct ErrorContext<'item> {+ pub item: &'item syn::ItemEnum,+ pub shape: ErrorShape,+}++impl<'item> ErrorContext<'item> {+ pub fn from_item(item: &'item syn::ItemEnum) -> Self {+ let shape = ErrorShape::from_variants(&item.variants);+ Self {+ item,+ shape,+ }+ }+}diff --git a/crates/bindings/src/contexts/implementation_context.rs b/crates/bindings/src/contexts/implementation_context.rsnew file mode 100644index 000000000..b7919742f--- /dev/null+++ b/crates/bindings/src/contexts/implementation_context.rs@@ -0,0 +1,144 @@+use proc_macro2::TokenStream;+use quote::quote;+use syn::{Attribute, ImplItem, ItemImpl, parse::Parser};++use crate::{+ backends::{Backend, Napi, Pyo3, Uniffi, Wasm},+ contexts::MethodMetadata,+ types::{Kind, MethodFlavor},+};++pub struct ImplementationContext {+ pub self_type: syn::Type,+ pub item: ItemImpl,+ pub methods: Vec<MethodMetadata>,+}++impl ImplementationContext {+ pub fn from_token_stream(tokens: TokenStream) -> syn::Result<Self> {+ let mut item: ItemImpl = syn::parse2(tokens)?;+ let self_type = (*item.self_ty).clone();++ let mut methods: Vec<MethodMetadata> = Vec::new();+ let mut retained_items: Vec<ImplItem> = Vec::new();++ for impl_item in std::mem::take(&mut item.items) {+ match impl_item {+ ImplItem::Fn(mut method) => {+ let flavor = parse_method_flavor(&method).ok_or_else(|| {+ syn::Error::new_spanned(+ &method.sig,+ format!(+ "Method `{}` inside `bindings::export(Implementation)` must be annotated with `#[bindings::export(Method(...))]`",+ method.sig.ident+ ),+ )+ })?;+ strip_export_attributes(&mut method.attrs);++ let extracted = matches!(flavor, MethodFlavor::Factory | MethodFlavor::FactoryWithCallback);++ if !extracted {+ let metadata_for_attrs = MethodMetadata {+ method: method.clone(),+ flavor,+ };+ apply_backend_method_attributes(&mut method, &metadata_for_attrs)?;+ }++ methods.push(MethodMetadata {+ method: method.clone(),+ flavor,+ });++ if !extracted {+ retained_items.push(ImplItem::Fn(method));+ }+ },+ other => retained_items.push(other),+ }+ }+ item.items = retained_items;++ Ok(Self {+ self_type,+ item,+ methods,+ })+ }++ pub fn all_methods(&self) -> impl Iterator<Item = &MethodMetadata> {+ self.methods.iter()+ }++ pub fn methods_of(+ &self,+ flavor: MethodFlavor,+ ) -> impl Iterator<Item = &MethodMetadata> {+ self.methods.iter().filter(move |metadata| metadata.flavor == flavor)+ }++ pub fn self_type_ident(&self) -> Option<&syn::Ident> {+ match &self.self_type {+ syn::Type::Path(type_path) => type_path.path.segments.last().map(|segment| &segment.ident),+ _ => None,+ }+ }++ pub fn has_async_method(&self) -> bool {+ self.item+ .items+ .iter()+ .any(|impl_item| matches!(impl_item, syn::ImplItem::Fn(method) if method.sig.asyncness.is_some()))+ }+}++fn apply_backend_method_attributes(+ method: &mut syn::ImplItemFn,+ metadata: &MethodMetadata,+) -> syn::Result<()> {+ let napi_tokens = Napi::method_attributes(metadata);+ let pyo3_tokens = Pyo3::method_attributes(metadata);+ let uniffi_tokens = Uniffi::method_attributes(metadata);+ let wasm_tokens = Wasm::method_attributes(metadata);+ let combined = quote! {+ #napi_tokens+ #pyo3_tokens+ #uniffi_tokens+ #wasm_tokens+ };+ let parsed_attributes = Attribute::parse_outer.parse2(combined)?;+ method.attrs.extend(parsed_attributes);+ Ok(())+}++fn parse_method_flavor(method: &syn::ImplItemFn) -> Option<MethodFlavor> {+ method.attrs.iter().find_map(|attribute| {+ if !is_export_attribute(attribute) {+ return None;+ }+ let kind: Kind = attribute.parse_args().ok()?;+ match kind {+ Kind::Method(flavor) => Some(flavor),+ _ => None,+ }+ })+}++fn strip_export_attributes(attributes: &mut Vec<Attribute>) {+ attributes.retain(|attribute| !is_export_attribute(attribute));+}++fn is_export_attribute(attribute: &Attribute) -> bool {+ let path = attribute.path();+ let Some(last) = path.segments.last() else {+ return false;+ };+ if last.ident != "export" {+ return false;+ }+ matches!(+ path.segments.first(),+ Some(first) if first.ident == "bindings" || first.ident == "export"+ )+}diff --git a/crates/bindings/src/contexts/method_metadata.rs b/crates/bindings/src/contexts/method_metadata.rsnew file mode 100644index 000000000..87c4439b2--- /dev/null+++ b/crates/bindings/src/contexts/method_metadata.rs@@ -0,0 +1,117 @@+use syn::Ident;++use crate::types::MethodFlavor;++pub struct MethodMetadata {+ pub method: syn::ImplItemFn,+ pub flavor: MethodFlavor,+}++impl MethodMetadata {+ pub fn is_async(&self) -> bool {+ self.method.sig.asyncness.is_some()+ }++ pub fn returns_result(&self) -> bool {+ let return_type = match &self.method.sig.output {+ syn::ReturnType::Default => return false,+ syn::ReturnType::Type(_, return_type) => return_type.as_ref(),+ };+ let path = match return_type {+ syn::Type::Path(type_path) => &type_path.path,+ _ => return false,+ };+ path.segments.last().map(|segment| segment.ident == "Result").unwrap_or(false)+ }++ pub fn receiver(&self) -> Option<&syn::Receiver> {+ self.method.sig.inputs.iter().find_map(|argument| match argument {+ syn::FnArg::Receiver(receiver) => Some(receiver),+ _ => None,+ })+ }++ pub fn typed_args(&self) -> Vec<&syn::PatType> {+ self.method+ .sig+ .inputs+ .iter()+ .filter_map(|argument| match argument {+ syn::FnArg::Typed(pat_type) => Some(pat_type),+ syn::FnArg::Receiver(_) => None,+ })+ .collect()+ }++ pub fn arg_idents(&self) -> Vec<Ident> {+ self.typed_args()+ .iter()+ .filter_map(|pat_type| match pat_type.pat.as_ref() {+ syn::Pat::Ident(pat_ident) => Some(pat_ident.ident.clone()),+ _ => None,+ })+ .collect()+ }++ pub fn callback_inputs(&self) -> Option<Vec<syn::Type>> {+ for input in &self.method.sig.inputs {+ let syn::FnArg::Typed(pat_type) = input else {+ continue;+ };+ if let Some(inputs) = extract_void_fn_inputs(&pat_type.ty) {+ return Some(inputs);+ }+ }+ None+ }+}++fn extract_void_fn_inputs(ty: &syn::Type) -> Option<Vec<syn::Type>> {+ let inner = extract_box_inner(ty)?;+ let syn::Type::TraitObject(trait_object) = inner else {+ return None;+ };+ for bound in &trait_object.bounds {+ let syn::TypeParamBound::Trait(trait_bound) = bound else {+ continue;+ };+ let segment = trait_bound.path.segments.last()?;+ if segment.ident != "Fn" && segment.ident != "FnMut" && segment.ident != "FnOnce" {+ continue;+ }+ let syn::PathArguments::Parenthesized(paren) = &segment.arguments else {+ continue;+ };+ let returns_unit = match &paren.output {+ syn::ReturnType::Default => true,+ syn::ReturnType::Type(_, ty) => match ty.as_ref() {+ syn::Type::Tuple(tuple) => tuple.elems.is_empty(),+ _ => false,+ },+ };+ if !returns_unit {+ return None;+ }+ return Some(paren.inputs.iter().cloned().collect());+ }+ None+}++fn extract_box_inner(ty: &syn::Type) -> Option<&syn::Type> {+ let syn::Type::Path(type_path) = ty else {+ return None;+ };+ let segment = type_path.path.segments.last()?;+ if segment.ident != "Box" {+ return None;+ }+ let syn::PathArguments::AngleBracketed(args) = &segment.arguments else {+ return None;+ };+ for argument in &args.args {+ if let syn::GenericArgument::Type(inner) = argument {+ return Some(inner);+ }+ }+ None+}diff --git a/crates/bindings/src/contexts/mod.rs b/crates/bindings/src/contexts/mod.rsnew file mode 100644index 000000000..468c747df--- /dev/null+++ b/crates/bindings/src/contexts/mod.rs@@ -0,0 +1,15 @@+mod alias_context;+mod class_context;+mod enumeration_context;+mod error_context;+mod implementation_context;+mod method_metadata;+mod structure_context;++pub use alias_context::AliasContext;+pub use class_context::ClassContext;+pub use enumeration_context::{EnumerationContext, EnumerationShape};+pub use error_context::{ErrorContext, ErrorShape};+pub use implementation_context::ImplementationContext;+pub use method_metadata::MethodMetadata;+pub use structure_context::StructureContext;diff --git a/crates/bindings/src/contexts/structure_context.rs b/crates/bindings/src/contexts/structure_context.rsnew file mode 100644index 000000000..4af07c6c5--- /dev/null+++ b/crates/bindings/src/contexts/structure_context.rs@@ -0,0 +1,6 @@+use crate::types::StructureFlavor;++pub struct StructureContext<'item> {+ pub flavor: StructureFlavor,+ pub item: &'item syn::ItemStruct,+}diff --git a/crates/bindings/src/lib.rs b/crates/bindings/src/lib.rsindex 0352b8bd4..da8f5dd5d 100644--- a/crates/bindings/src/lib.rs+++ b/crates/bindings/src/lib.rs@@ -1,76 +1,33 @@-mod napi;-mod pyo3;-mod uniffi;-mod wasm;+mod backends;+mod contexts;+mod types;use proc_macro::TokenStream;+use proc_macro2::TokenStream as TokenStream2;use quote::quote;-use syn::{- Attribute, Ident, ImplItem, ItemImpl, Token,- parse::{Parse, ParseStream},- parse_macro_input,-};--pub(crate) enum BindingKind {- Enum,- Struct,- Class,- ClassCloneable,- Stream,- Alias,- Implementation,- Method,- Constructor,- Factory,- FactoryWithCallback,- Getter,- Setter,- StreamNext,- Error,-}+use syn::parse_macro_input;-pub(crate) enum MethodFlavor {- Plain,- Constructor,- Factory,- Getter,- Setter,-}--struct ExportArguments {- kind: BindingKind,-}+use crate::{+ backends::Backend,+ contexts::{AliasContext, ClassContext, EnumerationContext, ErrorContext, ImplementationContext, StructureContext},+ types::{ClassFlavor, Kind, StructureFlavor},+};-impl Parse for ExportArguments {- fn parse(input: ParseStream) -> syn::Result<Self> {- let identifier: Ident = input.parse()?;- let kind = match identifier.to_string().as_str() {- "Enum" => BindingKind::Enum,- "Struct" => BindingKind::Struct,- "Class" => BindingKind::Class,- "ClassCloneable" => BindingKind::ClassCloneable,- "Stream" => BindingKind::Stream,- "Alias" => BindingKind::Alias,- "Implementation" => BindingKind::Implementation,- "Method" => BindingKind::Method,- "Constructor" => BindingKind::Constructor,- "Factory" => BindingKind::Factory,- "FactoryWithCallback" => BindingKind::FactoryWithCallback,- "Getter" => BindingKind::Getter,- "Setter" => BindingKind::Setter,- "StreamNext" => BindingKind::StreamNext,- "Error" => BindingKind::Error,- other => {- return Err(syn::Error::new(identifier.span(), format!("Unknown binding kind: {other}")));- },- };- if input.peek(Token![,]) {- return Err(input.error("bindings::export accepts a single kind argument"));+macro_rules! all_backends {+ ($method:ident, $($args:tt)*) => {{+ let rust_tokens = $crate::backends::Rust::$method($($args)*);+ let napi_tokens = $crate::backends::Napi::$method($($args)*);+ let pyo3_tokens = $crate::backends::Pyo3::$method($($args)*);+ let uniffi_tokens = $crate::backends::Uniffi::$method($($args)*);+ let wasm_tokens = $crate::backends::Wasm::$method($($args)*);+ ::quote::quote! {+ #rust_tokens+ #napi_tokens+ #pyo3_tokens+ #uniffi_tokens+ #wasm_tokens}- Ok(ExportArguments {- kind,- })- }+ }};}#[proc_macro_attribute]@@ -78,351 +35,132 @@ pub fn export(arguments: TokenStream,item: TokenStream,) -> TokenStream {- let ExportArguments {- kind,- } = parse_macro_input!(arguments as ExportArguments);+ let kind = parse_macro_input!(arguments as Kind);match kind {- BindingKind::Enum => {- let item = parse_macro_input!(item as syn::Item);- let item_enum = match &item {- syn::Item::Enum(item_enum) => item_enum,- _ => {- return syn::Error::new_spanned(&item, "bindings::export(Enum) must be applied to an enum")- .to_compile_error()- .into();- },- };-- let mut has_unit_fields = false;- let mut has_named_fields = false;- for variant in &item_enum.variants {- match variant.fields {- syn::Fields::Unit => has_unit_fields = true,- syn::Fields::Named(_) => has_named_fields = true,- syn::Fields::Unnamed(_) => {- return syn::Error::new_spanned(- &variant.fields,- "bindings::export(Enum) variants must use named fields (use `{}` for empty variants), tuple variants are not supported",- )- .to_compile_error()- .into();- },- }- }- if has_unit_fields && has_named_fields {- return syn::Error::new_spanned(- &item_enum.ident,- "bindings::export(Enum) variants must all be unit (e.g. `Foo`) or all be named (e.g. `Foo {}`, `Foo { x: i64 }`), mixing is not supported",- )- .to_compile_error()- .into();- }-- let enum_is_data = has_named_fields;- let uniffi = uniffi::attributes(&kind);- let pyo3 = pyo3::attributes(&kind);- let wasm = wasm::attributes(&kind);-- if enum_is_data {- let variant_classes = napi::enum_variant_classes(&item_enum.ident, &item_enum.variants);- quote! {- #uniffi- #pyo3- #wasm- #item- #variant_classes- }- .into()- } else {- let napi = napi::attributes(&kind);- quote! {- #napi- #uniffi- #pyo3- #wasm- #item- }- .into()- }- },- BindingKind::Struct | BindingKind::Class | BindingKind::ClassCloneable | BindingKind::Stream => {- let item = parse_macro_input!(item as syn::Item);- let type_name = match &item {- syn::Item::Struct(item_struct) => Some(&item_struct.ident),- _ => None,- };- let napi = napi::attributes(&kind);- let uniffi = uniffi::attributes(&kind);- let pyo3 = pyo3::attributes(&kind);- let wasm = wasm::attributes(&kind);- let napi_value = match (&kind, type_name) {- (BindingKind::Struct, Some(ident)) => napi::struct_value_implementations(ident),- (BindingKind::ClassCloneable, Some(ident)) => napi::class_value_implementations(ident),- _ => quote! {},- };- quote! {- #napi- #uniffi- #pyo3- #wasm- #item- #napi_value- }- .into()- },- BindingKind::Alias => {- let item = parse_macro_input!(item as syn::ItemType);- let napi = napi::attributes(&kind);- let uniffi = uniffi::attributes(&kind);- let pyo3 = pyo3::attributes(&kind);- let wasm = wasm::attributes(&kind);- quote! {- #napi- #uniffi- #pyo3- #wasm- #item- }- .into()- },- BindingKind::Implementation => {- let mut item_implementation = match syn::parse::<ItemImpl>(item) {- Ok(item_implementation) => item_implementation,- Err(error) => return error.to_compile_error().into(),- };- let self_type = item_implementation.self_ty.clone();-- let mut callback_factories: Vec<syn::ImplItemFn> = Vec::new();- item_implementation.items.retain(|item| match item {- ImplItem::Fn(method) if method_has_factory_with_callback(method) => {- callback_factories.push(method.clone());- false- },- _ => true,- });-- let mut factories: Vec<syn::ImplItemFn> = Vec::new();- item_implementation.items.retain(|item| match item {- ImplItem::Fn(method) if method_has_factory(method) => {- let mut stripped = method.clone();- strip_bindings_export_attrs(&mut stripped.attrs);- factories.push(stripped);- false- },- _ => true,- });-- let mut stream_next_methods: Vec<syn::ImplItemFn> = Vec::new();- for item in &item_implementation.items {- if let ImplItem::Fn(method) = item {- if method_has_stream_next(method) {- stream_next_methods.push(method.clone());- }- }- }-- for item in &mut item_implementation.items {- if let ImplItem::Fn(method) = item {- rewrite_method_attributes(&mut method.attrs);- }- }-- let callback_expansions: Vec<proc_macro2::TokenStream> = callback_factories- .iter()- .map(|method| {- let napi_expansion = napi::factory_with_callback(&self_type, method);- let uniffi_expansion = uniffi::factory_with_callback(&self_type, method);- quote! {- #napi_expansion- #uniffi_expansion- }- })- .collect();-- let stream_expansions: Vec<proc_macro2::TokenStream> =- stream_next_methods.iter().map(|method| napi::stream_next_generator(&self_type, method)).collect();-- let factory_expansions: Vec<proc_macro2::TokenStream> = factories- .iter()- .map(|method| {- let plain_impl = quote! {- impl #self_type {- #method- }- };- let napi_expansion = napi::factory(&self_type, method);- let uniffi_expansion = uniffi::factory(&self_type, method);- let pyo3_expansion = pyo3::factory(&self_type, method);- quote! {- #plain_impl- #napi_expansion- #uniffi_expansion- #pyo3_expansion- }- })- .collect();-- let has_async_methods = item_implementation- .items- .iter()- .any(|item| matches!(item, ImplItem::Fn(method) if method.sig.asyncness.is_some()));- let napi = napi::attributes(&kind);- let uniffi = uniffi::implementation_attribute(has_async_methods);- let pyo3 = pyo3::attributes(&kind);- let wasm = wasm::attributes(&kind);- quote! {- #napi- #uniffi- #pyo3- #wasm- #item_implementation- #( #callback_expansions )*- #( #stream_expansions )*- #( #factory_expansions )*- }- .into()- },- BindingKind::Method- | BindingKind::Constructor- | BindingKind::Factory- | BindingKind::FactoryWithCallback- | BindingKind::Getter- | BindingKind::Setter- | BindingKind::StreamNext => {- let tokens = proc_macro2::TokenStream::from(item);- quote! { #tokens }.into()- },- BindingKind::Error => {- let item = parse_macro_input!(item as syn::Item);- let item_enum = match &item {- syn::Item::Enum(item_enum) => item_enum,- _ => {- return syn::Error::new_spanned(&item, "Error can only be applied to enums")- .to_compile_error()- .into();- },- };- let type_name = &item_enum.ident;- let all_unit_variants =- item_enum.variants.iter().all(|variant| matches!(variant.fields, syn::Fields::Unit));- let napi_attribute = if all_unit_variants {- quote! {- #[cfg_attr(feature = "bindings-napi", napi_derive::napi(string_enum))]- }- } else {- quote! {- #[cfg_attr(feature = "bindings-napi", napi_derive::napi)]- }- };- let napi_value = if all_unit_variants {- quote! {}- } else {- napi::struct_value_implementations(type_name)- };- let uniffi = uniffi::error_attribute();- let napi_implementations = napi::error_implementations(type_name);- let pyo3_implementations = pyo3::error_implementations(type_name);- let wasm_implementations = wasm::error_implementations(type_name);- quote! {- #napi_attribute- #uniffi- #item- #napi_value- #napi_implementations- #pyo3_implementations- #wasm_implementations- }- .into()- },+ Kind::Enumeration => dispatch_enumeration(item),+ Kind::Structure(flavor) => dispatch_structure(item, flavor),+ Kind::Class(flavor) => dispatch_class(item, flavor),+ Kind::Alias => dispatch_alias(item),+ Kind::Implementation => dispatch_implementation(item),+ Kind::Method(_) => item,+ Kind::Error => dispatch_error(item),}}-fn rewrite_method_attributes(attributes: &mut Vec<Attribute>) {- let mut rewritten_attributes: Vec<Attribute> = Vec::with_capacity(attributes.len());- for attribute in attributes.drain(..) {- match method_flavor(&attribute) {- Some(flavor) => {- rewritten_attributes.push(napi::method_attribute(&flavor));- if let Some(attribute) = uniffi::method_attribute(&flavor) {- rewritten_attributes.push(attribute);- }- if let Some(attribute) = pyo3::method_attribute(&flavor) {- rewritten_attributes.push(attribute);- }- },- None => rewritten_attributes.push(attribute),- }+fn dispatch_enumeration(item: TokenStream) -> TokenStream {+ let parsed: syn::ItemEnum = match syn::parse(item) {+ Ok(item_enum) => item_enum,+ Err(error) => return error.to_compile_error().into(),+ };+ let context = match EnumerationContext::from_item(&parsed) {+ Ok(context) => context,+ Err(error) => return error.to_compile_error().into(),+ };+ let attributes = all_backends!(enumeration_attributes, &context);+ let companions = all_backends!(enumeration_companions, &context);+ quote! {+ #attributes+ #parsed+ #companions}- *attributes = rewritten_attributes;+ .into()}-fn method_flavor(attribute: &Attribute) -> Option<MethodFlavor> {- if !is_exportable_attribute(attribute) {- return None;- }- let arguments: ExportArguments = attribute.parse_args().ok()?;- match arguments.kind {- BindingKind::Method => Some(MethodFlavor::Plain),- BindingKind::Constructor => Some(MethodFlavor::Constructor),- BindingKind::Factory => Some(MethodFlavor::Factory),- BindingKind::Getter => Some(MethodFlavor::Getter),- BindingKind::Setter => Some(MethodFlavor::Setter),- BindingKind::StreamNext => Some(MethodFlavor::Plain),- _ => None,+fn dispatch_structure(+ item: TokenStream,+ flavor: StructureFlavor,+) -> TokenStream {+ let parsed: syn::ItemStruct = match syn::parse(item) {+ Ok(item_struct) => item_struct,+ Err(error) => return error.to_compile_error().into(),+ };+ let context = StructureContext {+ flavor,+ item: &parsed,+ };+ let attributes = all_backends!(structure_attributes, &context);+ let companions = all_backends!(structure_companions, &context);+ quote! {+ #attributes+ #parsed+ #companions}+ .into()}-fn method_has_factory(method: &syn::ImplItemFn) -> bool {- method.attrs.iter().any(|attribute| {- if !is_exportable_attribute(attribute) {- return false;- }- let Ok(arguments): syn::Result<ExportArguments> = attribute.parse_args() else {- return false;- };- matches!(arguments.kind, BindingKind::Factory)- })-}--fn strip_bindings_export_attrs(attrs: &mut Vec<Attribute>) {- attrs.retain(|attribute| !is_exportable_attribute(attribute));+fn dispatch_class(+ item: TokenStream,+ flavor: ClassFlavor,+) -> TokenStream {+ let parsed: syn::ItemStruct = match syn::parse(item) {+ Ok(item_struct) => item_struct,+ Err(error) => return error.to_compile_error().into(),+ };+ let context = ClassContext {+ flavor,+ item: &parsed,+ };+ let attributes = all_backends!(class_attributes, &context);+ let companions = all_backends!(class_companions, &context);+ quote! {+ #attributes+ #parsed+ #companions+ }+ .into()}-fn method_has_stream_next(method: &syn::ImplItemFn) -> bool {- method.attrs.iter().any(|attribute| {- if !is_exportable_attribute(attribute) {- return false;- }- let Ok(arguments): syn::Result<ExportArguments> = attribute.parse_args() else {- return false;- };- matches!(arguments.kind, BindingKind::StreamNext)- })+fn dispatch_alias(item: TokenStream) -> TokenStream {+ let parsed: syn::ItemType = match syn::parse(item) {+ Ok(item_type) => item_type,+ Err(error) => return error.to_compile_error().into(),+ };+ let context = AliasContext;+ let attributes = all_backends!(alias_attributes, &context);+ let companions = all_backends!(alias_companions, &context);+ quote! {+ #attributes+ #parsed+ #companions+ }+ .into()}-fn method_has_factory_with_callback(method: &syn::ImplItemFn) -> bool {- method.attrs.iter().any(|attribute| {- if !is_exportable_attribute(attribute) {- return false;- }- let Ok(arguments): syn::Result<ExportArguments> = attribute.parse_args() else {- return false;- };- matches!(arguments.kind, BindingKind::FactoryWithCallback)- })+fn dispatch_error(item: TokenStream) -> TokenStream {+ let parsed: syn::ItemEnum = match syn::parse(item) {+ Ok(item_enum) => item_enum,+ Err(error) => return error.to_compile_error().into(),+ };+ let context = ErrorContext::from_item(&parsed);+ let attributes = all_backends!(error_attributes, &context);+ let companions = all_backends!(error_companions, &context);+ quote! {+ #attributes+ #parsed+ #companions+ }+ .into()}-fn is_exportable_attribute(attribute: &Attribute) -> bool {- let path = attribute.path();- let Some(last) = path.segments.last() else {- return false;+fn dispatch_implementation(item: TokenStream) -> TokenStream {+ let context = match ImplementationContext::from_token_stream(item.into()) {+ Ok(context) => context,+ Err(error) => return error.to_compile_error().into(),};- if last.ident != "export" {- return false;- }- match path.segments.first() {- Some(first) if first.ident == "bindings" || first.ident == "export" => true,- _ => false,++ let attributes = all_backends!(implementation_attributes, &context);+ let companions = all_backends!(implementation_companions, &context);+ let item_implementation = &context.item;++ let method_companions: Vec<TokenStream2> =+ context.all_methods().map(|metadata| all_backends!(method_companions, &context, metadata)).collect();++ quote! {+ #attributes+ #item_implementation+ #companions+ #( #method_companions )*}+ .into()}diff --git a/crates/bindings/src/pyo3.rs b/crates/bindings/src/pyo3.rsdeleted file mode 100644index fd43a3563..000000000--- a/crates/bindings/src/pyo3.rs+++ /dev/null@@ -1,84 +0,0 @@-use quote::quote;-use syn::{Attribute, Ident, parse_quote};--use crate::{BindingKind, MethodFlavor};--pub fn attributes(kind: &BindingKind) -> proc_macro2::TokenStream {- match kind {- BindingKind::Enum => quote! {- #[cfg_attr(feature = "bindings-pyo3", pyo3::pyclass(eq, from_py_object))]- },- BindingKind::Struct => quote! {- #[cfg_attr(feature = "bindings-pyo3", pyo3::pyclass(get_all, from_py_object))]- },- BindingKind::Class | BindingKind::ClassCloneable | BindingKind::Stream => quote! {- #[cfg_attr(feature = "bindings-pyo3", pyo3::pyclass)]- },- BindingKind::Implementation => quote! {- #[cfg_attr(feature = "bindings-pyo3", pyo3::pymethods)]- },- _ => quote! {},- }-}--pub fn method_attribute(flavor: &MethodFlavor) -> Option<Attribute> {- match flavor {- MethodFlavor::Plain | MethodFlavor::Getter | MethodFlavor::Setter => None,- MethodFlavor::Constructor => Some(parse_quote! {- #[cfg_attr(feature = "bindings-pyo3", new)]- }),- MethodFlavor::Factory => Some(parse_quote! {- #[cfg_attr(feature = "bindings-pyo3", staticmethod)]- }),- }-}--pub fn factory(- self_type: &syn::Type,- method: &syn::ImplItemFn,-) -> proc_macro2::TokenStream {- let method_ident = &method.sig.ident;- let method_name = method_ident.to_string();- let wrapper_ident = quote::format_ident!("{}_bindings_pyo3", method_ident);- let inputs = &method.sig.inputs;- let output = &method.sig.output;- let asyncness = &method.sig.asyncness;- let arg_idents = factory_arg_idents(inputs);- let forward_await = asyncness.as_ref().map(|_| quote! { .await });-- quote! {- #[cfg(feature = "bindings-pyo3")]- #[pyo3::pymethods]- impl #self_type {- #[staticmethod]- #[pyo3(name = #method_name)]- pub #asyncness fn #wrapper_ident( #inputs ) #output {- <#self_type>::#method_ident( #( #arg_idents ),* )#forward_await- }- }- }-}--fn factory_arg_idents(inputs: &syn::punctuated::Punctuated<syn::FnArg, syn::Token![,]>) -> Vec<syn::Ident> {- inputs- .iter()- .filter_map(|arg| match arg {- syn::FnArg::Typed(pat_type) => match pat_type.pat.as_ref() {- syn::Pat::Ident(pat_ident) => Some(pat_ident.ident.clone()),- _ => None,- },- syn::FnArg::Receiver(_) => None,- })- .collect()-}--pub fn error_implementations(type_name: &Ident) -> proc_macro2::TokenStream {- quote! {- #[cfg(feature = "bindings-pyo3")]- impl From<#type_name> for pyo3::PyErr {- fn from(error: #type_name) -> Self {- pyo3::exceptions::PyRuntimeError::new_err(error.to_string())- }- }- }-}diff --git a/crates/bindings/src/types/class_flavor.rs b/crates/bindings/src/types/class_flavor.rsnew file mode 100644index 000000000..4aa5da356--- /dev/null+++ b/crates/bindings/src/types/class_flavor.rs@@ -0,0 +1,4 @@+pub enum ClassFlavor {+ Plain,+ Stream,+}diff --git a/crates/bindings/src/types/kind.rs b/crates/bindings/src/types/kind.rsnew file mode 100644index 000000000..66ff7bb6c--- /dev/null+++ b/crates/bindings/src/types/kind.rs@@ -0,0 +1,129 @@+use syn::{+ Ident, Token, parenthesized,+ parse::{Parse, ParseStream},+};++use super::{class_flavor::ClassFlavor, method_flavor::MethodFlavor, structure_flavor::StructureFlavor};++pub enum Kind {+ Enumeration,+ Structure(StructureFlavor),+ Class(ClassFlavor),+ Alias,+ Implementation,+ Method(MethodFlavor),+ Error,+}++impl Parse for Kind {+ fn parse(input: ParseStream) -> syn::Result<Self> {+ let identifier: Ident = input.parse()?;+ let kind = match identifier.to_string().as_str() {+ "Enumeration" => {+ ensure_no_arguments(input, "Enumeration")?;+ Kind::Enumeration+ },+ "Structure" => {+ let flavor = if input.peek(syn::token::Paren) {+ let content;+ parenthesized!(content in input);+ let flavor_identifier: Ident = content.parse()?;+ match flavor_identifier.to_string().as_str() {+ "Plain" => StructureFlavor::Plain,+ "Class" => StructureFlavor::Class,+ other => {+ return Err(syn::Error::new(+ flavor_identifier.span(),+ format!("Unknown Structure flavor: {other}, expected `Plain` or `Class`"),+ ));+ },+ }+ } else {+ StructureFlavor::Plain+ };+ Kind::Structure(flavor)+ },+ "Class" => {+ let flavor = if input.peek(syn::token::Paren) {+ let content;+ parenthesized!(content in input);+ let flavor_identifier: Ident = content.parse()?;+ match flavor_identifier.to_string().as_str() {+ "Plain" => ClassFlavor::Plain,+ "Stream" => ClassFlavor::Stream,+ other => {+ return Err(syn::Error::new(+ flavor_identifier.span(),+ format!("Unknown Class flavor: {other}, expected `Plain` or `Stream`"),+ ));+ },+ }+ } else {+ ClassFlavor::Plain+ };+ Kind::Class(flavor)+ },+ "Alias" => {+ ensure_no_arguments(input, "Alias")?;+ Kind::Alias+ },+ "Implementation" => {+ ensure_no_arguments(input, "Implementation")?;+ Kind::Implementation+ },+ "Method" => {+ let flavor = if input.peek(syn::token::Paren) {+ let content;+ parenthesized!(content in input);+ let flavor_identifier: Ident = content.parse()?;+ match flavor_identifier.to_string().as_str() {+ "Plain" => MethodFlavor::Plain,+ "Constructor" => MethodFlavor::Constructor,+ "Factory" => MethodFlavor::Factory,+ "FactoryWithCallback" => MethodFlavor::FactoryWithCallback,+ "Getter" => MethodFlavor::Getter,+ "Setter" => MethodFlavor::Setter,+ "StreamNext" => MethodFlavor::StreamNext,+ other => {+ return Err(syn::Error::new(+ flavor_identifier.span(),+ format!(+ "Unknown Method flavor: {other}, expected one of `Plain`, `Constructor`, `Factory`, `FactoryWithCallback`, `Getter`, `Setter`, `StreamNext`"+ ),+ ));+ },+ }+ } else {+ MethodFlavor::Plain+ };+ Kind::Method(flavor)+ },+ "Error" => {+ ensure_no_arguments(input, "Error")?;+ Kind::Error+ },+ other => {+ return Err(syn::Error::new(+ identifier.span(),+ format!(+ "Unknown bindings::export kind: {other}, expected one of `Enumeration`, `Structure`, `Class`, `Alias`, `Implementation`, `Method`, `Error`"+ ),+ ));+ },+ };+ if input.peek(Token![,]) {+ return Err(input.error("Bindings::export accepts a single kind argument"));+ }+ Ok(kind)+ }+}++fn ensure_no_arguments(+ input: ParseStream,+ kind_name: &str,+) -> syn::Result<()> {+ if input.peek(syn::token::Paren) {+ return Err(input.error(format!("Kind `{kind_name}` does not accept arguments")));+ }+ Ok(())+}diff --git a/crates/bindings/src/types/method_flavor.rs b/crates/bindings/src/types/method_flavor.rsnew file mode 100644index 000000000..0e0c26891--- /dev/null+++ b/crates/bindings/src/types/method_flavor.rs@@ -0,0 +1,10 @@+#[derive(Clone, Copy, Eq, Hash, PartialEq)]+pub enum MethodFlavor {+ Plain,+ Constructor,+ Factory,+ FactoryWithCallback,+ Getter,+ Setter,+ StreamNext,+}diff --git a/crates/bindings/src/types/mod.rs b/crates/bindings/src/types/mod.rsnew file mode 100644index 000000000..c2bdb8c58--- /dev/null+++ b/crates/bindings/src/types/mod.rs@@ -0,0 +1,9 @@+mod class_flavor;+mod kind;+mod method_flavor;+mod structure_flavor;++pub use class_flavor::ClassFlavor;+pub use kind::Kind;+pub use method_flavor::MethodFlavor;+pub use structure_flavor::StructureFlavor;diff --git a/crates/bindings/src/types/structure_flavor.rs b/crates/bindings/src/types/structure_flavor.rsnew file mode 100644index 000000000..8d2120e5b--- /dev/null+++ b/crates/bindings/src/types/structure_flavor.rs@@ -0,0 +1,4 @@+pub enum StructureFlavor {+ Plain,+ Class,+}diff --git a/crates/bindings/src/wasm.rs b/crates/bindings/src/wasm.rsdeleted file mode 100644index 5dfa30e9e..000000000--- a/crates/bindings/src/wasm.rs+++ /dev/null@@ -1,30 +0,0 @@-use quote::quote;-use syn::Ident;--use crate::BindingKind;--pub fn attributes(kind: &BindingKind) -> proc_macro2::TokenStream {- match kind {- BindingKind::Enum | BindingKind::Struct => quote! {- #[cfg_attr(feature = "bindings-wasm", derive(tsify::Tsify))]- #[cfg_attr(feature = "bindings-wasm", tsify(into_wasm_abi, from_wasm_abi))]- },- BindingKind::Class | BindingKind::ClassCloneable | BindingKind::Stream | BindingKind::Implementation => {- quote! {- #[cfg_attr(feature = "bindings-wasm", wasm_bindgen::prelude::wasm_bindgen)]- }- },- _ => quote! {},- }-}--pub fn error_implementations(type_name: &Ident) -> proc_macro2::TokenStream {- quote! {- #[cfg(feature = "bindings-wasm")]- impl From<#type_name> for wasm_bindgen::JsValue {- fn from(error: #type_name) -> Self {- wasm_bindgen::JsValue::from_str(&error.to_string())- }- }- }-}diff --git a/crates/cli-release/src/handlers/generate_swift_extensions.rs b/crates/cli-release/src/handlers/generate_swift_extensions.rsindex edbd07abd..efc3bbd16 100644--- a/crates/cli-release/src/handlers/generate_swift_extensions.rs+++ b/crates/cli-release/src/handlers/generate_swift_extensions.rs@@ -388,7 +388,13 @@ fn is_bindings_export_with(if !matches_path {return false;}- attribute.parse_args::<syn::Ident>().map(|ident| ident == kind).unwrap_or(false)+ let syn::Meta::List(list) = &attribute.meta else {+ return false;+ };+ list.tokens+ .to_string()+ .split(|character: char| !character.is_alphanumeric() && character != '_')+ .any(|token| token == kind)}fn render_extensions_file(diff --git a/crates/cli-release/src/handlers/mod.rs b/crates/cli-release/src/handlers/mod.rsindex f9ec2dd94..425e948e4 100644--- a/crates/cli-release/src/handlers/mod.rs+++ b/crates/cli-release/src/handlers/mod.rs@@ -1,4 +1,5 @@mod generate_swift_extensions;+mod prepare_bindings_python;mod prepare_bindings_swift;mod prepare_bindings_ts;mod prepare_docs;@@ -10,6 +11,7 @@ mod prepare_workspace_ts_napi;mod sync_into_repo;pub use generate_swift_extensions::generate_swift_extensions;+pub use prepare_bindings_python::prepare_bindings_python;pub use prepare_bindings_swift::prepare_bindings_swift;pub use prepare_bindings_ts::prepare_bindings_ts;pub use prepare_docs::prepare_docs;diff --git a/crates/cli-release/src/handlers/prepare_bindings_python.rs b/crates/cli-release/src/handlers/prepare_bindings_python.rsnew file mode 100644index 000000000..0fcd031e0--- /dev/null+++ b/crates/cli-release/src/handlers/prepare_bindings_python.rs@@ -0,0 +1,57 @@+use std::process::{Command, Stdio};++use crate::types::{Environment, Error};++pub fn prepare_bindings_python(environment: &Environment) -> Result<(), Error> {+ let bindings_python_path = environment.bindings().python_path();+ if !bindings_python_path.exists() {+ return Err(Error::PathNotFound {+ path: bindings_python_path,+ });+ }++ let manifest_path = environment.package_uzu().root_path.join("Cargo.toml");+ if !manifest_path.exists() {+ return Err(Error::PathNotFound {+ path: manifest_path,+ });+ }++ let build_status = Command::new("maturin")+ .args(["build", "--release", "--features", "bindings-pyo3", "--strip", "--manifest-path"])+ .arg(&manifest_path)+ .current_dir(&bindings_python_path)+ .stdout(Stdio::inherit())+ .stderr(Stdio::inherit())+ .status()+ .map_err(|_| Error::UnableToPrepareBindingsPython)?;+ if !build_status.success() {+ return Err(Error::UnableToPrepareBindingsPython);+ }++ let sync_status = Command::new("uv")+ .args(["sync", "--reinstall-package", "uzu"])+ .current_dir(&bindings_python_path)+ .stdout(Stdio::inherit())+ .stderr(Stdio::inherit())+ .status()+ .map_err(|_| Error::UnableToPrepareBindingsPython)?;+ if !sync_status.success() {+ return Err(Error::UnableToPrepareBindingsPython);+ }++ let annotate_status = Command::new("uv")+ .arg("run")+ .arg("--directory")+ .arg(&bindings_python_path)+ .args(["python", "-c", "import uzu; uzu.generate_annotations()"])+ .stdout(Stdio::inherit())+ .stderr(Stdio::inherit())+ .status()+ .map_err(|_| Error::UnableToPrepareBindingsPython)?;+ if !annotate_status.success() {+ return Err(Error::UnableToPrepareBindingsPython);+ }++ Ok(())+}diff --git a/crates/cli-release/src/main.rs b/crates/cli-release/src/main.rsindex e765aeed0..47c5087e4 100644--- a/crates/cli-release/src/main.rs+++ b/crates/cli-release/src/main.rs@@ -3,8 +3,8 @@ use std::path::PathBuf;use clap::{CommandFactory, Parser, Subcommand, ValueEnum};use cli_release::{handlers::{- SyncSource, prepare_bindings_swift, prepare_bindings_ts, prepare_workspace_swift, prepare_workspace_swift_spm,- prepare_workspace_ts, prepare_workspace_ts_napi, sync_into_repo,+ SyncSource, prepare_bindings_python, prepare_bindings_swift, prepare_bindings_ts, prepare_workspace_swift,+ prepare_workspace_swift_spm, prepare_workspace_ts, prepare_workspace_ts_napi, sync_into_repo,},types::{Environment, Error},};@@ -41,6 +41,7 @@ enum Commands {enum BindingLanguage {Swift,Ts,+ Python,}fn prepare_bindings(@@ -53,10 +54,12 @@ fn prepare_bindings(prepare_workspace_ts_napi(environment)?;prepare_bindings_ts(environment)?;},+ Some(BindingLanguage::Python) => prepare_bindings_python(environment)?,None => {prepare_workspace_ts_napi(environment)?;prepare_bindings_ts(environment)?;prepare_bindings_swift(environment)?;+ prepare_bindings_python(environment)?;},}Ok(())diff --git a/crates/cli-release/src/types/bindings.rs b/crates/cli-release/src/types/bindings.rsindex 5dcb72c53..50eb7eef5 100644--- a/crates/cli-release/src/types/bindings.rs+++ b/crates/cli-release/src/types/bindings.rs@@ -36,3 +36,9 @@ impl Bindings {self.swift_path().join("uzu.xcframework")}}++impl Bindings {+ pub fn python_path(&self) -> PathBuf {+ self.root_path.join("python")+ }+}diff --git a/crates/cli-release/src/types/error.rs b/crates/cli-release/src/types/error.rsindex 27c66a4e2..1ce64ea47 100644--- a/crates/cli-release/src/types/error.rs+++ b/crates/cli-release/src/types/error.rs@@ -30,6 +30,8 @@ pub enum Error {UnableToPrepareBindingsSwift,#[error("Unable to prepare bindings/ts")]UnableToPrepareBindingsTS,+ #[error("Unable to prepare bindings/python")]+ UnableToPrepareBindingsPython,#[error("Unable to prepare workspace/ts")]UnableToPrepareWorkspaceTS,#[error("Unable to prepare workspace/ts-npm")]diff --git a/crates/nagare/Cargo.toml b/crates/nagare/Cargo.tomlindex 76b8d0181..5f6103647 100644--- a/crates/nagare/Cargo.toml+++ b/crates/nagare/Cargo.toml@@ -18,15 +18,29 @@ bindings = ["bindings-pyo3","bindings-wasm",]-bindings-uniffi = ["shoji/bindings-uniffi", "dep:uniffi"]+bindings-uniffi = [+ "bindings-types/bindings-uniffi",+ "shoji/bindings-uniffi",+ "dep:uniffi",+]bindings-napi = [+ "bindings-types/bindings-napi","shoji/bindings-napi","dep:napi","dep:napi-derive","dep:napi-build",]-bindings-pyo3 = ["shoji/bindings-pyo3", "dep:pyo3"]+bindings-pyo3 = [+ "bindings-types/bindings-pyo3",+ "shoji/bindings-pyo3",+ "dep:pyo3",+ "dep:pyo3-build-config",+ "dep:pyo3-async-runtimes",+ "dep:pyo3-stub-gen",+ "dep:inventory",+]bindings-wasm = [+ "bindings-types/bindings-wasm","shoji/bindings-wasm","dep:wasm-bindgen","dep:serde-wasm-bindgen",@@ -35,6 +49,7 @@ bindings-wasm = [][dependencies]+bindings-types.workspace = truebindings.workspace = trueshoji.workspace = truehanashi.workspace = true@@ -51,6 +66,9 @@ uniffi = { workspace = true, optional = true }napi = { workspace = true, optional = true }napi-derive = { workspace = true, optional = true }pyo3 = { workspace = true, optional = true }+pyo3-async-runtimes = { workspace = true, optional = true }+pyo3-stub-gen = { workspace = true, optional = true }+inventory = { workspace = true, optional = true }wasm-bindgen = { workspace = true, optional = true }serde-wasm-bindgen = { workspace = true, optional = true }wasm-bindgen-futures = { workspace = true, optional = true }@@ -58,3 +76,4 @@ tsify = { workspace = true, optional = true }[build-dependencies]napi-build = { workspace = true, optional = true }+pyo3-build-config = { workspace = true, optional = true }diff --git a/crates/nagare/build.rs b/crates/nagare/build.rsindex 6de3825da..43dd98946 100644--- a/crates/nagare/build.rs+++ b/crates/nagare/build.rs@@ -1,4 +1,6 @@fn main() {#[cfg(feature = "bindings-napi")]napi_build::setup();+ #[cfg(feature = "bindings-pyo3")]+ pyo3_build_config::add_extension_module_link_args();}diff --git a/crates/nagare/src/chat/error.rs b/crates/nagare/src/chat/error.rsindex 39ce91287..77b0f85de 100644--- a/crates/nagare/src/chat/error.rs+++ b/crates/nagare/src/chat/error.rs@@ -1,7 +1,7 @@use serde::{Deserialize, Serialize};#[bindings::export(Error)]-#[derive(Debug, Clone, Serialize, Deserialize, thiserror::Error)]+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, thiserror::Error)]#[non_exhaustive]pub enum ChatSessionError {#[error("Backend error: {message}")]diff --git a/crates/nagare/src/chat/mod.rs b/crates/nagare/src/chat/mod.rsindex 0a28bec05..54c6dfc0b 100644--- a/crates/nagare/src/chat/mod.rs+++ b/crates/nagare/src/chat/mod.rs@@ -21,8 +21,8 @@ use shoji::{};use tokio::sync::{Mutex, mpsc};-#[bindings::export(Enum)]-#[derive(Debug, Clone, Serialize, Deserialize)]+#[bindings::export(Enumeration)]+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub enum ChatSessionStreamChunk {Replies {replies: Vec<ChatReply>,@@ -32,7 +32,7 @@ pub enum ChatSessionStreamChunk {},}-#[bindings::export(Stream)]+#[bindings::export(Class(Stream))]#[derive(Clone)]pub struct ChatSessionStream {receiver: Arc<Mutex<mpsc::UnboundedReceiver<Result<Vec<ChatReply>, ChatSessionError>>>>,@@ -41,7 +41,7 @@ pub struct ChatSessionStream {#[bindings::export(Implementation)]impl ChatSessionStream {- #[bindings::export(StreamNext)]+ #[bindings::export(Method(StreamNext))]pub async fn next(&self) -> Option<ChatSessionStreamChunk> {match self.receiver.lock().await.recv().await {Some(Ok(replies)) => Some(ChatSessionStreamChunk::Replies {@@ -54,13 +54,13 @@ impl ChatSessionStream {}}- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub fn cancel_token(&self) -> CancelToken {self.cancel_token.clone()}}-#[bindings::export(Enum)]+#[bindings::export(Enumeration)]#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]pub enum ChatSessionState {Idle,@@ -75,6 +75,7 @@ enum Instance {}#[bindings::export(Class)]+#[derive(Clone)]pub struct ChatSession {instance: Arc<Mutex<Instance>>,state: Arc<Mutex<ChatSessionState>>,@@ -111,12 +112,12 @@ impl ChatSession {#[bindings::export(Implementation)]impl ChatSession {- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub async fn state(&self) -> ChatSessionState {*self.state.lock().await}- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub async fn messages(&self) -> Vec<ChatMessage> {self.messages.lock().await.clone()}diff --git a/crates/nagare/src/classification/error.rs b/crates/nagare/src/classification/error.rsindex 7f916bacb..42c9b77f3 100644--- a/crates/nagare/src/classification/error.rs+++ b/crates/nagare/src/classification/error.rs@@ -1,5 +1,5 @@#[bindings::export(Error)]-#[derive(Debug, Clone, thiserror::Error)]+#[derive(Debug, Clone, PartialEq, thiserror::Error)]#[non_exhaustive]pub enum ClassificationSessionError {#[error("Backend error: {message}")]diff --git a/crates/nagare/src/classification/mod.rs b/crates/nagare/src/classification/mod.rsindex da4a685ea..571cf8ff5 100644--- a/crates/nagare/src/classification/mod.rs+++ b/crates/nagare/src/classification/mod.rs@@ -15,7 +15,7 @@ use shoji::{};use tokio::sync::{Mutex, mpsc};-#[bindings::export(Enum)]+#[bindings::export(Enumeration)]#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]pub enum ClassificationSessionState {Idle,@@ -28,6 +28,7 @@ struct InstanceHolder {}#[bindings::export(Class)]+#[derive(Clone)]pub struct ClassificationSession {holder: Arc<Mutex<InstanceHolder>>,state: Arc<Mutex<ClassificationSessionState>>,@@ -65,7 +66,7 @@ impl ClassificationSession {#[bindings::export(Implementation)]impl ClassificationSession {- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub async fn state(&self) -> ClassificationSessionState {*self.state.lock().await}diff --git a/crates/nagare/src/text_to_speech/error.rs b/crates/nagare/src/text_to_speech/error.rsindex 69565f364..c8bea1159 100644--- a/crates/nagare/src/text_to_speech/error.rs+++ b/crates/nagare/src/text_to_speech/error.rs@@ -1,7 +1,7 @@use serde::{Deserialize, Serialize};#[bindings::export(Error)]-#[derive(Debug, Clone, Serialize, Deserialize, thiserror::Error)]+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, thiserror::Error)]#[non_exhaustive]pub enum TextToSpeechSessionError {#[error("Backend error: {message}")]diff --git a/crates/nagare/src/text_to_speech/mod.rs b/crates/nagare/src/text_to_speech/mod.rsindex f205d28e6..d92fbcca7 100644--- a/crates/nagare/src/text_to_speech/mod.rs+++ b/crates/nagare/src/text_to_speech/mod.rs@@ -14,8 +14,8 @@ use shoji::{};use tokio::sync::{Mutex, mpsc};-#[bindings::export(Enum)]-#[derive(Debug, Clone, Serialize, Deserialize)]+#[bindings::export(Enumeration)]+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub enum TextToSpeechSessionStreamChunk {PcmBatch {batch: PcmBatch,@@ -25,7 +25,7 @@ pub enum TextToSpeechSessionStreamChunk {},}-#[bindings::export(Stream)]+#[bindings::export(Class(Stream))]#[derive(Clone)]pub struct TextToSpeechSessionStream {receiver: Arc<Mutex<mpsc::UnboundedReceiver<Result<PcmBatch, TextToSpeechSessionError>>>>,@@ -34,7 +34,7 @@ pub struct TextToSpeechSessionStream {#[bindings::export(Implementation)]impl TextToSpeechSessionStream {- #[bindings::export(StreamNext)]+ #[bindings::export(Method(StreamNext))]pub async fn next(&self) -> Option<TextToSpeechSessionStreamChunk> {match self.receiver.lock().await.recv().await {Some(Ok(batch)) => Some(TextToSpeechSessionStreamChunk::PcmBatch {@@ -47,13 +47,13 @@ impl TextToSpeechSessionStream {}}- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub fn cancel_token(&self) -> CancelToken {self.cancel_token.clone()}}-#[bindings::export(Enum)]+#[bindings::export(Enumeration)]#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]pub enum TextToSpeechSessionState {Idle,@@ -66,6 +66,7 @@ struct InstanceHolder {}#[bindings::export(Class)]+#[derive(Clone)]pub struct TextToSpeechSession {holder: Arc<Mutex<InstanceHolder>>,state: Arc<Mutex<TextToSpeechSessionState>>,@@ -103,7 +104,7 @@ impl TextToSpeechSession {#[bindings::export(Implementation)]impl TextToSpeechSession {- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub async fn state(&self) -> TextToSpeechSessionState {*self.state.lock().await}diff --git a/crates/shoji/Cargo.toml b/crates/shoji/Cargo.tomlindex 02f2de291..f237c9fe4 100644--- a/crates/shoji/Cargo.toml+++ b/crates/shoji/Cargo.toml@@ -18,10 +18,23 @@ bindings = ["bindings-pyo3","bindings-wasm",]-bindings-uniffi = ["dep:uniffi"]-bindings-napi = ["dep:napi", "dep:napi-derive", "dep:napi-build"]-bindings-pyo3 = ["dep:pyo3"]+bindings-uniffi = ["bindings-types/bindings-uniffi", "dep:uniffi"]+bindings-napi = [+ "bindings-types/bindings-napi",+ "dep:napi",+ "dep:napi-derive",+ "dep:napi-build",+]+bindings-pyo3 = [+ "bindings-types/bindings-pyo3",+ "dep:pyo3",+ "dep:pyo3-build-config",+ "dep:pyo3-async-runtimes",+ "dep:pyo3-stub-gen",+ "dep:inventory",+]bindings-wasm = [+ "bindings-types/bindings-wasm","dep:wasm-bindgen","dep:serde-wasm-bindgen","dep:wasm-bindgen-futures",@@ -29,6 +42,7 @@ bindings-wasm = [][dependencies]+bindings-types.workspace = truebindings.workspace = trueserde.workspace = trueserde_json.workspace = true@@ -41,6 +55,9 @@ uniffi = { workspace = true, optional = true }napi = { workspace = true, optional = true }napi-derive = { workspace = true, optional = true }pyo3 = { workspace = true, optional = true }+pyo3-async-runtimes = { workspace = true, optional = true }+pyo3-stub-gen = { workspace = true, optional = true }+inventory = { workspace = true, optional = true }wasm-bindgen = { workspace = true, optional = true }serde-wasm-bindgen = { workspace = true, optional = true }wasm-bindgen-futures = { workspace = true, optional = true }@@ -48,3 +65,4 @@ tsify = { workspace = true, optional = true }[build-dependencies]napi-build = { workspace = true, optional = true }+pyo3-build-config = { workspace = true, optional = true }diff --git a/crates/shoji/build.rs b/crates/shoji/build.rsindex 6de3825da..43dd98946 100644--- a/crates/shoji/build.rs+++ b/crates/shoji/build.rs@@ -1,4 +1,6 @@fn main() {#[cfg(feature = "bindings-napi")]napi_build::setup();+ #[cfg(feature = "bindings-pyo3")]+ pyo3_build_config::add_extension_module_link_args();}diff --git a/crates/shoji/src/types/basic/cancel_token.rs b/crates/shoji/src/types/basic/cancel_token.rsindex 9247086c7..e71e4d7b7 100644--- a/crates/shoji/src/types/basic/cancel_token.rs+++ b/crates/shoji/src/types/basic/cancel_token.rs@@ -16,7 +16,7 @@ impl CancelToken {#[bindings::export(Implementation)]impl CancelToken {- #[bindings::export(Factory)]+ #[bindings::export(Method(Factory))]pub fn create() -> Self {Self::new()}@@ -26,7 +26,7 @@ impl CancelToken {self.inner.cancel();}- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub fn is_cancelled(&self) -> bool {self.inner.is_cancelled()}diff --git a/crates/shoji/src/types/basic/context_length.rs b/crates/shoji/src/types/basic/context_length.rsindex 2c7bde0bd..df7996235 100644--- a/crates/shoji/src/types/basic/context_length.rs+++ b/crates/shoji/src/types/basic/context_length.rs@@ -1,6 +1,6 @@use serde::{Deserialize, Serialize};-#[bindings::export(Enum)]+#[bindings::export(Enumeration)]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]pub enum ContextLength {Default {},diff --git a/crates/shoji/src/types/basic/feature.rs b/crates/shoji/src/types/basic/feature.rsindex 07c179a23..f47a03205 100644--- a/crates/shoji/src/types/basic/feature.rs+++ b/crates/shoji/src/types/basic/feature.rs@@ -1,6 +1,6 @@use serde::{Deserialize, Serialize};-#[bindings::export(ClassCloneable)]+#[bindings::export(Structure(Class))]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]pub struct Feature {pub name: String,diff --git a/crates/shoji/src/types/basic/file.rs b/crates/shoji/src/types/basic/file.rsindex 4b641ee51..c6f5ca40c 100644--- a/crates/shoji/src/types/basic/file.rs+++ b/crates/shoji/src/types/basic/file.rs@@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};use crate::types::basic::{Hash, HashMethod};-#[bindings::export(ClassCloneable)]+#[bindings::export(Structure(Class))]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub struct File {@@ -14,12 +14,12 @@ pub struct File {#[bindings::export(Implementation)]impl File {- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub fn crc32c(&self) -> Option<String> {self.hashes.iter().find(|hash| hash.method == HashMethod::CRC32C).map(|hash| hash.value.clone())}- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub fn md5(&self) -> Option<String> {self.hashes.iter().find(|hash| hash.method == HashMethod::MD5).map(|hash| hash.value.clone())}diff --git a/crates/shoji/src/types/basic/grammar.rs b/crates/shoji/src/types/basic/grammar.rsindex fdf3d6aa0..ebb8d8082 100644--- a/crates/shoji/src/types/basic/grammar.rs+++ b/crates/shoji/src/types/basic/grammar.rs@@ -1,6 +1,6 @@use serde::{Deserialize, Serialize};-#[bindings::export(Enum)]+#[bindings::export(Enumeration)]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]pub enum Grammar {JsonAny {},diff --git a/crates/shoji/src/types/basic/hash.rs b/crates/shoji/src/types/basic/hash.rsindex a4426bd72..7a8032e83 100644--- a/crates/shoji/src/types/basic/hash.rs+++ b/crates/shoji/src/types/basic/hash.rs@@ -1,6 +1,6 @@use serde::{Deserialize, Serialize};-#[bindings::export(Enum)]+#[bindings::export(Enumeration)]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub enum HashMethod {@@ -10,7 +10,7 @@ pub enum HashMethod {MD5,}-#[bindings::export(ClassCloneable)]+#[bindings::export(Structure(Class))]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub struct Hash {diff --git a/crates/shoji/src/types/basic/image.rs b/crates/shoji/src/types/basic/image.rsindex 415385910..0dfbbbd33 100644--- a/crates/shoji/src/types/basic/image.rs+++ b/crates/shoji/src/types/basic/image.rs@@ -1,6 +1,6 @@use serde::{Deserialize, Serialize};-#[bindings::export(Enum)]+#[bindings::export(Enumeration)]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub enum ImageFormat {@@ -9,7 +9,7 @@ pub enum ImageFormat {Svg,}-#[bindings::export(Enum)]+#[bindings::export(Enumeration)]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub enum ImageTheme {@@ -17,7 +17,7 @@ pub enum ImageTheme {Dark,}-#[bindings::export(ClassCloneable)]+#[bindings::export(Structure(Class))]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub struct Image {diff --git a/crates/shoji/src/types/basic/metadata.rs b/crates/shoji/src/types/basic/metadata.rsindex 9e32e63b4..889f7676b 100644--- a/crates/shoji/src/types/basic/metadata.rs+++ b/crates/shoji/src/types/basic/metadata.rs@@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};use crate::types::basic::Image;-#[bindings::export(ClassCloneable)]+#[bindings::export(Structure(Class))]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub struct Metadata {@@ -15,7 +15,7 @@ pub struct Metadata {#[bindings::export(Implementation)]impl Metadata {- #[bindings::export(Factory)]+ #[bindings::export(Method(Factory))]pub fn external(name: String) -> Self {Self {identifier: "external".to_string(),diff --git a/crates/shoji/src/types/basic/pcm_batch.rs b/crates/shoji/src/types/basic/pcm_batch.rsindex 99e61da79..788517594 100644--- a/crates/shoji/src/types/basic/pcm_batch.rs+++ b/crates/shoji/src/types/basic/pcm_batch.rs@@ -2,7 +2,7 @@ use hound::{SampleFormat, WavSpec, WavWriter};use serde::{Deserialize, Serialize};#[bindings::export(Error)]-#[derive(Debug, Clone, thiserror::Error)]+#[derive(Debug, Clone, PartialEq, thiserror::Error)]#[non_exhaustive]pub enum PcmBatchError {#[error("Unable to save as wav: {message}")]@@ -11,7 +11,7 @@ pub enum PcmBatchError {},}-#[bindings::export(ClassCloneable)]+#[bindings::export(Structure(Class))]#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct PcmBatch {pub samples: Vec<f64>,@@ -28,12 +28,12 @@ impl PcmBatch {#[bindings::export(Implementation)]impl PcmBatch {- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub fn batch_size(&self) -> u32 {self.lengths.len() as u32}- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub fn total_frames(&self) -> u32 {self.lengths.iter().sum::<_>()}diff --git a/crates/shoji/src/types/basic/reasoning_effort.rs b/crates/shoji/src/types/basic/reasoning_effort.rsindex 80a2ded03..eea58ca4e 100644--- a/crates/shoji/src/types/basic/reasoning_effort.rs+++ b/crates/shoji/src/types/basic/reasoning_effort.rs@@ -5,7 +5,7 @@ use std::{use serde::{Deserialize, Deserializer, Serialize, Serializer, de};-#[bindings::export(Enum)]+#[bindings::export(Enumeration)]#[derive(Debug, Clone, PartialEq, Eq, Hash)]pub enum ReasoningEffort {Disabled,diff --git a/crates/shoji/src/types/basic/repository.rs b/crates/shoji/src/types/basic/repository.rsindex e11b8b683..2c652a642 100644--- a/crates/shoji/src/types/basic/repository.rs+++ b/crates/shoji/src/types/basic/repository.rs@@ -1,6 +1,6 @@use serde::{Deserialize, Serialize};-#[bindings::export(ClassCloneable)]+#[bindings::export(Structure(Class))]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub struct Repository {diff --git a/crates/shoji/src/types/basic/sampling_method.rs b/crates/shoji/src/types/basic/sampling_method.rsindex 13d1d251f..8f5e0ad65 100644--- a/crates/shoji/src/types/basic/sampling_method.rs+++ b/crates/shoji/src/types/basic/sampling_method.rs@@ -1,6 +1,6 @@use serde::{Deserialize, Serialize};-#[bindings::export(Enum)]+#[bindings::export(Enumeration)]#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub enum SamplingMethod {Greedy {},diff --git a/crates/shoji/src/types/basic/sampling_policy.rs b/crates/shoji/src/types/basic/sampling_policy.rsindex 2b7c6b2e0..ac613f7b9 100644--- a/crates/shoji/src/types/basic/sampling_policy.rs+++ b/crates/shoji/src/types/basic/sampling_policy.rs@@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};use crate::types::basic::SamplingMethod;-#[bindings::export(Enum)]+#[bindings::export(Enumeration)]#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub enum SamplingPolicy {Default {},diff --git a/crates/shoji/src/types/basic/sampling_seed.rs b/crates/shoji/src/types/basic/sampling_seed.rsindex 103708c6d..cc998be4c 100644--- a/crates/shoji/src/types/basic/sampling_seed.rs+++ b/crates/shoji/src/types/basic/sampling_seed.rs@@ -1,6 +1,6 @@use serde::{Deserialize, Serialize};-#[bindings::export(Enum)]+#[bindings::export(Enumeration)]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]pub enum SamplingSeed {Default {},diff --git a/crates/shoji/src/types/basic/token.rs b/crates/shoji/src/types/basic/token.rsindex e98361f21..a07de1754 100644--- a/crates/shoji/src/types/basic/token.rs+++ b/crates/shoji/src/types/basic/token.rs@@ -8,7 +8,7 @@ pub type TokenId = u32;#[bindings::export(Alias)]pub type TokenValue = String;-#[bindings::export(ClassCloneable)]+#[bindings::export(Structure(Class))]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub struct Token {diff --git a/crates/shoji/src/types/basic/tool_call.rs b/crates/shoji/src/types/basic/tool_call.rsindex 4aa3ab039..83e162373 100644--- a/crates/shoji/src/types/basic/tool_call.rs+++ b/crates/shoji/src/types/basic/tool_call.rs@@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};use crate::types::basic::Value;-#[bindings::export(ClassCloneable)]+#[bindings::export(Structure(Class))]#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub struct ToolCall {diff --git a/crates/shoji/src/types/basic/tool_description.rs b/crates/shoji/src/types/basic/tool_description.rsindex 4a769a6cb..a71044cdb 100644--- a/crates/shoji/src/types/basic/tool_description.rs+++ b/crates/shoji/src/types/basic/tool_description.rs@@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};use crate::types::basic::ToolFunction;-#[bindings::export(Enum)]+#[bindings::export(Enumeration)]#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(tag = "type", rename_all = "snake_case")]pub enum ToolDescription {diff --git a/crates/shoji/src/types/basic/tool_function.rs b/crates/shoji/src/types/basic/tool_function.rsindex 1ddff1946..fdb521a69 100644--- a/crates/shoji/src/types/basic/tool_function.rs+++ b/crates/shoji/src/types/basic/tool_function.rs@@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};use crate::types::basic::Value;-#[bindings::export(ClassCloneable)]+#[bindings::export(Structure(Class))]#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub struct ToolFunction {diff --git a/crates/shoji/src/types/basic/tool_namespace.rs b/crates/shoji/src/types/basic/tool_namespace.rsindex f3149d6b2..a4bd61adc 100644--- a/crates/shoji/src/types/basic/tool_namespace.rs+++ b/crates/shoji/src/types/basic/tool_namespace.rs@@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};use crate::types::basic::ToolDescription;-#[bindings::export(ClassCloneable)]+#[bindings::export(Structure(Class))]#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub struct ToolNamespace {diff --git a/crates/shoji/src/types/basic/translation_payload.rs b/crates/shoji/src/types/basic/translation_payload.rsindex d92ae8285..5c040be2d 100644--- a/crates/shoji/src/types/basic/translation_payload.rs+++ b/crates/shoji/src/types/basic/translation_payload.rs@@ -1,6 +1,6 @@use serde::{Deserialize, Serialize};-#[bindings::export(Enum)]+#[bindings::export(Enumeration)]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(tag = "type", rename_all = "snake_case")]pub enum TranslationPayload {diff --git a/crates/shoji/src/types/basic/value.rs b/crates/shoji/src/types/basic/value.rsindex 41ddcd59d..6f17c2756 100644--- a/crates/shoji/src/types/basic/value.rs+++ b/crates/shoji/src/types/basic/value.rs@@ -2,7 +2,7 @@ use std::fmt;use serde::{Deserialize, Deserializer, Serialize, Serializer};-#[bindings::export(ClassCloneable)]+#[bindings::export(Structure(Class))]#[derive(Clone, PartialEq)]pub struct Value {pub json: String,diff --git a/crates/shoji/src/types/model/accessibility.rs b/crates/shoji/src/types/model/accessibility.rsindex eeb59f06a..82d01870d 100644--- a/crates/shoji/src/types/model/accessibility.rs+++ b/crates/shoji/src/types/model/accessibility.rs@@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};use crate::types::{basic::Repository, model::ModelReference};-#[bindings::export(Enum)]+#[bindings::export(Enumeration)]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(tag = "type", rename_all = "snake_case")]pub enum ModelAccessibility {diff --git a/crates/shoji/src/types/model/backend.rs b/crates/shoji/src/types/model/backend.rsindex 11797302a..a7aaf79c2 100644--- a/crates/shoji/src/types/model/backend.rs+++ b/crates/shoji/src/types/model/backend.rs@@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};use crate::types::basic::Metadata;-#[bindings::export(ClassCloneable)]+#[bindings::export(Structure(Class))]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub struct ModelBackend {@@ -14,7 +14,7 @@ pub struct ModelBackend {#[bindings::export(Implementation)]impl ModelBackend {- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub fn name(&self) -> String {self.metadata.name.clone()}diff --git a/crates/shoji/src/types/model/family.rs b/crates/shoji/src/types/model/family.rsindex 58095ffd9..c6fae9eee 100644--- a/crates/shoji/src/types/model/family.rs+++ b/crates/shoji/src/types/model/family.rs@@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};use crate::types::{basic::Metadata, model::ModelVendor};-#[bindings::export(ClassCloneable)]+#[bindings::export(Structure(Class))]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub struct ModelFamily {@@ -14,7 +14,7 @@ pub struct ModelFamily {#[bindings::export(Implementation)]impl ModelFamily {- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub fn name(&self) -> String {self.metadata.name.clone()}diff --git a/crates/shoji/src/types/model/model.rs b/crates/shoji/src/types/model/model.rsindex 44cbae64a..595967d52 100644--- a/crates/shoji/src/types/model/model.rs+++ b/crates/shoji/src/types/model/model.rs@@ -8,7 +8,7 @@ use crate::types::{},};-#[bindings::export(ClassCloneable)]+#[bindings::export(Structure(Class))]#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub struct Model {@@ -25,7 +25,7 @@ pub struct Model {#[bindings::export(Implementation)]impl Model {- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub fn name(&self) -> String {let parts: Vec<Option<String>> = vec![self.family.as_ref().map(|family| family.name()),@@ -40,17 +40,17 @@ impl Model {}}- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub fn is_local(&self) -> bool {matches!(self.accessibility, ModelAccessibility::Local { .. })}- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub fn is_remote(&self) -> bool {matches!(self.accessibility, ModelAccessibility::Remote { .. })}- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub fn is_downloadable(&self) -> bool {matches!(self.accessibility,@@ -60,17 +60,17 @@ impl Model {)}- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub fn is_quantized(&self) -> bool {self.quantization.is_some()}- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub fn cache_identifier(&self) -> String {self.identifier.replace(":", "-").replace("/", "-")}- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub fn repo_ids(&self) -> Vec<String> {match &self.accessibility {ModelAccessibility::Local {@@ -111,7 +111,7 @@ impl Model {}}- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub fn local_external_path(&self) -> Option<String> {match &self.accessibility {ModelAccessibility::Local {@@ -134,7 +134,7 @@ impl Model {}}- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub fn reference_name(&self) -> Option<String> {match &self.accessibility {ModelAccessibility::Local {@@ -147,7 +147,7 @@ impl Model {}}- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub fn checkpoint_version(&self) -> Option<String> {match &self.accessibility {ModelAccessibility::Local {@@ -174,7 +174,7 @@ impl Model {#[bindings::export(Implementation)]impl Model {- #[bindings::export(Factory)]+ #[bindings::export(Method(Factory))]pub fn external(identifier: String,registry_identifier: String,@@ -209,27 +209,27 @@ impl Model {#[bindings::export(Implementation)]impl Model {- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub fn is_chat_capable(&self) -> bool {self.specializations.contains(&ModelSpecialization::Chat {})}- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub fn is_classification_capable(&self) -> bool {self.specializations.contains(&ModelSpecialization::Classification {})}- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub fn is_text_to_speech_capable(&self) -> bool {self.specializations.contains(&ModelSpecialization::TextToSpeech {})}- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub fn is_translation_capable(&self) -> bool {self.specializations.contains(&ModelSpecialization::Translation {})}- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub fn is_speculation_capable(&self) -> bool {self.specializations.contains(&ModelSpecialization::Speculation {})}diff --git a/crates/shoji/src/types/model/properties.rs b/crates/shoji/src/types/model/properties.rsindex dd812a91a..2ac051e17 100644--- a/crates/shoji/src/types/model/properties.rs+++ b/crates/shoji/src/types/model/properties.rs@@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};use crate::types::basic::Metadata;-#[bindings::export(ClassCloneable)]+#[bindings::export(Structure(Class))]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub struct ModelProperties {@@ -15,7 +15,7 @@ pub struct ModelProperties {#[bindings::export(Implementation)]impl ModelProperties {- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub fn name(&self) -> String {self.metadata.name.clone()}diff --git a/crates/shoji/src/types/model/quantization.rs b/crates/shoji/src/types/model/quantization.rsindex 7be908425..9a550c5f0 100644--- a/crates/shoji/src/types/model/quantization.rs+++ b/crates/shoji/src/types/model/quantization.rs@@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};use crate::types::{basic::Metadata, model::ModelVendor};-#[bindings::export(ClassCloneable)]+#[bindings::export(Structure(Class))]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub struct ModelQuantization {@@ -16,7 +16,7 @@ pub struct ModelQuantization {#[bindings::export(Implementation)]impl ModelQuantization {- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub fn name(&self) -> String {self.metadata.name.clone()}diff --git a/crates/shoji/src/types/model/reference.rs b/crates/shoji/src/types/model/reference.rsindex 164492065..019e93a8d 100644--- a/crates/shoji/src/types/model/reference.rs+++ b/crates/shoji/src/types/model/reference.rs@@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};use crate::types::basic::{File, Repository};-#[bindings::export(Enum)]+#[bindings::export(Enumeration)]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(tag = "type", rename_all = "snake_case")]pub enum ModelReference {diff --git a/crates/shoji/src/types/model/registry.rs b/crates/shoji/src/types/model/registry.rsindex 7ddd6de2e..fafd8cf21 100644--- a/crates/shoji/src/types/model/registry.rs+++ b/crates/shoji/src/types/model/registry.rs@@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};use crate::types::basic::Metadata;-#[bindings::export(ClassCloneable)]+#[bindings::export(Structure(Class))]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub struct ModelRegistry {@@ -13,7 +13,7 @@ pub struct ModelRegistry {#[bindings::export(Implementation)]impl ModelRegistry {- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub fn name(&self) -> String {self.metadata.name.clone()}diff --git a/crates/shoji/src/types/model/specialization.rs b/crates/shoji/src/types/model/specialization.rsindex f688ed96a..b23ee1b45 100644--- a/crates/shoji/src/types/model/specialization.rs+++ b/crates/shoji/src/types/model/specialization.rs@@ -1,6 +1,6 @@use serde::{Deserialize, Serialize};-#[bindings::export(Enum)]+#[bindings::export(Enumeration)]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(tag = "type", rename_all = "snake_case")]pub enum ModelSpecialization {diff --git a/crates/shoji/src/types/model/vendor.rs b/crates/shoji/src/types/model/vendor.rsindex b1af22410..d856839d3 100644--- a/crates/shoji/src/types/model/vendor.rs+++ b/crates/shoji/src/types/model/vendor.rs@@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};use crate::types::basic::Metadata;-#[bindings::export(ClassCloneable)]+#[bindings::export(Structure(Class))]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub struct ModelVendor {@@ -13,7 +13,7 @@ pub struct ModelVendor {#[bindings::export(Implementation)]impl ModelVendor {- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub fn name(&self) -> String {self.metadata.name.clone()}diff --git a/crates/shoji/src/types/session/chat/capabilities.rs b/crates/shoji/src/types/session/chat/capabilities.rsindex 0ddba94ad..aa6ab4ff6 100644--- a/crates/shoji/src/types/session/chat/capabilities.rs+++ b/crates/shoji/src/types/session/chat/capabilities.rs@@ -1,6 +1,6 @@use serde::{Deserialize, Serialize};-#[bindings::export(ClassCloneable)]+#[bindings::export(Structure(Class))]#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct ChatModelCapabilities {pub supports_reasoning: bool,diff --git a/crates/shoji/src/types/session/chat/config.rs b/crates/shoji/src/types/session/chat/config.rsindex da2f470da..ed2fc2de2 100644--- a/crates/shoji/src/types/session/chat/config.rs+++ b/crates/shoji/src/types/session/chat/config.rs@@ -5,7 +5,7 @@ use crate::types::{session::chat::ChatSpeculationPreset,};-#[bindings::export(ClassCloneable)]+#[bindings::export(Structure(Class))]#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct ChatConfig {pub context_length: ContextLength,@@ -25,7 +25,7 @@ impl Default for ChatConfig {#[bindings::export(Implementation)]impl ChatConfig {- #[bindings::export(Factory)]+ #[bindings::export(Method(Factory))]pub fn create() -> Self {Self::default()}diff --git a/crates/shoji/src/types/session/chat/content_block.rs b/crates/shoji/src/types/session/chat/content_block.rsindex 4a984597b..4de09a3b3 100644--- a/crates/shoji/src/types/session/chat/content_block.rs+++ b/crates/shoji/src/types/session/chat/content_block.rs@@ -7,7 +7,7 @@ use serde::{Deserialize, Deserializer, Serialize, Serializer, de};use crate::types::basic::{ReasoningEffort, ToolCall, ToolNamespace, TranslationPayload, Value};-#[bindings::export(Enum)]+#[bindings::export(Enumeration)]#[derive(Debug, Clone, PartialEq, Eq, Hash)]pub enum ChatContentBlockType {Identity,@@ -100,7 +100,7 @@ impl<'d> Deserialize<'d> for ChatContentBlockType {}}-#[bindings::export(Enum)]+#[bindings::export(Enumeration)]#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(tag = "type", rename_all = "snake_case")]pub enum ChatContentBlock {diff --git a/crates/shoji/src/types/session/chat/message.rs b/crates/shoji/src/types/session/chat/message.rsindex 9b9c9f1f9..e79735fa1 100644--- a/crates/shoji/src/types/session/chat/message.rs+++ b/crates/shoji/src/types/session/chat/message.rs@@ -7,7 +7,7 @@ use crate::types::{session::chat::{ChatContentBlock, ChatRole},};-#[bindings::export(Struct)]+#[bindings::export(Structure)]#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub struct ChatMessageMetadata {@@ -22,7 +22,7 @@ impl From<HashMap<String, Value>> for ChatMessageMetadata {}}-#[bindings::export(ClassCloneable)]+#[bindings::export(Structure(Class))]#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub struct ChatMessage {@@ -33,7 +33,7 @@ pub struct ChatMessage {#[bindings::export(Implementation)]impl ChatMessage {- #[bindings::export(Factory)]+ #[bindings::export(Method(Factory))]pub fn for_role(role: ChatRole) -> Self {Self {role,@@ -44,27 +44,27 @@ impl ChatMessage {}}- #[bindings::export(Factory)]+ #[bindings::export(Method(Factory))]pub fn system() -> Self {Self::for_role(ChatRole::System {})}- #[bindings::export(Factory)]+ #[bindings::export(Method(Factory))]pub fn developer() -> Self {Self::for_role(ChatRole::Developer {})}- #[bindings::export(Factory)]+ #[bindings::export(Method(Factory))]pub fn user() -> Self {Self::for_role(ChatRole::User {})}- #[bindings::export(Factory)]+ #[bindings::export(Method(Factory))]pub fn assistant() -> Self {Self::for_role(ChatRole::Assistant {})}- #[bindings::export(Factory)]+ #[bindings::export(Method(Factory))]pub fn tool() -> Self {Self::for_role(ChatRole::Tool {})}@@ -159,12 +159,12 @@ macro_rules! blocks_by_type {#[bindings::export(Implementation)]impl ChatMessage {- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub fn reasoning_effort(&self) -> Option<ReasoningEffort> {blocks_by_type!(self, ReasoningEffort, value).next()}- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub fn text(&self) -> Option<String> {blocks_by_type!(self, Text, value).reduce(|mut text, value| {text.push_str(&value);@@ -172,7 +172,7 @@ impl ChatMessage {})}- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub fn reasoning(&self) -> Option<String> {blocks_by_type!(self, Reasoning, value).reduce(|mut reasoning, value| {reasoning.push_str(&value);@@ -180,12 +180,12 @@ impl ChatMessage {})}- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub fn tool_namespaces(&self) -> Vec<ToolNamespace> {blocks_by_type!(self, Tools, namespaces).flatten().collect()}- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub fn tool_calls(&self) -> Vec<ToolCall> {blocks_by_type!(self, ToolCall, value).collect()}diff --git a/crates/shoji/src/types/session/chat/reply/config.rs b/crates/shoji/src/types/session/chat/reply/config.rsindex aa87f6785..413f60998 100644--- a/crates/shoji/src/types/session/chat/reply/config.rs+++ b/crates/shoji/src/types/session/chat/reply/config.rs@@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};use crate::types::basic::{Grammar, SamplingMethod, SamplingPolicy};-#[bindings::export(ClassCloneable)]+#[bindings::export(Structure(Class))]#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct ChatReplyConfig {pub token_limit: Option<u32>,@@ -22,7 +22,7 @@ impl Default for ChatReplyConfig {#[bindings::export(Implementation)]impl ChatReplyConfig {- #[bindings::export(Factory)]+ #[bindings::export(Method(Factory))]pub fn create() -> Self {Self::default()}diff --git a/crates/shoji/src/types/session/chat/reply/finish_reason.rs b/crates/shoji/src/types/session/chat/reply/finish_reason.rsindex d2ae4d166..f756aa6ee 100644--- a/crates/shoji/src/types/session/chat/reply/finish_reason.rs+++ b/crates/shoji/src/types/session/chat/reply/finish_reason.rs@@ -1,6 +1,6 @@use serde::{Deserialize, Serialize};-#[bindings::export(Enum)]+#[bindings::export(Enumeration)]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]pub enum ChatReplyFinishReason {Stop,diff --git a/crates/shoji/src/types/session/chat/reply/mod.rs b/crates/shoji/src/types/session/chat/reply/mod.rsindex 62ff43fa6..c43233df2 100644--- a/crates/shoji/src/types/session/chat/reply/mod.rs+++ b/crates/shoji/src/types/session/chat/reply/mod.rs@@ -9,7 +9,7 @@ pub use stats::ChatReplyStats;use crate::types::session::chat::ChatMessage;-#[bindings::export(ClassCloneable)]+#[bindings::export(Structure(Class))]#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct ChatReply {pub message: ChatMessage,diff --git a/crates/shoji/src/types/session/chat/reply/stats.rs b/crates/shoji/src/types/session/chat/reply/stats.rsindex 018fd6e7d..c63148f8e 100644--- a/crates/shoji/src/types/session/chat/reply/stats.rs+++ b/crates/shoji/src/types/session/chat/reply/stats.rs@@ -1,6 +1,6 @@use serde::{Deserialize, Serialize};-#[bindings::export(ClassCloneable)]+#[bindings::export(Structure(Class))]#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]pub struct ChatReplyStats {pub duration: f64,@@ -13,7 +13,7 @@ pub struct ChatReplyStats {#[bindings::export(Implementation)]impl ChatReplyStats {- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub fn tokens_count(&self) -> Option<u32> {self.tokens_count_input.and_then(|input| self.tokens_count_output.map(|output| input + output))}diff --git a/crates/shoji/src/types/session/chat/role.rs b/crates/shoji/src/types/session/chat/role.rsindex 8a3bf1eb9..1fa75f04e 100644--- a/crates/shoji/src/types/session/chat/role.rs+++ b/crates/shoji/src/types/session/chat/role.rs@@ -6,7 +6,7 @@ use std::{use serde::{Deserialize, Deserializer, Serialize, Serializer, de};-#[bindings::export(Enum)]+#[bindings::export(Enumeration)]#[derive(Debug, Clone, PartialEq, Eq, Hash)]pub enum ChatRole {User {},diff --git a/crates/shoji/src/types/session/chat/speculation_preset.rs b/crates/shoji/src/types/session/chat/speculation_preset.rsindex f18e8fb65..af541d10a 100644--- a/crates/shoji/src/types/session/chat/speculation_preset.rs+++ b/crates/shoji/src/types/session/chat/speculation_preset.rs@@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};use crate::types::basic::Feature;-#[bindings::export(Enum)]+#[bindings::export(Enumeration)]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]pub enum ChatSpeculationPreset {GeneralChat {},diff --git a/crates/shoji/src/types/session/classification/label.rs b/crates/shoji/src/types/session/classification/label.rsindex 72216281a..79b4b020a 100644--- a/crates/shoji/src/types/session/classification/label.rs+++ b/crates/shoji/src/types/session/classification/label.rs@@ -1,6 +1,6 @@use serde::{Deserialize, Serialize};-#[bindings::export(ClassCloneable)]+#[bindings::export(Structure(Class))]#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct ClassificationLabel {pub index: i64,diff --git a/crates/shoji/src/types/session/classification/message.rs b/crates/shoji/src/types/session/classification/message.rsindex 8b1106e2e..556a397a5 100644--- a/crates/shoji/src/types/session/classification/message.rs+++ b/crates/shoji/src/types/session/classification/message.rs@@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};use crate::types::session::classification::ClassificationRole;-#[bindings::export(ClassCloneable)]+#[bindings::export(Structure(Class))]#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub struct ClassificationMessage {@@ -24,12 +24,12 @@ impl ClassificationMessage {#[bindings::export(Implementation)]impl ClassificationMessage {- #[bindings::export(Factory)]+ #[bindings::export(Method(Factory))]pub fn user(content: String) -> Self {Self::new(ClassificationRole::User, content)}- #[bindings::export(Factory)]+ #[bindings::export(Method(Factory))]pub fn assistant(content: String) -> Self {Self::new(ClassificationRole::Assistant, content)}diff --git a/crates/shoji/src/types/session/classification/output.rs b/crates/shoji/src/types/session/classification/output.rsindex 099bbb9d4..6a6069fa8 100644--- a/crates/shoji/src/types/session/classification/output.rs+++ b/crates/shoji/src/types/session/classification/output.rs@@ -4,13 +4,13 @@ use serde::{Deserialize, Serialize};use crate::types::session::classification::ClassificationStats;-#[bindings::export(Struct)]+#[bindings::export(Structure)]#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct ClassificationOutputProbabilities {pub values: HashMap<String, f64>,}-#[bindings::export(ClassCloneable)]+#[bindings::export(Structure(Class))]#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct ClassificationOutput {pub logits: Vec<f64>,diff --git a/crates/shoji/src/types/session/classification/role.rs b/crates/shoji/src/types/session/classification/role.rsindex cd0dd954e..b3bb4a912 100644--- a/crates/shoji/src/types/session/classification/role.rs+++ b/crates/shoji/src/types/session/classification/role.rs@@ -1,6 +1,6 @@use serde::{Deserialize, Serialize};-#[bindings::export(Enum)]+#[bindings::export(Enumeration)]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]pub enum ClassificationRole {User,diff --git a/crates/shoji/src/types/session/classification/stats.rs b/crates/shoji/src/types/session/classification/stats.rsindex 27e6939b6..c59312cc9 100644--- a/crates/shoji/src/types/session/classification/stats.rs+++ b/crates/shoji/src/types/session/classification/stats.rs@@ -1,6 +1,6 @@use serde::{Deserialize, Serialize};-#[bindings::export(ClassCloneable)]+#[bindings::export(Structure(Class))]#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct ClassificationStats {pub preprocessing_duration: f64,diff --git a/crates/shoji/src/types/session/text_to_speech/stats.rs b/crates/shoji/src/types/session/text_to_speech/stats.rsindex 0c31f7471..d035842c9 100644--- a/crates/shoji/src/types/session/text_to_speech/stats.rs+++ b/crates/shoji/src/types/session/text_to_speech/stats.rs@@ -1,6 +1,6 @@use serde::{Deserialize, Serialize};-#[bindings::export(ClassCloneable)]+#[bindings::export(Structure(Class))]#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct TextToSpeechStats {pub text_length: u32,diff --git a/crates/uzu/Cargo.toml b/crates/uzu/Cargo.tomlindex 83263135c..844088cb8 100644--- a/crates/uzu/Cargo.toml+++ b/crates/uzu/Cargo.toml@@ -22,19 +22,31 @@ bindings = ["bindings-wasm",]bindings-uniffi = [+ "bindings-types/bindings-uniffi","shoji/bindings-uniffi","nagare/bindings-uniffi","dep:uniffi",]bindings-napi = [+ "bindings-types/bindings-napi","shoji/bindings-napi","nagare/bindings-napi","dep:napi","dep:napi-derive","dep:napi-build",]-bindings-pyo3 = ["shoji/bindings-pyo3", "nagare/bindings-pyo3", "dep:pyo3"]+bindings-pyo3 = [+ "bindings-types/bindings-pyo3",+ "shoji/bindings-pyo3",+ "nagare/bindings-pyo3",+ "dep:pyo3",+ "dep:pyo3-build-config",+ "dep:pyo3-async-runtimes",+ "dep:pyo3-stub-gen",+ "dep:inventory",+]bindings-wasm = [+ "bindings-types/bindings-wasm","shoji/bindings-wasm","nagare/bindings-wasm","dep:wasm-bindgen",@@ -44,6 +56,7 @@ bindings-wasm = [][dependencies]+bindings-types.workspace = truebindings.workspace = truebackend-uzu.workspace = trueshoji.workspace = true@@ -51,6 +64,9 @@ uniffi = { workspace = true, optional = true }napi = { workspace = true, optional = true }napi-derive = { workspace = true, optional = true }pyo3 = { workspace = true, optional = true }+pyo3-async-runtimes = { workspace = true, optional = true }+pyo3-stub-gen = { workspace = true, optional = true }+inventory = { workspace = true, optional = true }wasm-bindgen = { workspace = true, optional = true }serde-wasm-bindgen = { workspace = true, optional = true }wasm-bindgen-futures = { workspace = true, optional = true }@@ -91,6 +107,9 @@ chrono.workspace = truetempfile.workspace = trueindicatif.workspace = truedotenvy.workspace = true+schemars.workspace = true+serde_json.workspace = true[build-dependencies]napi-build = { workspace = true, optional = true }+pyo3-build-config = { workspace = true, optional = true }diff --git a/crates/uzu/build.rs b/crates/uzu/build.rsindex 6de3825da..43dd98946 100644--- a/crates/uzu/build.rs+++ b/crates/uzu/build.rs@@ -1,4 +1,6 @@fn main() {#[cfg(feature = "bindings-napi")]napi_build::setup();+ #[cfg(feature = "bindings-pyo3")]+ pyo3_build_config::add_extension_module_link_args();}diff --git a/crates/uzu/examples/chat.rs b/crates/uzu/examples/chat.rsnew file mode 100644index 000000000..059d0ecef--- /dev/null+++ b/crates/uzu/examples/chat.rs@@ -0,0 +1,48 @@+use uzu::{+ engine::{Engine, EngineConfig},+ session::chat::ChatSessionStreamChunk,+ types::session::chat::{ChatConfig, ChatMessage, ChatReplyConfig},+};++#[tokio::main]+async fn main() -> Result<(), Box<dyn std::error::Error>> {+ let engine_config = EngineConfig::default();+ let engine = Engine::new(engine_config).await?;++ let model = engine.model("Qwen/Qwen3-0.6B".to_string()).await?.ok_or("Model not found")?;+ let downloader = engine.download(&model).await?;+ while let Some(update) = downloader.next().await {+ println!("Download progress: {}", update.progress());+ }++ let messages = vec![+ ChatMessage::system().with_text("You are a helpful assistant".to_string()),+ ChatMessage::user().with_text("Tell me a short, funny story about a robot".to_string()),+ ];+ let session = engine.chat(model, ChatConfig::default()).await?;+ let stream = session.reply_with_stream(messages, ChatReplyConfig::default()).await;+ let mut last_message: Option<ChatMessage> = None;+ while let Some(chunk) = stream.next().await {+ match chunk {+ ChatSessionStreamChunk::Replies {+ replies,+ } => {+ if let Some(reply) = replies.first() {+ last_message = Some(reply.message.clone());+ println!("Generated tokens: {}", reply.stats.tokens_count_output.unwrap_or_default());+ }+ },+ ChatSessionStreamChunk::Error {+ error,+ } => {+ println!("Error: {error}");+ },+ }+ }+ if let Some(message) = last_message {+ println!("Reasoning: {}", message.reasoning().unwrap_or_default());+ println!("Text: {}", message.text().unwrap_or_default());+ }++ Ok(())+}diff --git a/crates/uzu/examples/chat_for_classification.rs b/crates/uzu/examples/chat_for_classification.rsnew file mode 100644index 000000000..a33337b30--- /dev/null+++ b/crates/uzu/examples/chat_for_classification.rs@@ -0,0 +1,56 @@+use uzu::{+ engine::{Engine, EngineConfig},+ types::{+ basic::{Feature, ReasoningEffort, SamplingMethod},+ session::chat::{ChatConfig, ChatMessage, ChatReplyConfig, ChatSpeculationPreset},+ },+};++#[tokio::main]+async fn main() -> Result<(), Box<dyn std::error::Error>> {+ let engine_config = EngineConfig::default();+ let engine = Engine::new(engine_config).await?;++ let model = engine.model("Qwen/Qwen3-0.6B".to_string()).await?.ok_or("Model not found")?;+ let downloader = engine.download(&model).await?;+ while let Some(update) = downloader.next().await {+ println!("Download progress: {}", update.progress());+ }++ let feature = Feature {+ name: "sentiment".to_string(),+ values: vec![+ "Happy".to_string(),+ "Sad".to_string(),+ "Angry".to_string(),+ "Fearful".to_string(),+ "Surprised".to_string(),+ "Disgusted".to_string(),+ ],+ };+ let chat_config = ChatConfig::default().with_speculation_preset(Some(ChatSpeculationPreset::Classification {+ feature: feature.clone(),+ }));+ let session = engine.chat(model, chat_config).await?;++ let text_to_detect_feature = "Today's been awesome! Everything just feels right, and I can't stop smiling.";+ let prompt = format!(+ "Text is: \"{text_to_detect_feature}\". Choose {} from the list: {}. Answer with one word. Don't add a dot at the end.",+ feature.name,+ feature.values.join(", ")+ );+ let messages = vec![+ ChatMessage::system().with_reasoning_effort(ReasoningEffort::Disabled),+ ChatMessage::user().with_text(prompt),+ ];++ let chat_reply_config =+ ChatReplyConfig::default().with_token_limit(Some(32)).with_sampling_method(SamplingMethod::Greedy {});+ let replies = session.reply(messages, chat_reply_config).await?;+ if let Some(reply) = replies.first() {+ println!("Prediction: {}", reply.message.text().unwrap_or_default());+ println!("Generated tokens: {}", reply.stats.tokens_count_output.unwrap_or_default());+ }++ Ok(())+}diff --git a/crates/uzu/examples/chat_for_summarization.rs b/crates/uzu/examples/chat_for_summarization.rsnew file mode 100644index 000000000..68f6a4a96--- /dev/null+++ b/crates/uzu/examples/chat_for_summarization.rs@@ -0,0 +1,47 @@+use uzu::{+ engine::{Engine, EngineConfig},+ types::{+ basic::{ReasoningEffort, SamplingMethod},+ session::chat::{ChatConfig, ChatMessage, ChatReplyConfig, ChatSpeculationPreset},+ },+};++#[tokio::main]+async fn main() -> Result<(), Box<dyn std::error::Error>> {+ let engine_config = EngineConfig::default();+ let engine = Engine::new(engine_config).await?;++ let model = engine.model("Qwen/Qwen3-0.6B".to_string()).await?.ok_or("Model not found")?;+ let downloader = engine.download(&model).await?;+ while let Some(update) = downloader.next().await {+ println!("Download progress: {}", update.progress());+ }++ let text_to_summarize = "A Large Language Model (LLM) is a type of artificial intelligence that processes and generates human-like text. \+ It is trained on vast datasets containing books, articles, and web content, allowing it to understand and predict language patterns. \+ LLMs use deep learning, particularly transformer-based architectures, to analyze text, recognize context, and generate coherent responses. \+ These models have a wide range of applications, including chatbots, content creation, translation, and code generation. \+ One of the key strengths of LLMs is their ability to generate contextually relevant text based on prompts. \+ They utilize self-attention mechanisms to weigh the importance of words within a sentence, improving accuracy and fluency. \+ Examples of popular LLMs include OpenAI's GPT series, Google's BERT, and Meta's LLaMA. \+ As these models grow in size and sophistication, they continue to enhance human-computer interactions, \+ making AI-powered communication more natural and effective.";+ let prompt = format!("Text is: \"{text_to_summarize}\". Write only summary itself.");+ let messages = vec![+ ChatMessage::system().with_reasoning_effort(ReasoningEffort::Disabled),+ ChatMessage::user().with_text(prompt),+ ];++ let chat_config = ChatConfig::default().with_speculation_preset(Some(ChatSpeculationPreset::Summarization {}));+ let session = engine.chat(model, chat_config).await?;++ let chat_reply_config =+ ChatReplyConfig::default().with_token_limit(Some(256)).with_sampling_method(SamplingMethod::Greedy {});+ let replies = session.reply(messages, chat_reply_config).await?;+ if let Some(reply) = replies.first() {+ println!("Summary: {}", reply.message.text().unwrap_or_default());+ println!("Generation t/s: {}", reply.stats.generate_tokens_per_second.unwrap_or_default());+ }++ Ok(())+}diff --git a/crates/uzu/examples/classifier.rs b/crates/uzu/examples/classifier.rsnew file mode 100644index 000000000..f7926bcc9--- /dev/null+++ b/crates/uzu/examples/classifier.rs@@ -0,0 +1,24 @@+use uzu::{+ engine::{Engine, EngineConfig},+ types::session::classification::ClassificationMessage,+};++#[tokio::main]+async fn main() -> Result<(), Box<dyn std::error::Error>> {+ let engine_config = EngineConfig::default();+ let engine = Engine::new(engine_config).await?;++ let model = engine.model("trymirai/chat-moderation-router".to_string()).await?.ok_or("Model not found")?;+ let downloader = engine.download(&model).await?;+ while let Some(update) = downloader.next().await {+ println!("Download progress: {}", update.progress());+ }++ let messages = vec![ClassificationMessage::user("Hi".to_string())];++ let session = engine.classification(model).await?;+ let output = session.classify(messages).await?;+ println!("Output: {:?}", output.probabilities.values);++ Ok(())+}diff --git a/crates/uzu/examples/cloud.rs b/crates/uzu/examples/cloud.rsnew file mode 100644index 000000000..fa0f25e74--- /dev/null+++ b/crates/uzu/examples/cloud.rs@@ -0,0 +1,29 @@+use uzu::{+ engine::{Engine, EngineConfig},+ types::{+ basic::ReasoningEffort,+ session::chat::{ChatConfig, ChatMessage, ChatReplyConfig},+ },+};++#[tokio::main]+async fn main() -> Result<(), Box<dyn std::error::Error>> {+ let engine_config = EngineConfig::default().with_openai_api_key("OPENAI_API_KEY".to_string());+ let engine = Engine::new(engine_config).await?;++ let model = engine.model("gpt-5".to_string()).await?.ok_or("Model not found")?;++ let messages = vec![+ ChatMessage::system().with_reasoning_effort(ReasoningEffort::Low),+ ChatMessage::user().with_text("How LLMs work".to_string()),+ ];++ let session = engine.chat(model, ChatConfig::default()).await?;+ let replies = session.reply(messages, ChatReplyConfig::default()).await?;+ if let Some(reply) = replies.first() {+ println!("Reasoning: {}", reply.message.reasoning().unwrap_or_default());+ println!("Text: {}", reply.message.text().unwrap_or_default());+ }++ Ok(())+}diff --git a/crates/uzu/examples/quick_start.rs b/crates/uzu/examples/quick_start.rsnew file mode 100644index 000000000..917877cd8--- /dev/null+++ b/crates/uzu/examples/quick_start.rs@@ -0,0 +1,31 @@+use uzu::{+ engine::{Engine, EngineConfig},+ types::session::chat::{ChatConfig, ChatMessage, ChatReplyConfig},+};++#[tokio::main]+async fn main() -> Result<(), Box<dyn std::error::Error>> {+ let engine_config = EngineConfig::default();+ let engine = Engine::new(engine_config).await?;++ let model = engine.model("Qwen/Qwen3-0.6B".to_string()).await?.ok_or("Model not found")?;+ let downloader = engine.download(&model).await?;+ while let Some(update) = downloader.next().await {+ println!("Download progress: {}", update.progress());+ }++ let session = engine.chat(model, ChatConfig::default()).await?;++ let messages = vec![+ ChatMessage::system().with_text("You are a helpful assistant".to_string()),+ ChatMessage::user().with_text("Tell me a short, funny story about a robot".to_string()),+ ];++ let replies = session.reply(messages, ChatReplyConfig::default()).await?;+ if let Some(reply) = replies.last() {+ println!("Reasoning: {}", reply.message.reasoning().unwrap_or_default());+ println!("Text: {}", reply.message.text().unwrap_or_default());+ }++ Ok(())+}diff --git a/crates/uzu/examples/quick_start_chat.rs b/crates/uzu/examples/quick_start_chat.rsdeleted file mode 100644index a27f240d6..000000000--- a/crates/uzu/examples/quick_start_chat.rs+++ /dev/null@@ -1,25 +0,0 @@-use uzu::{- engine::{Engine, EngineConfig},- types::session::chat::{ChatConfig, ChatMessage, ChatReplyConfig},-};--#[tokio::main]-async fn main() -> Result<(), Box<dyn std::error::Error>> {- let config = EngineConfig::default();- let engine = Engine::new(config).await?;-- let model = engine.model("Qwen/Qwen3-0.6B".to_string()).await?.ok_or("Model not found")?;- while let Some(update) = engine.download(&model).await?.next().await {- println!("Downloading: {}", update.progress());- }-- let session = engine.chat(model, ChatConfig::default()).await?;- let outputs = session- .reply(vec![ChatMessage::user().with_text("Tell about London".to_string())], ChatReplyConfig::default())- .await?;- for output in outputs {- println!("{}", output.message.text().unwrap_or_default());- }-- Ok(())-}diff --git a/crates/uzu/examples/snippets.rs b/crates/uzu/examples/snippets.rsnew file mode 100644index 000000000..76afec628--- /dev/null+++ b/crates/uzu/examples/snippets.rs@@ -0,0 +1,189 @@+use uzu::{+ engine::{Engine, EngineConfig},+ types::{+ basic::{Feature, ReasoningEffort, SamplingMethod},+ session::chat::{ChatConfig, ChatMessage, ChatReplyConfig, ChatSpeculationPreset},+ },+};++async fn quick_start_example() -> Result<(), Box<dyn std::error::Error>> {+ // snippet:quick-start+ let engine_config = EngineConfig::default();+ let engine = Engine::new(engine_config).await?;++ let model = engine.model("Qwen/Qwen3-0.6B".to_string()).await?.ok_or("Model not found")?;+ let downloader = engine.download(&model).await?;+ while let Some(update) = downloader.next().await {+ println!("Download progress: {}", update.progress());+ }++ let messages = vec![+ ChatMessage::system().with_text("You are a helpful assistant".to_string()),+ ChatMessage::user().with_text("Tell me a short, funny story about a robot".to_string()),+ ];++ let session = engine.chat(model, ChatConfig::default()).await?;+ let replies = session.reply(messages, ChatReplyConfig::default()).await?;+ let message = replies.first().map(|reply| reply.message.clone());+ // endsnippet:quick-start++ if let Some(message) = message {+ println!("Reasoning: {}", message.reasoning().unwrap_or_default());+ println!("Text: {}", message.text().unwrap_or_default());+ }++ Ok(())+}++async fn chat_example() -> Result<(), Box<dyn std::error::Error>> {+ // snippet:engine-create+ let engine_config = EngineConfig::default();+ let engine = Engine::new(engine_config).await?;+ // endsnippet:engine-create++ // snippet:model-choose+ let model = engine.model("Qwen/Qwen3-0.6B".to_string()).await?.ok_or("Model not found")?;+ // endsnippet:model-choose++ // snippet:model-download+ let downloader = engine.download(&model).await?;+ while let Some(update) = downloader.next().await {+ println!("Download progress: {}", update.progress());+ }+ // endsnippet:model-download++ // snippet:session-create-general+ let session = engine.chat(model, ChatConfig::default()).await?;+ // endsnippet:session-create-general++ // snippet:session-input-general+ let messages = vec![+ ChatMessage::system().with_text("You are a helpful assistant".to_string()),+ ChatMessage::user().with_text("Tell me a short, funny story about a robot".to_string()),+ ];+ // endsnippet:session-input-general++ // snippet:session-run-general+ let replies = session.reply(messages, ChatReplyConfig::default()).await?;+ let message = replies.first().map(|reply| reply.message.clone());+ // endsnippet:session-run-general++ if let Some(message) = message {+ println!("Reasoning: {}", message.reasoning().unwrap_or_default());+ println!("Text: {}", message.text().unwrap_or_default());+ }++ Ok(())+}++async fn summarization_example() -> Result<(), Box<dyn std::error::Error>> {+ let engine_config = EngineConfig::default();+ let engine = Engine::new(engine_config).await?;++ let model = engine.model("Qwen/Qwen3-0.6B".to_string()).await?.ok_or("Model not found")?;+ let downloader = engine.download(&model).await?;+ while let Some(update) = downloader.next().await {+ println!("Download progress: {}", update.progress());+ }++ // snippet:session-input-summarization+ let text_to_summarize = "A Large Language Model (LLM) is a type of artificial intelligence that processes and generates human-like text. \+ It is trained on vast datasets containing books, articles, and web content, allowing it to understand and predict language patterns. \+ LLMs use deep learning, particularly transformer-based architectures, to analyze text, recognize context, and generate coherent responses. \+ These models have a wide range of applications, including chatbots, content creation, translation, and code generation. \+ One of the key strengths of LLMs is their ability to generate contextually relevant text based on prompts. \+ They utilize self-attention mechanisms to weigh the importance of words within a sentence, improving accuracy and fluency. \+ Examples of popular LLMs include OpenAI's GPT series, Google's BERT, and Meta's LLaMA. \+ As these models grow in size and sophistication, they continue to enhance human-computer interactions, \+ making AI-powered communication more natural and effective.";+ let prompt = format!("Text is: \"{text_to_summarize}\". Write only summary itself.");+ let messages = vec![+ ChatMessage::system().with_reasoning_effort(ReasoningEffort::Disabled),+ ChatMessage::user().with_text(prompt),+ ];+ // endsnippet:session-input-summarization++ // snippet:session-create-summarization+ let chat_config = ChatConfig::default().with_speculation_preset(Some(ChatSpeculationPreset::Summarization {}));+ let session = engine.chat(model, chat_config).await?;+ // endsnippet:session-create-summarization++ // snippet:session-run-summarization+ let chat_reply_config =+ ChatReplyConfig::default().with_token_limit(Some(256)).with_sampling_method(SamplingMethod::Greedy {});+ let replies = session.reply(messages, chat_reply_config).await?;+ let reply = replies.first().cloned();+ // endsnippet:session-run-summarization++ if let Some(reply) = reply {+ println!("Summary: {}", reply.message.text().unwrap_or_default());+ println!("Generation t/s: {}", reply.stats.generate_tokens_per_second.unwrap_or_default());+ }++ Ok(())+}++async fn classification_example() -> Result<(), Box<dyn std::error::Error>> {+ let engine_config = EngineConfig::default();+ let engine = Engine::new(engine_config).await?;++ let model = engine.model("Qwen/Qwen3-0.6B".to_string()).await?.ok_or("Model not found")?;+ let downloader = engine.download(&model).await?;+ while let Some(update) = downloader.next().await {+ println!("Download progress: {}", update.progress());+ }++ // snippet:session-create-classification+ let feature = Feature {+ name: "sentiment".to_string(),+ values: vec![+ "Happy".to_string(),+ "Sad".to_string(),+ "Angry".to_string(),+ "Fearful".to_string(),+ "Surprised".to_string(),+ "Disgusted".to_string(),+ ],+ };+ let chat_config = ChatConfig::default().with_speculation_preset(Some(ChatSpeculationPreset::Classification {+ feature: feature.clone(),+ }));+ let session = engine.chat(model, chat_config).await?;+ // endsnippet:session-create-classification++ // snippet:session-input-classification+ let text_to_detect_feature = "Today's been awesome! Everything just feels right, and I can't stop smiling.";+ let prompt = format!(+ "Text is: \"{text_to_detect_feature}\". Choose {} from the list: {}. Answer with one word. Don't add a dot at the end.",+ feature.name,+ feature.values.join(", ")+ );+ let messages = vec![+ ChatMessage::system().with_reasoning_effort(ReasoningEffort::Disabled),+ ChatMessage::user().with_text(prompt),+ ];+ // endsnippet:session-input-classification++ // snippet:session-run-classification+ let chat_reply_config =+ ChatReplyConfig::default().with_token_limit(Some(32)).with_sampling_method(SamplingMethod::Greedy {});+ let replies = session.reply(messages, chat_reply_config).await?;+ let reply = replies.first().cloned();+ // endsnippet:session-run-classification++ if let Some(reply) = reply {+ println!("Prediction: {}", reply.message.text().unwrap_or_default());+ println!("Generated tokens: {}", reply.stats.tokens_count_output.unwrap_or_default());+ }++ Ok(())+}++#[tokio::main]+async fn main() -> Result<(), Box<dyn std::error::Error>> {+ quick_start_example().await?;+ chat_example().await?;+ summarization_example().await?;+ classification_example().await?;+ Ok(())+}diff --git a/crates/uzu/examples/ssm.rs b/crates/uzu/examples/ssm.rsnew file mode 100644index 000000000..90e26fae0--- /dev/null+++ b/crates/uzu/examples/ssm.rs@@ -0,0 +1,26 @@+use uzu::{+ engine::{Engine, EngineConfig},+ types::session::chat::{ChatConfig, ChatMessage, ChatReplyConfig},+};++#[tokio::main]+async fn main() -> Result<(), Box<dyn std::error::Error>> {+ let engine_config = EngineConfig::default();+ let engine = Engine::new(engine_config).await?;++ let model = engine.model("cartesia-ai/Llamba-1B-4bit-mlx".to_string()).await?.ok_or("Model not found")?;+ let downloader = engine.download(&model).await?;+ while let Some(update) = downloader.next().await {+ println!("Download progress: {}", update.progress());+ }++ let messages = vec![ChatMessage::user().with_text("Tell me a short, funny story about a robot".to_string())];++ let session = engine.chat(model, ChatConfig::default()).await?;+ let replies = session.reply(messages, ChatReplyConfig::default()).await?;+ if let Some(reply) = replies.first() {+ println!("Text: {}", reply.message.text().unwrap_or_default());+ }++ Ok(())+}diff --git a/crates/uzu/examples/structured_output.rs b/crates/uzu/examples/structured_output.rsnew file mode 100644index 000000000..055027035--- /dev/null+++ b/crates/uzu/examples/structured_output.rs@@ -0,0 +1,55 @@+use schemars::{JsonSchema, schema_for};+use serde::{Deserialize, Serialize};+use uzu::{+ engine::{Engine, EngineConfig},+ types::{+ basic::{Grammar, ReasoningEffort},+ session::chat::{ChatConfig, ChatMessage, ChatReplyConfig},+ },+};++#[derive(Debug, Serialize, Deserialize, JsonSchema)]+struct Country {+ name: String,+ capital: String,+}++#[derive(Debug, Serialize, Deserialize, JsonSchema)]+struct CountryList {+ countries: Vec<Country>,+}++#[tokio::main]+async fn main() -> Result<(), Box<dyn std::error::Error>> {+ let engine_config = EngineConfig::default();+ let engine = Engine::new(engine_config).await?;++ let model = engine.model("Qwen/Qwen3-0.6B".to_string()).await?.ok_or("Model not found")?;+ let downloader = engine.download(&model).await?;+ while let Some(update) = downloader.next().await {+ println!("Download progress: {}", update.progress());+ }++ let schema_string = serde_json::to_string(&schema_for!(CountryList))?;+ let messages = vec![+ ChatMessage::system().with_reasoning_effort(ReasoningEffort::Disabled),+ ChatMessage::user().with_text(+ "Give me a JSON object containing a list of 3 countries, where each country has name and capital fields"+ .to_string(),+ ),+ ];++ let session = engine.chat(model, ChatConfig::default()).await?;+ let chat_reply_config = ChatReplyConfig::default().with_grammar(Some(Grammar::JsonSchema {+ schema: schema_string,+ }));+ let replies = session.reply(messages, chat_reply_config).await?;+ if let Some(reply) = replies.first() {+ if let Some(text) = reply.message.text() {+ let parsed: CountryList = serde_json::from_str(&text)?;+ println!("{parsed:#?}");+ }+ }++ Ok(())+}diff --git a/crates/uzu/examples/text_to_speech.rs b/crates/uzu/examples/text_to_speech.rsnew file mode 100644index 000000000..e8ecd4078--- /dev/null+++ b/crates/uzu/examples/text_to_speech.rs@@ -0,0 +1,26 @@+use uzu::engine::{Engine, EngineConfig};++#[tokio::main]+async fn main() -> Result<(), Box<dyn std::error::Error>> {+ let engine_config = EngineConfig::default();+ let engine = Engine::new(engine_config).await?;++ let model = engine.model("fishaudio/s1-mini".to_string()).await?.ok_or("Model not found")?;+ let downloader = engine.download(&model).await?;+ while let Some(update) = downloader.next().await {+ println!("Download progress: {}", update.progress());+ }++ let text = "London is the capital of United Kingdom and one of the world's most influential cities, \+ known for its rich history, cultural diversity, and global significance in finance, politics, and the arts. \+ Situated along the River Thames, the city blends historic landmarks like Tower of London and Buckingham Palace \+ with modern architecture such as The Shard. London is also home to renowned institutions including the British Museum \+ and vibrant areas like Covent Garden, offering a mix of history, entertainment, and innovation that attracts millions of visitors each year.";+ let output_path = dirs::home_dir().ok_or("Home not found")?.join("Desktop").join("output.wav");+ let session = engine.text_to_speech(model).await?;+ let pcm_batch = session.synthesize(text.to_string()).await?;+ pcm_batch.save_as_wav(output_path.to_string_lossy().to_string())?;+ println!("Output saved to: {}", output_path.display());++ Ok(())+}diff --git a/crates/uzu/src/device/error.rs b/crates/uzu/src/device/error.rsindex 8a59f421f..98cbd2672 100644--- a/crates/uzu/src/device/error.rs+++ b/crates/uzu/src/device/error.rs@@ -1,5 +1,5 @@#[bindings::export(Error)]-#[derive(Debug, Clone, thiserror::Error)]+#[derive(Debug, Clone, PartialEq, thiserror::Error)]#[non_exhaustive]pub enum DeviceError {#[error("Unsupported device")]diff --git a/crates/uzu/src/device/mod.rs b/crates/uzu/src/device/mod.rsindex 553906794..3be7506b2 100644--- a/crates/uzu/src/device/mod.rs+++ b/crates/uzu/src/device/mod.rs@@ -6,7 +6,7 @@ use os::{application_identifier, home_path, is_environment_sandboxed, is_keyringuse serde::{Deserialize, Serialize};use sysinfo::System;-#[bindings::export(ClassCloneable)]+#[bindings::export(Structure(Class))]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub struct Device {@@ -46,7 +46,7 @@ impl Device {#[bindings::export(Implementation)]impl Device {- #[bindings::export(Factory)]+ #[bindings::export(Method(Factory))]pub fn create() -> Result<Self, DeviceError> {Self::new()}diff --git a/crates/uzu/src/engine/callback.rs b/crates/uzu/src/engine/callback.rsindex a62845440..0ece994f6 100644--- a/crates/uzu/src/engine/callback.rs+++ b/crates/uzu/src/engine/callback.rs@@ -22,7 +22,7 @@ impl EngineCallback {#[bindings::export(Implementation)]impl EngineCallback {- #[bindings::export(FactoryWithCallback)]+ #[bindings::export(Method(FactoryWithCallback))]pub fn create(callback: Box<dyn Fn() + Send + Sync>) -> Self {Self::new(callback)}diff --git a/crates/uzu/src/engine/config.rs b/crates/uzu/src/engine/config.rsindex a028f8651..a70dd78c7 100644--- a/crates/uzu/src/engine/config.rs+++ b/crates/uzu/src/engine/config.rs@@ -14,7 +14,7 @@ const KEY_XAI_API_KEY: &str = "XAI_API_KEY";const KEY_BASETEN_API_KEY: &str = "BASETEN_API_KEY";const KEY_OPENROUTER_API_KEY: &str = "OPENROUTER_API_KEY";-#[bindings::export(ClassCloneable)]+#[bindings::export(Structure(Class))]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub struct EngineConfig {@@ -33,7 +33,7 @@ pub struct EngineConfig {#[bindings::export(Implementation)]impl EngineConfig {- #[bindings::export(Factory)]+ #[bindings::export(Method(Factory))]pub fn create() -> Self {Self::default()}diff --git a/crates/uzu/src/engine/downloader.rs b/crates/uzu/src/engine/downloader.rsindex 79b6125c1..ce5c5b85d 100644--- a/crates/uzu/src/engine/downloader.rs+++ b/crates/uzu/src/engine/downloader.rs@@ -11,6 +11,7 @@ use crate::{};#[bindings::export(Class)]+#[derive(Clone)]pub struct Downloader {identifier: String,storage: SharedAccess<Storage>,@@ -30,7 +31,7 @@ impl Downloader {#[bindings::export(Implementation)]impl Downloader {- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub async fn state(&self) -> Option<DownloadState> {self.storage.lock().await.state(&self.identifier).await}@@ -80,7 +81,7 @@ impl Downloader {}}-#[bindings::export(Stream)]+#[bindings::export(Class(Stream))]#[derive(Clone)]pub struct DownloaderStream {identifier: String,@@ -108,7 +109,7 @@ impl DownloaderStream {#[bindings::export(Implementation)]impl DownloaderStream {- #[bindings::export(StreamNext)]+ #[bindings::export(Method(StreamNext))]pub async fn next(&self) -> Option<DownloaderStreamUpdate> {let mut stream_guard = self.stream.lock().await;let stream = stream_guard.as_mut()?;@@ -138,7 +139,7 @@ impl DownloaderStream {}}-#[bindings::export(ClassCloneable)]+#[bindings::export(Structure(Class))]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]pub struct DownloaderStreamUpdate {pub bytes_total: i64,@@ -147,7 +148,7 @@ pub struct DownloaderStreamUpdate {#[bindings::export(Implementation)]impl DownloaderStreamUpdate {- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub fn progress(&self) -> f32 {if self.bytes_total == 0 {0.0diff --git a/crates/uzu/src/engine/error.rs b/crates/uzu/src/engine/error.rsindex 1f0beca6b..e187edf75 100644--- a/crates/uzu/src/engine/error.rs+++ b/crates/uzu/src/engine/error.rs@@ -1,5 +1,5 @@#[bindings::export(Error)]-#[derive(Debug, Clone, thiserror::Error)]+#[derive(Debug, Clone, PartialEq, thiserror::Error)]#[non_exhaustive]pub enum EngineError {#[error("Tokio error: {message}")]diff --git a/crates/uzu/src/engine/mod.rs b/crates/uzu/src/engine/mod.rsindex 3eebb9d97..7475d74a2 100644--- a/crates/uzu/src/engine/mod.rs+++ b/crates/uzu/src/engine/mod.rs@@ -42,6 +42,7 @@ use crate::{};#[bindings::export(Class)]+#[derive(Clone)]pub struct Engine {registry: SharedAccess<MergedRegistry>,storage: SharedAccess<Storage>,@@ -143,7 +144,7 @@ impl Engine {#[bindings::export(Implementation)]impl Engine {- #[bindings::export(Factory)]+ #[bindings::export(Method(Factory))]pub async fn create(config: EngineConfig) -> Result<Self, EngineError> {Self::new(config).await}@@ -202,52 +203,52 @@ impl Engine {#[bindings::export(Implementation)]impl Engine {- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub async fn models(&self) -> Result<Vec<Model>, EngineError> {self.registry.lock().await.models().await.map_err(EngineError::from)}- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub async fn models_local(&self) -> Result<Vec<Model>, EngineError> {Ok(self.models().await?.into_iter().filter(|model| model.is_local()).collect())}- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub async fn models_remote(&self) -> Result<Vec<Model>, EngineError> {Ok(self.models().await?.into_iter().filter(|model| model.is_remote()).collect())}- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub async fn models_downloadable(&self) -> Result<Vec<Model>, EngineError> {Ok(self.models().await?.into_iter().filter(|model| model.is_downloadable()).collect())}- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub async fn models_for_chat(&self) -> Result<Vec<Model>, EngineError> {Ok(self.models().await?.into_iter().filter(|model| model.is_chat_capable()).collect())}- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub async fn models_for_classification(&self) -> Result<Vec<Model>, EngineError> {Ok(self.models().await?.into_iter().filter(|model| model.is_classification_capable()).collect())}- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub async fn models_for_text_to_speech(&self) -> Result<Vec<Model>, EngineError> {Ok(self.models().await?.into_iter().filter(|model| model.is_text_to_speech_capable()).collect())}- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub async fn models_for_translation(&self) -> Result<Vec<Model>, EngineError> {Ok(self.models().await?.into_iter().filter(|model| model.is_translation_capable()).collect())}- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub async fn models_for_speculation(&self) -> Result<Vec<Model>, EngineError> {Ok(self.models().await?.into_iter().filter(|model| model.is_speculation_capable()).collect())}- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub async fn model_registries(&self) -> Result<Vec<ModelRegistry>, EngineError> {let mut registries: Vec<_> = self.models()@@ -261,7 +262,7 @@ impl Engine {Ok(registries)}- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub async fn model_vendors(&self) -> Result<Vec<ModelVendor>, EngineError> {let mut vendors: Vec<_> = self.model_families()@@ -290,7 +291,7 @@ impl Engine {.collect())}- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub async fn model_families(&self) -> Result<Vec<ModelFamily>, EngineError> {let mut families: Vec<_> = self.models()@@ -435,7 +436,7 @@ impl Engine {self.downloader(model).state().await}- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub async fn download_states(&self) -> HashMap<String, DownloadState> {self.storage.lock().await.states().await}diff --git a/crates/uzu/src/keyring/error.rs b/crates/uzu/src/keyring/error.rsindex 936914a78..5bc41106a 100644--- a/crates/uzu/src/keyring/error.rs+++ b/crates/uzu/src/keyring/error.rs@@ -1,5 +1,5 @@#[bindings::export(Error)]-#[derive(Debug, Clone, thiserror::Error)]+#[derive(Debug, Clone, PartialEq, thiserror::Error)]#[non_exhaustive]pub enum KeyringError {#[error("Backend error: {message}")]diff --git a/crates/uzu/src/keyring/mod.rs b/crates/uzu/src/keyring/mod.rsindex a6669dcee..7b1a4ca0b 100644--- a/crates/uzu/src/keyring/mod.rs+++ b/crates/uzu/src/keyring/mod.rs@@ -11,6 +11,7 @@ const SERVICE_PREFIX: &str = "com.trymirai.keyring";const BASE_KEY: &str = "keys";#[bindings::export(Class)]+#[derive(Clone)]pub struct Keyring {device: Device,service_name: String,@@ -61,7 +62,7 @@ impl Keyring {#[bindings::export(Implementation)]impl Keyring {- #[bindings::export(Factory)]+ #[bindings::export(Method(Factory))]pub fn create() -> Result<Self, KeyringError> {Self::new()}diff --git a/crates/uzu/src/lib.rs b/crates/uzu/src/lib.rsindex eaf09e2ac..85dcfeed3 100644--- a/crates/uzu/src/lib.rs+++ b/crates/uzu/src/lib.rs@@ -1,6 +1,33 @@#[cfg(feature = "bindings-uniffi")]uniffi::setup_scaffolding!();+#[cfg(feature = "bindings-pyo3")]+#[pyo3::pyfunction]+fn generate_annotations() -> pyo3::PyResult<()> {+ let annotations = pyo3_stub_gen::StubInfo::from_pyproject_toml("pyproject.toml")+ .map_err(|error| pyo3::exceptions::PyRuntimeError::new_err(error.to_string()))?;+ annotations.generate().map_err(|error| pyo3::exceptions::PyRuntimeError::new_err(error.to_string()))?;+ Ok(())+}++#[cfg(feature = "bindings-pyo3")]+#[pyo3::pymodule]+fn uzu(m: &pyo3::Bound<'_, pyo3::types::PyModule>) -> pyo3::PyResult<()> {+ use pyo3::types::PyModuleMethods;++ let mut builder = tokio::runtime::Builder::new_multi_thread();+ builder.enable_all();+ pyo3_async_runtimes::tokio::init(builder);+ for entry in ::inventory::iter::<::bindings_types::PyClassRegistration>() {+ (entry.register)(m)?;+ }+ m.add_function(pyo3::wrap_pyfunction!(generate_annotations, m)?)?;+ Ok(())+}++#[cfg(feature = "bindings-pyo3")]+pyo3_stub_gen::define_stub_info_gatherer!(pyo3_bindings_annotations);+#[cfg(not(target_family = "wasm"))]pub mod device;#[cfg(not(target_family = "wasm"))]diff --git a/crates/uzu/src/registry/error.rs b/crates/uzu/src/registry/error.rsindex f099d3c33..493cf0edf 100644--- a/crates/uzu/src/registry/error.rs+++ b/crates/uzu/src/registry/error.rs@@ -1,5 +1,5 @@#[bindings::export(Error)]-#[derive(Debug, Clone, thiserror::Error)]+#[derive(Debug, Clone, PartialEq, thiserror::Error)]#[non_exhaustive]pub enum RegistryError {#[error("Unable to create: {message}")]diff --git a/crates/uzu/src/storage/error.rs b/crates/uzu/src/storage/error.rsindex 15ad97593..cd04057e2 100644--- a/crates/uzu/src/storage/error.rs+++ b/crates/uzu/src/storage/error.rs@@ -1,7 +1,7 @@use crate::{registry::RegistryError, storage::types::DownloadPhase};#[bindings::export(Error)]-#[derive(Debug, Clone, thiserror::Error)]+#[derive(Debug, Clone, PartialEq, thiserror::Error)]#[non_exhaustive]pub enum StorageError {#[error("Unable to create directory: {path}")]diff --git a/crates/uzu/src/storage/types/download_phase.rs b/crates/uzu/src/storage/types/download_phase.rsindex 262a8f80b..a02898c1e 100644--- a/crates/uzu/src/storage/types/download_phase.rs+++ b/crates/uzu/src/storage/types/download_phase.rs@@ -1,6 +1,6 @@use serde::{Deserialize, Serialize};-#[bindings::export(Enum)]+#[bindings::export(Enumeration)]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]pub enum DownloadPhase {NotDownloaded {},diff --git a/crates/uzu/src/storage/types/download_state.rs b/crates/uzu/src/storage/types/download_state.rsindex 6a20a813f..a7188fc0f 100644--- a/crates/uzu/src/storage/types/download_state.rs+++ b/crates/uzu/src/storage/types/download_state.rs@@ -3,7 +3,7 @@ use serde::{Deserialize, Serialize};use crate::storage::types::DownloadPhase;-#[bindings::export(ClassCloneable)]+#[bindings::export(Structure(Class))]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]pub struct DownloadState {pub total_bytes: i64,@@ -74,7 +74,7 @@ impl DownloadState {#[bindings::export(Implementation)]impl DownloadState {- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub fn progress(&self) -> f32 {if self.total_bytes == 0 {0.0@@ -83,17 +83,17 @@ impl DownloadState {}}- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub fn is_in_progress(&self) -> bool {self.phase.is_in_progress()}- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub fn can_pause(&self) -> bool {self.phase.can_pause()}- #[bindings::export(Getter)]+ #[bindings::export(Method(Getter))]pub fn can_delete(&self) -> bool {self.phase.can_delete()}