Skip to main content

BestAI Router

A flexible Python library for routing between different LLM models based on various criteria like cost, capabilities, and performance.

Features

  • Route requests between different LLM models based on:
    • Cost efficiency
    • Model capabilities
    • Performance (custom strategies can be implemented)
  • Support for multiple LLM providers:
    • OpenAI
    • Anthropic
    • Easily extendable to other providers
  • Simple client API for unified access to different models
  • Configurable routing strategies

Installation

pip install bestai

Or install from source:

git clone https://github.com/yourusername/bestairouter.git
cd bestairouter
pip install -e .

Quick Start

Environment Setup

First, set up your API keys in your environment:

export OPENAI_API_KEY=your_openai_api_key
export ANTHROPIC_API_KEY=your_anthropic_api_key

Alternatively, you can create a .env file in your project root:

OPENAI_API_KEY=your_openai_api_key
ANTHROPIC_API_KEY=your_anthropic_api_key

Basic Usage

Here's a simple example of using the router with a capability-based strategy:

from bestai.router import CapabilityBasedRoutingStrategy, ModelProvider, ModelRouter
from bestai.client import RoutedLLMClient, OpenAIClient, AnthropicClient

# Define models and their capabilities
models = {
    "gpt-3.5-turbo": {
        "provider": ModelProvider.OPENAI,
        "capabilities": ["text_generation", "summarization"],
    },
    "gpt-4": {
        "provider": ModelProvider.OPENAI,
        "capabilities": ["text_generation", "summarization", "code_generation", "reasoning"],
    },
    "claude-2": {
        "provider": ModelProvider.ANTHROPIC,
        "capabilities": ["text_generation", "summarization", "code_generation"],
    },
}

# Extract capabilities for the routing strategy
model_capabilities = {
    model_id: config["capabilities"]
    for model_id, config in models.items()
}

# Create the routing strategy
strategy = CapabilityBasedRoutingStrategy(model_capabilities, default_model="gpt-3.5-turbo")

# Create the router
router = ModelRouter(models, strategy, default_model="gpt-3.5-turbo")

# Create clients for each model
clients = {
    "gpt-3.5-turbo": OpenAIClient(model="gpt-3.5-turbo"),
    "gpt-4": OpenAIClient(model="gpt-4"),
    "claude-2": AnthropicClient(model="claude-2"),
}

# Create the routed client
routed_client = RoutedLLMClient(router, clients)

# Generate a response
response = routed_client.generate("Write a Python function to calculate the Fibonacci sequence.")
print(response)

Advanced Usage

Cost-Based Routing

Use the cost-based strategy to optimize for cost efficiency:

from bestai.router import CostBasedRoutingStrategy, ModelRouter

# Define model costs
model_costs = {
    "gpt-3.5-turbo": 0.002,  # per 1K tokens
    "gpt-4": 0.05,
    "claude-2": 0.03,
}

# Create the strategy
strategy = CostBasedRoutingStrategy(model_costs, default_model="gpt-3.5-turbo")

# Create the router
router = ModelRouter(models, strategy, default_model="gpt-3.5-turbo")

Custom Routing Strategy

You can implement your own routing strategy by subclassing RoutingStrategy:

from bestai.router import RoutingStrategy
from typing import Dict, Optional, Any

class PerformanceBasedStrategy(RoutingStrategy):
    def __init__(self, model_performances: Dict[str, float], default_model: str):
        self.model_performances = model_performances
        self.default_model = default_model
    
    def select_model(self, input_text: str, context: Optional[Dict[str, Any]] = None) -> str:
        # Implement your custom routing logic here
        return self.default_model

Examples

Check out the examples directory for more complete examples.

License

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

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Download files

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

Source Distribution

bestai-0.1.0.tar.gz (9.6 kB view details)

Uploaded Source

Built Distribution

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

bestai-0.1.0-py3-none-any.whl (9.2 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: bestai-0.1.0.tar.gz
  • Upload date:
  • Size: 9.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.2

File hashes

Hashes for bestai-0.1.0.tar.gz
Algorithm Hash digest
SHA256 f8f003e77683d09d29191a4e7a1c901d6158b50088979287042c4c68eefeb56f
MD5 d0ed387722b67069ad0c85263f9c0cfe
BLAKE2b-256 2c615d7f4f2d7397d2ed690f8914deb6b96359dc86a74c3f174067a34cec5d41

See more details on using hashes here.

File details

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

File metadata

  • Download URL: bestai-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 9.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.2

File hashes

Hashes for bestai-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 ee18975931dd17a279005f1dec8fa05f86a1fa5587fc620741fca9f8664ab77f
MD5 9f4039b2c5caf9286239df367e409eda
BLAKE2b-256 0dbdd6db2c8089de1fe5562c74c926584151176c75a3b0c8e2f95db259596bed

See more details on using hashes here.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 files

Supported by

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