Skip to main content

A unified client for various AI providers

Project description

IndoxRouter Client

A unified client for various AI providers, including OpenAI, anthropic, Google, and Mistral.

Features

  • Unified API: Access multiple AI providers through a single API
  • Simple Interface: Easy-to-use methods for chat, completion, embeddings, and image generation
  • Error Handling: Standardized error handling across providers
  • Authentication: Secure cookie-based authentication

Installation

pip install indoxrouter

Usage

Initialization

from indoxrouter import Client

# Initialize with API key
client = Client(api_key="your_api_key")

# Using environment variables
# Set INDOX_ROUTER_API_KEY environment variable
import os
os.environ["INDOX_ROUTER_API_KEY"] = "your_api_key"
client = Client()

# Connect to a custom server
client = Client(
    api_key="your_api_key",
    base_url="https://your-indoxrouter-server.com"
)

Authentication

IndoxRouter uses cookie-based authentication with JWT tokens. The client handles this automatically by:

  1. Taking your API key and exchanging it for JWT tokens using the server's authentication endpoints
  2. Storing the JWT tokens in cookies
  3. Using the cookies for subsequent requests
  4. Automatically refreshing tokens when they expire
# Authentication is handled automatically when creating the client
client = Client(api_key="your_api_key")

Testing Your API Key

The package includes a test script to verify your API key and connection:

# Run the test script with your API key
python -m indoxrouter.test_api_key --api-key YOUR_API_KEY

# Or set the environment variable and run
export INDOX_ROUTER_API_KEY=YOUR_API_KEY
python -m indoxrouter.test_api_key

# To see detailed debugging information
python -m indoxrouter.test_api_key --debug

Chat Completions

response = client.chat(
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Tell me a joke."}
    ],
    model="openai/gpt-4o-mini",  # Provider/model format
    temperature=0.7
)

print(response["choices"][0]["message"]["content"])

Text Completions

response = client.completion(
    prompt="Once upon a time,",
    model="openai/gpt-4o-mini",
    max_tokens=100
)

print(response["choices"][0]["text"])

Embeddings

response = client.embeddings(
    text=["Hello world", "AI is amazing"],
    model="openai/text-embedding-3-small"
)

print(f"Dimensions: {len(response['data'][0]['embedding'])}")
print(f"First embedding: {response['data'][0]['embedding'][:5]}...")

Image Generation

# OpenAI Image Generation
response = client.images(
    prompt="A serene landscape with mountains and a lake",
    model="openai/dall-e-3",
    size="1024x1024",
    quality="standard",  # Options: standard, hd
    style="vivid"  # Options: vivid, natural
)

print(f"Image URL: {response['data'][0]['url']}")

# Google Imagen Image Generation
from indoxrouter.constants import GOOGLE_IMAGE_MODEL

response = client.images(
    prompt="A robot holding a red skateboard in a futuristic city",
    model=GOOGLE_IMAGE_MODEL,
    n=2,  # Generate 2 images
    negative_prompt="broken, damaged, low quality",
    guidance_scale=7.5,  # Control adherence to prompt
    seed=42,  # For reproducible results
)

# xAI Grok Image Generation
from indoxrouter.constants import XAI_IMAGE_MODEL

response = client.images(
    prompt="A cat in a tree",
    model=XAI_IMAGE_MODEL,
    n=1,
    response_format="b64_json"  # Get base64 encoded image
)

# Access base64 encoded image data
if "b64_json" in response["data"][0]:
    b64_data = response["data"][0]["b64_json"]
    # Use the base64 data (e.g., to display in HTML or save to file)

Streaming Responses

for chunk in client.chat(
    messages=[{"role": "user", "content": "Write a short story."}],
    model="openai/gpt-4o-mini",
    stream=True
):
    if chunk.get("choices") and len(chunk["choices"]) > 0:
        content = chunk["choices"][0].get("delta", {}).get("content", "")
        print(content, end="", flush=True)

Getting Available Models

# Get all providers and models
providers = client.models()
for provider in providers:
    print(f"Provider: {provider['name']}")
    for model in provider["models"]:
        print(f"  - {model['id']}: {model['description'] or ''}")

# Get models for a specific provider
openai_provider = client.models("openai")
print(f"OpenAI models: {[m['id'] for m in openai_provider['models']]}")

Error Handling

from indoxrouter import Client, ModelNotFoundError, ProviderError

try:
    client = Client(api_key="your_api_key")
    response = client.chat(
        messages=[{"role": "user", "content": "Hello"}],
        model="nonexistent-provider/nonexistent-model"
    )
except ModelNotFoundError as e:
    print(f"Model not found: {e}")
except ProviderError as e:
    print(f"Provider error: {e}")

Context Manager

with Client(api_key="your_api_key") as client:
    response = client.chat(
        messages=[{"role": "user", "content": "Hello!"}],
        model="openai/gpt-4o-mini"
    )
    print(response["choices"][0]["message"]["content"])
# Client is automatically closed when exiting the block

License

This project is licensed under the MIT License - see the LICENSE file for details.

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

indoxrouter-0.1.19.tar.gz (30.3 kB view details)

Uploaded Source

Built Distribution

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

indoxrouter-0.1.19-py3-none-any.whl (14.2 kB view details)

Uploaded Python 3

File details

Details for the file indoxrouter-0.1.19.tar.gz.

File metadata

  • Download URL: indoxrouter-0.1.19.tar.gz
  • Upload date:
  • Size: 30.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.3

File hashes

Hashes for indoxrouter-0.1.19.tar.gz
Algorithm Hash digest
SHA256 e1fdd8b87d1662928668b1c6d07299b95eb548b6102f9b289f35e8d162616ced
MD5 c9b5647e67deb88a366522ffa6d3a470
BLAKE2b-256 601ca5d4dfc77b966ff4cd56876fb5519d788e389fc7419671420fc4bc56c9aa

See more details on using hashes here.

File details

Details for the file indoxrouter-0.1.19-py3-none-any.whl.

File metadata

  • Download URL: indoxrouter-0.1.19-py3-none-any.whl
  • Upload date:
  • Size: 14.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.3

File hashes

Hashes for indoxrouter-0.1.19-py3-none-any.whl
Algorithm Hash digest
SHA256 7f199542b9aa74ba30d56371ac1074ebfa257819f2ef2f685081db93cb0c2d08
MD5 1cf3fa9e985571a4a1438734988360a6
BLAKE2b-256 1b076d4cdfc28f724a49a21629aab03315207b52f27e9adb438e7f285a31d50e

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