Menu

One LLM Gateway for Several Providers in FastAPI: Routing, Retries and Cost Tracking
📰

One LLM Gateway for Several Providers in FastAPI: Routing, Retries and Cost Tracking

DEV Community: fastapi·BoilerShelf·12 days ago
#Quqp6HEe
#devtofastapi#devto#dev#provider#usage
Long article (1476 words) — no AI summary yet.
Reading 0:00
15s threshold

Short answer: An LLM gateway gives FastAPI features one way to request a model by role. The gateway maps the role to an approved model, keeps the request within a deadline, and records the attempts and usage. Keep provider-specific prompts, response fields and error mappings inside adapters so the rest of the application can work with your own types.

How do you design one interface for several LLM providers?

Define the shape once, in your own types, so no provider's response object leaks into the rest of the code.

from dataclasses import dataclass from typing import AsyncIterator , Protocol

@dataclass class Usage : input_tokens : int output_tokens : int

@dataclass class Completion : text : str model : str usage : Usage

class Provider ( Protocol ) : async def complete ( self , model : str , messages : list [ dict ] , ** opts ) -> Completion : . . . def stream ( self , model : str , messages : list [ dict ] , ** opts ) -> AsyncIterator [ str ] : . .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.