diff --git a/modules/chat/history.go b/modules/chat/history.go new file mode 100644 index 000000000..6fd769390 --- /dev/null +++ b/modules/chat/history.go @@ -0,0 +1,108 @@ +package chat + +import ( + "fmt" + + "github.com/samcharles93/ai-sdk/chat" +) + +// A reply is replayed with the turns before it, so an old conversation grows +// past any model's window. The middle of a long history is replaced with a +// summary of what it held; the newest messages always survive, because they are +// what the next reply answers. +const ( + // historyWindow is how many earlier turns are read for one reply. It is the + // 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 + // 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.]" +) + +// 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 +// whole request. +func estimateTokens(s string) int { + ascii, nonASCII := 0, 0 + for _, r := range s { + if r < 128 { + ascii++ + continue + } + nonASCII++ + } + return ascii/4 + nonASCII +} + +// historyCost is the estimated size of a message list. +func historyCost(messages []chat.Message) int { + total := 0 + for _, m := range messages { + total += estimateTokens(m.Content) + } + return total +} + +// summariseHistory holds messages to budget by replacing the middle with one +// summary message. Messages at or under the budget come back untouched. +func summariseHistory(messages []chat.Message, budget int) []chat.Message { + if len(messages) < 2 || budget <= 0 || historyCost(messages) <= budget { + return messages + } + + // The newest messages are the most relevant, so the middle is dropped + // first. The last message is the question being answered: even when it + // alone exceeds the budget it is sent whole, because a silently shortened + // question is answered wrongly. + for keep := min(keepRecent, len(messages)-1); keep >= 1; keep-- { + held := hold(messages, keep) + if historyCost(held) <= budget { + return held + } + } + return hold(messages, 1) +} + +// hold is messages with everything before its last keep messages summarised. +func hold(messages []chat.Message, keep int) []chat.Message { + middle := messages[:len(messages)-keep] + out := make([]chat.Message, 0, keep+1) + out = append(out, chat.Message{Role: chat.RoleSystem, Content: summarise(middle)}) + return append(out, messages[len(messages)-keep:]...) +} + +// summarise says what a dropped middle held, without asking a model to read it: +// the turn is already answered by the reply it produced, and a summarising call +// would put a second model request in front of every compressed turn. +func summarise(middle []chat.Message) string { + if len(middle) == 0 { + return summarisedMarker + } + var fromOperator, fromArchie int + for _, m := range middle { + switch m.Role { + case chat.RoleUser: + fromOperator++ + case chat.RoleAssistant: + fromArchie++ + } + } + return fmt.Sprintf( + "%s\n\n[%d messages removed (~%d tokens): %d from the operator, %d from Archie. From: %q ... To: %q]", + summarisedMarker, + len(middle), + historyCost(middle), + fromOperator, + fromArchie, + truncateRunes(middle[0].Content, 80), + truncateRunes(middle[len(middle)-1].Content, 80), + ) +} diff --git a/modules/chat/history_test.go b/modules/chat/history_test.go new file mode 100644 index 000000000..6fada5bcd --- /dev/null +++ b/modules/chat/history_test.go @@ -0,0 +1,77 @@ +package chat + +import ( + "strings" + "testing" + + "github.com/samcharles93/ai-sdk/chat" +) + +// 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. +func TestSummariseHistory(t *testing.T) { + // aTurn is one exchange: the operator's message and Archie's reply, each + // about 2000 tokens, so sixty turns are well past the replay budget. + pad := strings.Repeat("x", 8_000) + aTurn := func(i int) []chat.Message { + return []chat.Message{ + {Role: chat.RoleUser, Content: "question " + string(rune('a'+i%26)) + " " + pad}, + {Role: chat.RoleAssistant, Content: "answer " + string(rune('a'+i%26)) + " " + pad}, + } + } + many := make([]chat.Message, 0, 120) + for i := range 60 { + many = append(many, aTurn(i)...) + } + + // A message too large to fit beside anything else, and a question after it. + huge := make([]chat.Message, 0, 40) + for i := range 20 { + huge = append(huge, chat.Message{Role: chat.RoleAssistant, Content: strings.Repeat("x", 40_000)}, chat.Message{Role: chat.RoleUser, Content: "and then " + string(rune('a'+i))}) + } + const question = "what did we decide about the retry policy?" + + cases := []struct { + name string + messages []chat.Message + budget int + // kept is how many trailing messages must survive unchanged. + kept int + // fits reports whether the result must be inside the budget. + fits bool + // 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 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}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + out := summariseHistory(tc.messages, tc.budget) + if len(out) < tc.kept { + t.Fatalf("kept %d messages, want at least %d", len(out), tc.kept) + } + if got, want := out[len(out)-1], tc.messages[len(tc.messages)-1]; got.Content != want.Content { + t.Errorf("last message is %q, want the question %q", got.Content, want.Content) + } + for i := 1; i <= tc.kept; i++ { + if got, want := out[len(out)-i].Content, tc.messages[len(tc.messages)-i].Content; got != want { + t.Errorf("message %d from the end is %q, want %q unchanged", i, got, want) + } + } + if got := len(out) < len(tc.messages); got != tc.compressed { + t.Fatalf("history compressed = %t, want %t (%d of %d messages sent)", got, tc.compressed, len(out), len(tc.messages)) + } + if tc.compressed && (out[0].Role != chat.RoleSystem || !strings.Contains(out[0].Content, summarisedMarker)) { + t.Errorf("history was shortened without a summary in front of it: %q", out[0].Content) + } + if tc.fits && historyCost(out) > tc.budget { + t.Errorf("history is %d tokens, over the %d budget", historyCost(out), tc.budget) + } + }) + } +} diff --git a/modules/chat/turn.go b/modules/chat/turn.go index 707a8f699..5c51e4708 100644 --- a/modules/chat/turn.go +++ b/modules/chat/turn.go @@ -24,8 +24,6 @@ import ( const ( // maxConcurrentTurns bounds the conversations answered at once. maxConcurrentTurns = 4 - // historyTurns is how many earlier turns a turn's model sees. - historyTurns = 20 // maxSteps bounds the model calls one turn makes. maxSteps = 16 // turnTimeout ends a turn that never finishes. @@ -185,7 +183,7 @@ func (m *Module) generate(ctx context.Context, t store.Turn) (string, string, er if err != nil { return "", "", fmt.Errorf("agent model %s: %w", model.Model, err) } - history, err := m.store.History(ctx, t.SessionID, t.Seq, historyTurns) + history, err := m.store.History(ctx, t.SessionID, t.Seq, historyWindow) if err != nil { return "", "", err } @@ -203,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: conversation(history, t), + Model: model.Model, ModelInfo: info, System: system, Messages: summariseHistory(conversation(history, t), historyBudget), Tools: tools, MaxSteps: maxSteps, }) if err != nil {