Provider-agnostic LLM calls for Go apps, with an ordered fallback chain — zero third-party dependencies.
Designed to be dropped into the same apps as go-draw, go-wiki and go-login: one interface, two client shapes covering every provider worth calling, and a chain that tries the primary then each backup.
- One interface —
Providerhas a single method. Swapping vendors is a config change. - Ordered fallback — a
Chainis primary, backup 1, backup 2.Response.Providerreports who actually served the call. - Retry before fallback — a provider that returns 503 under load is tried again, briefly, before the chain gives up on the model you chose and pays someone else.
- Fails through for the right reasons — a 429, a 5xx, a timeout or a dead key moves to the next provider; a 400 does not, because a malformed request will be rejected identically by the backup.
- Two clients cover everything — a native Anthropic Messages client (so Claude vision works properly), and one OpenAI-compatible client covering OpenAI, NVIDIA NIM, DeepSeek, OpenRouter, Groq, Together, Mistral, xAI and Ollama.
- Vision — attach images to a message; both clients inline them, so nothing has to be publicly hosted to be analysed.
- Defensive JSON —
ExtractJSONdigs a value out of prose and code fences, and repairs one truncated mid-generation without ever inventing content. - Uniform config —
AI_1_*,AI_2_*,AI_3_*environment variables build a chain, so every app configures its slots identically.
Deliberately out of scope: caching, quotas and rate limiting. Those need the app's own schema and policy, and belong in the app.
go get github.com/anchoo2kewl/go-ai
package main
import (
"context"
"fmt"
"log"
ai "github.com/anchoo2kewl/go-ai"
)
func main() {
// Reads AI_1_PROVIDER / AI_1_MODEL / AI_1_API_KEY, then AI_2_*, AI_3_*.
chain, err := ai.ChainFromEnv()
if err != nil {
log.Fatal(err)
}
resp, err := chain.Complete(context.Background(), ai.Request{
System: "You are a concise assistant.",
Messages: []ai.Message{ai.UserText("Name three compound lifts.")},
MaxTokens: 300,
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("[%s / %s] %s\n", resp.Provider, resp.Model, resp.Text)
}Slots are read from AI_1_, AI_2_, … and stop at the first gap.
AI_1_PROVIDER=anthropic
AI_1_MODEL=claude-sonnet-5
AI_1_API_KEY=sk-ant-...
AI_2_PROVIDER=openai # backup 1
AI_2_MODEL=gpt-5.2
AI_2_API_KEY=sk-...
AI_3_PROVIDER=ollama # backup 2, self-hosted, no key
AI_3_MODEL=llama3.1
AI_3_BASE_URL=http://localhost:11434/v1| Variable | Required | Notes |
|---|---|---|
AI_n_PROVIDER |
yes | Ends the scan when absent |
AI_n_MODEL |
usually | Required for OpenAI-compatible providers |
AI_n_API_KEY |
usually | Optional for a local Ollama |
AI_n_BASE_URL |
no | Required for a provider not built in |
AI_n_TIMEOUT_SECONDS |
no | Defaults to 150 |
AI_MAX_ATTEMPTS |
no | Tries per provider, including the first. Defaults to 3; 1 disables retry |
AI_RETRY_BASE_MS |
no | First backoff interval. Defaults to 500 |
The two retry variables are chain-wide rather than per slot — per-slot retry budgets are complexity nobody has asked for.
ChainFromEnvPrefix("ANALYSIS") reads ANALYSIS_1_* instead, for an app
running more than one chain.
chain, err := ai.NewChainFromSlots(
ai.Slot{Provider: "anthropic", Model: "claude-sonnet-5", APIKey: primaryKey},
ai.Slot{Provider: "deepseek", Model: "deepseek-v4-flash", APIKey: backupKey},
)Slots that aren't configured are skipped, so three slots can be passed when
only the first is filled in. ErrNoProviders comes back when none are — treat
it as "AI features are off" rather than a startup failure.
chain.OnFallback(func(provider string, err error) {
log.Warn("ai provider failed, trying the next", "provider", provider, "err", err)
})resp, err := chain.Complete(ctx, ai.Request{
System: "Estimate the food in the photo. Reply with JSON only.",
Messages: []ai.Message{
ai.UserImage("What is in this meal, and roughly how many calories?", "image/jpeg", photoBytes),
},
MaxTokens: 1200,
JSON: true,
})
var estimate struct {
Items []struct {
Name string `json:"name"`
Kcal float64 `json:"kcal"`
} `json:"items"`
}
if err := ai.ExtractJSON(resp.Text, &estimate); err != nil {
return err
}ExtractJSON handles what models actually return rather than what they were
asked for:
- Strips
```jsonfences and surrounding prose. - Finds the first balanced object or array, tracking string state so a brace inside a value doesn't corrupt the scan.
- Repairs a reply truncated by the token ceiling, by closing the containers still open at the last clean boundary.
The repair only ever emits a prefix of the model's own output plus closing
punctuation. It can drop an incomplete trailing item; it cannot invent one. A
number is a cut point only when a delimiter follows it, so a truncated 1234
is discarded rather than salvaged as 12.
| Name | Client | Endpoint |
|---|---|---|
anthropic |
Messages API | https://api.anthropic.com/v1 |
openai |
OpenAI-compatible | https://api.openai.com/v1 |
nvidia |
OpenAI-compatible | https://integrate.api.nvidia.com/v1 |
deepseek |
OpenAI-compatible | https://api.deepseek.com/v1 |
openrouter |
OpenAI-compatible | https://openrouter.ai/api/v1 |
groq |
OpenAI-compatible | https://api.groq.com/openai/v1 |
together |
OpenAI-compatible | https://api.together.xyz/v1 |
mistral |
OpenAI-compatible | https://api.mistral.ai/v1 |
xai |
OpenAI-compatible | https://api.x.ai/v1 |
ollama |
OpenAI-compatible | http://localhost:11434/v1 |
Anything else works with an explicit BaseURL. An unknown provider name with
no base URL is an error rather than a default — silently falling back to some
other vendor's endpoint would send your key to a service you never chose.
A failure means one of three things, and conflating them is expensive either way: retrying a bad API key adds latency to an answer that was never coming, while falling through on a momentary 503 abandons the model you chose and pays a different vendor for a worse one.
| Failure | Outcome | Why |
|---|---|---|
| Network error, timeout, dropped connection | retry, then fall through | Usually over in a second |
| 408, 429 | retry, then fall through | Busy now, not wrong |
| 5xx | retry, then fall through | Capacity pressure is rarely an outage |
| 401, 402, 403 | fall through immediately | A key that is bad now will be bad in half a second — but says nothing about the next provider's |
| 404 | fall through immediately | Usually a retired model id: the case a backup exists for, and one no amount of waiting fixes |
| Other 4xx (400, 413, 422 …) | stop | The request was rejected on its merits; the backup will reject it identically |
| Context cancelled | stop | The caller has already given up |
By default each provider gets three attempts, with roughly 0.5s and 2s of backoff — so a blip costs a few seconds rather than the whole request. Backoff is exponential with full jitter: without it, every caller that hit the same outage retries in lockstep and arrives together the moment the provider returns.
A Retry-After header is honoured in place of the computed delay, but only up
to MaxRetryAfter (20s). Beyond that the chain falls through instead — a
provider asking you to wait two minutes is telling you to go elsewhere.
Retry never starves the fallback. Retry and fallback compete for one
budget, and a provider that hangs until its own timeout can spend nearly all of
it in a single attempt. Retrying it then consumes the remainder, and the chain
never reaches a backup that would have answered in a second — which is the
whole reason the chain exists. So a retry only happens when the caller's
deadline can also absorb another attempt afterwards, keeping
FallbackReserve (20s) back for the providers not yet tried. A caller with no
deadline has no budget to protect and retries normally.
chain.WithRetry(ai.RetryPolicy{
MaxAttempts: 4,
BaseDelay: 200 * time.Millisecond,
MaxDelay: 5 * time.Second,
MaxRetryAfter: 30 * time.Second,
})
chain.WithRetry(ai.NoRetry()) // one attempt per provider
chain.OnRetry(func(provider string, attempt int, delay time.Duration, err error) {
log.Warn("retrying", "provider", provider, "attempt", attempt, "in", delay, "err", err)
})Response.Retries reports how many retries the answering provider needed, so a
slot that is struggling is visible rather than showing up only as latency.
OnRetry fires per retry, OnFallback once per provider abandoned.
When every provider fails, the error names each one and why.
ai.go package doc, Request/Response/Message, the Provider interface
options.go functional options: WithBaseURL, WithModel, WithTimeout
chain.go Chain — ordered fallback and the per-provider attempt loop
retry.go RetryPolicy, jittered backoff, and the retry/fallthrough/fatal classifier
anthropic.go native Claude Messages client
openaicompat.go one client for every OpenAI-compatible endpoint
config.go Slot, environment-driven chain construction
json.go ExtractJSON — fence stripping, balanced scan, truncation repair
_examples/chain a runnable example
MIT