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".
See Documentation/llm-factory.md for the full resolution rules, the skills section, and testing hooks such as the overridable NewLLM variable.
Index ¶
- Variables
- func CreateLLM(cfg *ProviderConfig, preferredModels []string, opts *Options) (llms.Model, error)
- func ResolveExact(ctx context.Context, f Factory, provider, model, orgID string) (llms.Model, error)
- type Config
- type ExactResolver
- type Factory
- type HTTPClient
- type ModelFilterFunc
- type ModelOptions
- type OpenAIConfig
- type Option
- type Options
- type OrgConfig
- type ProviderConfig
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.
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.
Types ¶
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 model name.
// The model name can be in the format of <provider_name>/<model_name>.
// 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.
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.
// - 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.
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
}
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 model name.
// The model name can be in the format of <provider_name>/<model_name>.
// 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 string `json:"default_model,omitempty" yaml:"default_model,omitempty"`
AvailableModels []string `json:"available_models,omitempty" yaml:"available_models,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.).