Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Principle:51bitquant Ai hedge fund crypto Multi Provider LLM Abstraction

From Leeroopedia
Knowledge Sources
Domains LLM_Integration, Provider_Abstraction
Last Updated 2026-10-28 14:00 GMT

Overview

An abstraction pattern that exposes multiple LLM backends behind a uniform interface, dispatching by a provider string and caching instances for reuse.

Description

Multi-provider LLM abstraction lets the pipeline swap the underlying model (OpenAI, Groq, OpenRouter, Gemini, Anthropic, Ollama) without changing call sites. A factory function takes a `provider` string, reads provider-specific credentials from environment variables, applies a default base URL, and returns a LangChain chat model instance. `@lru_cache` ensures the client is constructed once per (provider, model, base_url) tuple. An unsupported provider raises immediately.

This addresses vendor lock-in and lets users choose models by cost, latency, or availability (e.g. local Ollama for privacy, Groq for speed, OpenAI for quality) via a single config field.

Usage

Use this pattern whenever the decision-maker's model should be config-selectable. Read the provider/model from `Settings.model`, resolve via the factory, and let the rest of the code use the returned `Runnable` interface uniformly. Set the appropriate API key environment variable per provider.

Theoretical Basis

The factory F maps a config tuple to an instance of a common interface I:

Failed to parse (syntax error): {\displaystyle F: (\text{provider}, \text{model}, \text{base\_url}) \rightarrow I }

with memoization:

F(p,m,u)={cache[(p,m,u)]if existsconstruct(p,m,u)∧cacheotherwise

Dispatch:

construct(p,m,u)=Adapterp(keyp,u∨defaultp,m)

Pseudo-code:

# Abstract pattern
@lru_cache
def get_llm(provider, model, base_url=None):
    adapters = {"openai": ChatOpenAI, "groq": ChatGroq, ...}
    key = env_key[provider]
    url = base_url or default_url[provider]
    return adapters[provider](api_key=key, base_url=url, model=model)

Practical Guide

  • Normalize timeout and retry settings across providers for consistent behavior.
  • Cache instances: constructing a client per bar is wasteful and can hit rate limits.
  • Raise `ValueError` on unknown providers at factory call time (fail fast), not at first invocation.
  • For local providers (Ollama), omit API-key handling and use a localhost default URL.

Related Pages

Implemented By

Uses Heuristic

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment