Skip to main content

VisionAI SDK for Python

Project description

VisionAI SDK for Python

Python client library for VisionAI authentication and Vision Language Model (VLM) inference services.

Features

  • Dual Authentication: Email/password login or OAuth client credentials
  • Auto Token Management: Automatic token refresh before expiration
  • JWT Validation: Built-in token signature and expiration verification
  • VLM Inference: Submit and poll vision-language model tasks
  • Async Support: Full async/await support with AsyncClient
  • Type Safe: Full type hints with Pydantic validation

Installation

pip install visionai-sdk-python

Quick Start

Synchronous Usage

from visionai_sdk_python import Client

# Initialize client
client = Client(
    auth_url="https://auth.visionai.example.com",
    vlm_url="https://vlm.visionai.example.com"
)

# Login with email/password
token = client.login("user@example.com", "your-password")

# Submit VLM inference request
response = client.chat({
    "img": "https://example.com/image.jpg",  # or ["url1", "url2"] for multiple images
    "prompt": "Describe this image",
    "temperature": 0.7,
    "max_tokens": 500
})

print(f"Chat ID: {response.chat_id}")
print(f"Status: {response.status}")

# Poll for results
result = client.get_chat(response.chat_id)
if result.status == "completed":
    print(f"Result: {result.message}")

# Close client when done
client.close()

Asynchronous Usage

import asyncio
from visionai_sdk_python import AsyncClient

async def main():
    async with AsyncClient(
        auth_url="https://auth.visionai.example.com",
        vlm_url="https://vlm.visionai.example.com"
    ) as client:
        # OAuth client credentials flow
        await client.get_access_token(
            client_id="your-client-id",
            client_secret="your-client-secret"
        )

        # Submit inference
        response = await client.chat({
            "img": "https://example.com/image.jpg",
            "prompt": "What objects are in this image?",
            "temperature": 0.2
        })

        # Poll until completed
        while True:
            result = await client.get_chat(response.chat_id)
            if result.status in ("completed", "failed", "timeout"):
                break
            await asyncio.sleep(1)

        if result.status == "completed":
            print(f"Answer: {result.message}")
        else:
            print(f"Error: {result.error}")

asyncio.run(main())

Authentication

Email/Password Login

client = Client(auth_url="...", vlm_url="...")
token = client.login("user@example.com", "password")

OAuth Client Credentials

client = Client(auth_url="...", vlm_url="...")
token = client.get_access_token(
    client_id="your-client-id",
    client_secret="your-client-secret"
)

Tokens are stored internally and automatically refreshed before expiration.

VLM Inference

Submit Chat Request

from visionai_sdk_python.models import NIMRequestModel

# Using dict
response = client.chat({
    "img": "https://example.com/image.jpg",
    "prompt": "Analyze this image",
    "temperature": 0.7,
    "max_tokens": 1000,
    "top_p": 0.9
})

# Using typed model
request = NIMRequestModel(
    img=["https://example.com/img1.jpg", "https://example.com/img2.jpg"],
    prompt="Compare these images",
    temperature=0.5,
    max_tokens=500
)
response = client.chat(request)

Check Result

result = client.get_chat(response.chat_id)

if result.status == "completed":
    print(result.message)
elif result.status in ("failed", "timeout"):
    print(f"Error: {result.error}")

Response Status:

  • pending: Request queued
  • running: Processing
  • completed: Success, check message
  • failed: Error, check error
  • timeout: Request timeout

Token Validation

# Validate any JWT token
is_valid = client.is_token_valid("eyJhbGci...")
if is_valid:
    print("Token is valid")
else:
    print("Token is expired or invalid")

Configuration

client = Client(
    auth_url="https://auth.example.com",
    vlm_url="https://vlm.example.com",
    allowed_issuers=["https://auth.example.com"],  # Optional: restrict token issuers
    verify_ssl=True,                                # SSL verification
    timeout=10.0,                                   # Request timeout in seconds
    max_connections=100,                            # Connection pool size
    max_keepalive_connections=20                    # Keepalive connections
)

Error Handling

from visionai_sdk_python import (
    VisionaiSDKError,
    AuthenticationError,
    NetworkError,
    ClientError,
    ServerError
)

try:
    client.login("user@example.com", "wrong-password")
except AuthenticationError as e:
    print(f"Auth failed: {e}")
except NetworkError as e:
    print(f"Network error: {e}")
except VisionaiSDKError as e:
    print(f"SDK error: {e}")

Exception Hierarchy:

  • VisionaiSDKError: Base exception
    • AuthenticationError: 401 Unauthorized
    • PermissionDeniedError: 403 Forbidden
    • ClientError: 4xx client errors
    • ServerError: 5xx server errors
    • NetworkError: Connection/timeout errors
    • JwksDiscoveryError: OIDC discovery failures

Context Manager Usage

Recommended for automatic resource cleanup:

# Sync
with Client(auth_url="...", vlm_url="...") as client:
    client.login("user@example.com", "password")
    response = client.chat({"img": "...", "prompt": "..."})
# client.close() called automatically

# Async
async with AsyncClient(auth_url="...", vlm_url="...") as client:
    await client.login("user@example.com", "password")
    response = await client.chat({"img": "...", "prompt": "..."})
# client.close() called automatically

Development

Install Dependencies

# Using uv (recommended)
uv sync

# Or with pip
pip install -e ".[dev]"

Run Tests

pytest

Requirements

  • Python >= 3.11
  • httpx >= 0.28.1
  • pydantic >= 2.12.5
  • cryptography >= 46.0.5
  • PyJWT[cryptography] >= 2.8.0

Support

For issues and questions, please open an issue on GitHub.

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

visionai_sdk_python-0.1.0rc3.tar.gz (45.1 kB view details)

Uploaded Source

Built Distribution

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

visionai_sdk_python-0.1.0rc3-py3-none-any.whl (17.1 kB view details)

Uploaded Python 3

File details

Details for the file visionai_sdk_python-0.1.0rc3.tar.gz.

File metadata

  • Download URL: visionai_sdk_python-0.1.0rc3.tar.gz
  • Upload date:
  • Size: 45.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for visionai_sdk_python-0.1.0rc3.tar.gz
Algorithm Hash digest
SHA256 e23b36cde894a0715a884434ba60d66c4a19b6561c2d3abb1df313423bc8ad5a
MD5 75ce3122ac1dbf95865a857f795413ad
BLAKE2b-256 c7cbc0ad63ae9d442b088281b4057154c89c0c502e4a8e53fb3bfce6d9b1ce81

See more details on using hashes here.

File details

Details for the file visionai_sdk_python-0.1.0rc3-py3-none-any.whl.

File metadata

File hashes

Hashes for visionai_sdk_python-0.1.0rc3-py3-none-any.whl
Algorithm Hash digest
SHA256 b9738e64d6f9740b5e06acc1ee3eaa3d7413ae5e1dc7a6f702110f0718863a45
MD5 9220cf1058a87422da4e0d41032dde46
BLAKE2b-256 0b7450832449efe9cd89424f4a22270efb062632fb49ed9f34dc0affb4c4c374

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