feat(governance,chat): size a model's chat history by its own window (#2018)
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.
This commit is contained in:
7 files changed
+139
-10
No files matched your search
@@ -2435,6 +2435,14 @@ components:
|
||||
class:
|
||||
readOnly: true
|
||||
type: string
|
||||
context_window:
|
||||
format: int64
|
||||
readOnly: true
|
||||
type: integer
|
||||
max_output_tokens:
|
||||
format: int64
|
||||
readOnly: true
|
||||
type: integer
|
||||
model:
|
||||
description: The model's name on the provider
|
||||
type: string
|
||||
|
||||
@@ -165,6 +165,9 @@ func wire(log *slog.Logger, configPath string, cfg Config, db *sqlx.DB) (*binary
|
||||
settings.UseCredentials(orgCredentials{conns: conns, orgID: string(governance.DefaultOrgID)})
|
||||
// An account links a channel account on the connectors that can link.
|
||||
settings.UseChannels(conns)
|
||||
// A model's window comes from the published catalogue, cached under the
|
||||
// state directory so a restart reads it from disk.
|
||||
settings.UseModelCatalogue(filepath.Join(cfg.StateDir, "model-catalogue.json"))
|
||||
|
||||
sys := system.New(system.Bootstrap{
|
||||
Listen: cfg.Listen, Database: DatabaseHost(cfg.Database.URL), Schemas: len(schemas),
|
||||
|
||||
+24
-5
@@ -15,17 +15,36 @@ const (
|
||||
// ceiling on what a conversation can carry forward at all, well above what
|
||||
// any window holds, so summarisation decides what actually goes.
|
||||
historyWindow = 200
|
||||
// historyBudget is the prompt size the replayed history is held to.
|
||||
// shortcut: a fixed budget for every model, because the module is told a
|
||||
// model's name and nothing about its window; read the window from
|
||||
// governance when it carries one, and derive the budget from it.
|
||||
historyBudget = 64_000
|
||||
// assumedHistoryBudget is the replay budget for a model whose window the
|
||||
// catalogue doesn't publish: half of the window a chat model is assumed to
|
||||
// have, leaving the other half for the system prompt, the tools and the
|
||||
// reply.
|
||||
assumedHistoryBudget = 64_000
|
||||
// keepRecent is how many of the newest messages survive summarisation.
|
||||
keepRecent = 20
|
||||
// summarisedMarker opens the summary that replaces a dropped middle.
|
||||
summarisedMarker = "[Earlier conversation has been summarised to stay within the model's context window.]"
|
||||
)
|
||||
|
||||
// historyBudgetFor is the prompt size a replay is held to, given the model's
|
||||
// window and output limit in tokens. A model with no published window is sized
|
||||
// by the assumed one.
|
||||
func historyBudgetFor(contextWindow, maxOutput int) int {
|
||||
if contextWindow <= 0 {
|
||||
return assumedHistoryBudget
|
||||
}
|
||||
// The reply comes out of the same window, and the system prompt and tool
|
||||
// schemas take roughly an eighth of it for the instructions this an agent
|
||||
// carries into every turn.
|
||||
reserve := max(maxOutput, 0) + contextWindow/8
|
||||
if budget := contextWindow - reserve; budget > 0 {
|
||||
return budget
|
||||
}
|
||||
// A window the reply alone would fill still has to replay something: an
|
||||
// eighth of it holds the question and a short answer.
|
||||
return max(contextWindow/8, 1)
|
||||
}
|
||||
|
||||
// estimateTokens counts a message's tokens as four ASCII characters or one
|
||||
// non-ASCII rune each. It over-counts rather than under-counts: compressing a
|
||||
// message too early costs a little context, and one that doesn't fit loses the
|
||||
|
||||
@@ -7,6 +7,30 @@ import (
|
||||
"github.com/samcharles93/ai-sdk/chat"
|
||||
)
|
||||
|
||||
// Guards the replay budget: a model's own window decides how much history it
|
||||
// carries, and a model that published none is still answered within a sane
|
||||
// prompt instead of failing the request on its window.
|
||||
func TestHistoryBudgetFor(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
contextWindow int
|
||||
maxOutput int
|
||||
want int
|
||||
}{
|
||||
{name: "no published window falls back to the assumed budget", contextWindow: 0, want: assumedHistoryBudget},
|
||||
{name: "a large window reserves what the reply needs", contextWindow: 200_000, maxOutput: 8_000, want: 200_000 - 8_000 - 25_000},
|
||||
{name: "a small window still replays some history", contextWindow: 8_000, maxOutput: 4_000, want: 8_000 - 4_000 - 1_000},
|
||||
{name: "a window the reply alone fills keeps an eighth", contextWindow: 1_000, maxOutput: 8_000, want: 125},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := historyBudgetFor(tc.contextWindow, tc.maxOutput); got != tc.want {
|
||||
t.Errorf("historyBudgetFor(%d, %d) = %d, want %d", tc.contextWindow, tc.maxOutput, got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Guards the replay of a long conversation: the newest messages and the
|
||||
// question being answered survive, and what is sent fits the budget, so an old
|
||||
// conversation is answered instead of failing the request on its window.
|
||||
@@ -43,8 +67,8 @@ func TestSummariseHistory(t *testing.T) {
|
||||
// compressed reports whether the middle must have been dropped.
|
||||
compressed bool
|
||||
}{
|
||||
{name: "a short history is replayed untouched", messages: []chat.Message{{Role: chat.RoleUser, Content: "hi"}, {Role: chat.RoleAssistant, Content: "hello"}, {Role: chat.RoleUser, Content: question}}, budget: historyBudget, kept: 3, fits: true},
|
||||
{name: "a long history keeps its newest messages", messages: many, budget: historyBudget, kept: keepRecent, fits: true, compressed: true},
|
||||
{name: "a short history is replayed untouched", messages: []chat.Message{{Role: chat.RoleUser, Content: "hi"}, {Role: chat.RoleAssistant, Content: "hello"}, {Role: chat.RoleUser, Content: question}}, budget: assumedHistoryBudget, kept: 3, fits: true},
|
||||
{name: "a long history keeps its newest messages", messages: many, budget: assumedHistoryBudget, kept: keepRecent, fits: true, compressed: true},
|
||||
{name: "a small budget keeps at least the question", messages: many, budget: 2_000, kept: 1, fits: false, compressed: true},
|
||||
{name: "a history whose own messages overflow keeps the question", messages: append(huge, chat.Message{Role: chat.RoleUser, Content: question}), budget: 2_000, kept: 1, fits: false, compressed: true},
|
||||
}
|
||||
|
||||
@@ -201,7 +201,7 @@ func (m *Module) generate(ctx context.Context, t store.Turn) (string, string, er
|
||||
SessionID: t.SessionID.String(), Memory: memory, Instructions: instructions, Now: time.Now(),
|
||||
})
|
||||
stream, err := core.StreamText(ctx, guardedProvider{Provider: provider, m: m, d: d, t: t, offered: tools}, core.GenerateOptions{
|
||||
Model: model.Model, ModelInfo: info, System: system, Messages: summariseHistory(conversation(history, t), historyBudget),
|
||||
Model: model.Model, ModelInfo: info, System: system, Messages: summariseHistory(conversation(history, t), historyBudgetFor(model.ContextWindow, model.MaxOutputTokens)),
|
||||
Tools: tools, MaxSteps: maxSteps,
|
||||
})
|
||||
if err != nil {
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
@@ -217,6 +218,11 @@ type Model struct {
|
||||
BaseURL string `json:"base_url,omitempty" readOnly:"true"`
|
||||
APIKeyCredentialID *uuid.UUID `json:"api_key_credential_id,omitempty" format:"uuid" readOnly:"true"`
|
||||
APIKeyCredential string `json:"api_key_credential,omitempty" readOnly:"true"`
|
||||
// ContextWindow and MaxOutputTokens are the model's size in tokens, as the
|
||||
// published catalogue gives it. Zero means it published neither, so a
|
||||
// caller that has to fit inside the window uses its own default.
|
||||
ContextWindow int `json:"context_window,omitempty" readOnly:"true"`
|
||||
MaxOutputTokens int `json:"max_output_tokens,omitempty" readOnly:"true"`
|
||||
}
|
||||
|
||||
// Credentials resolves a credential's token and display name by id. It is the
|
||||
@@ -279,6 +285,11 @@ type Module struct {
|
||||
oidc *oidcLogin
|
||||
setup *SetupSignal
|
||||
channels ChannelLinks
|
||||
|
||||
// The published model catalogue, read once, and the file it is cached in.
|
||||
cataloguePath string
|
||||
catalogueOnce sync.Once
|
||||
catalogue *runtime.Runtime
|
||||
}
|
||||
|
||||
// NewModule returns the governance module for orgID. The ai-sdk provider
|
||||
@@ -324,12 +335,14 @@ func (m *Module) AgentModelForAlias(ctx context.Context, alias string) (Model, e
|
||||
}
|
||||
return Model{}, ErrNoAgentModel
|
||||
}
|
||||
return Model{
|
||||
model := Model{
|
||||
ProviderID: role.ProviderID, Provider: role.Provider, Model: role.Model,
|
||||
Class: role.Class, BaseURL: role.BaseURL,
|
||||
APIKeyCredentialID: credentialIDPtr(role.APIKeyCredentialID),
|
||||
APIKeyCredential: m.credentialName(ctx, role.APIKeyCredentialID),
|
||||
}, nil
|
||||
}
|
||||
model.ContextWindow, model.MaxOutputTokens = m.modelFacts(ctx, model)
|
||||
return model, nil
|
||||
}
|
||||
|
||||
// Settings returns the organisation's settings, with a default for every one it
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
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
|
||||
}
|
||||
Reference in new issue
Block a user