Sider.ai
  • Chat
  • Wisebase
  • Utensili
  • Estensione
  • Clienti
  • Prezzi
Scarica ora
Login

Impara più velocemente, pensa più profondamente e cresci in modo più intelligente con Sider.

Prodotti
App
  • Estensioni
  • iOS
  • Android
  • Mac OS
  • Windows
Wisebase
  • Wisebase
  • Deep Research
  • Scholar Research
  • Math Solver
  • Rec NoteNew
  • Audio To Text
  • Gamified Learning
  • Interactive Reading
  • ChatPDF
Strumenti
  • Creatore di Siti WebNew
  • AI SlidesNew
  • Scrittore di saggi AI
  • Nano Banana Pro
  • Nano Banana Infographic
  • Generatore di immagini AI
  • Generatore di Brainrot Italiano
  • Rimuovi sfondo
  • Cambia sfondo
  • Cancellatore di foto
  • Rimuovi testo
  • Ritocca
  • Ingranditore di immagini
  • Crea
  • Traduttore AI
  • Traduttore di immagini
  • Traduttore PDF
Sider
  • Contattaci
  • Centro assistenza
  • Scarica
  • Prezzi
  • Piano Educativo
  • Novità
  • Blog
  • Comunità
  • Partner
  • Affiliazione
  • Invita
©2026 Tutti i diritti riservati
Termini di utilizzo
Informativa sulla privacy
  • Pagina iniziale
  • Blog
  • Strumenti AI
  • Come usare LiteLLM: una guida pratica con esempi, suggerimenti professionali e flussi di lavoro reali

Come usare LiteLLM: una guida pratica con esempi, suggerimenti professionali e flussi di lavoro reali

Aggiornato il 25 set 2025

6 min


Come Usare LiteLLM: Una Guida Pratica con Esempi, Suggerimenti Avanzati e Flussi di Lavoro Reali

Se hai mai desiderato che ogni API di modello si comportasse come quella di OpenAI, adorerai LiteLLM. È un gateway leggero che ti consente di chiamare oltre 100 LLM con un'unica interfaccia compatibile con OpenAI, localmente nel codice o tramite un proxy centrale che puoi condividere tra i team. In questo tutorial, esamineremo l'installazione, l'utilizzo di base e avanzato, lo streaming, il batching, i tentativi, la memorizzazione nella cache, il tracciamento dei costi e la distribuzione del proxy LiteLLM con guardrail e routing. Includeremo anche esempi in Python e JavaScript e modelli reali.
Vale la pena notare: se desideri un modo rapido per prototipare prompt, porre domande su più modelli e organizzare i risultati, Sider.AI può essere un valido alleato per la ricerca e l'iterazione mentre colleghi il tuo stack basato su LiteLLM. Integra il tuo flusso di lavoro aiutandoti a confrontare gli output e a perfezionare i prompt prima di codificarli.
Adotteremo un approccio pratico e orientato alla soluzione, in modo che tu possa fare copia-incolla e rilasciare.

Cos'è LiteLLM (e Perché i Team lo Usano)

  • Un'API per molti modelli: chiama Anthropic, OpenAI, Google, Azure, Cohere, Mistral, Bedrock e altri utilizzando funzioni in stile OpenAI.
  • Due modi per usarlo:
  • SDK Client (Python/JS): Utilizzo rapido in script, server, notebook.
  • Proxy (Gateway LLM): Servizio centralizzato per routing, autenticazione, logging, controllo dei costi e osservabilità.
  • Compatibilità Drop-in: scambia i modelli senza riscrivere la tua app.
  • Funzionalità operative: tentativi, timeout, streaming, batching, caching, tracing e report sui costi pronti all'uso.
Se hai appena iniziato, dai una scorsa alla documentazione ufficiale di Introduzione per un modello mentale rapido. Per esempi pratici, il tutorial di DataCamp è un ottimo compagno con codice passo passo. Se preferisci i video, c'è anche un corso accelerato per principianti.

Avvio Rapido: Installa e la Tua Prima Chiamata

Installa

# Python
pip install litellm
# Node.js
npm install litellm

Variabili d'Ambiente

# Esempio: utilizzo di OpenAI + Anthropic + Mistral
export OPENAI_API_KEY=sk-...
export ANTHROPIC_API_KEY=sk-ant-...
export MISTRAL_API_KEY=sk-mis-...

Python: Completamento Chat Minimo

from litellm import completion
resp = completion(
model="gpt-4o-mini", # or "anthropic/claude-3-5-sonnet", "mistral/mistral-large"
messages=.
---
## Streaming, Tools, and JSON Mode
### Streaming Responses
```python
from litellm import completion
for chunk in completion(
model="gpt-4o-mini",
messages=.
### Cost and Token Usage
LiteLLM can track token usage and estimate cost per request, model, or project. With the proxy, you can export usage to logs, dashboards, or a billing sink. This is invaluable when you mix vendors with different pricing.
---
## The LiteLLM Proxy (LLM Gateway)
If you’re a team or platform, the proxy is the real superpower: a central service with routing, auth, rate limits, logging, and observability. You interact with it using the OpenAI API surface so your app code barely changes.
### Start the Proxy
```bash
# simplest local run
litellm --port 4000
Per impostazione predefinita, espone endpoint compatibili con OpenAI come /v1/chat/completions. Punta il tuo client OpenAI esistente a ` e sei a posto.

Configura Provider e Chiavi

Crea config.yaml:
model_list:
- model_name: gpt-4o-mini
litellm_params:
model: openai/gpt-4o-mini
api_key: ${OPENAI_API_KEY}
- model_name: claude-3-5-sonnet
litellm_params:
model: anthropic/claude-3-5-sonnet
api_key: ${ANTHROPIC_API_KEY}
router:
strategy: simple_weighted
routes:
- model: gpt-4o-mini
weight: 0.6
- model: claude-3-5-sonnet
weight: 0.4
rate_limits:
requests_per_minute: 120
logging:
level: info
sink: stdout
auth:
api_keys:
- key: svc-app-123
Esegui con la configurazione:
litellm --config config.yaml --port 4000

Usa il Proxy dagli SDK OpenAI (Nessuna Modifica al Codice)

from openai import OpenAI
client = OpenAI(base_url=" api_key="svc-app-123")
resp = client.chat.completions.create(
model="gpt-4o-mini",
messages=.
---
## Advanced Routing: Latency, Cost, or Reliability
You can implement routing strategies like:
- Weighted round-robin to A/B models
- Lowest-latency-first by region
- Cost-aware routing for non-critical endpoints
- Fallback-on-error/retry across providers
With a router policy, you can say “prefer cheap, fall back to premium for tough prompts.” This offers high availability and predictable budgets.
---
## Guardrails, Moderation, and Safety
Add pre- and post-processing middleware to strip PII, enforce safety filters, or moderate outputs before returning to clients. Combine provider-native moderation (e.g., OpenAI, Google) with your own policy checks in the proxy. Example: require JSON schema validation and re-ask when invalid.
---
## Observability and Logging
- Enable request/response logging with redaction.
- Export metrics to Prometheus/Grafana or your APM.
- Trace latency, tokens, and cost by endpoint and user.
This turns “model roulette” into a managed service with SLOs and budgets.
---
## Real-World Usage Patterns
1) Multi-vendor resilience
- Primary: fast/cheap model; Fallback: high-accuracy model on 429/5xx.
- Benefits: better uptime, cost control, and stable quality.
2) Feature flag model upgrades
- Use router weights to canary a new model to 5% of traffic; monitor metrics; ramp up when stable.
3) Product tiers
- Free tier routed to small models; Pro tier to premium models.
4) Prompt registries and templates
- Centralize prompts in the proxy so services inherit improvements without redeploys.
5) Team billing and budgets
- Track spend by API key; enforce soft and hard limits per team or product.
---
## Security and Compliance Checklist
- Store provider keys in your secret manager; reference via env vars in config.
- Turn on request redaction and PII scrubbing in logs.
- Use per-service API keys for the proxy; rotate regularly.
- Set org-wide rate limits and quotas.
- Add allowlists/denylists for models and endpoints.
---
## Troubleshooting: Fast Fixes
- “Unauthorized” via proxy: Check `auth.api_keys` and that your client uses `base_url` + correct key.
- Model not found: Ensure `model_list` contains the friendly name you’re calling.
- Timeouts: Increase `timeout` or route to a lower-latency provider region.
- Weird outputs: Enable JSON schema + validation; add retries and fallbacks.
- Cost spikes: Turn on caching; route bulk traffic to cheaper models; set per-key quotas.
For deeper dives and latest features, the official docs are updated frequently and worth bookmarking. Tutorials like DataCamp’s guide are great for hands-on patterns, and the beginner crash course video can help you see the concepts in action.
---
## Put It All Together: Reference App Skeleton (Python FastAPI)
```python
# app.py
from fastapi import FastAPI
from pydantic import BaseModel
from litellm import completion
import os
class ChatReq(BaseModel):
question: str
app = FastAPI
@app.post("/ask")
async def ask(req: ChatReq):
resp = completion(
model=os.getenv("DEFAULT_MODEL", "gpt-4o-mini"),
messages=.
### FAQ
Q1:What is LiteLLM and why use it over direct provider SDKs?
LiteLLM is an OpenAI-compatible gateway for 100+ LLMs, giving you one API and one mental model. It reduces vendor lock-in, simplifies routing, and adds ops features like caching, retries, and cost tracking.
Q2:How do I use LiteLLM with the OpenAI SDK?
Point the SDK’s base URL to the LiteLLM proxy and use your proxy API key. Your code can stay the same while the proxy swaps providers or models behind the scenes.
Q3:Can LiteLLM stream responses and return JSON?
Yes. Use `stream=True` to get token streams, and `response_format` with JSON schema to enforce structured outputs across providers.
Q4:How do I control costs across different LLM providers?
Enable usage logging and cost estimation, add caching, set rate limits, and route bulk traffic to cheaper models via the proxy. Monitor with dashboards for budgets and SLOs.
Q5:Is LiteLLM suitable for production teams?
Yes. The proxy provides auth, rate limits, routing, observability, and safety middleware. It’s designed as an LLM gateway that centralizes governance while keeping your app OpenAI-compatible.

Articoli Recenti
Come Padroneggiare ChatPDF: Approfondimenti Rapidi da Documenti Complessi

Come Padroneggiare ChatPDF: Approfondimenti Rapidi da Documenti Complessi

La migliore alternativa a X Auto-Translation per documenti rapidi e precisi

La migliore alternativa a X Auto-Translation per documenti rapidi e precisi

La traduzione AI di Samsung non disponibile in Iran? Soluzioni pratiche

La traduzione AI di Samsung non disponibile in Iran? Soluzioni pratiche

Strumenti di traduzione persiana: una guida pratica per un lavoro più rapido e preciso

Strumenti di traduzione persiana: una guida pratica per un lavoro più rapido e preciso

La migliore alternativa a Grok per ricerche approfondite e citate

La migliore alternativa a Grok per ricerche approfondite e citate

Le 15 principali funzionalità dei generatori di immagini AI che userai davvero

Le 15 principali funzionalità dei generatori di immagini AI che userai davvero