recursive/flint-v1.0:free lost its upstreams (OpenRouter 503 'no upstreams available'), so deployments that set only AI_API_KEY inherited a dead default. DefaultModel and the BYO suggested-model list now use slugs verified live on 2026-11-03; README/RUNNING examples updated. Deployments with an explicit AI_MODEL (dev, core) were unaffected.
460 lines
14 KiB
Go
460 lines
14 KiB
Go
// Package ai is the LLM gateway (AI features). Configuration is data,
|
|
// implementation is code:
|
|
//
|
|
// - IMPLEMENTATION: provider adapters (OpenAI-compatible — OpenRouter,
|
|
// OpenAI, Grok, Groq, Ollama, any house gateway — plus native Anthropic
|
|
// and Google Gemini), one shared netguard-dialed HTTP client, per-user
|
|
// outbound budgets, balanced-brace JSON extraction.
|
|
// - CONFIG: resolved per request via ResolveForUser — the user's own
|
|
// stored BYO config (UserAiConfig, key encrypted at rest) wins; the
|
|
// server env config (AI_API_KEY/AI_MODEL/AI_BASE_URL) is used only when
|
|
// the user's PLAN permits spending the operator's key
|
|
// (entitlements.AllowServerAI: premium/core/selfhosted — free and
|
|
// standard are bring-your-own-key, per the plan matrix).
|
|
//
|
|
// Rules: API keys live in env or encrypted rows, never in logs; provider
|
|
// error bodies are truncated before surfacing (they can reflect keys);
|
|
// model output is never trusted — callers parse via ExtractJSON + schema
|
|
// validation (see internal/agent).
|
|
package ai
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"net/url"
|
|
"os"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/andrew/superbrain/internal/config"
|
|
crypt "github.com/andrew/superbrain/internal/crypto"
|
|
"github.com/andrew/superbrain/internal/db"
|
|
"github.com/andrew/superbrain/internal/entitlements"
|
|
"github.com/andrew/superbrain/internal/netguard"
|
|
"github.com/andrew/superbrain/internal/outbound"
|
|
)
|
|
|
|
// DefaultModel is the fallback for the server env config (OpenRouter free
|
|
// tier). User configs always carry an explicit model. Free slugs rotate on
|
|
// OpenRouter (recursive/flint-v1.0:free lost its upstreams around 2026-11);
|
|
// when swapping this, probe /api/v1/models for ":free" ids first — and note
|
|
// deployments that set AI_MODEL explicitly are unaffected either way.
|
|
const DefaultModel = "nvidia/nemotron-3-ultra-550b-a55b:free"
|
|
|
|
const defaultOpenAIBase = "https://openrouter.ai/api/v1"
|
|
|
|
// Providers (UserAiConfig.provider CHECK mirrors this list).
|
|
const (
|
|
ProviderOpenAICompatible = "openai-compatible"
|
|
ProviderAnthropic = "anthropic"
|
|
ProviderGemini = "gemini"
|
|
)
|
|
|
|
func ValidProvider(p string) bool {
|
|
switch p {
|
|
case ProviderOpenAICompatible, ProviderAnthropic, ProviderGemini:
|
|
return true
|
|
}
|
|
return false
|
|
}
|
|
|
|
// ErrNoAI means neither a user BYO config nor a plan-permitted server key
|
|
// is available. Callers answer 428 with a pointer to Settings → AI.
|
|
var ErrNoAI = errors.New("ai: no configuration available for this user")
|
|
|
|
// Resolved is one usable endpoint. Source is "user" (BYO) or "server"
|
|
// (env); it feeds budget keys and the status endpoint, never prompts.
|
|
// Instructions carries the user's optional custom system instructions
|
|
// (BYO configs only; the server key has none). They apply to the in-app
|
|
// assistant persona — server-owned contracts (automation compiler, page
|
|
// extraction) must never include them.
|
|
type Resolved struct {
|
|
Provider string
|
|
BaseURL string
|
|
Model string
|
|
APIKey string
|
|
Instructions string
|
|
Source string
|
|
UserID string
|
|
}
|
|
|
|
// client dials through netguard for every provider (public ranges +
|
|
// 443/80 unless the operator pinned the host or allowed private ranges).
|
|
var client = &http.Client{
|
|
Timeout: 90 * time.Second,
|
|
Transport: &http.Transport{
|
|
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
|
if netguard.AllowPrivate() {
|
|
return netguard.DialContext(ctx, network, address)
|
|
}
|
|
return netguard.DialContextPorts(ctx, network, address, 80, 443)
|
|
},
|
|
IdleConnTimeout: 30 * time.Second,
|
|
MaxIdleConns: 8,
|
|
MaxIdleConnsPerHost: 4,
|
|
},
|
|
}
|
|
|
|
// ServerConfigured reports whether the env-level gateway is set (used by
|
|
// the status endpoint; whether a user may USE it is a plan question).
|
|
func ServerConfigured() bool { return strings.TrimSpace(os.Getenv("AI_API_KEY")) != "" }
|
|
|
|
func serverConfig() (Resolved, bool) {
|
|
key := strings.TrimSpace(os.Getenv("AI_API_KEY"))
|
|
if key == "" {
|
|
return Resolved{}, false
|
|
}
|
|
model := strings.TrimSpace(os.Getenv("AI_MODEL"))
|
|
if model == "" {
|
|
model = DefaultModel
|
|
}
|
|
base := strings.TrimRight(strings.TrimSpace(os.Getenv("AI_BASE_URL")), "/")
|
|
provider := strings.TrimSpace(os.Getenv("AI_PROVIDER"))
|
|
if provider == "" {
|
|
provider = ProviderOpenAICompatible
|
|
}
|
|
if base == "" {
|
|
switch provider {
|
|
case ProviderAnthropic:
|
|
base = "https://api.anthropic.com"
|
|
case ProviderGemini:
|
|
base = "https://generativelanguage.googleapis.com"
|
|
default:
|
|
base = defaultOpenAIBase
|
|
}
|
|
}
|
|
return Resolved{Provider: provider, BaseURL: base, Model: model, APIKey: key, Source: "server"}, true
|
|
}
|
|
|
|
// ResolveForUser applies the resolution chain: the user's enabled BYO
|
|
// config first, then the server key iff the user's plan may spend it.
|
|
func ResolveForUser(ctx context.Context, d *db.DB, userID string) (Resolved, error) {
|
|
var id, provider, baseURL, model, encKey, instructions string
|
|
var enabled bool
|
|
err := d.QueryRowContext(ctx,
|
|
`SELECT id, provider, "baseUrl", model, "apiKey", instructions, enabled FROM "UserAiConfig" WHERE "ownerId"=$1`,
|
|
userID).Scan(&id, &provider, &baseURL, &model, &encKey, &instructions, &enabled)
|
|
if err == nil && enabled && encKey != "" {
|
|
key, decErr := crypt.Decrypt(encKey, config.Load().EncryptionSecret())
|
|
if decErr != nil {
|
|
return Resolved{}, fmt.Errorf("ai: stored key cannot be decrypted; re-enter it in Settings: %w", decErr)
|
|
}
|
|
return Resolved{
|
|
Provider: provider, BaseURL: strings.TrimRight(baseURL, "/"),
|
|
Model: model, APIKey: key, Instructions: instructions,
|
|
Source: "user", UserID: userID,
|
|
}, nil
|
|
}
|
|
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
|
return Resolved{}, err
|
|
}
|
|
// Plan gate on the OPERATOR's key: free/standard tenants are BYO-only
|
|
// (entitlements.AllowServerAI), so a hosted instance never silently
|
|
// burns house credits for plans that promise "use your own AI".
|
|
var tenantID *string
|
|
if e := d.QueryRowContext(ctx, `SELECT "tenantId" FROM "User" WHERE id=$1`, userID).Scan(&tenantID); e != nil {
|
|
return Resolved{}, e
|
|
}
|
|
tid := ""
|
|
if tenantID != nil {
|
|
tid = *tenantID
|
|
}
|
|
plan, e := db.NewTenantRepo(d).Plan(ctx, tid)
|
|
if e != nil {
|
|
return Resolved{}, e
|
|
}
|
|
if r, ok := serverConfig(); ok && entitlements.AllowServerAI(plan) {
|
|
r.UserID = userID
|
|
return r, nil
|
|
}
|
|
return Resolved{}, ErrNoAI
|
|
}
|
|
|
|
// Message is one chat turn. Roles are normalized ("assistant" is accepted
|
|
// and mapped per provider, e.g. Gemini's "model").
|
|
type Message struct {
|
|
Role string `json:"role"`
|
|
Content string `json:"content"`
|
|
}
|
|
|
|
// Complete sends one system+user exchange through a resolved endpoint.
|
|
func Complete(ctx context.Context, r Resolved, system, user string) (string, error) {
|
|
return CompleteMessages(ctx, r, system, []Message{{Role: "user", Content: user}})
|
|
}
|
|
|
|
// CompleteMessages sends a multi-turn conversation with a server-owned
|
|
// system prompt. Callers cap the message count/size before calling.
|
|
func CompleteMessages(ctx context.Context, r Resolved, system string, msgs []Message) (string, error) {
|
|
if r.APIKey == "" {
|
|
return "", ErrNoAI
|
|
}
|
|
if len(msgs) == 0 {
|
|
return "", errors.New("ai: no messages")
|
|
}
|
|
// Per-user (BYO) or shared (server) budget: a slow provider must not
|
|
// pile up goroutines either way.
|
|
budgetKey := "ai:server"
|
|
if r.Source == "user" {
|
|
budgetKey = "ai:user:" + r.UserID
|
|
}
|
|
release, _, ok := outbound.Reserve(budgetKey, 10, time.Minute)
|
|
if !ok {
|
|
return "", errors.New("ai: busy, try again shortly")
|
|
}
|
|
defer release()
|
|
|
|
switch r.Provider {
|
|
case ProviderAnthropic:
|
|
return completeAnthropic(ctx, r, system, msgs)
|
|
case ProviderGemini:
|
|
return completeGemini(ctx, r, system, msgs)
|
|
default:
|
|
return completeOpenAI(ctx, r, system, msgs)
|
|
}
|
|
}
|
|
|
|
func completeOpenAI(ctx context.Context, r Resolved, system string, msgs []Message) (string, error) {
|
|
all := make([]map[string]string, 0, len(msgs)+1)
|
|
all = append(all, map[string]string{"role": "system", "content": system})
|
|
for _, m := range msgs {
|
|
role := m.Role
|
|
if role != "assistant" && role != "user" {
|
|
role = "user"
|
|
}
|
|
all = append(all, map[string]string{"role": role, "content": m.Content})
|
|
}
|
|
payload, err := json.Marshal(map[string]any{"model": r.Model, "messages": all})
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, r.BaseURL+"/chat/completions", bytes.NewReader(payload))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
req.Header.Set("Content-Type", "application/json")
|
|
req.Header.Set("Authorization", "Bearer "+r.APIKey)
|
|
body, status, err := do(req)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if status != 200 {
|
|
return "", providerError(status, body)
|
|
}
|
|
var out struct {
|
|
Choices []struct {
|
|
Message struct {
|
|
Content string `json:"content"`
|
|
} `json:"message"`
|
|
} `json:"choices"`
|
|
Error *struct {
|
|
Message string `json:"message"`
|
|
} `json:"error"`
|
|
}
|
|
if err := json.Unmarshal(body, &out); err != nil {
|
|
return "", fmt.Errorf("ai: unreadable provider response: %w", err)
|
|
}
|
|
if out.Error != nil {
|
|
return "", fmt.Errorf("ai: provider error: %s", truncate(out.Error.Message, 200))
|
|
}
|
|
if len(out.Choices) == 0 {
|
|
return "", errors.New("ai: provider returned no choices")
|
|
}
|
|
return out.Choices[0].Message.Content, nil
|
|
}
|
|
|
|
func completeAnthropic(ctx context.Context, r Resolved, system string, msgs []Message) (string, error) {
|
|
all := make([]map[string]string, 0, len(msgs))
|
|
for _, m := range msgs {
|
|
role := m.Role
|
|
if role != "assistant" && role != "user" {
|
|
role = "user"
|
|
}
|
|
all = append(all, map[string]string{"role": role, "content": m.Content})
|
|
}
|
|
payload, err := json.Marshal(map[string]any{
|
|
"model": r.Model,
|
|
"max_tokens": 1024,
|
|
"system": system,
|
|
"messages": all,
|
|
})
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, r.BaseURL+"/v1/messages", bytes.NewReader(payload))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
req.Header.Set("Content-Type", "application/json")
|
|
req.Header.Set("x-api-key", r.APIKey)
|
|
req.Header.Set("anthropic-version", "2023-06-01")
|
|
body, status, err := do(req)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if status != 200 {
|
|
return "", providerError(status, body)
|
|
}
|
|
var out struct {
|
|
Content []struct {
|
|
Type string `json:"type"`
|
|
Text string `json:"text"`
|
|
} `json:"content"`
|
|
Error *struct {
|
|
Message string `json:"message"`
|
|
} `json:"error"`
|
|
}
|
|
if err := json.Unmarshal(body, &out); err != nil {
|
|
return "", fmt.Errorf("ai: unreadable provider response: %w", err)
|
|
}
|
|
if out.Error != nil {
|
|
return "", fmt.Errorf("ai: provider error: %s", truncate(out.Error.Message, 200))
|
|
}
|
|
var text string
|
|
for _, c := range out.Content {
|
|
if c.Type == "text" {
|
|
text += c.Text
|
|
}
|
|
}
|
|
if text == "" {
|
|
return "", errors.New("ai: provider returned no text")
|
|
}
|
|
return text, nil
|
|
}
|
|
|
|
func completeGemini(ctx context.Context, r Resolved, system string, msgs []Message) (string, error) {
|
|
contents := make([]map[string]any, 0, len(msgs))
|
|
for _, m := range msgs {
|
|
role := "user"
|
|
if m.Role == "assistant" {
|
|
role = "model"
|
|
}
|
|
contents = append(contents, map[string]any{
|
|
"role": role,
|
|
"parts": []map[string]string{{"text": m.Content}},
|
|
})
|
|
}
|
|
payload, err := json.Marshal(map[string]any{
|
|
"system_instruction": map[string]any{"parts": []map[string]string{{"text": system}}},
|
|
"contents": contents,
|
|
})
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
// The key travels in a HEADER (x-goog-api-key), never the URL: Go's HTTP
|
|
// error strings include the full URL, and errors get logged.
|
|
endpoint := fmt.Sprintf("%s/v1beta/models/%s:generateContent", r.BaseURL, url.PathEscape(r.Model))
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(payload))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
req.Header.Set("Content-Type", "application/json")
|
|
req.Header.Set("x-goog-api-key", r.APIKey)
|
|
body, status, err := do(req)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if status != 200 {
|
|
return "", providerError(status, body)
|
|
}
|
|
var out struct {
|
|
Candidates []struct {
|
|
Content struct {
|
|
Parts []struct {
|
|
Text string `json:"text"`
|
|
} `json:"parts"`
|
|
} `json:"content"`
|
|
} `json:"candidates"`
|
|
Error *struct {
|
|
Message string `json:"message"`
|
|
} `json:"error"`
|
|
}
|
|
if err := json.Unmarshal(body, &out); err != nil {
|
|
return "", fmt.Errorf("ai: unreadable provider response: %w", err)
|
|
}
|
|
if out.Error != nil {
|
|
return "", fmt.Errorf("ai: provider error: %s", truncate(out.Error.Message, 200))
|
|
}
|
|
var text string
|
|
if len(out.Candidates) > 0 {
|
|
for _, p := range out.Candidates[0].Content.Parts {
|
|
text += p.Text
|
|
}
|
|
}
|
|
if text == "" {
|
|
return "", errors.New("ai: provider returned no text")
|
|
}
|
|
return text, nil
|
|
}
|
|
|
|
func do(req *http.Request) ([]byte, int, error) {
|
|
res, err := client.Do(req)
|
|
if err != nil {
|
|
return nil, 0, err
|
|
}
|
|
defer res.Body.Close()
|
|
body, err := io.ReadAll(io.LimitReader(res.Body, 4<<20))
|
|
return body, res.StatusCode, err
|
|
}
|
|
|
|
// providerError never echoes the full body: provider errors can reflect
|
|
// account details or the request's Authorization context.
|
|
func providerError(status int, body []byte) error {
|
|
return fmt.Errorf("ai: provider answered %d: %s", status, truncate(string(body), 200))
|
|
}
|
|
|
|
// ExtractJSON pulls the first balanced JSON object out of a model reply
|
|
// (models wrap JSON in prose or code fences despite instructions).
|
|
func ExtractJSON(s string) (json.RawMessage, error) {
|
|
if i := strings.Index(s, "```"); i >= 0 {
|
|
rest := s[i+3:]
|
|
if j := strings.Index(rest, "```"); j > 0 {
|
|
s = rest[:j]
|
|
}
|
|
}
|
|
start := strings.Index(s, "{")
|
|
if start < 0 {
|
|
return nil, errors.New("ai: no JSON object in model reply")
|
|
}
|
|
depth := 0
|
|
inStr := false
|
|
esc := false
|
|
for i := start; i < len(s); i++ {
|
|
c := s[i]
|
|
switch {
|
|
case inStr:
|
|
if esc {
|
|
esc = false
|
|
} else if c == '\\' {
|
|
esc = true
|
|
} else if c == '"' {
|
|
inStr = false
|
|
}
|
|
case c == '"':
|
|
inStr = true
|
|
case c == '{':
|
|
depth++
|
|
case c == '}':
|
|
depth--
|
|
if depth == 0 {
|
|
return json.RawMessage(s[start : i+1]), nil
|
|
}
|
|
}
|
|
}
|
|
return nil, errors.New("ai: unbalanced JSON in model reply")
|
|
}
|
|
|
|
func truncate(s string, n int) string {
|
|
rs := []rune(s)
|
|
if len(rs) <= n {
|
|
return s
|
|
}
|
|
return string(rs[:n])
|
|
}
|