catalog

package
v1.261022.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 21, 2026 License: MPL-2.0 Imports: 20 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

claude_model_catalog.go is the per-vendor model capability catalog: what each model can do, declared once per model family, independent of which provider serves it. It complements providers.json (see provider_catalog.go), the offering registry (who serves which model, at which endpoint, with what limits) — capability facts live here, deployment facts live there.

Layout: one <vendor>.models.json data file plus one <vendor>_model_catalog.go loader per vendor (claude.models.json + claude_model_catalog.go today; openai/gemini can follow the same pattern). Each file only carries the fields its loader actually consumes — deliberately not a mirror of the vendor's full /v1/models response, whose unused fields (display names, dates, unrelated capability flags) are dead weight.

The `reasoning` block's shape and field names (supported_efforts, ...) follow OpenRouter's model-list schema rather than Anthropic's own nested `capabilities.effort.<level>.supported` tree. One field has no OpenRouter equivalent: `dialects`. OpenRouter's clients never see wire-protocol differences between backends — OpenRouter's own proxy absorbs that. This package IS that proxy layer for Anthropic, so it has to know which raw request shape a model accepts: "budget" (thinking.type=enabled + budget_tokens) and/or "adaptive" (thinking.type=adaptive). `mandatory: true` (also an OpenRouter field) marks models that reject thinking.type=disabled. Models with no `reasoning` block at all do not support extended thinking.

Update the JSON when new models land instead of hardcoding model names in code; the completeness test in this package fails when providers.json offers a Claude model this catalog does not describe.

claude.models.snapshot.json is a separate, unmodified mirror of Anthropic's actual /v1/models response — the ground truth to cross-check claude.models.json against when adding or revising an entry. It is not embedded and no code reads it; it goes stale as new models ship (it currently covers 10 of the 19 models in claude.models.json — models added afterward had their reasoning capabilities inferred from the newest snapshot entry rather than sourced, see .design/model-data.md) and should be refreshed by hand from the live API when convenient, not on every edit.

Index

Constants

View Source
const CatalogCacheFileName = "provider_catalog.json"
View Source
const CatalogGitHubURL = "https://raw.githubusercontent.com/tingly-dev/tingly-box/main/internal/catalog/providers.json"
View Source
const DefaultCatalogCacheTTL = 12 * time.Hour // Default TTL for template cache
View Source
const DefaultCatalogHTTPTimeout = 30 * time.Second // Default HTTP timeout for fetching templates
View Source
const ModelCacheTTL = time.Hour

ModelCacheTTL is how long a cached model list is considered fresh. After this duration, GetModels returns empty so the caller re-fetches.

Variables

This section is empty.

Functions

func EmbeddedCatalogJSON added in v1.261006.2

func EmbeddedCatalogJSON() map[CatalogKind][]byte

EmbeddedCatalogJSON returns the catalog documents compiled into the binary.

func ValidateProviderCatalog

func ValidateProviderCatalog(tmpl *ProviderCatalog) error

ValidateProviderCatalog validates a provider template

Types

type CapabilitySchema

type CapabilitySchema struct {
	BuiltIn      bool         `json:"built_in"`
	ToolType     string       `json:"tool_type,omitempty"`
	ToolName     string       `json:"tool_name,omitempty"`
	DocURL       string       `json:"doc_url,omitempty"`
	ResultFormat ResultFormat `json:"result_format,omitempty"`
}

type CatalogCacheData

type CatalogCacheData struct {
	Registry ProviderCatalogRegistry `json:"registry"`
	CachedAt time.Time               `json:"cached_at"`
	Version  string                  `json:"version"`
	ETag     string                  `json:"etag,omitempty"`
}

CatalogCacheData represents the cache file structure

type CatalogKind added in v1.261006.2

type CatalogKind string

CatalogKind identifies which catalog a JSON document is.

const (
	// KindProviders is providers.json (the offering registry).
	KindProviders CatalogKind = "providers"
	// KindClaudeModels is claude.models.json (the Claude capability catalog).
	KindClaudeModels CatalogKind = "claude-models"
)

func DetectCatalogKind added in v1.261006.2

func DetectCatalogKind(data []byte) (CatalogKind, error)

DetectCatalogKind tells the catalogs apart by shape: providers.json is an object with a "providers" key, claude.models.json is a top-level array.

type CatalogSource

type CatalogSource int

CatalogSource tracks where templates were loaded from

const (
	// CatalogSourceGitHub - From GitHub templates
	CatalogSourceGitHub CatalogSource = iota
	// CatalogSourceLocal - From local embedded templates
	CatalogSourceLocal
)

type CatalogSourcePreference

type CatalogSourcePreference int

CatalogSourcePreference defines the priority order for loading templates

const (
	// PreferenceDefault: Cache -> GitHub -> Embedded
	PreferenceDefault CatalogSourcePreference = iota
	// PreferenceEmbedded: Embedded only (no network requests)
	PreferenceEmbedded
	// PreferenceEmbeddedFirst: Embedded -> Cache -> GitHub
	PreferenceEmbeddedFirst
)

type CheckIssue added in v1.261006.2

type CheckIssue struct {
	Catalog CatalogKind `json:"catalog"`
	// Subject is the provider or model the problem is about; empty for
	// document-level problems (e.g. unparseable JSON).
	Subject string `json:"subject,omitempty"`
	Message string `json:"message"`
}

CheckIssue is one validity problem found in a catalog.

func CheckCatalogs added in v1.261006.2

func CheckCatalogs(docs map[CatalogKind][]byte) []CheckIssue

CheckCatalogs runs every check over the given documents (keyed by kind): each catalog on its own, then consistency across them.

func CheckClaudeCatalogJSON added in v1.261006.2

func CheckClaudeCatalogJSON(data []byte) []CheckIssue

CheckClaudeCatalogJSON validates a claude.models.json document: strict decoding, unique non-empty ids, and known dialect / effort values.

func CheckCrossCatalog added in v1.261006.2

func CheckCrossCatalog(providersJSON, claudeJSON []byte) []CheckIssue

CheckCrossCatalog verifies that every Claude model offered by a provider in providers.json has an entry in the Claude capability catalog. Documents that failed to parse yield no cross-catalog issues (their own check reports why).

func CheckProviderCatalogJSON added in v1.261006.2

func CheckProviderCatalogJSON(data []byte) []CheckIssue

CheckProviderCatalogJSON validates a providers.json document: it must decode (type errors count), map key == id, ValidateProviderCatalog per provider, and model ids are unique and non-empty within each provider. Unknown fields are deliberately tolerated: providers.json carries reference-only metadata (sources, note, last_updated, ...) that Go drops by design.

func (CheckIssue) String added in v1.261006.2

func (i CheckIssue) String() string

type ClaudeThinkingCaps

type ClaudeThinkingCaps struct {
	// ThinkingEnabled: accepts thinking.type=enabled with budget_tokens.
	ThinkingEnabled bool
	// ThinkingAdaptive: accepts thinking.type=adaptive.
	ThinkingAdaptive bool
	// ThinkingMandatory: thinking cannot be turned off — the API rejects
	// thinking.type=disabled with a 400 asking for adaptive. Consumers must
	// send adaptive instead of disabling (see ops.ApplyAnthropic*ModelTransform).
	ThinkingMandatory bool
	// EffortLevels: supported output_config.effort values (e.g. "low", "max").
	// Empty means the model has no effort support.
	EffortLevels map[string]bool
}

ClaudeThinkingCaps describes which thinking dialects a cataloged Claude model accepts.

func LookupClaudeThinkingCaps

func LookupClaudeThinkingCaps(model string) (ClaudeThinkingCaps, bool)

LookupClaudeThinkingCaps resolves a model name to the catalog's thinking capabilities. The longest catalog key contained in the (lowercased) name wins; ok=false when the model is not in the catalog.

func (ClaudeThinkingCaps) SupportsEffort

func (c ClaudeThinkingCaps) SupportsEffort() bool

SupportsEffort reports whether the model accepts output_config.effort at all.

type ModelInfo

type ModelInfo struct {
	ID          string `json:"id"`
	Description string `json:"description,omitempty"`
	Context     int    `json:"context,omitempty"`
	MaxOutput   int    `json:"max_output,omitempty"`

	// OpenAIEndpoints declares which OpenAI endpoint(s) THIS model supports,
	// for a template whose catalog mixes vendors (OpenCode Zen: most models
	// are Chat-only, a few are Responses-only, and some may support both) —
	// a fact ProviderCatalog.OpenAIEndpointMode can't express since it's one
	// value per provider. A list rather than a single value so a model that
	// answers on both endpoints can say so, instead of only ever declaring
	// one. Empty means no declaration for this model: falls through exactly
	// as if this field didn't exist (defers to the provider default, which
	// resolves to Chat unless the provider itself declares otherwise). Static
	// and hand-maintained: an unlisted model just falls through to the
	// provider default (see .design/openai-endpoint-routing.md §10). Values:
	// any subset of "chat", "responses"; unrecognized entries are ignored so
	// a typo degrades to "no declaration" rather than a wrong route.
	OpenAIEndpoints []string `json:"openai_endpoints,omitempty"`
}

ModelInfo represents detailed information about a model

type ModelListManager

type ModelListManager struct {
	// contains filtered or unexported fields
}

ModelListManager manages models for different providers using SQLite database

func NewModelListManager

func NewModelListManager(store *db.ModelStore) *ModelListManager

NewModelListManager wraps the StoreManager's ModelStore. There is deliberately no constructor that opens its own connection: this manager used to do exactly that, giving the process a second connection pool (and a second AutoMigrate over provider_models) against the same tingly.db StoreManager had just opened. Closing is the StoreManager's job.

func (*ModelListManager) GetAllProviders

func (mm *ModelListManager) GetAllProviders() []string

GetAllProviders returns all provider UUIDs that have models

func (*ModelListManager) GetFetchFailure

func (mm *ModelListManager) GetFetchFailure(uid string) (string, bool)

GetFetchFailure returns the last recorded fetch error for a provider, if any.

func (*ModelListManager) GetLastUpdatedAt added in v1.261022.1

func (mm *ModelListManager) GetLastUpdatedAt(uid string) (time.Time, bool)

GetLastUpdatedAt returns when the provider's list was last saved.

func (*ModelListManager) GetModels

func (mm *ModelListManager) GetModels(uid string) []string

GetModels returns models for a provider by reading from database. Returns empty if the cached record is older than ModelCacheTTL.

func (*ModelListManager) GetProviderInfo

func (mm *ModelListManager) GetProviderInfo(uid string) (apiBase string, lastUpdated string, exists bool)

GetProviderInfo returns basic info about a provider by reading from database

func (*ModelListManager) GetStaleModels added in v1.261022.1

func (mm *ModelListManager) GetStaleModels(uid string) []string

GetStaleModels returns the last stored model list regardless of age. It is the fallback for when a refetch of an expired list fails: the previous real list beats an embedded template or nothing.

func (*ModelListManager) HasModels

func (mm *ModelListManager) HasModels(providerUUID string) bool

HasModels checks if a provider has models in the database

func (*ModelListManager) InvalidateModels added in v1.261022.1

func (mm *ModelListManager) InvalidateModels(uid string) error

InvalidateModels marks the cached list stale so the next read re-queries upstream; the list itself is kept as the stale fallback.

func (*ModelListManager) RemoveProvider

func (mm *ModelListManager) RemoveProvider(providerUUID string) error

RemoveProvider removes a provider's models from the database

func (*ModelListManager) SaveFetchFailure

func (mm *ModelListManager) SaveFetchFailure(provider *typ.Provider, lastErr string, raw json.RawMessage) error

SaveFetchFailure records a fetch error without clobbering an existing model list. raw is optional (the upstream body, when available).

func (*ModelListManager) SaveModels

func (mm *ModelListManager) SaveModels(provider *typ.Provider, models []string, source db.ModelSource) error

SaveModels saves models for a provider by UUID to the database. source should be db.ModelSourceAPI or db.ModelSourceTemplate.

func (*ModelListManager) SaveModelsWithRaw

func (mm *ModelListManager) SaveModelsWithRaw(provider *typ.Provider, models []string, source db.ModelSource, raw json.RawMessage) error

SaveModelsWithRaw saves a successful real upstream fetch (model list + raw payload) and clears any prior error fields.

type NamingRules

type NamingRules struct {
	KeyFormat      string `json:"key_format"`
	SlugRule1      string `json:"slug_rule_1,omitempty"`
	SlugRule2      string `json:"slug_rule_2,omitempty"`
	SlugRule3      string `json:"slug_rule_3,omitempty"`
	Variant        string `json:"variant,omitempty"`
	RequiredFields struct {
		CanonicalDomain string `json:"canonical_domain"`
		VendorFamily    string `json:"vendor_family"`
		Region          string `json:"region"`
		Plan            string `json:"plan"`
		ModelsSchema    string `json:"models_schema"`
	} `json:"required_fields"`
}

NamingRules defines the naming conventions for provider IDs

type ProviderCatalog

type ProviderCatalog struct {
	// Core identification
	ID      string `json:"id"`
	Name    string `json:"name"`
	Alias   string `json:"alias,omitempty"` // Display name with locale information
	Status  string `json:"status"`          // "active", "deprecated", etc.
	Valid   bool   `json:"valid"`
	Website string `json:"website"`

	// NEW: Structured metadata (Schema V2)
	CanonicalDomain string `json:"canonical_domain"` // API host (e.g., "api.anthropic.com")
	VendorFamily    string `json:"vendor_family"`    // Vendor aggregation key (e.g., "anthropic", "alibaba")
	Region          string `json:"region"`           // "cn" | "intl" | "global"
	Plan            string `json:"plan"`             // "standard" | "coding" | "oauth"

	Description string `json:"description"`

	// Documentation
	APIDoc     string `json:"api_doc"`
	ModelDoc   string `json:"model_doc"`
	PricingDoc string `json:"pricing_doc"`

	// API endpoints
	BaseURLOpenAI    string `json:"base_url_openai,omitempty"`
	BaseURLAnthropic string `json:"base_url_anthropic,omitempty"`

	// APIStyle explicitly declares the provider protocol ("openai" | "anthropic"
	// | "google"). Optional: when empty the style is inferred from which base URL
	// is set. Cloud templates that share a canonical_domain but differ by model
	// family (Vertex Claude vs Vertex Gemini) set this so template matching can
	// disambiguate them by the provider's APIStyle.
	APIStyle string `json:"api_style,omitempty"`

	// CHANGED: Models now include context/max_output directly (Schema V2)
	Models []ModelInfo `json:"models"`

	SupportsModelsEndpoint bool `json:"supports_models_endpoint"`

	// Authentication
	AuthType      string `json:"auth_type,omitempty"`      // "oauth", "key"
	OAuthProvider string `json:"oauth_provider,omitempty"` // OAuth provider type for oauth type providers

	// Capabilities
	WebSearchSchema string `json:"web_search_schema,omitempty"` // Reference to capability schema for web_search
	Icon            string `json:"icon,omitempty"`              // Icon identifier (e.g., "openai", "anthropic") for Lobe Icons

	// Capacity configuration for TacticCapacityBased load balancing
	// TotalCapacity is the total seat count for this provider (shared across all models)
	TotalCapacity *int `json:"total_capacity,omitempty"`
	// DefaultModelCapacity is the default seat count per model (template)
	// Each model inherits this unless overridden
	DefaultModelCapacity *int `json:"default_model_capacity,omitempty"`
	// ModelCapacities allows per-model capacity overrides
	ModelCapacities map[string]int `json:"model_capacities,omitempty"` // model name -> capacity

	// OpenAIEndpointMode declares which OpenAI endpoints providers instantiated
	// from this template expose. Plain string at this layer; cast to the typed
	// ai.OpenAIEndpointMode when assigned to a Provider. Values: "" (Chat,
	// default), "responses" (Codex-style), "both" (OpenAI proper).
	OpenAIEndpointMode string `json:"openai_endpoint_mode,omitempty"`
}

ProviderCatalog represents a predefined provider configuration template

type ProviderCatalogManager

type ProviderCatalogManager struct {
	// contains filtered or unexported fields
}

ProviderCatalogManager manages provider templates with -tier fallback

func NewProviderCatalogManager

func NewProviderCatalogManager(opts ...ProviderCatalogManagerOption) *ProviderCatalogManager

NewProviderCatalogManager creates a new provider catalog manager. With no options it uses only the embedded catalog — no network or cache I/O — since an unset githubURL makes Initialize skip straight to embedded templates regardless of source preference. Pass WithGitHubURL to opt into syncing from GitHub (CatalogGitHubURL for the real catalog, or a test double).

func (*ProviderCatalogManager) FetchTemplates

FetchTemplates fetches templates from URL (http://, https://, or file://)

func (*ProviderCatalogManager) GetAllTemplates

func (tm *ProviderCatalogManager) GetAllTemplates() map[string]*ProviderCatalog

GetAllTemplates returns all templates

func (*ProviderCatalogManager) GetEmbeddedModelsForProvider

func (tm *ProviderCatalogManager) GetEmbeddedModelsForProvider(provider *typ.Provider) ([]string, error)

GetEmbeddedModelsForProvider returns models from the compile-time embedded providers.json, bypassing any disk cache. Use this for fallback paths where the provider API is unavailable, so the result is always the binary's built-in defaults rather than a potentially stale cache.

func (*ProviderCatalogManager) GetMaxTokensForModel

func (tm *ProviderCatalogManager) GetMaxTokensForModel(provider, model string) int

GetMaxTokensForModel returns the maximum allowed tokens for a specific model using the provider templates. If templates are not available, falls back to the global default. It checks in order: 1. Exact match in Models array (ModelInfo.MaxOutput) 2. ModelCapacities override (for capacity-based limits) 3. Global default

func (*ProviderCatalogManager) GetMaxTokensForModelByProvider

func (tm *ProviderCatalogManager) GetMaxTokensForModelByProvider(provider *typ.Provider, model string) int

GetMaxTokensForModelByProvider returns the maximum allowed tokens for a specific model using the provider templates matched by APIBase or OAuthProvider. This is the preferred method as it correctly matches templates regardless of user-defined provider name.

func (*ProviderCatalogManager) GetModelInfoForProvider added in v1.261022.1

func (tm *ProviderCatalogManager) GetModelInfoForProvider(provider *typ.Provider, model string) (ModelInfo, bool)

GetModelInfoForProvider returns the catalog entry for model on the template matched to provider (by APIBase / OAuth issuer / cloud identity, never by the user-defined provider name).

func (*ProviderCatalogManager) GetModelsForProvider

func (tm *ProviderCatalogManager) GetModelsForProvider(provider *typ.Provider) ([]string, CatalogSource, error)

GetModelsForProvider returns models for a provider using template-only hierarchy: 1. GitHub/embedded templates with models list Note: API-based model fetching is now handled by the client layer (client.ModelLister) This method only returns static models from templates

func (*ProviderCatalogManager) GetOpenAIEndpointOverrideForModel

func (tm *ProviderCatalogManager) GetOpenAIEndpointOverrideForModel(provider *typ.Provider, model string) ai.OpenAIEndpointMode

GetOpenAIEndpointOverrideForModel looks up ModelInfo.OpenAIEndpoints for this model on this provider's template and returns the mode it declares. ai.EndpointModeUnknown means no declaration — resolve exactly as if this function didn't exist. Matched by template like GetMaxTokensForModelByProvider, so it works regardless of the provider's display name.

func (*ProviderCatalogManager) GetTemplate

func (tm *ProviderCatalogManager) GetTemplate(id string) (*ProviderCatalog, error)

GetTemplate returns a provider template by ID

func (*ProviderCatalogManager) GetVersion

func (tm *ProviderCatalogManager) GetVersion() string

GetVersion returns the current template version

func (*ProviderCatalogManager) GetWebSearchSchemaForProvider

func (tm *ProviderCatalogManager) GetWebSearchSchemaForProvider(provider *typ.Provider) *CapabilitySchema

GetWebSearchSchemaForProvider returns the web search capability schema for a provider Returns nil if the provider doesn't have web_search_schema defined or the schema doesn't exist

func (*ProviderCatalogManager) Initialize

func (tm *ProviderCatalogManager) Initialize(ctx context.Context) error

Initialize loads templates according to the source preference: - PreferenceDefault: Cache -> GitHub -> Embedded - PreferenceEmbedded: Embedded only (no network requests) - PreferenceEmbeddedFirst: Embedded -> Cache -> GitHub

func (*ProviderCatalogManager) ProviderHasBuiltInWebSearch

func (tm *ProviderCatalogManager) ProviderHasBuiltInWebSearch(provider *typ.Provider) bool

ProviderHasBuiltInWebSearch checks if a provider has built-in web_search capability Returns true if the provider has a web_search_schema with BuiltIn=true

type ProviderCatalogManagerOption

type ProviderCatalogManagerOption func(*ProviderCatalogManager)

ProviderCatalogManagerOption configures a ProviderCatalogManager at construction time.

func EmbeddedOnly

func EmbeddedOnly() ProviderCatalogManagerOption

EmbeddedOnly restricts the manager to embedded templates only, with no GitHub sync. Behaviorally the same as the zero-value default (no WithGitHubURL), but states that intent explicitly for callers — tests and offline/development scenarios that must never touch the network or the on-disk cache, and want that guaranteed even if the default ever changes.

func WithGitHubURL

func WithGitHubURL(url string) ProviderCatalogManagerOption

WithGitHubURL sets where the manager syncs templates from. Unset (the default), it means no GitHub sync — embedded templates only.

func WithSourcePreference

func WithSourcePreference(preference CatalogSourcePreference) ProviderCatalogManagerOption

WithSourcePreference sets the priority order for loading templates (Cache -> GitHub -> Embedded by default; see CatalogSourcePreference).

type ProviderCatalogRegistry

type ProviderCatalogRegistry struct {
	SchemaVersion     int                          `json:"_schema_version"`
	NamingRules       *NamingRules                 `json:"_naming_rules,omitempty"`
	Providers         map[string]*ProviderCatalog  `json:"providers"`
	CapabilitySchemas map[string]*CapabilitySchema `json:"capability_schemas,omitempty"`
	Version           string                       `json:"version"`
	LastUpdated       string                       `json:"last_updated"`
}

ProviderCatalogRegistry represents the provider template registry structure from GitHub

type ResultFormat

type ResultFormat struct {
	Type        string                 `json:"type"`
	Description string                 `json:"description,omitempty"`
	Structure   map[string]interface{} `json:"structure,omitempty"`
}

ResultFormat describes how to format tool results

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL