Skip to main content

vlunaai

Official async Python SDK for VlunaAI Billing and Usage Gate APIs.

The SDK bundles:

  • A shared async HTTP client (httpx) with retries + idempotency keys
  • Authentication helpers (Service Key signing, Bearer token via context)
  • Generated Pydantic v2 models

Documentation:

  • https://docs.vluna.ai/docs/adapters/sdk

Installation

pip install vlunaai

Requires Python >= 3.8.

Package contents

  • Async service client for server-to-server (/mgt/v1) APIs
  • Async bearer client for end-user (/api/v1) APIs
  • Service Key authentication helpers
  • Generated Pydantic v2 models and typed request/response surfaces

Quickstart (Service Key, server-to-server)

Configure Service Key auth (S2S):

  • If you use Vluna Cloud (hosted), get these values from the dashboard.
  • If you self-host, provision them using your Vluna deployment and service-key setup flow.

Set them in the environment where you run your sdk integration:

export VLUNA_REALM_ID='...'
export VLUNA_SERVICE_KEY_ID='pk-...'
export VLUNA_SERVICE_KEY_SECRET='...'

Use ServiceClient for service-to-service calls to the management surface (/mgt/v1).

import asyncio
import os

from vlunaai import (
  VlunaAIConfig,
  RequestContext,
  ServiceClientOptions,
  ServiceKeyCredentials,
  create_service_client,
)


def env(name: str) -> str:
  value = os.environ.get(name)
  if not value:
    raise RuntimeError(f'Missing environment variable: {name}')
  return value


async def main() -> None:
  service_base_url = os.environ.get('VLUNA_SERVICE_BASE_URL', 'https://us-central1.api.vluna.ai/mgt/v1')
  realm_id = env('VLUNA_REALM_ID')
  principal_id = YOUR_PRINCIPAL_ID  # your customer's organization/team/workspace id
  user_id = YOUR_USER_ID

  client = create_service_client(
    ServiceClientOptions(
      config=VlunaAIConfig(
        base_url=service_base_url,
        realm_id=realm_id,
      ),
      service_key=ServiceKeyCredentials(
        key_id=env('VLUNA_SERVICE_KEY_ID'),
        secret=env('VLUNA_SERVICE_KEY_SECRET'),  # base64-encoded secret
      ),
    )
  )
  try:
    ctx = RequestContext(principal_id=principal_id, user_id=user_id)
    feature_code = 'openai.gpt-4o'

    # 1) authorize: ask Vluna for a lease before performing work
    authz = await client.gate_authorize(body={'feature_code': feature_code, 'feature_family_code': 'llm.standard'}, context=ctx)
    if not authz.data:
      raise RuntimeError('gate_authorize returned no data')
    lease = authz.data.lease

    # ...perform the protected work...

    # 2) commit: report usage once the work completes
    commit = await client.gate_commit(
      body={'lease': lease, 'feature_code': feature_code, 'quantity_minor': '12345'},
      context=ctx,
    )
    print(commit.model_dump())

    # 3) billing helpers
    balance = await client.get_credit_balance(context=ctx)
    print(balance.model_dump())

    # 4) token issuance: your backend can return this access_token to your frontend/mobile app for bearer-auth calls.
    token_envelope = await client.issue_platform_token(
      body={
        'principal_id': principal_id,
        'user_id': user_id,
        'scopes': ['checkout', 'portal'],
        'session_ttl_sec': 900,
      },
      context=ctx,
    )
    if not token_envelope.data:
      raise RuntimeError('issue_platform_token returned no data')
    access_token = token_envelope.data.access_token
    print(access_token)

  finally:
    await client.close()


asyncio.run(main())

Preflight result mode

ServiceClientOptions.error_mode defaults to result. In this mode, gate_preflight() returns either GatePreflightSuccess or GatePreflightError; declared admission denials are typed results rather than integration exceptions.

from vlunaai import GatePreflightError

result = await client.gate_preflight(
  body={'feature_code': 'openai.gpt-4o'},
  context=RequestContext(principal_id=principal_id, user_id=user_id),
)

if isinstance(result, GatePreflightError):
  print(result.status, result.code, result.hints, result.meta, result.trace_id)
else:
  print(result.status, result.data.as_of)

Set error_mode='raise' to receive VlunaAIError for non-2xx responses. A 200 preflight response is always validated strictly and must contain valid data.

Quickstart (Bearer token, end-user calls)

Use BearerClient for user/bearer-auth calls to the public surface (/api/v1).

In a typical setup, your frontend/mobile app fetches an platform access token from your backend (issued via the S2S flow above), then uses it as a bearer token for end-user calls.

import asyncio
import os

from vlunaai import (
  VlunaAIConfig,
  BearerClientOptions,
  RequestContext,
  create_bearer_client,
)


def env(name: str) -> str:
  value = os.environ.get(name)
  if not value:
    raise RuntimeError(f'Missing environment variable: {name}')
  return value


async def main() -> None:
  bearer_base_url = os.environ.get('VLUNA_BEARER_BASE_URL', 'https://us-central1.api.vluna.ai/api/v1')
  realm_id = env('VLUNA_REALM_ID')
  access_token = env('VLUNA_ACCESS_TOKEN')  # obtain from your backend (see ServiceClient.issue_platform_token)

  client = create_bearer_client(
    BearerClientOptions(
      config=VlunaAIConfig(
        base_url=bearer_base_url,
        realm_id=realm_id,
      )
    )
  )
  try:
    ctx = RequestContext(access_token=access_token)
    products = await client.list_catalog_products(context=ctx)
    print(products)

    billing_state = await client.get_current_billing_state(context=ctx)
    wallet = billing_state.data.wallet_balance
    print(wallet.available_balance.xusd if wallet else None)
  finally:
    await client.close()


asyncio.run(main())

Current Billing State includes a compact wallet summary for user-scoped views; account-scoped views return wallet_balance=None. Call the full Wallet API only when grant composition or conversion diagnostics are needed. Generated Pydantic models validate known fields and preserve unknown fields for additive API changes.

Key concepts

realm_id

  • Required in VlunaAIConfig.
  • Identifies the Realm (business project) and is sent as X-Realm-Id on every request.

billing_account_id

  • Payor/account-scoped endpoints may use billing_account_id (sent as X-Billing-Account-Id) or principal_id.
  • Runtime metering and gate endpoints should not use billing_account_id as the user subject.

principal_id

  • Your business identifier for the payor account (for example org_id, team_id, or workspace_id).
  • For service-key runtime calls, pass it with user_id via RequestContext(principal_id=..., user_id=...).

user_id

  • Your business identifier for the runtime user inside the billing account.
  • Required with principal_id for service-key gate, wallet, budget, and event calls.

More details:

  • https://docs.vluna.ai/docs/adapters/sdk

Metadata

Release files for vlunaai 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for vlunaai 0.3.0
File Size Uploaded Provenance
vlunaai-0.3.0.tar.gz 93.1 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for vlunaai 0.3.0
File Interpreter ABI Platform
vlunaai-0.3.0-py3-none-any.whl Python 3 none any Details

Total release size: 139.8 kB

Release files / vlunaai-0.3.0.tar.gz

Download URL vlunaai-0.3.0.tar.gz
Size 93.1 kB
Tags Source
SHA-256 checksum
How to use checksums
f5c3336410ac86e23d47bb7decdcbbb68868aea5d37640a07e7da4023d3bca5a
BLAKE2b-256 checksum
How to use checksums
083722e0eadaebe9f74f749b731336f3941ab6f655b22d379888cba4f06b10c3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.6

Release files / vlunaai-0.3.0-py3-none-any.whl

Download URL vlunaai-0.3.0-py3-none-any.whl
Size 46.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
558d8d48ccfaf4b93bdc5b22a4bd88d8e7808e2b6a6655a396868cae6688f436
BLAKE2b-256 checksum
How to use checksums
e463a3e759d8e13f33d34fbc6480d4014f74aeefa99d9e3fc0ea7b146d6c9cf7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.6

Security for vlunaai 0.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page