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:24mlight A Share investment Agent Unified LLM Gateway

From Leeroopedia
Knowledge Sources
Domains LLM_Infrastructure, API_Design
Last Updated 2026-10-10 14:00 GMT

Overview

A unified gateway pattern that abstracts multiple LLM providers (Gemini, OpenAI-compatible APIs) behind a single get_chat_completion interface with automatic client detection, exponential backoff retry, and OpenAI-format message compatibility.

Description

A unified LLM gateway solves the problem of provider lock-in and configuration complexity by providing a single entry point for all LLM calls. Key features:

  1. Auto-Detection: A LLMClientFactory determines the appropriate client (Gemini or OpenAI-compatible) based on environment variables and parameters. The client_type="auto" mode automatically selects the best available provider.
  1. OpenAI Message Format: All messages use the standard OpenAI format ([{"role": "system", "content": "..."}, {"role": "user", "content": "..."}]), regardless of the underlying provider.
  1. Exponential Backoff Retry: Uses the backoff library with exponential retry on exceptions, with a maximum of 5 retries and 300 seconds max wait time.
  1. Geographic Error Handling: Detects Gemini API geo-restriction errors and provides user-friendly messages suggesting VPN usage.

Usage

Use this principle when:

  • Building systems that need to switch between LLM providers without changing call sites
  • Requiring retry logic for flaky LLM API endpoints
  • Supporting multiple LLM backends (Gemini, OpenAI, self-hosted) through a unified interface

Theoretical Basis

The gateway pattern:

# Abstract pattern (not real implementation)
def get_chat_completion(messages, model=None, client_type="auto"):
    client = LLMClientFactory.create_client(
        client_type=client_type, model=model
    )
    return client.get_completion(
        messages=messages,
        max_retries=3,
        initial_retry_delay=1
    )

Factory pattern:

  • client_type="gemini" → Google Gemini client
  • client_type="openai_compatible" → OpenAI-compatible API
  • client_type="auto" → Auto-detect from environment variables

Message format (OpenAI-compatible):

messages = [
    {"role": "system", "content": "You are a financial analyst..."},
    {"role": "user", "content": "Analyze this stock..."}
]

Related Pages

Implemented By

Uses Heuristics

Page Connections

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