Skip to main content

A custom Python SDK for interacting with AI models, compatible with OpenAI's API format

Project description

AI SDK Python

A comprehensive Python SDK for interacting with AI models, compatible with OpenAI's API format and supporting multiple providers.

Features

  • 🤖 Multiple Provider Support: OpenAI, LiteLLM, and VLLM providers
  • 🔄 Streaming Support: Real-time streaming responses with event handling
  • 🛡️ Error Handling: Comprehensive error handling with custom exceptions
  • 🔧 Flexible Configuration: Environment variables, config files, and programmatic setup
  • 📦 Easy Integration: Simple, intuitive API design
  • 🎯 Type Safety: Full type hints support

Installation

pip install ai-sdk

For development:

pip install ai-sdk[dev]

Quick Start

Basic Usage

from ai_sdk import AISDKClient

# Initialize client
client = AISDKClient(
    api_key="your-api-key",
    provider="openai"  # or "vllm", "litellm"
)

# Create chat completion
response = client.chat().create(
    model="gpt-3.5-turbo",
    messages=[
        {"role": "user", "content": "Hello, world!"}
    ]
)

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

Streaming

# Stream responses in real-time
response = client.chat().create(
    model="gpt-3.5-turbo",
    messages=[{"role": "user", "content": "Tell me a story"}],
    stream=True
)

for chunk in response:
    if chunk['choices'][0]['delta'].get('content'):
        print(chunk['choices'][0]['delta']['content'], end='', flush=True)

Provider-Specific Examples

VLLM Provider with New Format

client = AISDKClient(provider="vllm", api_key="your-key")

# New format supports complex user content objects
response = client.chat().create(
    system_prompt="You are a helpful AI assistant",
    messages=[
        {
            "role": "user",
            "content": {
                "query": "What is Python?",
                "detail_level": "intermediate",
                "include_examples": True
            }
        }
    ],
    model="model_name"
)

Configuration

Environment Variables

export AI_SDK_API_KEY="your-api-key"
export AI_SDK_BASE_URL="https://api.openai.com/v1"
export AI_SDK_TIMEOUT="30.0"

Builder Pattern

client = (AISDKClient.builder()
           .with_provider("vllm")
           .with_api_key("your-key")
           .with_base_url("https://your-vllm-endpoint")
           .with_timeout(60.0)
           .build())

Providers

OpenAI Provider

  • Base URL: https://api.openai.com/v1
  • Models: GPT-3.5, GPT-4, and all OpenAI models
  • Features: Chat, completions, embeddings

VLLM Provider

  • Custom Endpoints: Supports any VLLM deployment
  • New Format: Enhanced message format with complex user content
  • Streaming: Optimized real-time streaming

LiteLLM Provider

  • Unified Interface: Access 100+ models through LiteLLM
  • Model Support: OpenAI, Anthropic, Cohere, and more
  • Fallback: Automatic fallback between providers

API Reference

Client

  • AISDKClient() - Main client class
  • chat() - Access chat completions
  • completions() - Access text completions
  • embeddings() - Access embeddings

Chat Completions

  • create() - Create chat completion or stream
  • Parameters: messages, model, temperature, stream, etc.

Error Handling

from ai_sdk.exceptions import (
    AISDKException,
    APIException,
    AuthenticationException,
    RateLimitException
)

try:
    response = client.chat().create(...)
except AuthenticationException:
    print("Invalid API key")
except RateLimitException:
    print("Rate limit exceeded")
except AISDKException as e:
    print(f"SDK Error: {e}")

Development

Setup

git clone https://github.com/Dhruv1969Karnwal/ai-sdk-python
cd ai-sdk-python
pip install -e ".[dev]"

Running Tests

pytest

Code Formatting

black ai_sdk
flake8 ai_sdk
mypy ai_sdk

Examples

See the examples/ directory for comprehensive usage examples:

  • new_format_example.py - VLLM new format examples
  • debug_streaming.py - Streaming debug examples
  • test_clean_streaming.py - Clean streaming tests

Requirements

  • Python 3.7+
  • httpx>=0.23.0
  • typing_extensions>=3.7.4 (Python < 3.8)

Optional Dependencies

  • litellm>=1.0.0 (for LiteLLM provider)

License

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

Support

Contributing

Contributions are welcome! Please see our Contributing Guide for details.

Changelog

See CHANGELOG.md for version history.

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

nexgen_sdk-0.1.0.tar.gz (25.9 kB view details)

Uploaded Source

Built Distribution

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

nexgen_sdk-0.1.0-py3-none-any.whl (29.9 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for nexgen_sdk-0.1.0.tar.gz
Algorithm Hash digest
SHA256 7acd941cf73a1cea7c78c252e4d0e8f5caa0c05bec69f0d16fa9838398848aef
MD5 4bdace6af40b7a47ca51a04677b42caf
BLAKE2b-256 e3e7caaa554d51d16a74d7ed42471507dc58104d43e55614b85ae5eb1a3926fd

See more details on using hashes here.

File details

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

File metadata

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

File hashes

Hashes for nexgen_sdk-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 4807649a4e1f4ffc5efcbdcabf059984f97240a26ecc850d33c83d1547c64bcb
MD5 94a6d38e03adc928132133c797ff8936
BLAKE2b-256 afb478579f4e4c70010bb60a7b0d99800b6f843d22957cc0b71acc0bed07e50c

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