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 // 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 // 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), ) }