Skip to main content

Python SDK for Cluster Protocol — Decentralized AI Inference Gateway

Project description

Cluster Protocol Python SDK

Python SDK for the Cluster Protocol Decentralized AI Inference Gateway. OpenAI-compatible API with typed responses, automatic retries, and async support.

Installation

pip install cluster-sdk

Quick Start

from cluster_sdk import ClusterClient

client = ClusterClient(api_key="cp_your_key_here")

response = client.chat.completions.create(
    model="deepseek-ai/DeepSeek-V3",
    messages=[{"role": "user", "content": "Hello!"}],
)
print(response.choices[0].message.content)

Streaming

stream = client.chat.completions.create(
    model="deepseek-ai/DeepSeek-V3",
    messages=[{"role": "user", "content": "Write a poem"}],
    stream=True,
)
for chunk in stream:
    print(chunk.choices[0].delta.content or "", end="")

Embeddings

result = client.embeddings.create(
    input="The quick brown fox jumps over the lazy dog",
    model="BAAI/bge-large-en-v1.5",
)
print(f"Dimensions: {len(result.data[0].embedding)}")

# Batch embedding
result = client.embeddings.create(
    input=["First sentence", "Second sentence"],
    model="BAAI/bge-large-en-v1.5",
)
for emb in result.data:
    print(f"[{emb.index}] {len(emb.embedding)}d vector")

Dataset Marketplace

# Browse datasets
listing = client.datasets.list(search="sentiment", category="nlp")
for ds in listing.datasets:
    print(f"{ds.name}{ds.pricingType}{ds.downloadCount} downloads")

# Get dataset details
dataset = client.datasets.get("imdb-reviews-v2")
print(f"{dataset.name}: {dataset.description}")

# Purchase a dataset
receipt = client.datasets.purchase(dataset.id)
print(f"Purchase status: {receipt.status}")

# Check access
access = client.datasets.check_access(dataset.id)
print(f"Has access: {access.hasAccess}")

Async Client

import asyncio
from cluster_sdk import AsyncClusterClient

async def main():
    async with AsyncClusterClient(api_key="cp_your_key_here") as client:
        # Chat
        response = await client.chat.completions.create(
            model="deepseek-ai/DeepSeek-V3",
            messages=[{"role": "user", "content": "Hello!"}],
        )
        print(response.choices[0].message.content)

        # Embeddings
        emb = await client.embeddings.create(
            input="Hello world",
            model="BAAI/bge-large-en-v1.5",
        )
        print(f"Embedding dim: {len(emb.data[0].embedding)}")

        # Datasets
        listing = await client.datasets.list(search="finance")
        print(f"Found {listing.pagination.total} datasets")

asyncio.run(main())

Models & Balance

# List models
for model in client.models.list():
    print(f"{model.id}: {model.owned_by}")

# Check balance
balance = client.balance.get()
print(f"${balance.usd:.2f}")

# Usage history
usage = client.usage.get()
print(f"Total cost: ${usage.total_cost:.4f}")

Error Handling

from cluster_sdk import ClusterClient
from cluster_sdk.exceptions import (
    AuthenticationError,
    InsufficientBalanceError,
    RateLimitError,
    ModelNotFoundError,
)

try:
    response = client.chat.completions.create(
        model="deepseek-ai/DeepSeek-V3",
        messages=[{"role": "user", "content": "Hello"}],
    )
except AuthenticationError:
    print("Invalid API key — check your cp_ key")
except InsufficientBalanceError:
    print("Top up your balance at clusterprotocol.ai")
except RateLimitError as e:
    print(f"Rate limited: {e}")  # Auto-retried with Retry-After header
except ModelNotFoundError:
    print("Model not found — check client.models.list()")

Rate-limited (429) and server error (5xx) requests are automatically retried with exponential backoff. The SDK respects the Retry-After header when present.

Configuration

Parameter Env Variable Default
api_key CLUSTER_API_KEY
base_url CLUSTER_BASE_URL https://api.clusterprotocol.ai
timeout 60s
max_retries 3

License

Apache-2.0

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

cluster_sdk-0.1.0.tar.gz (16.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

cluster_sdk-0.1.0-py3-none-any.whl (16.0 kB view details)

Uploaded Python 3

File details

Details for the file cluster_sdk-0.1.0.tar.gz.

File metadata

  • Download URL: cluster_sdk-0.1.0.tar.gz
  • Upload date:
  • Size: 16.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.2

File hashes

Hashes for cluster_sdk-0.1.0.tar.gz
Algorithm Hash digest
SHA256 cdbad34a5b6e51ae2bfe5e4331ed414bdbe0bdf25133de830c55c7a844f47c67
MD5 9fd58ebd84dd8f1ddaa192bc202d81d8
BLAKE2b-256 43a198e4bd09c3f795831c05088fdfcd66ec1a98cfc914f359041f25e4d38aeb

See more details on using hashes here.

File details

Details for the file cluster_sdk-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: cluster_sdk-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 16.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.2

File hashes

Hashes for cluster_sdk-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 41d167c65c0213b3d51e013f5ac4452e8c0b7c7a457caae3054836de94767343
MD5 6f1d76c24fa36407408c4df8d9bcd266
BLAKE2b-256 3c3fdae21cd6f3839a454e63eccc7a39402d462c6174a136a10f2347847b8278

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page