llm-connect
Let the users of a web app bring their own LLM: pick a provider and a model from a catalog, paste
a key (or point at Ollama / LM Studio, or run a small model in the page with webslm), test the
connection, save, then call the model through the AI SDK straight from the
browser.
- Framework-free core: provider registry,
createModel / loadModel, testConnection, and
a settings store you can drive from any UI. llm-connect/react binds it to React; Svelte reads it
as a store.
- Five providers built in: OpenAI, Anthropic (and Anthropic-compatible APIs), Google, Mistral,
and every provider of the generic
@ai-sdk/openai-compatible SDK (DeepSeek, Z.ai, Groq…).
Each SDK loads only when used.
- Models in the page, no key: webslm as a provider: a
small model (SmolLM2, Qwen3, LFM2…) downloaded once from Hugging Face into the browser's cache,
then run on WebGPU or WebAssembly. Its connection test is the download, with progress.
- The catalog comes from llm-models, built live in the browser
(
liveCatalog) with a static models.json as fallback, and a recommended model per provider.
- The key never sits in clear text:
secureStorage encrypts it with AES-GCM under a
non-extractable key, createKeyVault keeps the keys of several providers behind a passphrase,
and a custom endpoint must be https (plain http only on this machine).
- Each provider's request rules: reasoning effort per provider and model, what each model
accepts (sampling, prefill, tools, web search), Claude's adaptive thinking, stateless OpenAI
Responses calls, headers that pass a browser's CORS preflight, and errors classified without
the key.
- Video:
startVideo / checkVideo (llm-connect/video) render with any video model
llm-models lists, at
OpenRouter, the Vercel AI Gateway, fal.ai, Google (Veo), xAI or Replicate, as jobs a server stores
and checks later from any process.
- Images:
generateImages (llm-connect/image) with the image models of OpenRouter, the
Vercel AI Gateway, fal.ai, OpenAI, Google (Gemini), xAI or Replicate, as bytes with their media
type and the cost when the provider reports it.
- Speech:
generateSpeechAudio (llm-connect/speech) speaks a text with the speech models of
the AI Gateway, fal.ai, OpenAI, Google (Gemini TTS) or ElevenLabs; listVoices gives the voices.
- Speech to text:
transcribe with the provider's own transcription model (OpenAI, Gemini,
Mistral, Groq), or on the device with NVIDIA Parakeet or Canary (llm-connect/nemo) or Whisper
(llm-connect/whisper), all in one shape and timed to the word.
Install
npm install llm-connect llm-models ai @ai-sdk/openai @ai-sdk/anthropic @ai-sdk/google @ai-sdk/mistral @ai-sdk/openai-compatible
For images, speech or video, add the SDKs of the providers you call (see Images,
Speech and Video).
ai (v7), the @ai-sdk/* packages (v4) and @ai-sdk/openai-compatible (v3) are optional peers:
install the ones your users can pick. Add webslm to offer models that run in the
page.
react (18+) is only needed for llm-connect/react.
The store builds the catalog in the browser when settings open (see
The catalog). Write the fallback at build time:
npx llm-models catalog --npm callable --require openai,anthropic,google,mistral --out public/models.json
Call a model
import { generateText } from "ai";
import { loadModel } from "llm-connect";
const model = await loadModel(settings); // imports @ai-sdk/anthropic on first use
const { text } = await generateText({ model, prompt: "Hello" });
settings is what the store saves (LlmSettings):
| Field |
|
apiKey, model |
The key and the catalog model id |
providerId, providerName, providerNpm, providerApi |
The catalog provider: its SDK package and base URL |
customEndpoint, customModel |
An OpenAI-compatible server (Ollama, LM Studio, webslm serve, vLLM…); wins over the provider |
headers |
Extra request headers |
language |
Code of the language answers are written in ("fr") |
Both take options as a second argument:
| Option |
Default |
|
fetch |
globalThis.fetch |
The fetch every request of the model goes through: route them through your own wrapper (logging, a proxy, a network policy) |
strictHeaders |
false |
Send only the headers the provider's API defines (plus content-type and accept); the settings' headers are dropped |
createModel(settings) does the same synchronously, for providers you registered yourself:
import { createModel, registerProvider, fromSDK } from "llm-connect";
import { register as registerAnthropic } from "llm-connect/providers/anthropic";
import { createOpenAI } from "@ai-sdk/openai";
registerAnthropic(); // or "llm-connect/providers/all" for the five
registerProvider("openai", fromSDK(createOpenAI));
registerProvider("my-llm", (config) => myLanguageModel(config.apiKey, config.model));
The registry is shared by every copy of llm-connect loaded in the page, so a library and the app
that resolve different installs still see the same providers.
What the built-in providers take care of:
- A custom endpoint goes through the OpenAI SDK with Chat Completions; the official OpenAI URL
keeps the Responses API.
- Every request goes through
guardedFetch, which removes the user-agent header the AI SDK adds
(no provider's CORS preflight allows it, and Firefox sends it).
- Anthropic's own API gets the
anthropic-dangerous-direct-browser-access header. An
Anthropic-compatible provider (MiniMax…) gets its own base URL, so its key never goes to
Anthropic, and not that header, which its preflight does not allow. Its base URL works with
or without the trailing /v1 (anthropicBaseUrl): gateways document it without, for
Anthropic's own clients, as Z.ai does with https://api.z.ai/api/anthropic.
- A gateway that answers an error with HTTP 200 and a JSON body (Z.ai:
{"code":500,"msg":"404 NOT_FOUND","success":false}) gets the status the body stands for
(maskedErrorStatus), so the call fails with the provider's message instead of a parse error
or a stream that ends without a finish.
- The generic SDK refuses a provider without URL, asks for the usage chunk at the end of a stream
(
stream_options.include_usage), and turns structured output (json_schema) into
json_object plus the schema in a system message, for APIs such as GLM.
guardedFetch(kind, { fetch, strictHeaders }) is exported for providers you register yourself:
pass it as their fetch.
Models in the page: webslm
webslm runs small language models in the browser, straight from
their Hugging Face checkpoints: no server, no key, nothing sent to a provider. llm-connect offers it
as the provider webslm ("webslm (in this browser)"), next to the catalog's.
npm install llm-connect llm-models ai webslm
const store = createLlmSettingsStore({
catalog: liveCatalog({ fallbackUrl: "/models.json" }),
storage: secureStorage({ prefsKey: "my-app-ai", dbName: "my-app-secrets" }),
webslm: true, // the provider "webslm", listed after the recommended ones
});
store.selectProvider("webslm"); // webslm's recommended model (SmolLM2 360M)
await store.searchWebslm("qwen"); // add Hugging Face models webslm runs to the list
await store.test(); // downloads and loads the model: state.loadProgress follows it
await store.save(); // no key needed
- Models: webslm's curated list (
CURATED_MODELS: name, download size, reasoning for the
models that think first), then whatever searchWebslm(query) finds on Hugging Face: supported
architectures with safetensors weights, up to 2B parameters, not gated (state.searchingWebslm
while it runs). The model id is the Hugging Face repository id.
- Settings:
{ providerId: "webslm", providerNpm: "webslm", model: "<repo id>", apiKey: "" }.
isConfigured, canSave and canTest need a model and no key; the key typed for another
provider is not saved with it.
- Test:
testConnection downloads the model (once: later loads read the browser's cache, even
offline) and loads it, calling onProgress with webslm's progress (phase: resolve,
download, load, ready; overallLoadedBytes / overallTotalBytes). The store exposes it as
state.loadProgress while test() runs. No timeout unless timeoutMs sets one. A gated
repository fails with auth, a missing one with http 404, no network with cors, an
unsupported checkpoint with config and webslm's message. mode: "generate" runs a short
generation as well.
- Call:
loadModel(settings) imports llm-connect/providers/webslm (and webslm) on first use
and returns webslm's AI SDK model. Every model for one repository shares the weights loaded in
the page; generations run one after the other. Streaming, stop sequences, maxOutputTokens,
temperature, top-p, top-k, penalties, seed, abort signals and reasoning parts work as with any
provider; the reasoning effort sets a thinking budget. JSON output (Output.object, a
responseFormat with a schema) is constrained to its schema by webslm's grammar, token by
token. Tools are called only when toolChoice forces a single one; otherwise they are
unsupported (a warning), so the capabilities say tools: false. isWebslmModel(model) tells it apart, and
model.load({ onProgress }) loads it ahead of the first call.
- Load options:
register({ loadOptions: { device: "cpu", quant: "q4" } }) from
llm-connect/providers/webslm before the first call (see webslm's loadModel options).
- Page setup: webslm downloads from Hugging Face, so a CSP needs
https://huggingface.co https://*.hf.co in connect-src, plus 'wasm-unsafe-eval' in script-src. Its fastest CPU build needs a
cross-origin isolated page (COOP/COEP headers); without it webslm picks a slower one.
webslmCatalogProvider() and searchWebslmModels(query) give the same lists without the store.
webslm serve
The webslm command-line tool also serves models as an OpenAI-compatible endpoint, like LM Studio:
webslm serve HuggingFaceTB/SmolLM2-360M-Instruct --cors listens on http://127.0.0.1:8080/v1.
ENDPOINT_PRESETS.webslm fills that endpoint and model in a custom endpoint; --cors lets the
page call it, and --api-key sets the key the dialog then sends.
Call options
What a call may carry depends on the provider and the model. callOptions builds the provider
options for the model the settings point to, to spread into streamText or generateText:
import { streamText } from "ai";
import { callOptions, callProblem, loadModel, resolveCapabilities, providerKindOf } from "llm-connect";
const capabilities = resolveCapabilities({
kind: providerKindOf(settings), // "anthropic" | "openai" | "google" | "mistral" | "openai-compatible"
modelId: settings.model,
catalog: slimModel, // the catalog's entry, optional
});
const call = { effort: "high", messages } as const;
const problem = callProblem(settings, call, capabilities); // null, or { code, message }
if (problem) throw new Error(problem.message);
const result = streamText({
model: await loadModel(settings),
messages,
...callOptions(settings, { effort: "high", capabilities }),
});
Per protocol, callOptions sends:
| Protocol |
Options |
| Anthropic |
Claude 4.6 and later: output_config.effort and adaptive thinking with display: "summarized" (left out when the call sets a sampling parameter, which thinking refuses). Earlier models: a thinking budget, with the output cap lowered so the sum stays within the model's limit. refusalFallback: true opts in to the server-side refusal fallback (fallbacks: "default") on Anthropic's own API, for the models that have one |
| OpenAI (Responses, official URL) |
store: false, so OpenAI keeps no conversation state. On a reasoning model, include: ["reasoning.encrypted_content"] and a reasoning summary; the effort as reasoning.effort |
| Gemini |
Thought summaries on a reasoning model; the effort as thinkingLevel (Gemini 3) or a thinking budget (Gemini 2.5) |
| Mistral, OpenAI-compatible |
Nothing: a server may refuse a parameter it does not know |
Replaying a conversation needs nothing more: pass back each turn's response.messages. Their
reasoning parts carry Anthropic's thinking signatures, OpenAI's encrypted reasoning and Gemini's
thought signatures, and the SDK sends them back unchanged.
callOptions throws LlmCallError (code: "effort") for an effort the model does not take.
callProblem(settings, call, capabilities?) checks the rest before any network call, rather than
letting a parameter be dropped: an effort or sampling parameter the model refuses, a sampling
parameter next to a thinking budget, an assistant message last (prefill), a system message after
the first one, tools, a forced tool choice, web search, images, PDFs, audio, video, and the output
cap.
Reasoning effort