Documentation
¶
Overview ¶
Package llmfactory constructs provider models from configuration, resolves assistant→model preferences (with optional per-organization overrides), and supports capability filtering and per-org model restrictions.
It is the only place in the module that knows how to build a provider client, so application code and assistants stay provider-agnostic.
1. Configuration ¶
Providers, defaults and assistant mappings are declared in YAML. String values support env:// and file:// expansion, so tokens stay out of the file.
default_provider: OPENAI
providers:
- name: OPENAI
token: env://OPENAI_API_KEY
default_model: gpt-5.1
available_models: [gpt-5.1, gpt-5.1-mini]
open_ai:
api_type: OPENAI
- name: ANTHROPIC
token: env://ANTHROPIC_API_KEY
default_model: claude-sonnet-4-8
available_models: [claude-opus-4-8, claude-sonnet-4-8]
open_ai:
api_type: ANTHROPIC
assistant_models:
default: [OPENAI/gpt-5.1]
coder: [OPENAI/gpt-5.1, ANTHROPIC/claude-opus-4-8]
orgs_override:
"1000":
assistant_models:
default: [OPENAI/gpt-5.1-mini]
open_ai.api_type selects the provider family and therefore the capability set: OPENAI|AZURE|AZURE_AD|OPENROUTER|PERPLEXITY|OPENAI_BEDROCK|ANTHROPIC| ANTHROPIC_BEDROCK|BEDROCK|GOOGLEAI|CLOUDFLARE.
2. Load and resolve a model ¶
fac, err := llmfactory.Load("llm.yaml")
if err != nil {
return err
}
// Resolve the model configured for the "coder" assistant, falling back to
// assistant_models.default and then to the default provider's default_model.
model, err := fac.GetModel(ctx, llmfactory.ModelOptions{AssistantName: "coder"})
assistants.Assistant calls GetModel with its own Name() and the org ID from the chatmodel.ChatContext, so naming an assistant is what binds it to an assistant_models entry.
3. Require capabilities ¶
RequiredCapabilities is an all-of mask: only providers whose type supports every requested capability are considered. This is stricter than llms.ProviderType.Supports, which reports whether any requested bit is set.
model, err := fac.GetModel(ctx, llmfactory.ModelOptions{
AssistantName: "coder",
RequiredCapabilities: llms.CapabilityJSONSchema |
llms.CapabilityFunctionCalling,
})
4. Restrict models per organization ¶
A ModelFilterFunc is consulted for every candidate, including the default-model fallback. Use it for quota, entitlements or cost policy.
filter := func(ctx context.Context, orgID, assistantName, modelName string) bool {
if orgID == "free-tier" && strings.Contains(modelName, "opus") {
return false // block expensive models for this org
}
return true
}
fac := llmfactory.New(cfg, llmfactory.WithModelFilter(filter))
// or derive a restricted factory that shares the client caches:
tenantFactory := fac.WithModelFilter(filter)
The assistantName argument is normalized to "default" when empty, and modelName may arrive bare or provider-qualified as "PROVIDER/model". It is always a concrete model ID, never a pattern, and carries no effort suffix.
5. Effort, patterns and the deny-list ¶
A model reference is [PROVIDER/]MODEL[,EFFORT]. The effort after the comma (none, low, medium, high, xhigh or max) is used when a call does not set one with WithReasoningEffort. "*" and "?" turn a model name into a pattern.
providers:
- name: ANTHROPIC
token: env://ANTHROPIC_API_KEY
default_model: claude-sonnet-4-8,medium
available_models:
- claude-opus-4-8,high
- claude-sonnet-4-8
- claude-haiku-*,low
disabled_models:
- "*-preview"
max_effort: xhigh
open_ai:
api_type: ANTHROPIC
assistant_models:
coder:
- ANTHROPIC/claude-sonnet-*,high
available_models stays the allow-list, disabled_models wins over it, and max_effort caps every call to the provider. A pattern in assistant_models selects the best match among the models listed by name in available_models. Each level is sent as the nearest one the selected model accepts.
LoadConfig validates the references and effort levels. New cannot fail, so for a Config built in code call Config.Validate first.
6. Model discovery ¶
Providers retire models and ship new ones. With a discovery section the factory reads the model list from the provider (OPENAI, OPENROUTER, ANTHROPIC and GOOGLEAI), so that a pattern selects models nobody listed and a model the provider no longer serves gives way to the newest allowed model of its family. Without the section nothing changes.
providers:
- name: ANTHROPIC
token: env://ANTHROPIC_API_KEY
default_model: claude-sonnet-*,medium
available_models:
- claude-fable-*,high
- claude-sonnet-*
discovery:
enabled: true
refresh: 6h
open_ai:
api_type: ANTHROPIC
assistant_models:
coder:
- ANTHROPIC/claude-fable-5-1
When the provider retires claude-fable-5-1, "coder" resolves to the newest model that claude-fable-* allows. available_models stays the only grant of access. The list is fetched on first use and refreshed in the background; a failed fetch keeps the last list and never fails GetModel.
Resolve reports what a reference selects right now, without building a client, and RefreshModels reads the lists on demand:
res, err := llmfactory.Resolve(ctx, fac, llmfactory.ModelOptions{AssistantName: "coder"})
if err != nil {
return err
}
// res.Model "claude-fable-5-2", res.Reason llmfactory.ReasonFamily
See Documentation/llm-factory.md for the full resolution rules, the effort mapping per provider, the skills section, and testing hooks such as the overridable NewLLM and NewModelLister variables.
Index ¶
- Variables
- func CreateLLM(cfg *ProviderConfig, preferredModels []string, opts *Options) (llms.Model, error)
- func CreateModelLister(cfg *ProviderConfig, opts *Options) (llms.ModelLister, error)
- func RefreshModels(ctx context.Context, f Factory) error
- func ResolveExact(ctx context.Context, f Factory, provider, model, orgID string) (llms.Model, error)
- type Catalog
- type Config
- type DiscoveryConfig
- type ExactResolver
- type Factory
- type HTTPClient
- type ModelFilterFunc
- type ModelOptions
- type OpenAIConfig
- type Option
- type Options
- type OrgConfig
- type ProviderConfig
- type Resolution
- type ResolutionReason
Constants ¶
This section is empty.
Variables ¶
var ErrModelNotFound = errors.New("model not found")
ErrModelNotFound indicates that an exact model is absent or not allowed.
var NewLLM = CreateLLM
NewLLM is a wrapper for CreateLLM to allow for overriding the default implementation.
var NewModelLister = CreateModelLister
NewModelLister is a wrapper for CreateModelLister to allow for overriding the default implementation. The factory calls it once per provider with discovery, on the first fetch of its model list.
Functions ¶
func CreateLLM ¶ added in v0.7.36
CreateLLM builds a provider client from its configuration, choosing the first of preferredModels that the provider offers and falling back to its default model. The provider family is selected by cfg.OpenAI.APIType; an unknown type returns an error.
Assign to the NewLLM variable to substitute this in tests.
func CreateModelLister ¶ added in v1.0.173
func CreateModelLister(cfg *ProviderConfig, opts *Options) (llms.ModelLister, error)
CreateModelLister builds the client that lists the models of a provider, from the same configuration and options as its model clients. The provider family is selected by cfg.OpenAI.APIType; a type that does not advertise llms.CapabilityModels returns llms.ErrModelListNotSupported.
Assign to the NewModelLister variable to substitute this in tests.
func RefreshModels ¶ added in v1.0.173
RefreshModels reads the model list of every provider with discovery now, to warm a factory at start-up or to pick up a provider change at once. It requires a factory that implements Catalog.
Types ¶
type Catalog ¶ added in v1.0.173
type Catalog interface {
// Resolve reports the model GetModel selects for the options, without
// building a client. It answers what a pattern or a retired model means
// right now.
Resolve(ctx context.Context, opts ModelOptions) (*Resolution, error)
// Refresh reads the model list of every provider with discovery now and
// waits for them. A list that cannot be read stays as it was; the errors
// are returned joined.
Refresh(ctx context.Context) error
}
Catalog is an optional factory extension for the providers whose model list is read: it shows what a resolution selects, and reads the lists on demand. Assert it on a Factory, or use Resolve and RefreshModels.
type Config ¶
type Config struct {
// Providers specifies the list of providers to use
Providers []*ProviderConfig `json:"providers" yaml:"providers"`
// DefaultProvider specifies the default provider to use
DefaultProvider string `json:"default_provider" yaml:"default_provider"`
// AssistantModels specifies the mapping of assistants to models.
// key is the assistant name, value is the list of model references to
// try in order. A reference is [<provider>/]<model>[,<effort>]: the
// provider is a provider name or an upper-case provider type, the model
// may be a pattern with "*" and "?", and the effort is the default
// reasoning effort for that assistant.
// Use `default: <model_name>` as the default model for assistants.
AssistantModels map[string][]string `json:"assistant_models" yaml:"assistant_models"`
// Orgs specifies the organizations configuration to override the global configuration.
Orgs map[string]*OrgConfig `json:"orgs_override" yaml:"orgs_override"`
// Skills specifies the skills configuration.
Skills *skills.Config `json:"skills,omitempty" yaml:"skills,omitempty"`
}
Config is the top-level factory configuration for providers, defaults, assistant→model mappings and optional per‑org overrides and skills.
func (*Config) Validate ¶ added in v1.0.173
Validate checks the model references, effort levels and model policy of the configuration, and returns every problem found. LoadConfig calls it, so a configuration file with a mistyped effort or an unusable default model fails at load time instead of being skipped silently during resolution.
type DiscoveryConfig ¶ added in v1.0.173
type DiscoveryConfig struct {
// Enabled turns discovery on.
Enabled bool `json:"enabled" yaml:"enabled"`
// Refresh is how long a fetched list is trusted, as a duration string
// such as "6h". Empty means one hour; the minimum is one minute.
Refresh string `json:"refresh,omitempty" yaml:"refresh,omitempty"`
}
DiscoveryConfig controls reading the model list from a provider. It is accepted for the provider types that advertise llms.CapabilityModels: OPENAI, OPENROUTER, ANTHROPIC and GOOGLEAI.
type ExactResolver ¶ added in v0.21.160
type ExactResolver interface {
// GetModelExact resolves one provider/model under current organization filtering.
GetModelExact(ctx context.Context, provider, model, orgID string) (llms.Model, error)
}
ExactResolver is an optional factory extension that never falls back. Provider must identify one configured provider; model names may contain slashes.
type Factory ¶
type Factory interface {
// WithModelFilter sets a predicate used to restrict which models an org may use.
// Returns a new Factory with the filter applied.
WithModelFilter(filter ModelFilterFunc) Factory
// GetModel returns an LLM model that matches the given options.
//
// Resolution rules:
// - When ProviderType is set, a provider of that type is selected.
// - Otherwise, when AssistantName is set, the configured assistant model
// mapping (optionally per-org) is expanded into the preferred models.
// - The preferred models are tried in order; the first available and
// allowed model wins. An entry may be a pattern and may carry a
// default reasoning effort, as in "ANTHROPIC/claude-opus-*,high".
// - If no preferred model matches, the default model is returned.
//
// RequiredCapabilities, when non-zero, restricts the candidates to
// providers whose type supports ALL of the requested capabilities.
GetModel(ctx context.Context, opts ModelOptions) (llms.Model, error)
// Skills returns all loaded skills for the given agent sorted alphabetically by name.
// Use tags to filter skills by tags. The Skill must have all the tags provided.
Skills(agent string, tags ...string) skills.Skills
}
Factory is the interface for creating and managing LLM models. In multi-tenant environments, the OrgID is used to determine the LLM model to use for the organization. The factory can also be provided with a ModelFilterFunc to restrict which models an organization may use.
type HTTPClient ¶ added in v0.16.114
HTTPClient is primarily used to describe an *http.Client, but also supports custom implementations.
For bespoke implementations, prefer using an *http.Client with a custom transport. See http.RoundTripper for further information.
type ModelFilterFunc ¶ added in v0.19.141
type ModelFilterFunc func(ctx context.Context, orgID string, assistantName string, modelName string) bool
ModelFilterFunc reports whether the given model may be used for the org. Provide this to enforce per-org / per-assistant / per-model quota: return false when the model must not be used for the org (e.g. quota exceeded), true otherwise. The orgID can be empty, in which case the check applies globally. The assistantName can be empty, in which case the check applies globally. The modelName can be in the format of <provider_name>/<model_name>.
type ModelOptions ¶ added in v0.19.141
type ModelOptions struct {
// ProviderType specifies the provider type to use.
// If not specified, a matching provider will be used.
ProviderType llms.ProviderType
// OrgID specifies the organization ID to use,
// if configuration provides Org overrides.
OrgID string
// AssistantName specifies the assistant name to use.
AssistantName string
// PreferredModels specifies the preferred models to use, in order. Each
// entry is a model reference, [PROVIDER/]MODEL[,EFFORT]: the model may be
// a pattern, and the effort is the default for calls that set none.
PreferredModels []string
// RequiredCapabilities specifies the required capabilities the model must support.
// When non-zero, only providers whose type supports ALL of the requested
// capabilities are considered.
RequiredCapabilities llms.Capability
}
ModelOptions selects which model GetModel should return. See Factory.GetModel for the resolution rules.
type OpenAIConfig ¶
type OpenAIConfig struct {
// Converse enables the optional Bedrock portable inference connector.
Converse bool `json:"converse,omitempty" yaml:"converse,omitempty"`
// InferenceAPI selects the upstream API for the OpenAI portable inference
// connector: "responses", "chat", or empty for the provider default.
InferenceAPI string `json:"inference_api,omitempty" yaml:"inference_api,omitempty"`
BaseURL string `json:"base_url,omitempty" yaml:"base_url,omitempty"`
APIVersion string `json:"api_version,omitempty" yaml:"api_version,omitempty"`
// APIType specifies the type of API to use:
// OPENAI|AZURE|AZURE_AD|CLOUDFLARE|ANTHROPIC|GOOGLEAI|BEDROCK|OPENROUTER|PERPLEXITY
APIType string `json:"api_type,omitempty" yaml:"api_type,omitempty"`
// Organization is the organization ID for the OpenAI API.
Organization string `json:"organization,omitempty" yaml:"organization,omitempty"`
// Project is the project ID for the OpenAI API.
Project string `json:"project,omitempty" yaml:"project,omitempty"`
}
OpenAIConfig specifies API parameters for OpenAI‑style providers. APIType selects the provider family: OPENAI|AZURE|AZURE_AD|CLOUDFLARE|ANTHROPIC|GOOGLEAI|BEDROCK|OPENROUTER|PERPLEXITY.
type Option ¶ added in v0.16.114
type Option func(*Options)
Option configures Options.
func WithAWSConfigFactory ¶ added in v0.16.114
WithAWSConfigFactory supplies the AWS configuration used by the Bedrock-based providers (BEDROCK, ANTHROPIC_BEDROCK, OPENAI_BEDROCK). It is called once per model construction.
func WithHTTPClient ¶ added in v0.16.114
func WithHTTPClient(client HTTPClient) Option
WithHTTPClient allows setting a custom HTTP client. If not set, the default value is http.DefaultClient.
func WithModelFilter ¶ added in v0.19.141
func WithModelFilter(filter ModelFilterFunc) Option
WithModelFilter sets a predicate used to restrict which models an org may use, for example to enforce per-org / per-assistant / per-model quota.
type Options ¶ added in v0.16.114
type Options struct {
// HTTPClient is used to create a new HTTP client.
HTTPClient HTTPClient
// AwsConfigFactory is used to create a new AWS config.
AwsConfigFactory func() (*aws.Config, error)
// ModelFilter reports whether a model may be used for an org,
// e.g. to enforce per-org / per-model quota.
ModelFilter ModelFilterFunc
// Effort holds the reasoning effort settings of the model being
// constructed: the default and the ceiling from the configuration and,
// with discovery, the levels the provider reports for the model. The
// factory sets it for each model; a value given to New is not used.
Effort llms.EffortPolicy
}
Options customize model construction for providers that need extra clients or environment hooks, and allow installing per‑org model filters.
func NewOptions ¶ added in v0.16.114
NewOptions returns Options with the given options applied.
type OrgConfig ¶ added in v0.19.141
type OrgConfig struct {
// AssistantModels specifies the mapping of assistants to models.
// key is the assistant name, value is the list of model references to
// try in order. A reference is [<provider>/]<model>[,<effort>]: the
// provider is a provider name or an upper-case provider type, the model
// may be a pattern with "*" and "?", and the effort is the default
// reasoning effort for that assistant.
// Use `default: <model_name>` as the default model for assistants.
AssistantModels map[string][]string `json:"assistant_models" yaml:"assistant_models"`
}
OrgConfig defines assistant→model mappings that override global mappings for a given organization.
type ProviderConfig ¶
type ProviderConfig struct {
Name string `json:"name" yaml:"name"`
Token string `json:"token,omitempty" yaml:"token,omitempty"`
// DefaultModel is the model used when no preferred model matches. It does
// not need to be listed in AvailableModels.
DefaultModel string `json:"default_model,omitempty" yaml:"default_model,omitempty"`
// AvailableModels is the allow-list of model IDs and patterns. A model
// can be selected by name only when an entry matches it.
AvailableModels []string `json:"available_models,omitempty" yaml:"available_models,omitempty"`
// DisabledModels is the deny-list of model IDs and patterns. It wins over
// AvailableModels and DefaultModel.
DisabledModels []string `json:"disabled_models,omitempty" yaml:"disabled_models,omitempty"`
// MaxEffort is the highest reasoning effort a call to this provider may
// use: none, low, medium, high, xhigh or max. Empty means no ceiling.
MaxEffort string `json:"max_effort,omitempty" yaml:"max_effort,omitempty"`
// Discovery turns on reading the model list from the provider, so that
// patterns see models nobody listed and a retired model gives way to a
// newer one of its family. Nil means off.
Discovery *DiscoveryConfig `json:"discovery,omitempty" yaml:"discovery,omitempty"`
Headers map[string]string `json:"headers,omitempty" yaml:"headers,omitempty"`
OpenAI OpenAIConfig `json:"open_ai" yaml:"open_ai"`
}
ProviderConfig defines a single provider instance and its available models. The OpenAI field conveys the API style for both OpenAI proper and OpenAI‑compatible APIs (Azure, Perplexity, Cloudflare, etc.).
Model names in DefaultModel and AvailableModels may carry a default reasoning effort after a comma ("gpt-5.1,medium") and may be patterns in which "*" matches any run of characters and "?" exactly one ("claude-opus-*").
func (*ProviderConfig) FindModel ¶ added in v0.7.36
func (c *ProviderConfig) FindModel(models ...string) (string, error)
FindModel selects the first name from models that AvailableModels allows and DisabledModels does not deny. If none match, the default model is returned when one is set and usable. Returns an error when no model can be selected.
The names in models are concrete model IDs. Entries of the configuration that do not parse are ignored; Config.Validate reports them.
type Resolution ¶ added in v1.0.173
type Resolution struct {
// Provider is the name of the configured provider that serves the model.
Provider string
// Reference is the configuration entry that selected the model, as
// written: a preferred model, an assistant_models entry or default_model.
Reference string
// Model is the ID of the selected model.
Model string
// Effort is the reasoning effort policy the client of the model gets.
Effort llms.EffortPolicy
// Reason says how Reference selected Model.
Reason ResolutionReason
// Default is set when no preferred reference selected a model and the
// default model of the provider was used.
Default bool
// Verified is set when the model list of the provider confirmed that it
// serves Model. It is false without discovery, and until a list is read.
Verified bool
// Lifecycle is the lifecycle stage the provider reports for Model.
Lifecycle llms.ModelLifecycle
// RetiresAt is the announced end of service of Model, or zero.
RetiresAt time.Time
}
Resolution describes the model a resolution selects.
func Resolve ¶ added in v1.0.173
func Resolve(ctx context.Context, f Factory, opts ModelOptions) (*Resolution, error)
Resolve reports the model the factory selects for the options, without building a client. It requires a factory that implements Catalog.
type ResolutionReason ¶ added in v1.0.173
type ResolutionReason string
ResolutionReason says how a model reference selected a model.
const ( // ReasonExact means the reference named the model. ReasonExact ResolutionReason = "exact" // ReasonPattern means the model is the best match of a pattern. ReasonPattern ResolutionReason = "pattern" // ReasonFamily means the reference named a model that cannot be used, // because the provider no longer serves it or the configuration does not // allow it, and the model is the best usable one of the same family. ReasonFamily ResolutionReason = "family" )