The replay budget was fixed at half of an assumed 128k window, so a small local model was still handed more history than it accepts. A model now carries the context window and output limit the published catalogue gives it, read once into the state directory and cached on disk. Chat holds its replay to the window minus the reply and an eighth for the system prompt and tools, and keeps the assumed budget only for a model the catalogue publishes nothing about.
63 lines
2.0 KiB
Go
63 lines
2.0 KiB
Go
package governance
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
|
|
"github.com/samcharles93/ai-sdk/catalog"
|
|
"github.com/samcharles93/ai-sdk/runtime"
|
|
)
|
|
|
|
// catalogueTimeout bounds the one catalogue read, which fetches over the
|
|
// network only when the cache file is missing or stale.
|
|
const catalogueTimeout = 20 * time.Second
|
|
|
|
// UseModelCatalogue gives the module the file to cache the published model
|
|
// catalogue in. Without it a model carries no size, and a caller that has to
|
|
// fit inside the model's window falls back to its own default.
|
|
func (m *Module) UseModelCatalogue(cachePath string) {
|
|
m.cataloguePath = cachePath
|
|
}
|
|
|
|
// modelFacts returns a model's context window and output limit in tokens, as
|
|
// the catalogue publishes them. Both are zero when it publishes neither, which
|
|
// is a normal answer for a self-hosted model rather than a failure.
|
|
func (m *Module) modelFacts(ctx context.Context, model Model) (int, int) {
|
|
if m.cataloguePath == "" {
|
|
return 0, 0
|
|
}
|
|
m.catalogueOnce.Do(func() {
|
|
rt := runtime.NewRuntime(runtime.Config{CatalogCachePath: m.cataloguePath})
|
|
read, cancel := context.WithTimeout(context.WithoutCancel(ctx), catalogueTimeout)
|
|
defer cancel()
|
|
if err := rt.LoadCatalog(read); err != nil {
|
|
// Sizes are an optimisation: a model with none is sized by the
|
|
// caller's default, so this never fails the work that asked, and
|
|
// the read is not retried until the process restarts.
|
|
m.log.WarnContext(ctx, "read the model catalogue", "error", err)
|
|
return
|
|
}
|
|
m.catalogue = rt
|
|
})
|
|
if m.catalogue == nil {
|
|
return 0, 0
|
|
}
|
|
// The provider's class is its catalogue id; a deployment that names a
|
|
// provider of its own falls back to its name, which the catalogue
|
|
// normalises the same way.
|
|
provider := catalog.NormaliseProviderID(model.Class)
|
|
if provider == "" {
|
|
provider = catalog.NormaliseProviderID(model.Provider)
|
|
}
|
|
models, err := m.catalogue.Models(provider)
|
|
if err != nil {
|
|
return 0, 0
|
|
}
|
|
for _, info := range models {
|
|
if info.ID == model.Model {
|
|
return info.ContextWindow, info.MaxOutputTokens
|
|
}
|
|
}
|
|
return 0, 0
|
|
}
|