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

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

# Simple chat completion
response = client.create_chat_completion(
    model="openai/gpt-4",
    messages=[
        Message(role="system", content="You are a helpful assistant"),
        Message(role="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/v1")

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

# Using httpx instead of requests
client = InferenceGatewayClient(
    "http://localhost:8080/v1",
    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

response = client.create_chat_completion(
    model="openai/gpt-4",
    messages=[
        Message(role="system", content="You are a helpful assistant"),
        Message(role="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="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="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

# Define a weather tool using type-safe Pydantic models
from inference_gateway.models import ChatCompletionTool, FunctionObject, FunctionParameters

weather_tool = ChatCompletionTool(
    type="function",
    function=FunctionObject(
        name="get_current_weather",
        description="Get the current weather in a given location",
        parameters=FunctionParameters(
            type="object",
            properties={
                "location": {
                    "type": "string",
                    "description": "The city and state, e.g. San Francisco, CA"
                },
                "unit": {
                    "type": "string",
                    "enum": ["celsius", "fahrenheit"],
                    "description": "The temperature unit to use"
                }
            },
            required=["location"]
        )
    )
)

# Using tools in a chat completion
response = client.create_chat_completion(
    model="openai/gpt-4",
    messages=[
        Message(role="system", content="You are a helpful assistant with access to weather information"),
        Message(role="user", content="What is the weather like in New York?")
    ],
    tools=[weather_tool]  # Pass the tool definition
)

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

# Check if the model made a tool call
if response.choices[0].message.tool_calls:
    for tool_call in response.choices[0].message.tool_calls:
        print(f"Tool called: {tool_call.function.name}")
        print(f"Arguments: {tool_call.function.arguments}")

Listing Available MCP Tools

# List available MCP tools (requires MCP_ENABLE and MCP_EXPOSE to be set on the gateway)
tools = client.list_tools()
print("Available tools:", tools)

Server-Side Tool Management

The SDK currently supports listing available MCP tools, which is particularly useful for UI applications that need to display connected tools to users. The key advantage is that tools are managed server-side:

  • Automatic Tool Injection: Tools are automatically inferred and injected into requests by the Inference Gateway server
  • Simplified Client Code: No need to manually manage or configure tools in your client application
  • Transparent Tool Calls: During streaming chat completions with configured MCP servers, tool calls appear in the response stream - no special handling required except optionally displaying them to users

This architecture allows you to focus on LLM interactions while the gateway handles all tool management complexities behind the scenes.

Custom HTTP Configuration

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

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

Examples

For comprehensive examples demonstrating various use cases, see the examples directory:

  • List LLMs - How to list available models
  • Chat - Basic and advanced chat completion examples
  • Tools - Working with function tools
  • MCP - Model Context Protocol integration examples

Each example includes a detailed README with setup instructions and explanations.

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.1.tar.gz (20.0 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.1-py3-none-any.whl (14.4 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: inference_gateway-0.4.1.tar.gz
  • Upload date:
  • Size: 20.0 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.1.tar.gz
Algorithm Hash digest
SHA256 02a1173e5906cdf3c8a0eadffd09b4fe2896648e220261ca0ba51edd002ec45b
MD5 407e82f988318003e473c4385cd4b8f9
BLAKE2b-256 9348bf0a17431fa9a3867571a79d27e1df147e9eac29af82ab343487ce44c1b8

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for inference_gateway-0.4.1-py3-none-any.whl
Algorithm Hash digest
SHA256 205625a2c83c807da635f14853a1addb93df9e092fc8b74b2631389e8e51d91d
MD5 18eed5b54b53a1a8fad1bbc8918cac42
BLAKE2b-256 555670a5565a543b96e6cd4ee0e119059718e212ba9ce377fc82ee902aae53d5

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