-
Notifications
You must be signed in to change notification settings - Fork 197
feat(sdk/python): add python baseline sdk #4711
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
mark-vass-konghq
wants to merge
3
commits into
main
Choose a base branch
from
feat/python-sdk-baseline
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| [flake8] | ||
| max-line-length = 100 | ||
| extend-exclude = .venv,build,dist | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| /.venv/ | ||
| /.ruff_cache/ | ||
| /build/ | ||
| /dist/ | ||
| *.egg-info/ | ||
| __pycache__/ | ||
| *.py[cod] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| recursive-include examples *.py | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,154 @@ | ||
| # OpenMeter Python SDK (v3 baseline) | ||
|
|
||
| An idiomatic, hand-written Python SDK for the OpenMeter v3 API. This baseline | ||
| covers the same endpoint groups as the Go SDK baseline in PR #4644: meters and | ||
| plan add-ons. It is intentionally not a complete OpenMeter client. | ||
|
|
||
| ## Requirements | ||
|
|
||
| - Python 3.9 or newer | ||
| - Pydantic v2 | ||
| - httpx (async client only, installed through the `async` extra) | ||
|
|
||
| The sync `Client` uses only the Python standard library (`urllib`) for HTTP. | ||
| The async `AsyncClient` uses `httpx.AsyncClient` for true async I/O — no | ||
| thread pool involved. Pydantic is the only required runtime dependency. | ||
|
|
||
| ## Install | ||
|
|
||
| ```bash | ||
| python -m pip install ./sdk/python/openmeter | ||
| ``` | ||
|
|
||
| Install the async client dependencies with: | ||
|
|
||
| ```bash | ||
| python -m pip install "./sdk/python/openmeter[async]" | ||
| ``` | ||
|
|
||
| ## Client setup | ||
|
|
||
| The base URL must include the deployment's v3 prefix: | ||
|
|
||
| | Deployment | Base URL | | ||
| | --- | --- | | ||
| | Local | `http://127.0.0.1:8888/api/v3` | | ||
| | OpenMeter Cloud | `https://openmeter.cloud/api/v3` | | ||
| | Kong Konnect | `https://<region>.api.konghq.com/v3` | | ||
|
|
||
| ```python | ||
| from openmeter import Client | ||
|
|
||
| with Client( | ||
| "https://openmeter.cloud/api/v3", | ||
| token="om_...", | ||
| ) as client: | ||
| page = client.meters.list() | ||
| print(page.data) | ||
| ``` | ||
|
|
||
| The async client has the same resource groups and method names: | ||
|
|
||
| ```python | ||
| import asyncio | ||
|
|
||
| from openmeter import AsyncClient | ||
|
|
||
|
|
||
| async def main() -> None: | ||
| async with AsyncClient( | ||
| "https://openmeter.cloud/api/v3", | ||
| token="om_...", | ||
| ) as client: | ||
| async for meter in client.meters.list_all(): | ||
| print(meter.key) | ||
|
|
||
|
|
||
| asyncio.run(main()) | ||
| ``` | ||
|
|
||
| Complete runnable snippets live in [`examples/`](examples/). Public classes and | ||
| methods include docstrings, so `help(openmeter.Client)` and editor tooltips also | ||
| serve as API documentation. | ||
|
|
||
| ## Pydantic models | ||
|
|
||
| Request models validate v3 constraints before sending a request: | ||
|
|
||
| ```python | ||
| from openmeter import CreateMeterRequest | ||
|
|
||
| request = CreateMeterRequest( | ||
| name="Tokens Total", | ||
| key="tokens_total", | ||
| aggregation="sum", | ||
| event_type="prompt", | ||
| value_property="$.tokens", | ||
| ) | ||
| ``` | ||
|
|
||
| Unknown response fields are ignored to preserve additive API compatibility. | ||
| Response enum-like fields remain plain strings, allowing a newer server value to | ||
| round-trip through an older SDK. Request enum values are validated against the | ||
| current v3 contract. | ||
|
|
||
| ## Implemented endpoints | ||
|
|
||
| | Resource method | HTTP endpoint | | ||
| | --- | --- | | ||
| | `meters.create` / `meters.list` / `meters.list_all` | `POST`, `GET /openmeter/meters` | | ||
| | `meters.get` / `meters.update` / `meters.delete` | `GET`, `PUT`, `DELETE /openmeter/meters/{meterId}` | | ||
| | `meters.query` / `meters.query_csv` / `meters.query_csv_stream` | `POST /openmeter/meters/{meterId}/query` | | ||
| | `plan_addons.create` / `plan_addons.list` / `plan_addons.list_all` | `POST`, `GET /openmeter/plans/{planId}/addons` | | ||
| | `plan_addons.get` / `plan_addons.update` / `plan_addons.delete` | `GET`, `PUT`, `DELETE /openmeter/plans/{planId}/addons/{planAddonId}` | | ||
|
|
||
| `list_all` is a lazy iterator on the sync client and an async iterator on the | ||
| async client. Buffered JSON and CSV bodies are capped at 10 MiB. Use | ||
| `query_csv_stream` for large CSV exports and close it with `with` or `async with`. | ||
| Plan-add-on operations and meter update/query operations are marked unstable in | ||
| the current v3 specification and can evolve before they become stable. | ||
|
|
||
| ## Errors and transport | ||
|
|
||
| Non-2xx responses raise `APIError`, exposing `status_code`, `title`, `detail`, | ||
| `type`, `instance`, parsed invalid parameters, and the capped raw response body. | ||
| Transport failures raise `TransportError`; client-side model failures use | ||
| Pydantic's `ValidationError`. | ||
|
|
||
| The sync client accepts an optional `urllib.request.OpenerDirector` to customize | ||
| proxy, TLS, and authentication behavior without adding an HTTP dependency. The | ||
| async client accepts an optional preconfigured `httpx.AsyncClient` for the same | ||
| purpose. It follows standard proxy environment variables by default; pass | ||
| `trust_env=False` to ignore them. Pass `timeout=None` only when the caller | ||
| supplies another transport-level bound. | ||
|
|
||
| GET, PUT, DELETE, and read-only meter query requests are retried up to twice | ||
| with exponential backoff on connection failures or a 502/503/504 response. | ||
| Resource-creating POST requests are never retried, since a retry could duplicate | ||
| the resource or its notification/webhook side effects. | ||
|
|
||
| ## Development | ||
|
|
||
| The package uses [uv](https://docs.astral.sh/uv/) for the contributor environment | ||
| and lockfile. From `sdk/python/openmeter`, install the development dependencies | ||
| with the supported Python floor: | ||
|
|
||
| ```bash | ||
| uv sync --python 3.9 | ||
| ``` | ||
|
|
||
| Run linting, formatting, type checking, tests, and the package build through the | ||
| locked environment: | ||
|
|
||
| ```bash | ||
| uv run flake8 src tests examples | ||
| uv run ruff check . | ||
| uv run ruff format --check . | ||
| uv run pyright | ||
| uv run python -m unittest discover -s tests -v | ||
| uv build | ||
| ``` | ||
|
|
||
| Tests use `unittest` and a local standard-library HTTP server. Package consumers | ||
| do not need uv and can continue installing the SDK with pip or another Python | ||
| package manager. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| """List meters with the asynchronous v3 client.""" | ||
|
|
||
| import asyncio | ||
| import os | ||
|
|
||
| from openmeter import AsyncClient | ||
|
|
||
|
|
||
| async def main() -> None: | ||
| """Run the asynchronous example using environment-based configuration.""" | ||
|
|
||
| base_url = os.getenv("OPENMETER_BASE_URL", "http://127.0.0.1:8888/api/v3") | ||
| token = os.getenv("OPENMETER_TOKEN") | ||
|
|
||
| async with AsyncClient(base_url, token=token) as client: | ||
| async for meter in client.meters.list_all(): | ||
| print(meter.key, meter.aggregation) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| asyncio.run(main()) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| """List and query meters with the synchronous v3 client.""" | ||
|
|
||
| import os | ||
|
|
||
| from openmeter import Client, MeterQueryRequest | ||
|
|
||
|
|
||
| def main() -> None: | ||
| """Run the synchronous example using environment-based configuration.""" | ||
|
|
||
| base_url = os.getenv("OPENMETER_BASE_URL", "http://127.0.0.1:8888/api/v3") | ||
| token = os.getenv("OPENMETER_TOKEN") | ||
|
|
||
| with Client(base_url, token=token) as client: | ||
| for meter in client.meters.list_all(): | ||
| print(meter.key, meter.aggregation) | ||
|
|
||
| meter_id = os.getenv("OPENMETER_METER_ID") | ||
| if meter_id: | ||
| result = client.meters.query(meter_id, MeterQueryRequest()) | ||
| print(result.data) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,66 @@ | ||
| [build-system] | ||
| requires = ["setuptools>=77"] | ||
| build-backend = "setuptools.build_meta" | ||
|
|
||
| [project] | ||
| name = "openmeter" | ||
| version = "0.1.0" | ||
| description = "Idiomatic Python SDK for the OpenMeter v3 API" | ||
| readme = "README.md" | ||
| requires-python = ">=3.9" | ||
| license = "Apache-2.0" | ||
| authors = [ | ||
| { name = "OpenMeter", email = "info@openmeter.io" }, | ||
| ] | ||
| keywords = ["billing", "metering", "openmeter", "sdk", "usage"] | ||
| classifiers = [ | ||
| "Development Status :: 3 - Alpha", | ||
| "Intended Audience :: Developers", | ||
| "Programming Language :: Python :: 3", | ||
| "Programming Language :: Python :: 3.9", | ||
| "Programming Language :: Python :: 3.10", | ||
| "Programming Language :: Python :: 3.11", | ||
| "Programming Language :: Python :: 3.12", | ||
| "Programming Language :: Python :: 3.13", | ||
| "Programming Language :: Python :: 3.14", | ||
| "Typing :: Typed", | ||
| ] | ||
| dependencies = [ | ||
| "pydantic>=2.10,<3", | ||
| ] | ||
|
|
||
| [project.optional-dependencies] | ||
| async = [ | ||
| "httpx>=0.28.1,<1", | ||
| ] | ||
|
|
||
| [dependency-groups] | ||
| dev = [ | ||
| "build>=1.2,<2", | ||
| "flake8>=7,<8", | ||
| "httpx>=0.28.1,<1", | ||
| "pyright>=1.1.400,<2", | ||
| "ruff>=0.14,<1", | ||
| ] | ||
|
|
||
| [project.urls] | ||
| Documentation = "https://openmeter.io/docs" | ||
| Issues = "https://github.com/openmeterio/openmeter/issues" | ||
| Repository = "https://github.com/openmeterio/openmeter" | ||
|
|
||
| [tool.setuptools.packages.find] | ||
| where = ["src"] | ||
|
|
||
| [tool.ruff] | ||
| target-version = "py39" | ||
| line-length = 100 | ||
|
|
||
| [tool.ruff.lint] | ||
| select = ["E", "F", "I", "UP"] | ||
| # Optional/Union spellings keep annotations unambiguous for the Python 3.9 floor. | ||
| ignore = ["UP006", "UP007", "UP035", "UP045"] | ||
|
|
||
| [tool.pyright] | ||
| include = ["src", "examples"] | ||
| pythonVersion = "3.9" | ||
| typeCheckingMode = "standard" | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,112 @@ | ||
| """OpenMeter Python SDK for the v3 API baseline.""" | ||
|
|
||
| from typing import TYPE_CHECKING, Any | ||
|
|
||
| from ._version import __version__ | ||
| from .client import Client, Meters, PlanAddons | ||
| from .errors import ( | ||
| APIError, | ||
| InvalidIDError, | ||
| OpenMeterError, | ||
| PaginationError, | ||
| ResponseTooLargeError, | ||
| TransportError, | ||
| ) | ||
| from .models import ( | ||
| AddonReference, | ||
| CreateMeterRequest, | ||
| CreatePlanAddonRequest, | ||
| InvalidParameter, | ||
| Meter, | ||
| MeterAggregation, | ||
| MeterFilter, | ||
| MeterListParams, | ||
| MeterPage, | ||
| MeterQueryFilters, | ||
| MeterQueryGranularity, | ||
| MeterQueryRequest, | ||
| MeterQueryResult, | ||
| MeterQueryRow, | ||
| PageMeta, | ||
| PageParams, | ||
| PaginatedMeta, | ||
| PlanAddon, | ||
| PlanAddonListParams, | ||
| PlanAddonPage, | ||
| ProblemDetails, | ||
| ProductCatalogValidationError, | ||
| QueryFilterString, | ||
| QueryFilterStringMapItem, | ||
| StringFilter, | ||
| UpdateMeterRequest, | ||
| UpsertPlanAddonRequest, | ||
| ) | ||
|
|
||
| if TYPE_CHECKING: | ||
| from .aio import AsyncByteStream, AsyncClient | ||
|
|
||
| _ASYNC_EXPORTS = frozenset({"AsyncByteStream", "AsyncClient"}) | ||
|
|
||
|
|
||
| def __getattr__(name: str) -> Any: | ||
| if name not in _ASYNC_EXPORTS: | ||
| raise AttributeError(f"module {__name__!r} has no attribute {name!r}") | ||
|
|
||
| try: | ||
| from .aio import AsyncByteStream, AsyncClient | ||
| except ModuleNotFoundError as error: | ||
| if error.name != "httpx": | ||
| raise | ||
| raise ImportError( | ||
| "async support requires the 'async' extra: pip install 'openmeter[async]'" | ||
| ) from error | ||
|
|
||
| exports = { | ||
| "AsyncByteStream": AsyncByteStream, | ||
| "AsyncClient": AsyncClient, | ||
| } | ||
| globals().update(exports) | ||
| return exports[name] | ||
|
|
||
|
|
||
| __all__ = [ | ||
| "APIError", | ||
| "AddonReference", | ||
| "AsyncByteStream", | ||
| "AsyncClient", | ||
| "Client", | ||
| "CreateMeterRequest", | ||
| "CreatePlanAddonRequest", | ||
| "InvalidIDError", | ||
| "InvalidParameter", | ||
| "Meter", | ||
| "MeterAggregation", | ||
| "MeterFilter", | ||
| "MeterListParams", | ||
| "MeterPage", | ||
| "MeterQueryFilters", | ||
| "MeterQueryGranularity", | ||
| "MeterQueryRequest", | ||
| "MeterQueryResult", | ||
| "MeterQueryRow", | ||
| "Meters", | ||
| "OpenMeterError", | ||
| "PageMeta", | ||
| "PageParams", | ||
| "PaginatedMeta", | ||
| "PaginationError", | ||
| "PlanAddon", | ||
| "PlanAddonListParams", | ||
| "PlanAddonPage", | ||
| "PlanAddons", | ||
| "ProblemDetails", | ||
| "ProductCatalogValidationError", | ||
| "QueryFilterString", | ||
| "QueryFilterStringMapItem", | ||
| "ResponseTooLargeError", | ||
| "StringFilter", | ||
| "TransportError", | ||
| "UpdateMeterRequest", | ||
| "UpsertPlanAddonRequest", | ||
| "__version__", | ||
| ] |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win
Ensure the
py.typedmarker gets bundled in the wheel.Hey! I see we're building a typed SDK (love the
Typing :: Typedclassifier!), but we need to make sure thepy.typedmarker file actually makes it into the installed wheel.setuptoolswon't grab non-Python files automatically unless we explicitly specify them inpackage-data.Let's add that so downstream type checkers know the package is fully typed!
📦 Proposed fix to include the marker file
📝 Committable suggestion
🤖 Prompt for AI Agents