Skip to main content

A Python SDK for Inference Gateway

Project description

Inference Gateway Python SDK

A modern Python SDK for interacting with the Inference Gateway, providing a unified interface to multiple AI providers.

Features

  • 🔗 Unified interface for multiple AI providers (OpenAI, Anthropic, Ollama, etc.)
  • 🛡️ Type-safe operations using Pydantic models
  • ⚡ Support for both synchronous and streaming responses
  • 🚨 Built-in error handling and validation
  • 🔄 Proxy requests directly to provider APIs

Quick Start

Installation

pip install inference-gateway

Basic Usage

from inference_gateway import InferenceGatewayClient, Message, MessageRole

# Initialize client
client = InferenceGatewayClient("http://localhost:8080")

# Simple chat completion
response = client.create_chat_completion(
    model="openai/gpt-4",
    messages=[
        Message(role=MessageRole.SYSTEM, content="You are a helpful assistant"),
        Message(role=MessageRole.USER, content="Hello!")
    ]
)

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

Requirements

  • Python 3.8+
  • requests or httpx (for HTTP client)
  • pydantic (for data validation)

Client Configuration

from inference_gateway import InferenceGatewayClient

# Basic configuration
client = InferenceGatewayClient("http://localhost:8080")

# With authentication
client = InferenceGatewayClient(
    "http://localhost:8080",
    token="your-api-token",
    timeout=60.0  # Custom timeout
)

# Using httpx instead of requests
client = InferenceGatewayClient(
    "http://localhost:8080",
    use_httpx=True
)

Core Functionality

Listing Models

# List all available models
models = client.list_models()
print("All models:", models)

# Filter by provider
openai_models = client.list_models(provider="openai")
print("OpenAI models:", openai_models)

Chat Completions

Standard Completion

from inference_gateway import Message, MessageRole

response = client.create_chat_completion(
    model="openai/gpt-4",
    messages=[
        Message(role=MessageRole.SYSTEM, content="You are a helpful assistant"),
        Message(role=MessageRole.USER, content="Explain quantum computing")
    ],
    max_tokens=500
)

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

Streaming Completion

# Using Server-Sent Events (SSE)
for chunk in client.create_chat_completion_stream(
    model="ollama/llama2",
    messages=[
        Message(role=MessageRole.USER, content="Tell me a story")
    ],
    use_sse=True
):
    print(chunk.data, end="", flush=True)

# Using JSON lines
for chunk in client.create_chat_completion_stream(
    model="anthropic/claude-3",
    messages=[
        Message(role=MessageRole.USER, content="Explain AI safety")
    ],
    use_sse=False
):
    print(chunk["choices"][0]["delta"]["content"], end="", flush=True)

Proxy Requests

# Proxy request to OpenAI's API
response = client.proxy_request(
    provider="openai",
    path="/v1/models",
    method="GET"
)

print("OpenAI models:", response)

Health Checking

if client.health_check():
    print("API is healthy")
else:
    print("API is unavailable")

Error Handling

The SDK provides several exception types:

try:
    response = client.create_chat_completion(...)
except InferenceGatewayAPIError as e:
    print(f"API Error: {e} (Status: {e.status_code})")
    print("Response:", e.response_data)
except InferenceGatewayValidationError as e:
    print(f"Validation Error: {e}")
except InferenceGatewayError as e:
    print(f"General Error: {e}")

Advanced Usage

Using Tools

# List available MCP tools works when MCP_ENABLE and MCP_EXPOSE are set on the gateway
tools = client.list_tools()
print("Available tools:", tools)

# Use tools in chat completion works when MCP_ENABLE and MCP_EXPOSE are set to false on the gateway
response = client.create_chat_completion(
    model="openai/gpt-4",
    messages=[...],
    tools=[
        {
            "type": "function",
            "function": {
                "name": "get_current_weather",
                "description": "Get the current weather",
                "parameters": {...}
            }
        }
    ]
)

Custom HTTP Configuration

# With custom headers
client = InferenceGatewayClient(
    "http://localhost:8080",
    headers={"X-Custom-Header": "value"}
)

# With proxy settings
client = InferenceGatewayClient(
    "http://localhost:8080",
    proxies={"http": "http://proxy.example.com"}
)

License

This SDK is distributed under the MIT License, see LICENSE for more information.

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

inference_gateway-0.4.0.tar.gz (18.4 kB view details)

Uploaded Source

Built Distribution

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

inference_gateway-0.4.0-py3-none-any.whl (13.5 kB view details)

Uploaded Python 3

File details

Details for the file inference_gateway-0.4.0.tar.gz.

File metadata

  • Download URL: inference_gateway-0.4.0.tar.gz
  • Upload date:
  • Size: 18.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.10

File hashes

Hashes for inference_gateway-0.4.0.tar.gz
Algorithm Hash digest
SHA256 ca98d2f46298b4e4724974d62fab9ca23b72af236cd0ff9ecb9385ee3686aad7
MD5 bac2b5ba1201aaac0ad99de683ce593d
BLAKE2b-256 632d3ee03511277c1ba62f0475650a82f268066d63637820b53f35ccd4ec3c2d

See more details on using hashes here.

File details

Details for the file inference_gateway-0.4.0-py3-none-any.whl.

File metadata

File hashes

Hashes for inference_gateway-0.4.0-py3-none-any.whl
Algorithm Hash digest
SHA256 d90fe9869c1a4daf7c6e20a40488b555b98a222ea312e75d21c773463628c077
MD5 206fa48be32b6fd9bf0d44296ef11265
BLAKE2b-256 6cdcca8fad65a9cb582c51de260d7dd6a808e7ae925f141fdeaa91148ed1e964

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