API LLM gratuita per LangChain
LangChain si collega alle API compatibili con OpenAI tramite ChatOpenAI e OpenAIEmbeddings. Cambi l'URL base e la chiave. Questa guida punta entrambe le classi a FreeLLMAPI, che riunisce 45 piani gratuiti dei provider dietro una sola chiave. Il codice qui sotto funziona in Python e JavaScript e gestisce i limiti di frequenza.
Codice, nomi dei modelli ed etichette del catalogo in tempo reale sono mostrati in inglese.
Configura il gateway e i pacchetti
Installa FreeLLMAPI e aggiungi chiavi gratuite da due o più provider nella pagina Keys della dashboard. Copia la chiave unificata. Il tuo codice usa solo questa chiave. Le chiavi dei provider restano in FreeLLMAPI.
Installa FreeLLMAPI e i pacchetti LangChain
curl -fsSL https://freellmapi.co/install.sh | bash
# Python
pip install -U langchain langchain-openai
# JavaScript
npm install @langchain/openai @langchain/core zodVariabili d'ambiente
export FREELLMAPI_BASE_URL=http://localhost:3001/v1
export FREELLMAPI_API_KEY=<unified-key>Usa model="auto" per lasciare che il router scelga un modello. Puoi anche usare una strategia di routing, per esempio auto:fast o auto:smart. Funzionano anche un profilo con nome come auto:coding e un ID di modello fisso dal catalogo.
Per vedere quali modelli le tue chiavi possono chiamare ora, richiedi GET /v1/models?execution_status=ready. L'elenco completo contiene anche modelli senza chiave. Un modello con lo stato exhausted ha delle chiavi, ma tutte sono al limite in questo momento. Quello stato scompare quando finiscono i cooldown.
Elenca i modelli che possono rispondere ora
curl "http://localhost:3001/v1/models?execution_status=ready" \
-H "Authorization: Bearer <unified-key>"Chat con ChatOpenAI
In Python, imposta base_url e api_key. Il valore max_retries va al client OpenAI, che ripete gli errori 429 e 5xx con backoff esponenziale.
Python: chat e streaming
import os
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(
model="auto",
base_url=os.environ["FREELLMAPI_BASE_URL"],
api_key=os.environ["FREELLMAPI_API_KEY"],
temperature=0.2,
max_retries=3,
timeout=60,
include_response_headers=True,
)
msg = llm.invoke("Explain retrieval-augmented generation in two sentences.")
print(msg.content)
print("Served by:", msg.response_metadata["headers"].get("x-routed-via"))
for chunk in llm.stream("Write a haiku about SQLite."):
print(chunk.content, end="", flush=True)In JavaScript, metti l'URL base in configuration.baseURL. L'oggetto configuration va al client ufficiale dell'SDK OpenAI.
JavaScript: chat e streaming
import { ChatOpenAI } from "@langchain/openai";
const llm = new ChatOpenAI({
model: "auto",
apiKey: process.env.FREELLMAPI_API_KEY,
temperature: 0.2,
maxRetries: 3,
configuration: { baseURL: process.env.FREELLMAPI_BASE_URL },
});
const msg = await llm.invoke("Explain retrieval-augmented generation in two sentences.");
console.log(msg.content);
for await (const chunk of await llm.stream("Write a haiku about SQLite.")) {
process.stdout.write(String(chunk.content));
}L'intestazione x-routed-via mostra il provider e il modello che hanno risposto. Se il router ha cambiato provider, x-fallback-trail mostra ogni tentativo fallito e il motivo.
Strumenti e agenti
FreeLLMAPI passa i tools in stile OpenAI a ogni provider e restituisce i tool_calls in formato OpenAI. Per Gemini, traduce la richiesta nel formato di Google e viceversa. Usa bind_tools per una sola chiamata, oppure create_agent per un ciclo che esegue gli strumenti.
Python: bind_tools e create_agent
from langchain.agents import create_agent
from langchain_core.tools import tool
@tool
def get_weather(city: str) -> str:
"""Return the current weather for a city."""
return f"It is 18 C and cloudy in {city}."
# One call: the model returns the tool call, your code runs it
msg = llm.bind_tools([get_weather]).invoke("What is the weather in Dublin?")
print(msg.tool_calls)
# Agent loop: LangChain runs the tool and sends the result back
agent = create_agent(
model=llm,
tools=[get_weather],
system_prompt="You answer weather questions. Use the tool.",
)
result = agent.invoke({"messages": [{"role": "user", "content": "Weather in Dublin?"}]})
print(result["messages"][-1].content)JavaScript: bindTools
import { tool } from "@langchain/core/tools";
import { z } from "zod";
const getWeather = tool(
async ({ city }) => `It is 18 C and cloudy in ${city}.`,
{
name: "get_weather",
description: "Return the current weather for a city.",
schema: z.object({ city: z.string() }),
},
);
const reply = await llm.bindTools([getWeather]).invoke("What is the weather in Dublin?");
console.log(reply.tool_calls);Solo alcuni modelli gratuiti supportano le chiamate di strumenti. Con auto, mantieni nella catena di fallback i modelli che supportano le chiamate di strumenti, oppure crea un profilo per gli agenti. Questi modelli gratuiti oggi supportano gli strumenti:
| Modello | Gratis su | Contesto | Limiti gratuiti (offerta migliore) | Strumenti | Visione |
|---|---|---|---|---|---|
| GLM 5.3 | UnoRouter | 1M | 1 richieste/min 1 req/min per model | Sì | No |
| GLM 5.3 Flash | NVIDIA NIM, UnoRouter | 1M | 40 richieste/min 40 RPM | Sì | Sì |
| Gemini 3.8 Flash | Google AI Studio | 1M | Recurring provider quota | Sì | Sì |
| Qwen3.8 Flash Next | AMD Radeon Cloud | 262K | Recurring daily account allowance | Sì | No |
| Qwen3.8 Flash | ElectronHub | 1M | $0.25/week shared recurring credit | Sì | Sì |
| Gemini 3.7 Flash | Google AI Studio | 1M | 10 richieste/min 20 richieste/giorno 250,000 token/min ~3M | Sì | Sì |
| GPT-5.6 Luna | ElectronHub | 1M | $0.25/week shared recurring credit | Sì | Sì |
| Dots3 Note Preview | Kilo Gateway, OpenRouter | 512K | 20 richieste/min 50 richieste/giorno 50 req/day account-wide (1,000 after a $10 purchase) | Sì | Sì |
| DeepSeek V4 Flash | AMD Radeon Cloud, BazaarLink, ElectronHub | 1M | 10 richieste/min 50 richieste/giorno Shared rate limit | Sì | No |
| Qwen3.8 27B | ElectronHub, Groq, OVH AI Endpoints | 262K | 30 richieste/min 250 richieste/giorno 70,000 token/min ~6M | Sì | Sì |
Mostrati 10 di 109 modelli gratuiti corrispondenti. Vedi tutti i modelli.
Dati in tempo reale dal catalogo FreeLLMAPI (versione 2026.11.19, verificato il 2026-11-19). I limiti gratuiti cambiano spesso. Il catalogo viene verificato ogni giorno.
Embedding con OpenAIEmbeddings
Per impostazione predefinita, OpenAIEmbeddings in Python divide il testo con un tokenizer OpenAI e invia token. La maggior parte degli altri provider richiede testo grezzo. Imposta check_embedding_ctx_length=False per inviare testo.
Python: embedding
from langchain_openai import OpenAIEmbeddings
emb = OpenAIEmbeddings(
model="bge-m3", # one embedding family, 1024 dimensions
base_url=os.environ["FREELLMAPI_BASE_URL"],
api_key=os.environ["FREELLMAPI_API_KEY"],
check_embedding_ctx_length=False,
)
vectors = emb.embed_documents(["FreeLLMAPI pools free tiers.", "LangChain builds LLM apps."])
print(len(vectors), len(vectors[0]))JavaScript: embedding
import { OpenAIEmbeddings } from "@langchain/openai";
const emb = new OpenAIEmbeddings({
model: "bge-m3",
apiKey: process.env.FREELLMAPI_API_KEY,
configuration: { baseURL: process.env.FREELLMAPI_BASE_URL },
});
const vector = await emb.embedQuery("What does FreeLLMAPI do?");
console.log(vector.length);Il failover degli embedding di FreeLLMAPI non cambia mai il modello. Passa solo tra provider che servono la stessa famiglia. Così tutti i vettori in un unico vector store restano compatibili. Scegli una famiglia e mantienila. I modelli di embedding gratuiti oggi sono:
| Modello | Provider | Dimensioni | Input massimo | Limite gratuito |
|---|---|---|---|---|
Gemini Embeddinggemini-embedding-001 | Google AI Studio | 3072 | 2048 | 100 rpm · 1K req/day |
Nemotron Embed VL 1Bnvidia/llama-nemotron-embed-vl-1b-v2 | NVIDIA NIM | 2048 | 8192 | ~40 rpm |
Nemotron 3 Embed 1B (OR free)nvidia/nemotron-3-embed-1b:free | OpenRouter | 2048 | 32768 | 20 rpm · shared free daily cap |
SEA-LION E5 Embedding 600Maisingapore/SEA-LION-E5-Embedding-600M | SEA-LION | 1024 | 8192 | free · 10 rpm |
SEA-LION ModernBERT Embedding 300Maisingapore/SEA-LION-ModernBERT-Embedding-300M | SEA-LION | 1024 | 8192 | free · 10 rpm |
SEA-LION ModernBERT Embedding 600Maisingapore/SEA-LION-ModernBERT-Embedding-600M | SEA-LION | 1024 | 8192 | free · 10 rpm |
BGE-M3@cf/baai/bge-m3 | Cloudflare Workers AI | 1024 | 8192 | 10K neurons/day (shared) |
EmbeddingGemma 300M@cf/google/embeddinggemma-300m | Cloudflare Workers AI | 768 | 2048 | 10K neurons/day (shared) |
Qwen3 Embedding 0.6B@cf/qwen/qwen3-embedding-0.6b | Cloudflare Workers AI | 1024 | 8192 | 10K neurons/day (shared) |
Cohere Embed v4embed-v4.0 | Cohere | 1536 | 128000 | 1K calls/mo (shared w/ chat) |
Gemini Embedding 2gemini-embedding-2 | Google AI Studio | 3072 | 8192 | free-tier rate limited |
Nemotron 3 Embed 1Bnvidia/nemotron-3-embed-1b | NVIDIA NIM | 2048 | 4096 | ~40 rpm |
PLaMo Embedding 1B (CF)@cf/pfnet/plamo-embedding-1b | Cloudflare Workers AI | 2048 | 4096 | 10K neurons/day (shared) |
BGE Small EN v1.5 (CF)@cf/baai/bge-small-en-v1.5 | Cloudflare Workers AI | 384 | 512 | 10K neurons/day (shared) |
BGE Base EN v1.5 (CF)@cf/baai/bge-base-en-v1.5 | Cloudflare Workers AI | 768 | 512 | 10K neurons/day (shared) |
BGE Large EN v1.5 (CF)@cf/baai/bge-large-en-v1.5 | Cloudflare Workers AI | 1024 | 512 | 10K neurons/day (shared) |
Mistral Embedmistral-embed | Mistral | 1024 | 8192 | free mode · monthly cap (shared) |
Codestral Embedcodestral-embed | Mistral | 1536 | 8192 | free mode · monthly cap (shared) |
Llama Text Embed v2 (Pinecone)llama-text-embed-v2 | Pinecone | 1024 | 2048 | 5M tokens/mo per model |
Multilingual E5 Large (Pinecone)multilingual-e5-large | Pinecone | 1024 | 507 | 5M tokens/mo per model |
Nemotron 3 Embed 1B (Speka)nvidia/nemotron-3-embed-1b | Speka | 2048 | 8192 | $1/month shared across Speka models |
OpenAI: Text Embedding 3 Small (ElectronHub)text-embedding-3-small | ElectronHub | 1536 | 8192 | $0.25/week shared free credits |
OpenAI: Text Embedding 3 Large (ElectronHub)text-embedding-3-large | ElectronHub | 3072 | 8192 | $0.25/week shared free credits |
Nemotron 3 Embed 8B (Inferbase)nvidia-nemotron-3-embed-8b | Inferbase | 4096 | 8192 | 5,000 requests/month; 100 requests and $0.50 usage/day shared |
Qwen 3 Embedding 0.6B (Inferbase)qwen3-embedding-0-6b | Inferbase | 1024 | 8192 | 5,000 requests/month; 100 requests and $0.50 usage/day shared |
Qwen 3 Embedding 4B (Inferbase)qwen3-embedding-4b | Inferbase | 2560 | 8192 | 5,000 requests/month; 100 requests and $0.50 usage/day shared |
Qwen 3 Embedding 8B (Inferbase)qwen3-embedding-8b | Inferbase | 4096 | 8192 | 5,000 requests/month; 100 requests and $0.50 usage/day shared |
LFM2.5 Embedding 350M (LLMTR)liquid/lfm-2.5-embedding-350m-free | LLMTR | 1024 | 512 | Ongoing zero-price route; provider terms apply |
BGE-M3 (SEA-LION)BAAI/bge-m3 | SEA-LION | 1024 | 8192 | free · 10 rpm |
Cohere Embed English v3embed-english-v3.0 | Cohere | 1024 | 512 | 1K calls/mo (shared w/ chat) |
Qwen3 Embedding 8B (OVH)Qwen3-Embedding-8B | OVH AI Endpoints | 4096 | 32768 | free · anonymous 2 req/min per IP |
BGE-M3 (OVH)bge-m3 | OVH AI Endpoints | 1024 | 8192 | free · anonymous 2 req/min per IP |
BGE Multilingual Gemma2 (OVH)bge-multilingual-gemma2 | OVH AI Endpoints | 3584 | 8192 | free · anonymous 2 req/min per IP |
Mistral: Codestral Embed (ElectronHub)codestral-embed | ElectronHub | 1536 | 8192 | $0.25/week shared free credits |
Mistral: Mistral Embed (ElectronHub)mistral-embed | ElectronHub | 1024 | 8192 | $0.25/week shared free credits |
Google: Gemini Embedding 2 (ElectronHub)gemini-embedding-2 | ElectronHub | 3072 | 8192 | $0.25/week shared free credits |
Google: Gemini Embedding 001 (ElectronHub)gemini-embedding-001 | ElectronHub | 3072 | 2048 | $0.25/week shared free credits |
OpenAI: Text Embedding Ada 002 (ElectronHub)text-embedding-ada-002 | ElectronHub | 1536 | 8192 | $0.25/week shared free credits |
Cohere Embed English Light v3embed-english-light-v3.0 | Cohere | 384 | 512 | 1K calls/mo (shared w/ chat) |
Cohere Embed Multilingual v3embed-multilingual-v3.0 | Cohere | 1024 | 512 | 1K calls/mo (shared w/ chat) |
Cohere Embed Multilingual Light v3embed-multilingual-light-v3.0 | Cohere | 384 | 512 | 1K calls/mo (shared w/ chat) |
Dati in tempo reale dal catalogo FreeLLMAPI (versione 2026.11.19, verificato il 2026-11-19). I limiti gratuiti cambiano spesso. Il catalogo viene verificato ogni giorno.
Output strutturato, sessioni e scelta del modello
with_structured_output restituisce un oggetto Pydantic al posto del testo. Per impostazione predefinita, LangChain usa in questo caso il function calling. Questo metodo funziona su ogni modello gratuito che supporta gli strumenti.
Python: output strutturato
from pydantic import BaseModel, Field
class Ticket(BaseModel):
category: str = Field(description="billing, bug or other")
urgent: bool
classifier = llm.with_structured_output(Ticket)
ticket = classifier.invoke("The app crashes when I pay. Please fix it today.")
print(ticket.category, ticket.urgent)Non usare method="json_schema" con auto. Non tutti i provider gratuiti supportano l'output JSON schema rigoroso, e il router può scegliere un provider diverso per ogni richiesta.
FreeLLMAPI mantiene una conversazione sullo stesso modello per 30 minuti. Trova la conversazione dall'intestazione X-Session-Id. Se l'intestazione manca, usa un hash del primo messaggio utente. Per un'app di chat con molti utenti, invia un ID di sessione per ogni utente:
Python: una sessione per utente
def llm_for(user_id: str) -> ChatOpenAI:
return ChatOpenAI(
model="auto",
base_url=os.environ["FREELLMAPI_BASE_URL"],
api_key=os.environ["FREELLMAPI_API_KEY"],
default_headers={"X-Session-Id": f"user-{user_id}"},
max_retries=3,
)Scegli la stringa del modello per ogni parte della tua app:
| Attività nella tua app | Stringa del modello | Motivo |
|---|---|---|
| Risposte di chat per gli utenti | auto | Segue la catena che hai impostato nella dashboard |
| Agente con strumenti | auto:<profile> | Un profilo che ha solo modelli con chiamate di strumenti |
| Classificazione, routing, riassunti brevi | auto:fast | Ordina i modelli in base alla velocità misurata |
| Passaggi di ragionamento complessi | auto:smart | Ordina i modelli in base all'intelligenza |
| Test che devono essere ripetibili | Un ID di modello fisso | Stesso modello ogni volta, ma si ferma al limite di quel modello |
I piani gratuiti non hanno SLA. La latenza cambia durante la giornata, e i modelli più forti raggiungono per primi i limiti giornalieri. Testa le tue catene con i modelli che la catena userà davvero.
Limiti di frequenza e nuovi tentativi
FreeLLMAPI prova il provider successivo quando uno restituisce 429. Il tuo codice vede un 429 solo quando ogni chiave della catena è al limite. Allora la risposta ha un'intestazione Retry-After. Molti limiti giornalieri si reimpostano a mezzanotte UTC.
Per i job batch, aggiungi un secondo livello di nuovi tentativi con with_retry. Ripete l'intera runnable con backoff esponenziale e jitter.
Python: ripeti una catena sui limiti di frequenza
import openai
from langchain_core.prompts import ChatPromptTemplate
prompt = ChatPromptTemplate.from_messages([
("system", "Summarize the text in one sentence."),
("user", "{text}"),
])
chain = (prompt | llm).with_retry(
retry_if_exception_type=(openai.RateLimitError, openai.APITimeoutError),
wait_exponential_jitter=True,
stop_after_attempt=5,
)
# batch() runs requests in parallel; max_concurrency keeps the rate low
results = chain.batch(
[{"text": t} for t in ["First document.", "Second document."]],
config={"max_concurrency": 4},
)| Problema | Causa | Soluzione |
|---|---|---|
openai.AuthenticationError | Chiave unificata errata | Copia di nuovo la chiave dalla pagina Keys |
openai.NotFoundError su ogni chiamata | L'URL base non ha /v1 | Usa http://localhost:3001/v1 |
openai.RateLimitError | Tutte le chiavi della catena sono al limite | Aggiungi provider, riduci max_concurrency oppure attendi Retry-After |
| Errore di embedding su token o tipo di input | LangChain invia token, non testo | Imposta check_embedding_ctx_length=False |
tool_calls è vuoto | Il modello non supporta gli strumenti | Usa un modello dalla tabella degli strumenti o un profilo per gli strumenti |
| Manca il testo del ragionamento | ChatOpenAI mantiene solo i campi standard OpenAI | Leggi la risposta in content; i campi extra del provider non vengono mantenuti |
Domande frequenti
Posso usare un'API LLM gratuita con LangChain?
Sì. Qualsiasi API compatibile con OpenAI funziona con ChatOpenAI. Imposta base_url su http://localhost:3001/v1 e api_key sulla tua chiave unificata di FreeLLMAPI. Il router usa i piani gratuiti dei provider.
Come imposto un base URL personalizzato in LangChain ChatOpenAI?
In Python, passa base_url a ChatOpenAI. In JavaScript, passa configuration: { baseURL } al costruttore. Anche la variabile d'ambiente OPENAI_BASE_URL funziona in Python.
Gli agenti LangChain funzionano con i modelli gratuiti?
Sì, se il modello supporta le chiamate di strumenti. Usa create_agent con un modello ChatOpenAI e mantieni nella tua catena FreeLLMAPI i modelli con chiamate di strumenti.
Perché OpenAIEmbeddings fallisce con un provider non OpenAI?
Per impostazione predefinita invia gli ID dei token. La maggior parte degli altri provider richiede testo grezzo. Imposta check_embedding_ctx_length=False in Python.
Come gestisco gli errori 429 in LangChain?
Imposta max_retries su ChatOpenAI e aggiungi with_retry alla catena per i job batch. FreeLLMAPI passa già al provider successivo prima che il tuo codice veda un 429.
Guide correlate
- LLM gratuito per LlamaIndex
- API LLM gratuita in Python
- API LLM gratuita per RAG
- API gratuita per embedding
- API LLM gratuita con function calling
- Free LLM API per agenti IA
Fonti
- LangChain docs: ChatOpenAI integration (Python) (verificato il 20 November 2026)
- LangChain docs: ChatOpenAI integration (JavaScript) (verificato il 20 November 2026)
- LangChain docs: agents and create_agent (verificato il 20 November 2026)
- LangChain source: OpenAIEmbeddings note on OpenAI-compatible APIs (verificato il 20 November 2026)
- OpenAI Python SDK: retries and errors (verificato il 20 November 2026)
- FreeLLMAPI docs: REST API (tool calling, embeddings, response headers) (verificato il 20 November 2026)