Skip to main content

A unified Python connector for multiple LLM providers with YAML-driven configuration.

Project description

LLM Connector

A clean, modular Python connector providing a unified interface for various Large Language Model (LLM) providers, including OpenRouter, OpenAI, Anthropic, Google (Gemini), Groq, and local instances like llama.cpp and Ollama.

Features

  • Multiple Providers: Connect natively to OpenRouter, Google, OpenAI, Anthropic, Groq, local llama.cpp, and Ollama.
  • YAML Configuration: Manage all URLs, timeouts, retry logic, logging structures, and default models strictly through transparent YAML files (llm.yaml, security.yaml, logs.yaml).
  • Secure Overrides: Inject local offline IPs and enterprise pricing seamlessly via a .gitignore restricted override.yaml and keep API keys strictly in .env.
  • Resilient Connections: Features internal connection pooling, exponential backoff logic (for Rate Limits & 50x errors), and dynamically tracks OpenRouter internet pricing.
  • Dynamic Client Loading: Adapters load their heavy SDKs exclusively on-demand.

Installation

  1. Clone the repository:

    git clone https://github.com/isbogdanov/llm_connector.git
    cd llm_connector
    
  2. Install dependencies:

    pip install -r requirements.txt
    

Configuration

The architecture has been completely decoupled from heavy Python config files into a robust YAML system:

  1. API Keys (.env): Copy the environment template and insert your secret keys.

    cp .env.template .env
    

    API keys should exclusively live in .env and never be committed.

  2. Local Environment Overrides (conf/override.yaml): If you are running local inference servers (like Ollama or LLaMA.cpp), or if you want to hardcode specific contract prices, create an override file:

    cp conf/override.yaml.template conf/override.yaml
    

    This file is safely untracked by Git, meaning your local IP addresses won't leak into the remote repository.

  3. Base System Configuration (conf/llm.yaml, conf/logs.yaml, conf/security.yaml): These files define the core tracked architecture. You can tune defaults like default_provider, log rotation limits, and API retry backoff-factors directly inside them.

Usage

Import the chat_completion function from the connector.

from connector.connector import chat_completion

# Example messages
messages = [
    {"role": "system", "content": "You are a highly capable AI assistant."},
    {"role": "user", "content": "Explain the importance of context windows in LLMs."},
]

# 1. Using the default provider & model (defined in llm.yaml)
response, p_t, c_t, t_t, latency = chat_completion(messages)
print(f"Default Response: {response}")

# 2. Specifying a specific provider and native model
response_openrouter, _, _, _, _ = chat_completion(
    messages,
    provider=("openrouter", "anthropic/claude-3.5-sonnet"),
    temperature=0.5,
)

# 3. Hitting a local offline model
response_local, _, _, _, _ = chat_completion(
    messages,
    provider=("ollama", "llama3.1:8b"),
)

Creating Custom Adapters

This package is designed to be infinitely extensible. To add a brand-new API provider, follow these 3 steps:

  1. Create the Adapter Class: Add a new file in connector/adapters/ (e.g., my_adapter.py). It must inherit from AdapterBase and strictly implement the core chat_completion signature:

    from .adapter import AdapterBase
    
    class MyCustomAdapter(AdapterBase):
        def chat_completion(self, messages, model, temperature, max_tokens, top_p, **kwargs):
            # 1. Initialize your specific SDK client here
            # 2. Translate the generic 'messages' array into your provider's requested format
            # 3. Await the response
            # 4. Extract token usage and latency
            
            return response_text, prompt_tokens, completion_tokens, total_tokens, latency
    
  2. Export the Adapter: Expose your new adapter class inside connector/adapters/__init__.py:

    from .my_adapter import MyCustomAdapter
    __all__ = [..., "MyCustomAdapter"]
    
  3. Register it in the Router: Add your provider string internally into the get_adapter network factory inside connector/connector.py:

    elif provider_name == "my-custom-api":
        _adapters[provider_name] = MyCustomAdapter()
    

Testing

The testing suite natively utilizes pytest to rigidly guarantee the dynamic YAML hierarchy maps flawlessly to the internal routing logic without triggering infinite fallback loops.

To execute the entire engine diagnostic comprehensively, run:

pytest tests/

The local suite actively asserts:

  1. Integration Verification: Dynamically attempts to route offline dummy prompts safely through OpenRouter, OpenAI, Anthropic, Google, Groq, and your local/Ollama networking blocks.
  2. Security Validation: Explicitly deconstructs the requests.Session() engine upon boot and validates your exact security.yaml limits (Connection Pools, HTTP Max Retries, and network backoff_factors) are clamped physically to the memory pipeline.
  3. Adapter Isolation: Prevents SDK crosstalk by verifying requests generated for "groq" cannot accidentally bleed over or trigger "local" internal logic modules.

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

llm_connector-1.0.0.tar.gz (27.2 kB view details)

Uploaded Source

Built Distribution

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

llm_connector-1.0.0-py3-none-any.whl (36.8 kB view details)

Uploaded Python 3

File details

Details for the file llm_connector-1.0.0.tar.gz.

File metadata

  • Download URL: llm_connector-1.0.0.tar.gz
  • Upload date:
  • Size: 27.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.7

File hashes

Hashes for llm_connector-1.0.0.tar.gz
Algorithm Hash digest
SHA256 2901afe486690ffd6c90ba617530808c936d70bfbcd4439e9aafec594c2b7d99
MD5 507df105ea8355ae5b49b09e48fda47e
BLAKE2b-256 e54387fec7ce4d0090356ddf0b79289fb63fd24536e0d621377fe33eef255327

See more details on using hashes here.

File details

Details for the file llm_connector-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: llm_connector-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 36.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.7

File hashes

Hashes for llm_connector-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f9e5047c0cec9ebfd8068999886ddfab873b6844e9b59ced54c8ecb4ecddcc3c
MD5 de7a77f7f90ef7faaf9cf34ae05da44b
BLAKE2b-256 f7091d466a9a8b20745a61a9331091f1c8f450ccc94e218547e9725e9cdf3c62

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