Add Qwen3.8-27B to the default LITELLM_MODELS allowlist for per-tenant LiteLLM keys. Existing keys are updated separately via LiteLLM /key/update. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FKb71CELE4iptE9em1ZEgv
200 lines
5.5 KiB
Go
200 lines
5.5 KiB
Go
// Package llmkeys is the LiteLLM key-management client (D6): when the
|
|
// registry issues a Werkpilot licence it also provisions a per-tenant
|
|
// LiteLLM virtual key (POST /key/generate) with a monthly budget by plan and
|
|
// deletes it again on revoke (POST /key/delete).
|
|
//
|
|
// Authentication is the proxy master key (`Authorization: Bearer <key>`).
|
|
// The client is disabled — Enabled() false — when no master key is set;
|
|
// grants then carry no LLM key.
|
|
package llmkeys
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
const (
|
|
DefaultBaseURL = "https://llm.breakpilot.com"
|
|
DefaultBudgetDuration = "30d"
|
|
DefaultBudgetTrial = 5.0
|
|
DefaultBudgetDefault = 50.0
|
|
)
|
|
|
|
// DefaultModels are the models tenant keys may call.
|
|
var DefaultModels = []string{"Qwen3-Coder-30B-A3B-Instruct", "gpt-oss-120b", "Qwen3.8-27B"}
|
|
|
|
// ErrDisabled — no master key configured.
|
|
var ErrDisabled = errors.New("llmkeys: disabled (no master key)")
|
|
|
|
// ErrUnavailable wraps transport / 5xx failures.
|
|
var ErrUnavailable = errors.New("llmkeys: unavailable")
|
|
|
|
type Config struct {
|
|
BaseURL string
|
|
MasterKey string
|
|
Models []string
|
|
// USD per BudgetDuration window.
|
|
BudgetTrial float64
|
|
BudgetDefault float64
|
|
BudgetDuration string
|
|
Timeout time.Duration
|
|
}
|
|
|
|
type Client struct {
|
|
cfg Config
|
|
http *http.Client
|
|
}
|
|
|
|
// New returns a client; Enabled() is false when MasterKey is empty.
|
|
func New(cfg Config) *Client {
|
|
if cfg.BaseURL == "" {
|
|
cfg.BaseURL = DefaultBaseURL
|
|
}
|
|
cfg.BaseURL = strings.TrimRight(cfg.BaseURL, "/")
|
|
if len(cfg.Models) == 0 {
|
|
cfg.Models = append([]string(nil), DefaultModels...)
|
|
}
|
|
if cfg.BudgetTrial <= 0 {
|
|
cfg.BudgetTrial = DefaultBudgetTrial
|
|
}
|
|
if cfg.BudgetDefault <= 0 {
|
|
cfg.BudgetDefault = DefaultBudgetDefault
|
|
}
|
|
if cfg.BudgetDuration == "" {
|
|
cfg.BudgetDuration = DefaultBudgetDuration
|
|
}
|
|
if cfg.Timeout <= 0 {
|
|
cfg.Timeout = 10 * time.Second
|
|
}
|
|
return &Client{cfg: cfg, http: &http.Client{Timeout: cfg.Timeout}}
|
|
}
|
|
|
|
func (c *Client) Enabled() bool { return c != nil && c.cfg.MasterKey != "" }
|
|
|
|
// BaseURL is what tenants call (the OpenAI-compatible proxy root).
|
|
func (c *Client) BaseURL() string {
|
|
if c == nil {
|
|
return ""
|
|
}
|
|
return c.cfg.BaseURL
|
|
}
|
|
|
|
func (c *Client) Models() []string { return append([]string(nil), c.cfg.Models...) }
|
|
|
|
// Budget returns the monthly USD cap for a tenant: trial or default.
|
|
func (c *Client) Budget(trial bool) float64 {
|
|
if trial {
|
|
return c.cfg.BudgetTrial
|
|
}
|
|
return c.cfg.BudgetDefault
|
|
}
|
|
|
|
func (c *Client) BudgetDuration() string { return c.cfg.BudgetDuration }
|
|
|
|
// GenerateRequest — the /key/generate body subset we use.
|
|
type GenerateRequest struct {
|
|
KeyAlias string `json:"key_alias"`
|
|
Models []string `json:"models"`
|
|
MaxBudget float64 `json:"max_budget"`
|
|
BudgetDuration string `json:"budget_duration"`
|
|
Metadata map[string]any `json:"metadata,omitempty"`
|
|
TeamID string `json:"team_id,omitempty"`
|
|
Duration string `json:"duration,omitempty"` // key expiry, e.g. "30d"; empty ⇒ never
|
|
}
|
|
|
|
// Key — the secret (returned once) and the hashed token LiteLLM uses as the
|
|
// key's identifier (safe to persist; needed for /key/delete).
|
|
type Key struct {
|
|
Key string
|
|
TokenID string
|
|
}
|
|
|
|
// Generate provisions a virtual key.
|
|
func (c *Client) Generate(ctx context.Context, req GenerateRequest) (Key, error) {
|
|
if !c.Enabled() {
|
|
return Key{}, ErrDisabled
|
|
}
|
|
var out struct {
|
|
Key string `json:"key"`
|
|
Token string `json:"token"`
|
|
TokenID string `json:"token_id"`
|
|
}
|
|
if err := c.post(ctx, "/key/generate", req, &out); err != nil {
|
|
return Key{}, err
|
|
}
|
|
id := out.Token
|
|
if id == "" {
|
|
id = out.TokenID
|
|
}
|
|
if out.Key == "" || id == "" {
|
|
return Key{}, fmt.Errorf("llmkeys: /key/generate response lacks key/token")
|
|
}
|
|
return Key{Key: out.Key, TokenID: id}, nil
|
|
}
|
|
|
|
// Delete removes a key by its hashed token (or the sk-… secret). A key that
|
|
// is already gone (404) is not an error.
|
|
func (c *Client) Delete(ctx context.Context, tokenID string) error {
|
|
if !c.Enabled() {
|
|
return ErrDisabled
|
|
}
|
|
if tokenID == "" {
|
|
return nil
|
|
}
|
|
err := c.post(ctx, "/key/delete", map[string]any{"keys": []string{tokenID}}, nil)
|
|
var se *StatusError
|
|
if errors.As(err, &se) && se.Code == http.StatusNotFound {
|
|
return nil
|
|
}
|
|
return err
|
|
}
|
|
|
|
// StatusError — a non-2xx reply from LiteLLM.
|
|
type StatusError struct {
|
|
Code int
|
|
Body string
|
|
}
|
|
|
|
func (e *StatusError) Error() string {
|
|
return fmt.Sprintf("llmkeys: litellm responded %d: %s", e.Code, e.Body)
|
|
}
|
|
|
|
func (c *Client) post(ctx context.Context, path string, body any, out any) error {
|
|
buf, err := json.Marshal(body)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.cfg.BaseURL+path, bytes.NewReader(buf))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
req.Header.Set("Authorization", "Bearer "+c.cfg.MasterKey)
|
|
req.Header.Set("Content-Type", "application/json")
|
|
req.Header.Set("Accept", "application/json")
|
|
resp, err := c.http.Do(req)
|
|
if err != nil {
|
|
return fmt.Errorf("%w: %v", ErrUnavailable, err)
|
|
}
|
|
defer func() { _ = resp.Body.Close() }()
|
|
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
|
if resp.StatusCode >= 500 {
|
|
return fmt.Errorf("%w: %d %s", ErrUnavailable, resp.StatusCode, strings.TrimSpace(string(raw)))
|
|
}
|
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
|
return &StatusError{Code: resp.StatusCode, Body: strings.TrimSpace(string(raw))}
|
|
}
|
|
if out != nil {
|
|
if err := json.Unmarshal(raw, out); err != nil {
|
|
return fmt.Errorf("llmkeys: decode %s: %w", path, err)
|
|
}
|
|
}
|
|
return nil
|
|
}
|