* strategies for context management @ 2026-11-06 8:11 Ricardo Wurmus 2026-11-06 14:21 ` Arun Isaac 0 siblings, 1 reply; 29+ messages in thread From: Ricardo Wurmus @ 2026-11-06 8:11 UTC (permalink / raw) To: kaagum Hi, I've repeatedly found myself running out of space in the LLM context on simple tasks that involve reading a couple of files. In my case it would seem to be useful to control the size of the context or to inject hooks to manage context between calls. ACP specifies compaction, which is not supported by kaagum. Do you have plans for context management? -- Ricardo ^ permalink raw reply [flat|nested] 29+ messages in thread
* Re: strategies for context management 2026-11-06 8:11 strategies for context management Ricardo Wurmus @ 2026-11-06 14:21 ` Arun Isaac 2026-11-06 21:28 ` Ricardo Wurmus 0 siblings, 1 reply; 29+ messages in thread From: Arun Isaac @ 2026-11-06 14:21 UTC (permalink / raw) To: Ricardo Wurmus, kaagum Hi Ricardo, I haven't thought hard about context compaction or read much of the literature. But I'm open to ideas. Let me know what you have in mind. Something like Aider's repomap could be interesting: https://aider.chat/docs/repomap.html It might lessen the need for the LLM to read through lots of files. And, here's another idea of building a semantic code search database: https://github.com/zilliztech/claude-context This too might lessen the need for the LLM to read through lots of files. Some LLM providers such as OpenRouter provide context compaction on their end: https://openrouter.ai/docs/guides/features/message-transforms A really quick win could be to enable this in kaagum's LLM requests. Regards, Arun ^ permalink raw reply [flat|nested] 29+ messages in thread
* Re: strategies for context management 2026-11-06 14:21 ` Arun Isaac @ 2026-11-06 21:28 ` Ricardo Wurmus 2026-11-07 8:15 ` Ricardo Wurmus 2026-11-08 1:43 ` strategies for context management Arun Isaac 0 siblings, 2 replies; 29+ messages in thread From: Ricardo Wurmus @ 2026-11-06 21:28 UTC (permalink / raw) To: Arun Isaac; +Cc: Ricardo Wurmus, kaagum Hi Arun, > I haven't thought hard about context compaction or read much of > the > literature. But I'm open to ideas. Let me know what you have in > mind. it would be helpful to provide a means for users to delete or edit session messages to reduce the effective context. I don't know if kaagum's design makes this possible or if perhaps it is something that is not wanted due to design constraints. As far as I understand, however, it is up to agent harnesses to implement context management if they need it. > Something like Aider's repomap could be interesting: > https://aider.chat/docs/repomap.html It might lessen the need > for the > LLM to read through lots of files. > > And, here's another idea of building a semantic code search > database: > https://github.com/zilliztech/claude-context This too might > lessen the > need for the LLM to read through lots of files. My project involves processing research articles, so there's a lot of text. (I've got tools for running pdftotext and pdfimages in a Guix container to extract parts of articles.) Code search might help for navigating large software repositories, but my concern is with compacting all that text. Merely searching keywords and reading delimited chunks would not be sufficient, but reading chunks to summarize and write compacted progress would. -- Ricardo ^ permalink raw reply [flat|nested] 29+ messages in thread
* Re: strategies for context management 2026-11-06 21:28 ` Ricardo Wurmus @ 2026-11-07 8:15 ` Ricardo Wurmus 2026-11-08 1:35 ` Arun Isaac 2026-11-08 1:43 ` strategies for context management Arun Isaac 1 sibling, 1 reply; 29+ messages in thread From: Ricardo Wurmus @ 2026-11-07 8:15 UTC (permalink / raw) To: Arun Isaac; +Cc: Ricardo Wurmus, kaagum Ricardo Wurmus <rekado@elephly.net> writes: >> I haven't thought hard about context compaction or read much of >> the >> literature. But I'm open to ideas. Let me know what you have in >> mind. > > it would be helpful to provide a means for users to delete or > edit > session messages to reduce the effective context. I don't know > if > kaagum's design makes this possible or if perhaps it is > something that > is not wanted due to design constraints. > > As far as I understand, however, it is up to agent harnesses to > implement context management if they need it. My proposal is to add a compaction strategy record with a predicate and a handler. The predicate takes the current state and decides whether compaction should be performed. The handler takes state and returns new state. A complication is that a handler may issue LLM calls (e.g. to summarize stuff), and I don't know how this would slot into the TEA loop. Perhaps triggering session/fork would be appropriate then. Users could then provide their own compaction strategies, including none at all. -- Ricardo ^ permalink raw reply [flat|nested] 29+ messages in thread
* Re: strategies for context management 2026-11-07 8:15 ` Ricardo Wurmus @ 2026-11-08 1:35 ` Arun Isaac 2026-11-08 1:36 ` [PATCH] Support context compaction Arun Isaac 2026-11-09 13:25 ` strategies for context management Ricardo Wurmus 0 siblings, 2 replies; 29+ messages in thread From: Arun Isaac @ 2026-11-08 1:35 UTC (permalink / raw) To: Ricardo Wurmus; +Cc: Ricardo Wurmus, kaagum Hi Ricardo, > My proposal is to add a compaction strategy record with a predicate > and a handler. The predicate takes the current state and decides > whether compaction should be performed. The handler takes state and > returns new state. That's a neat interface—it avoids hard-coding a specific compacter; I like it. I have written up a draft (and completely untested) patch implementing it. Let me know what you think, and if you'd be happy to flesh it out and experiment with it a bit. The patch follows in a subsequent mail. Some differences from your proposal: - Instead of a predicate and a handler, I have a single function. The function can be identity for a no-compaction strategy. - The compacter doesn't update the state. The state remains complete and whole, just like without compaction. The compaction only happens in do-effect, just before querying the LLM. Other things to think about: - The compacter function is directly exposed to the JSON tree of the messages; we should probably introduce an <llm-request-message> record type abstraction. - The compacter function is not told how many tokens the previous LLM query took. This may be important information. - The compacter is a naked function; maybe a wrapping compacter record type would be wise, but I can't think of a pressing immediate reason to wrap it. - The --compacter argument only allows specifying compacters from user-specified files. Ideally, we'd want kaagum to provide a library of compacters, and the user to have some way of choosing from them as well. > A complication is that a handler may issue LLM calls (e.g. to > summarize stuff), and I don't know how this would slot into the TEA > loop. Perhaps triggering session/fork would be appropriate then. That is a valid use case, and we should support it. But it may be best to let the compacter make its own LLM calls without having to integrate those LLM calls into the TEA loop. Regards, Arun ^ permalink raw reply [flat|nested] 29+ messages in thread
* [PATCH] Support context compaction. 2026-11-08 1:35 ` Arun Isaac @ 2026-11-08 1:36 ` Arun Isaac 2026-11-09 13:25 ` strategies for context management Ricardo Wurmus 1 sibling, 0 replies; 29+ messages in thread From: Arun Isaac @ 2026-11-08 1:36 UTC (permalink / raw) To: Arun Isaac, Ricardo Wurmus; +Cc: kaagum --- bin/kaagum | 9 ++++++++- kaagum/tea.scm | 34 +++++++++++++++++++--------------- 2 files changed, 27 insertions(+), 16 deletions(-) diff --git a/bin/kaagum b/bin/kaagum index 2c8c9ee..14a65b1 100755 --- a/bin/kaagum +++ b/bin/kaagum @@ -53,6 +53,9 @@ exec guile --no-auto-compile -e main -s "$0" "$@" (option (list #\t "more-tools") #t #f (lambda (opt name arg result) (acons 'more-tools arg result))) + (option (list #c "compacter") #t #f + (lambda (opt name arg result) + (acons 'compacter arg result))) (option (list "kagi-api-key-command") #t #f (lambda (opt name arg result) (acons 'kagi-api-key-command arg result))) @@ -79,6 +82,7 @@ Run kaagum AI agent. -m, --model=MODEL LLM model name to start new sessions with (default: \"anthropic/claude-opus-4.8\") -t, --more-tools=FILE scheme file providing more tools to the agent + -c, --compacter=FILE scheme file providing context compacter --kagi-api-key-command=COMMAND command to run to get Kagi API key @@ -135,7 +139,10 @@ Run kaagum AI agent. '()) (if (assq-ref args 'more-tools) (load (assq-ref args 'more-tools)) - '()))))) + '())) + (if (assq-ref args 'compacter) + (load (assq-ref args 'compacter)) + identity)))) (parameterize ((%kagi-api-key (and kagi-api-key-command (get-api-key kagi-api-key-command)))) ;; (trace 'kagi "Key ~a" (%kagi-api-key)) diff --git a/kaagum/tea.scm b/kaagum/tea.scm index f3b2397..8d28213 100644 --- a/kaagum/tea.scm +++ b/kaagum/tea.scm @@ -962,7 +962,7 @@ in @code{tea-loop}." ((tool-call-result? message) (tool-call-result-effects message)))) -(define* (tea-loop state llm-base-uri llm-api-key models tools +(define* (tea-loop state llm-base-uri llm-api-key models tools compacter #:optional (events (let ((line (get-line (current-input-port)))) (and (not (eof-object? line)) (begin @@ -970,10 +970,10 @@ in @code{tea-loop}." (list (acp-message (json-string->scm line)))))))) "Run a @acronym{TEA, The Elm Architecture} loop starting with @var{state}. -@var{llm-base-uri}, @var{llm-api-key} and @var{tools} are the same as in -@code{run-tea-loop}. @var{models} is an association list mapping model IDs to -@code{<model>} objects, the first element of which is the default model. -@var{events} is an internal recursion variable." +@var{llm-base-uri}, @var{llm-api-key}, @var{tools} and @var{compacter} are the +same as in @code{run-tea-loop}. @var{models} is an association list mapping +model IDs to @code{<model>} objects, the first element of which is the default +model. @var{events} is an internal recursion variable." ;; Read a JSON-RPC message, handle it, and loop. (when events (let-values (((effects next-state) @@ -981,18 +981,18 @@ in @code{tea-loop}." (state-append-map (cut acp-effects <> models tools) events) state))) - (match (append-map (cut do-effect <> llm-base-uri llm-api-key tools) + (match (append-map (cut do-effect <> llm-base-uri llm-api-key tools compacter) effects) (() - (tea-loop next-state llm-base-uri llm-api-key models tools)) + (tea-loop next-state llm-base-uri llm-api-key models tools compacter)) ((events ...) - (tea-loop next-state llm-base-uri llm-api-key models tools events)))))) + (tea-loop next-state llm-base-uri llm-api-key models tools compacter events)))))) -(define (do-effect effect llm-base-uri llm-api-key tools) +(define (do-effect effect llm-base-uri llm-api-key tools compacter) "Do @var{effect}. Return list of events produced by the effect. -@var{llm-base-uri}, @var{llm-api-key} and @var{tools} are the same as in -@code{run-tea-loop}." +@var{llm-base-uri}, @var{llm-api-key}, @var{tools} and @var{compacter} are the +same as in @code{run-tea-loop}." (cond ;; Send message to client, and return the state unchanged. ((acp-message? effect) @@ -1009,7 +1009,7 @@ in @code{tea-loop}." (openai-query llm-base-uri llm-api-key (llm-request-model effect) - (llm-request-messages effect) + (compacter (llm-request-messages effect)) (map (match-lambda ((name . tool) (tool->spec name tool))) @@ -1018,16 +1018,20 @@ in @code{tea-loop}." ((tool-call? effect) (list (eval-tool-call effect tools))))) -(define (run-tea-loop llm-base-uri llm-api-key model tools) +(define (run-tea-loop llm-base-uri llm-api-key model tools compacter) "Run a @acronym{TEA, The Elm Architecture} loop. @var{llm-base-uri} is the base URI of the LLM provider. @var{llm-api-key} is the API key to authenticate with the LLM provider. @var{model} is the name of the model to initialize sessions with. @var{tools} is the list of tools made available to the LLM. It is an -association list matching tool names to @code{<tool>} objects." +association list matching tool names to @code{<tool>} objects. @var{compacter} +is a function that takes a list of messages and returns a compacted list of +messages to query the LLM with. The compacted messages hopefully use fewer +tokens than the original messages." (let ((models (openai-models llm-base-uri llm-api-key))) (tea-loop (state #f 0 0 '() '()) llm-base-uri llm-api-key (cons (assoc model models) (alist-delete model models)) - tools))) + tools + compacter))) -- 2.54.0 ^ permalink raw reply [flat|nested] 29+ messages in thread
* Re: strategies for context management 2026-11-08 1:35 ` Arun Isaac 2026-11-08 1:36 ` [PATCH] Support context compaction Arun Isaac @ 2026-11-09 13:25 ` Ricardo Wurmus 2026-11-10 23:42 ` Arun Isaac 1 sibling, 1 reply; 29+ messages in thread From: Ricardo Wurmus @ 2026-11-09 13:25 UTC (permalink / raw) To: Arun Isaac; +Cc: Ricardo Wurmus, kaagum Hi Arun, >> My proposal is to add a compaction strategy record with a >> predicate >> and a handler. The predicate takes the current state and >> decides >> whether compaction should be performed. The handler takes state >> and >> returns new state. > > That's a neat interface—it avoids hard-coding a specific > compacter; I > like it. > > I have written up a draft (and completely untested) patch > implementing > it. Let me know what you think, and if you'd be happy to flesh > it out > and experiment with it a bit. The patch follows in a subsequent > mail. Thank you! > Some differences from your proposal: > - Instead of a predicate and a handler, I have a single > function. The > function can be identity for a no-compaction strategy. > - The compacter doesn't update the state. The state remains > complete and > whole, just like without compaction. The compaction only happens > in > do-effect, just before querying the LLM. This means that the compaction function will see an ever-increasing number of messages. I understand that having more context can be useful to avoid drift and loss of important information, but it also means that compaction cannot build up its own state. It would have to perform the same work over and over again, just with more messages tacked on, yet it has no way to checkpoint its progress. Perhaps a compacter would need to bring its own infrastructure to avoid repeating work across turns. > Other things to think about: > - The compacter function is directly exposed to the JSON tree of > the > messages; we should probably introduce an <llm-request-message> > record > type abstraction. Yes, this seems like a good idea. > - The compacter function is not told how many tokens the > previous LLM > query took. This may be important information. Is that information available to kaagum? >> A complication is that a handler may issue LLM calls (e.g. to >> summarize stuff), and I don't know how this would slot into the >> TEA >> loop. Perhaps triggering session/fork would be appropriate >> then. > > That is a valid use case, and we should support it. But it may > be best > to let the compacter make its own LLM calls without having to > integrate > those LLM calls into the TEA loop. I don't know enough to understand why it would be desirable to let the compacter make its own calls instead of considering it an optional detour in the back and forth between kaagum and the LLM. -- Ricardo ^ permalink raw reply [flat|nested] 29+ messages in thread
* Re: strategies for context management 2026-11-09 13:25 ` strategies for context management Ricardo Wurmus @ 2026-11-10 23:42 ` Arun Isaac 2026-11-13 22:41 ` [PATCH 1/4] Add message record equality comparators Arun Isaac ` (4 more replies) 0 siblings, 5 replies; 29+ messages in thread From: Arun Isaac @ 2026-11-10 23:42 UTC (permalink / raw) To: Ricardo Wurmus; +Cc: Ricardo Wurmus, kaagum Hi Ricardo, > This means that the compaction function will see an ever-increasing > number of messages. I understand that having more context can be > useful to avoid drift and loss of important information, but it also > means that compaction cannot build up its own state. It would have to > perform the same work over and over again, just with more messages > tacked on, yet it has no way to checkpoint its progress. Perhaps a > compacter would need to bring its own infrastructure to avoid > repeating work across turns. It could memoize. That's fairly easy to implement. But I hear you. Let's keep both the original messages and the compacted messages in the state. We'll only send the compacted messages to the LLM and to the compacter, like you suggest. But we still need to keep the original messages for mundane things like saving and resuming sessions. kaagum doesn't support saving/resuming sessions yet, but might in the future. >> - The compacter function is not told how many tokens the previous LLM >> query took. This may be important information. > > Is that information available to kaagum? Yes, certainly. And kaagum passes on that information to the ACP client (agent-shell) too. In agent-shell, you can see the token usage using `M-x agent-shell-show-usage', among other places. Let's make the token usage information available to the compacter. Perhaps it can be a keyword argument #:tokens that is passed to the compacter function. > I don't know enough to understand why it would be desirable to let > the compacter make its own calls instead of considering it an > optional detour in the back and forth between kaagum and the LLM. Integrating the compacter into the TEA loop is very nice from the point of view of remaining strictly functional and free of side-effects. However, I'm leaning towards making it separate for the following reasons: Integrating the compacter into the TEA loop would mean we are exposing the TEA architecture—an implementation detail—to the compacter. If we ever decide to move away from the TEA architecture, we won't be able to. Also, the TEA architecture will make the compacter harder to write, and will probably frustrate end-users trying to write a compacter. We'll have to create several more record types—<compacter-llm-request>, <compacter-llm-response>, etc. to distinguish these from <llm-request> and <llm-response>. If we re-used the same record types, the TEA loop would not know whether they were meant for the compacter or as a regular LLM completion. The compacter may also want to use a different model or even a different LLM provider for summarizing—more reason to not conflate <compacter-llm-request> with <llm-request>. Let's start with a non-TEA compacter since it's simpler. If we ever need to, we can move to a TEA-integrated compacter later. I'll send a new WIP patch in the next couple of days. The compacter specifics apart, could you share some more details of your project and what you're trying to achieve? It might help me think along. Regards, Arun ^ permalink raw reply [flat|nested] 29+ messages in thread
* [PATCH 1/4] Add message record equality comparators. 2026-11-10 23:42 ` Arun Isaac @ 2026-11-13 22:41 ` Arun Isaac 2026-11-13 22:41 ` [PATCH 2/4] Support context compaction Arun Isaac ` (3 subsequent siblings) 4 siblings, 0 replies; 29+ messages in thread From: Arun Isaac @ 2026-11-13 22:41 UTC (permalink / raw) To: Arun Isaac, Ricardo Wurmus; +Cc: kaagum --- kaagum/message.scm | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/kaagum/message.scm b/kaagum/message.scm index 5cd3ec8..04ac559 100644 --- a/kaagum/message.scm +++ b/kaagum/message.scm @@ -17,7 +17,11 @@ ;;; along with kaagum. If not, see <https://www.gnu.org/licenses/>. (define-module (kaagum message) - #:use-module (kaagum records)) + #:use-module (kaagum records) + #:export (user-message=? + assistant-message=? + tool-message=? + message=?)) (define-public-record-type* (<user-message> user-message user-message?) (fields (content user-message-content))) @@ -29,3 +33,32 @@ (define-public-record-type* (<tool-message> tool-message tool-message?) (fields (tool-call-id tool-message-tool-call-id) (content tool-message-content))) + +(define (user-message=? message1 message2) + (equal? (user-message-content message1) + (user-message-content message2))) + +(define (assistant-message=? message1 message2) + (and (equal? (assistant-message-content message1) + (assistant-message-content message2)) + (equal? (assistant-message-tool-calls message1) + (assistant-message-tool-calls message2)))) + +(define (tool-message=? message1 message2) + (and (equal? (tool-message-tool-call-id message1) + (tool-message-tool-call-id message2)) + (equal? (tool-message-content message1) + (tool-message-content message2)))) + +(define (message=? message1 message2) + (cond + ((and (user-message? message1) + (user-message? message2)) + (user-message=? message1 message2)) + ((and (assistant-message? message1) + (assistant-message? message2)) + (assistant-message=? message1 message2)) + ((and (tool-message? message1) + (tool-message? message2)) + (tool-message=? message1 message2)) + (else #f))) -- 2.54.0 ^ permalink raw reply [flat|nested] 29+ messages in thread
* [PATCH 2/4] Support context compaction. 2026-11-10 23:42 ` Arun Isaac 2026-11-13 22:41 ` [PATCH 1/4] Add message record equality comparators Arun Isaac @ 2026-11-13 22:41 ` Arun Isaac 2026-11-13 22:41 ` [PATCH 3/4] Add sliding window compacter Arun Isaac ` (2 subsequent siblings) 4 siblings, 0 replies; 29+ messages in thread From: Arun Isaac @ 2026-11-13 22:41 UTC (permalink / raw) To: Arun Isaac, Ricardo Wurmus; +Cc: kaagum --- bin/kaagum | 13 +++- kaagum/compacters.scm | 25 +++++++ kaagum/tea.scm | 167 ++++++++++++++++++++++++++++++------------ 3 files changed, 157 insertions(+), 48 deletions(-) create mode 100644 kaagum/compacters.scm diff --git a/bin/kaagum b/bin/kaagum index 2c8c9ee..50fbb76 100755 --- a/bin/kaagum +++ b/bin/kaagum @@ -24,6 +24,7 @@ exec guile --no-auto-compile -e main -s "$0" "$@" (srfi srfi-26) (srfi srfi-37) (ice-9 match) + (kaagum compacters) ; for --compacter-eval expressions (kaagum config) (kaagum openai) (kaagum tea) @@ -53,6 +54,9 @@ exec guile --no-auto-compile -e main -s "$0" "$@" (option (list #\t "more-tools") #t #f (lambda (opt name arg result) (acons 'more-tools arg result))) + (option (list #\c "compacter-eval") #t #f + (lambda (opt name arg result) + (acons 'compacter-eval arg result))) (option (list "kagi-api-key-command") #t #f (lambda (opt name arg result) (acons 'kagi-api-key-command arg result))) @@ -79,6 +83,7 @@ Run kaagum AI agent. -m, --model=MODEL LLM model name to start new sessions with (default: \"anthropic/claude-opus-4.8\") -t, --more-tools=FILE scheme file providing more tools to the agent + -c, --compacter-eval=EXPR expression returning compacter (default: noop) --kagi-api-key-command=COMMAND command to run to get Kagi API key @@ -112,7 +117,8 @@ Run kaagum AI agent. invalid-option invalid-argument '((model . "anthropic/claude-opus-4.8") - (api-base-uri . "https://openrouter.ai/api"))))) + (api-base-uri . "https://openrouter.ai/api") + (compacter-eval . "noop-compacter"))))) (when (assq-ref args 'help) (print-usage program) (exit #t)) @@ -135,7 +141,10 @@ Run kaagum AI agent. '()) (if (assq-ref args 'more-tools) (load (assq-ref args 'more-tools)) - '()))))) + '())) + (eval (call-with-input-string (assq-ref args 'compacter-eval) + read) + (interaction-environment))))) (parameterize ((%kagi-api-key (and kagi-api-key-command (get-api-key kagi-api-key-command)))) ;; (trace 'kagi "Key ~a" (%kagi-api-key)) diff --git a/kaagum/compacters.scm b/kaagum/compacters.scm new file mode 100644 index 0000000..245d1ad --- /dev/null +++ b/kaagum/compacters.scm @@ -0,0 +1,25 @@ +;;; kaagum --- Tiny, security-focused AI agent in Guile +;;; Copyright © 2026 Arun Isaac <arunisaac@systemreboot.net> +;;; +;;; This file is part of kaagum. +;;; +;;; kaagum is free software: you can redistribute it and/or modify it +;;; under the terms of the GNU General Public License as published by +;;; the Free Software Foundation, either version 3 of the License, or +;;; (at your option) any later version. +;;; +;;; kaagum is distributed in the hope that it will be useful, but +;;; WITHOUT ANY WARRANTY; without even the implied warranty of +;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +;;; General Public License for more details. +;;; +;;; You should have received a copy of the GNU General Public License +;;; along with kaagum. If not, see <https://www.gnu.org/licenses/>. + +(define-module (kaagum compacters) + #:export (noop-compacter)) + +;; This is an identity compacter. It doesn't compact at all; it returns the +;; messages as they are. +(define* (noop-compacter messages #:key tokens context-length) + messages) diff --git a/kaagum/tea.scm b/kaagum/tea.scm index 3caf65e..a8467d1 100644 --- a/kaagum/tea.scm +++ b/kaagum/tea.scm @@ -67,11 +67,12 @@ #:key (input-tokens 0) (output-tokens 0) (thought-tokens 0) (cache-read-tokens 0) (cache-write-tokens 0) (cost 0) - cancelling? (messages '()) (pending-tool-calls '()) - (allowed-tools '()) (rejected-tools '())) + cancelling? (messages '()) (compacted-messages '()) + (pending-tool-calls '()) (allowed-tools '()) + (rejected-tools '())) (constructor cwd model input-tokens output-tokens thought-tokens cache-read-tokens cache-write-tokens cost - cancelling? messages pending-tool-calls + cancelling? messages compacted-messages pending-tool-calls allowed-tools rejected-tools))) (fields (cwd session-cwd lensed) (model session-model lensed) @@ -89,6 +90,7 @@ (cost session-cost lensed) (cancelling? session-cancelling? lensed) (messages session-messages lensed) + (compacted-messages session-compacted-messages lensed) (tool-calls session-tool-calls lensed) ;; List of tool names that are allowlisted for the session (allowed-tools session-allowed-tools lensed) @@ -126,6 +128,24 @@ state." (key-ref session-id) state-sessions)) +(define (state-compacted-messages session-id) + "Return a lens to focus on compacted messages of session with @var{session-id} in +state." + (compose session-compacted-messages + (key-ref session-id) + state-sessions)) + +(define (push-message session-id message state) + "Cons @var{message} onto both messages and compact messages of session with +@var{session-id} in @var{state}." + (-> state + (push (state-messages session-id) + message + <>) + (push (state-compacted-messages session-id) + message + <>))) + (define (state-tool-calls session-id) "Return a lens to focus on tool calls of session with @var{session-id} in state." (compose session-tool-calls @@ -201,9 +221,11 @@ state." (key-ref session-id) state-sessions)) -(define (llm-requests session-id) +(define (llm-requests session-id models) "Return the state-monadic list of @code{<llm-request>} objects for session with -@var{session-id}." +@var{session-id}. + +@var{models} is the same as in @code{tea-loop}." (state-let* ((state (current-state))) (state-return (if (and (null? (focus (state-tool-calls session-id) @@ -211,17 +233,41 @@ state." (not (focus (state-session-cancelling? session-id) state))) ;; There are no more tool calls in flight and a cancellation is not in - ;; progress; dispatch to LLM. - (list (llm-request session-id - (focus (state-model session-id) - state) - ;; Reverse because we have been prepending new - ;; messages onto the list. - (reverse (focus (state-messages session-id) - state)))) + ;; progress; compact before dispatching to LLM. + (list (compaction-request + session-id + ;; Reverse because we have been prepending new messages onto + ;; this list. + (reverse (focus (state-compacted-messages session-id) + state)) + (+ (focus (state-session-input-tokens session-id) + state) + (focus (state-session-output-tokens session-id) + state)) + (focus (compose model-context-length + (key-ref (focus (state-model session-id) + state))) + models))) ;; There are tool calls or a cancellation in progress; do nothing. (list))))) +(define (compaction-response-effects response) + (let ((session-id (compaction-response-session-id response))) + (state-begin + ;; Write compacted messages to state. + (state-let* ((state (current-state))) + (set-current-state (put (state-compacted-messages session-id) + ;; Reverse because we want to keep prepending new + ;; messages onto this list. + (reverse (compaction-response-messages response)) + state)) + ;; Dispatch compacted messages to LLM. + (state-return + (list (llm-request session-id + (focus (state-model session-id) + state) + (compaction-response-messages response)))))))) + (define-record-type* (<llm-request> llm-request llm-request?) (fields (session-id llm-request-session-id) (model llm-request-model) @@ -239,6 +285,16 @@ state." (cost llm-response-cost) (http-error? llm-response-http-error?))) +(define-record-type* (<compaction-request> compaction-request compaction-request?) + (fields (session-id compaction-request-session-id) + (messages compaction-request-messages) + (tokens compaction-request-tokens) + (context-length compaction-request-context-length))) + +(define-record-type* (<compaction-response> compaction-response compaction-response?) + (fields (session-id compaction-response-session-id) + (messages compaction-response-messages))) + (define (message->tree message) "Convert @var{message}, a @code{<user-message>}, @code{<assistant-message>} or @code{<tool-message>} object, to a JSON tree." @@ -549,10 +605,10 @@ in @code{tea-loop}." (else (state-begin (state-let* ((state (current-state))) - (set-current-state (push (state-messages session-id) - (user-message prompt) - state))) - (llm-requests session-id)))))) + (set-current-state (push-message session-id + (user-message prompt) + state))) + (llm-requests session-id models)))))) ("session/cancel" (let ((session-id (focus (in "params" "sessionId") request))) @@ -713,10 +769,10 @@ session with @var{session-id}. (state-let* ((state (current-state))) (set-current-state (-> state ;; Push tool call response onto messages. - (push (state-messages session-id) - (tool-message call-id - (tool-call-parse-failure-message c)) - <>)))) + (push-message session-id + (tool-message call-id + (tool-call-parse-failure-message c)) + <>)))) ;; Notify client about invalid tool call. (state-return (list (acp-message `(("jsonrpc" . "2.0") ("method" . "session/update") @@ -884,9 +940,9 @@ in @code{tea-loop}." (llm-response-cost response) <>) ;; Push LLM response onto messages. - (push (state-messages session-id) - llm-reply - <>)))) + (push-message session-id + llm-reply + <>)))) (state-let* ((tool-call-effects (state-append-map (lambda (call-json) (tool-call-effects session-id call-json tools)) @@ -907,25 +963,26 @@ in @code{tea-loop}." ;; Else, return what we have so far. (state-return effects))) ;; Maybe dispatch LLM requests. - (state-let* ((llm-requests (llm-requests session-id))) + (state-let* ((llm-requests (llm-requests session-id models))) (state-return (append effects llm-requests))))))))) -(define (tool-call-result-effects result) - "Return the state-monadic list of effects for new tool call @var{result}." +(define (tool-call-result-effects result models) + "Return the state-monadic list of effects for new tool call @var{result}. +@var{models} is the same as in @code{tea-loop}." (let ((session-id (tool-call-result-session-id result))) (state-begin (state-let* ((state (current-state))) (set-current-state (-> state ;; Push tool call result onto messages. - (push (state-messages session-id) - (tool-call-result-message result) - <>) + (push-message session-id + (tool-call-result-message result) + <>) ;; Delete tool call from session tool call list. (alist-delete-over (state-tool-calls session-id) (tool-call-result-call-id result) <>)))) ;; Send a notification for each tool call evaluated. - (state-let* ((llm-requests (llm-requests session-id))) + (state-let* ((llm-requests (llm-requests session-id models))) (state-return (cons (acp-message `(("jsonrpc" . "2.0") ("method" . "session/update") @@ -981,9 +1038,11 @@ in @code{tea-loop}." ((llm-response? message) (llm-response-effects message tools models)) ((tool-call-result? message) - (tool-call-result-effects message)))) + (tool-call-result-effects message models)) + ((compaction-response? message) + (compaction-response-effects message)))) -(define* (tea-loop state llm-base-uri llm-api-key models tools +(define* (tea-loop state llm-base-uri llm-api-key models tools compacter #:optional (events (let ((line (get-line (current-input-port)))) (and (not (eof-object? line)) (begin @@ -991,10 +1050,10 @@ in @code{tea-loop}." (list (acp-message (json-string->scm line)))))))) "Run a @acronym{TEA, The Elm Architecture} loop starting with @var{state}. -@var{llm-base-uri}, @var{llm-api-key} and @var{tools} are the same as in -@code{run-tea-loop}. @var{models} is an association list mapping model IDs to -@code{<model>} objects, the first element of which is the default model. -@var{events} is an internal recursion variable." +@var{llm-base-uri}, @var{llm-api-key}, @var{tools} and @var{compacter} are the +same as in @code{run-tea-loop}. @var{models} is an association list mapping +model IDs to @code{<model>} objects, the first element of which is the default +model. @var{events} is an internal recursion variable." ;; Read a JSON-RPC message, handle it, and loop. (when events (let-values (((effects next-state) @@ -1002,18 +1061,18 @@ in @code{tea-loop}." (state-append-map (cut acp-effects <> models tools) events) state))) - (match (append-map (cut do-effect <> llm-base-uri llm-api-key tools) + (match (append-map (cut do-effect <> llm-base-uri llm-api-key tools compacter) effects) (() - (tea-loop next-state llm-base-uri llm-api-key models tools)) + (tea-loop next-state llm-base-uri llm-api-key models tools compacter)) ((events ...) - (tea-loop next-state llm-base-uri llm-api-key models tools events)))))) + (tea-loop next-state llm-base-uri llm-api-key models tools compacter events)))))) -(define (do-effect effect llm-base-uri llm-api-key tools) +(define (do-effect effect llm-base-uri llm-api-key tools compacter) "Do @var{effect}. Return list of events produced by the effect. -@var{llm-base-uri}, @var{llm-api-key} and @var{tools} are the same as in -@code{run-tea-loop}." +@var{llm-base-uri}, @var{llm-api-key}, @var{tools} and @var{compacter} are the +same as in @code{run-tea-loop}." (cond ;; Send message to client, and return the state unchanged. ((acp-message? effect) @@ -1067,20 +1126,36 @@ in @code{tea-loop}." json) 0) #f))))) + ;; Send messages to compacter for compaction; trace this if the messages were + ;; actually compacted. + ((compaction-request? effect) + (let* ((messages (compaction-request-messages effect)) + (compacted-messages (compacter messages + #:tokens (compaction-request-tokens effect) + #:context-length (compaction-request-context-length effect)))) + (unless (every message=? messages compacted-messages) + (trace 'compacter "<- ~a" messages) + (trace 'compacter "-> ~a" compacted-messages)) + (list (compaction-response (compaction-request-session-id effect) + compacted-messages)))) ;; Evaluate tool, handle the result, and return the new state. ((tool-call? effect) (list (eval-tool-call effect tools))))) -(define (run-tea-loop llm-base-uri llm-api-key model tools) +(define (run-tea-loop llm-base-uri llm-api-key model tools compacter) "Run a @acronym{TEA, The Elm Architecture} loop. @var{llm-base-uri} is the base URI of the LLM provider. @var{llm-api-key} is the API key to authenticate with the LLM provider. @var{model} is the name of the model to initialize sessions with. @var{tools} is the list of tools made available to the LLM. It is an -association list matching tool names to @code{<tool>} objects." +association list matching tool names to @code{<tool>} objects. @var{compacter} +is a function that takes a list of messages and returns a compacted list of +messages to query the LLM with. The compacted messages hopefully use fewer +tokens than the original messages." (let ((models (openai-models llm-base-uri llm-api-key))) (tea-loop (state #f 0 0 '() '()) llm-base-uri llm-api-key (cons (assoc model models) (alist-delete model models)) - tools))) + tools + compacter))) -- 2.54.0 ^ permalink raw reply [flat|nested] 29+ messages in thread
* [PATCH 3/4] Add sliding window compacter. 2026-11-10 23:42 ` Arun Isaac 2026-11-13 22:41 ` [PATCH 1/4] Add message record equality comparators Arun Isaac 2026-11-13 22:41 ` [PATCH 2/4] Support context compaction Arun Isaac @ 2026-11-13 22:41 ` Arun Isaac 2026-11-13 22:41 ` [PATCH 4/4] Allow loading compacter from file Arun Isaac 2026-11-13 22:46 ` strategies for context management Arun Isaac 4 siblings, 0 replies; 29+ messages in thread From: Arun Isaac @ 2026-11-13 22:41 UTC (permalink / raw) To: Arun Isaac, Ricardo Wurmus; +Cc: kaagum --- kaagum/compacters.scm | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/kaagum/compacters.scm b/kaagum/compacters.scm index 245d1ad..6f6a3ad 100644 --- a/kaagum/compacters.scm +++ b/kaagum/compacters.scm @@ -17,9 +17,21 @@ ;;; along with kaagum. If not, see <https://www.gnu.org/licenses/>. (define-module (kaagum compacters) - #:export (noop-compacter)) + #:use-module (srfi srfi-1) + #:export (noop-compacter + sliding-window-compacter)) ;; This is an identity compacter. It doesn't compact at all; it returns the ;; messages as they are. (define* (noop-compacter messages #:key tokens context-length) messages) + +;; The sliding window compacter keeps only the N most recent messages once a +;; certain fraction of the context window has been used. +(define* (sliding-window-compacter #:key (n 10) (context-threshold 0.7)) + (lambda* (messages #:key tokens context-length) + (if (and (> (/ tokens context-length) + context-threshold) + (> (length messages) n)) + (take-right messages n) + messages))) -- 2.54.0 ^ permalink raw reply [flat|nested] 29+ messages in thread
* [PATCH 4/4] Allow loading compacter from file. 2026-11-10 23:42 ` Arun Isaac ` (2 preceding siblings ...) 2026-11-13 22:41 ` [PATCH 3/4] Add sliding window compacter Arun Isaac @ 2026-11-13 22:41 ` Arun Isaac 2026-11-13 22:46 ` strategies for context management Arun Isaac 4 siblings, 0 replies; 29+ messages in thread From: Arun Isaac @ 2026-11-13 22:41 UTC (permalink / raw) To: Arun Isaac, Ricardo Wurmus; +Cc: kaagum --- bin/kaagum | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/bin/kaagum b/bin/kaagum index 50fbb76..ac5ab4d 100755 --- a/bin/kaagum +++ b/bin/kaagum @@ -57,6 +57,9 @@ exec guile --no-auto-compile -e main -s "$0" "$@" (option (list #\c "compacter-eval") #t #f (lambda (opt name arg result) (acons 'compacter-eval arg result))) + (option (list "compacter-file") #t #f + (lambda (opt name arg result) + (acons 'compacter-file arg result))) (option (list "kagi-api-key-command") #t #f (lambda (opt name arg result) (acons 'kagi-api-key-command arg result))) @@ -84,6 +87,7 @@ Run kaagum AI agent. (default: \"anthropic/claude-opus-4.8\") -t, --more-tools=FILE scheme file providing more tools to the agent -c, --compacter-eval=EXPR expression returning compacter (default: noop) + --compacter-file=FILE scheme file providing compacter --kagi-api-key-command=COMMAND command to run to get Kagi API key @@ -142,9 +146,11 @@ Run kaagum AI agent. (if (assq-ref args 'more-tools) (load (assq-ref args 'more-tools)) '())) - (eval (call-with-input-string (assq-ref args 'compacter-eval) - read) - (interaction-environment))))) + (if (assq-ref args 'compacter-file) + (load (assq-ref args 'compacter-file)) + (eval (call-with-input-string (assq-ref args 'compacter-eval) + read) + (interaction-environment)))))) (parameterize ((%kagi-api-key (and kagi-api-key-command (get-api-key kagi-api-key-command)))) ;; (trace 'kagi "Key ~a" (%kagi-api-key)) -- 2.54.0 ^ permalink raw reply [flat|nested] 29+ messages in thread
* Re: strategies for context management 2026-11-10 23:42 ` Arun Isaac ` (3 preceding siblings ...) 2026-11-13 22:41 ` [PATCH 4/4] Allow loading compacter from file Arun Isaac @ 2026-11-13 22:46 ` Arun Isaac 2026-11-15 4:47 ` [PATCH v2 0/5] Context compaction Arun Isaac ` (5 more replies) 4 siblings, 6 replies; 29+ messages in thread From: Arun Isaac @ 2026-11-13 22:46 UTC (permalink / raw) To: Ricardo Wurmus; +Cc: kaagum Hi Ricardo, Please try out the new patches adding context management, and let me know what you think. For example, to use the sliding window compacter, you'd add something like "--compacter-eval=(sliding-window-compacter #:n 5 #:context-threshold 0.8)" to your agent-shell-kaagum-parameters. I'm particularly interested in hearing about the compacter interface and whether this works for you. And, I'm still interested in hearing more about your project so I may think along more effectively. Thanks, Arun ^ permalink raw reply [flat|nested] 29+ messages in thread
* [PATCH v2 0/5] Context compaction 2026-11-13 22:46 ` strategies for context management Arun Isaac @ 2026-11-15 4:47 ` Arun Isaac 2026-11-19 14:28 ` Ricardo Wurmus 2026-11-15 4:47 ` [PATCH v2 1/5] Support context compaction Arun Isaac ` (4 subsequent siblings) 5 siblings, 1 reply; 29+ messages in thread From: Arun Isaac @ 2026-11-15 4:47 UTC (permalink / raw) To: Arun Isaac, Ricardo Wurmus; +Cc: kaagum Hi Ricardo, Here's a new v2 patchset. I think this is looking pretty close to completion. Let me know what you think. Cheers! Arun Arun Isaac (5): Support context compaction. Add sliding window compacter. Add summarizing compacter. Document context compacters. Allow user-defined context compacters. README.md | 46 +++++++++++ bin/kaagum | 19 ++++- kaagum/compacters.scm | 159 ++++++++++++++++++++++++++++++++++++++ kaagum/tea.scm | 176 ++++++++++++++++++++++++++++++------------ 4 files changed, 349 insertions(+), 51 deletions(-) create mode 100644 kaagum/compacters.scm -- 2.54.0 ^ permalink raw reply [flat|nested] 29+ messages in thread
* Re: [PATCH v2 0/5] Context compaction 2026-11-15 4:47 ` [PATCH v2 0/5] Context compaction Arun Isaac @ 2026-11-19 14:28 ` Ricardo Wurmus 2026-11-19 14:29 ` Ricardo Wurmus 2026-11-19 18:43 ` Arun Isaac 0 siblings, 2 replies; 29+ messages in thread From: Ricardo Wurmus @ 2026-11-19 14:28 UTC (permalink / raw) To: Arun Isaac; +Cc: Ricardo Wurmus, kaagum Hi Arun, > Here's a new v2 patchset. I think this is looking pretty close > to > completion. Let me know what you think. Thank you for the patches. Unfortunately, it looks like (compaction-request-context-length effect) doesn't return the context length in my case. --8<---------------cut here---------------start------------->8--- WARNING: (kaagum web): imported module (rnrs conditions) overrides core binding `&error' Backtrace: In ice-9/boot-9.scm: 1791:12 11 (with-exception-handler _ _ #:unwind? _ #:unwind-for-type _) In unknown file: 10 (apply-smob/0 #<thunk 7fd284eaf3a0>) In ice-9/boot-9.scm: 740:2 9 (call-with-prompt _ _ #<procedure default-prompt-handler (k proc)>) In ice-9/eval.scm: 619:8 8 (_ #(#(#<directory (guile-user) 7fd284eb2c80>))) In ice-9/boot-9.scm: 161:2 7 (with-fluid* _ _ _) In ice-9/ports.scm: 439:17 6 (call-with-output-file _ _ #:binary _ #:encoding _) In ice-9/boot-9.scm: 161:2 5 (with-fluid* _ _ _) In kaagum/tea.scm: 1021:6 4 (tea-loop _ "https://llm.example.com" "sk-bf-..." (("vllm/Qwen/Qwen3.8-27B" . #<<model> name: #f description: #f context-length: #f>) ("vllm/Aleph-Alpha/Kolibri-1" . #<<model> name: #f description: #f context-length: #f>) ("vllm/google/medgemma-27b-it" . #<<model> name: #f description: #f context-length: #f>) ("vllm/onprem-ai/Apertus-v1.5-70B-FP8" . #<<model> name: #f description: #f context-length: #f>)) (("read" . #<<tool> description: …>) …) …) In srfi/srfi-1.scm: 789:15 3 (append-map #<procedure 7fd26522a380 at kaagum/tea.scm:1021:25 (t-9386c0004f0da33-21f8)> (#<<compaction-request> session-id: "session-0" model: "vllm/Qwen/Qwen3.8-27B" messages: (#<<user-message> content: "hello">) tokens: 0 context-length: #f>)) 702:17 2 (map1 (#<<compaction-request> session-id: "session-0" model: "vllm/Qwen/Qwen3.8-27B" messages: (#<<user-message> content: "hello">) tokens: 0 context-length: #f>)) In kaagum/tea.scm: 1091:11 1 (do-effect #<<compaction-request> session-id: "session-0" model: "vllm/Qwen/Qwen3.8-27B" messages: (#<<user-message> content: "hello">) tokens: 0 context-length: #f> "https://llm.example.com" "sk-bf-..." _ #<procedure 7fd264e9ce60 at kaagum/compacters.scm:109:2 (messages #:key tokens context-length)>) In kaagum/compacters.scm: 110:11 0 (_ (#<<user-message> content: "hello">) #:tokens _ #:context-length _) kaagum/compacters.scm:110:11: In procedure /: Wrong type argument in position 2: #f --8<---------------cut here---------------end--------------->8--- That's on the very first prompt after launching kaagum. -- Ricardo ^ permalink raw reply [flat|nested] 29+ messages in thread
* Re: [PATCH v2 0/5] Context compaction 2026-11-19 14:28 ` Ricardo Wurmus @ 2026-11-19 14:29 ` Ricardo Wurmus 2026-11-19 18:43 ` Arun Isaac 1 sibling, 0 replies; 29+ messages in thread From: Ricardo Wurmus @ 2026-11-19 14:29 UTC (permalink / raw) To: Arun Isaac, kaagum; +Cc: Ricardo Wurmus Ricardo Wurmus <rekado@elephly.net> writes: >> Here's a new v2 patchset. I think this is looking pretty close >> to >> completion. Let me know what you think. > > Thank you for the patches. Unfortunately, it looks like > (compaction-request-context-length effect) doesn't return the > context > length in my case. Forgot to mention: I'm passed the option --compacter-eval=(sliding-window-compacter) -- Ricardo ^ permalink raw reply [flat|nested] 29+ messages in thread
* Re: [PATCH v2 0/5] Context compaction 2026-11-19 14:28 ` Ricardo Wurmus 2026-11-19 14:29 ` Ricardo Wurmus @ 2026-11-19 18:43 ` Arun Isaac 2026-11-20 5:39 ` Ricardo Wurmus 1 sibling, 1 reply; 29+ messages in thread From: Arun Isaac @ 2026-11-19 18:43 UTC (permalink / raw) To: Ricardo Wurmus; +Cc: Ricardo Wurmus, kaagum Hi Ricardo, I suspect your LLM provider may not be providing the context length of the model. Could you look at the trace and verify? The very first web query kaagum makes is to get a list of the available models. You should be able to get at the JSON response using something like this. grep '^web: <-' /path/to/kaagum-trace | cut -d\ -f4- | jq . Regards, Arun ^ permalink raw reply [flat|nested] 29+ messages in thread
* Re: [PATCH v2 0/5] Context compaction 2026-11-19 18:43 ` Arun Isaac @ 2026-11-20 5:39 ` Ricardo Wurmus 2026-11-20 5:56 ` Ricardo Wurmus 0 siblings, 1 reply; 29+ messages in thread From: Ricardo Wurmus @ 2026-11-20 5:39 UTC (permalink / raw) To: Arun Isaac; +Cc: Ricardo Wurmus, kaagum Hi Arun, > I suspect your LLM provider may not be providing the context > length of > the model. Could you look at the trace and verify? The very > first web > query kaagum makes is to get a list of the available models. You > should > be able to get at the JSON response using something like this. > > grep '^web: <-' /path/to/kaagum-trace | cut -d\ -f4- | jq . Yeah, none of that information is provided: { "key_statuses": [ { "provider": "vllm", "status": "success", "key_id": "42b72370-6ff3-46b9-bab4-b277489d27f6" }, { "provider": "vllm", "status": "success", "key_id": "ed57be92-cd94-4687-9b33-d6b12dada6d0" }, { "provider": "vllm", "status": "success", "key_id": "e66025bf-24ae-4820-922a-1984a4208b2f" }, { "provider": "vllm", "status": "success", "key_id": "fdaa4171-3f94-4d63-900a-f3010cb67604" }, { "provider": "vllm", "status": "success", "key_id": "99e95636-f050-4f9f-8095-18e66087cb75" }, { "provider": "vllm", "status": "success", "key_id": "c784173d-0886-44e6-8de7-e9b3e9205aaf" }, { "provider": "vllm", "status": "success", "key_id": "764301f2-074d-4d64-8841-1a65213a85cb" }, { "provider": "vllm", "status": "success", "key_id": "339e3375-85db-41d5-b277-f559b122eaa5" }, { "provider": "vllm", "status": "success", "key_id": "b5121be1-f4a0-47f3-b64b-295a50d18a0e" }, { "provider": "vllm", "status": "success", "key_id": "7c30c0c8-6615-44d2-9fcc-cfd3ac16d581" } ], "extra_fields": { "chunk_index": 0, "latency": 36, "routing_info": {}, "request_type": "list_models" }, "data": [ { "owned_by": "vllm", "created": 1795098269, "id": "vllm/Aleph-Alpha/Kolibri-1" }, { "owned_by": "vllm", "created": 1795098269, "id": "vllm/Qwen/Qwen3.8-27B" }, { "owned_by": "vllm", "created": 1795098269, "id": "vllm/google/medgemma-27b-it" }, { "owned_by": "vllm", "created": 1795098269, "id": "vllm/onprem-ai/Apertus-v1.5-70B-FP8" } ] } I'll check on bifrost if this can be enabled. -- Ricardo ^ permalink raw reply [flat|nested] 29+ messages in thread
* Re: [PATCH v2 0/5] Context compaction 2026-11-20 5:39 ` Ricardo Wurmus @ 2026-11-20 5:56 ` Ricardo Wurmus 2026-11-20 13:42 ` Arun Isaac 0 siblings, 1 reply; 29+ messages in thread From: Ricardo Wurmus @ 2026-11-20 5:56 UTC (permalink / raw) To: Ricardo Wurmus; +Cc: Arun Isaac, kaagum Ricardo Wurmus <rekado@elephly.net> writes: >> I suspect your LLM provider may not be providing the context >> length >> of >> the model. Could you look at the trace and verify? The very >> first >> web >> query kaagum makes is to get a list of the available >> models. You >> should >> be able to get at the JSON response using something like this. >> >> grep '^web: <-' /path/to/kaagum-trace | cut -d\ -f4- | jq . > > Yeah, none of that information is provided:[...] Looks like a known problem with bifrost: https://github.com/maximhq/bifrost/issues/8914 -- Ricardo ^ permalink raw reply [flat|nested] 29+ messages in thread
* Re: [PATCH v2 0/5] Context compaction 2026-11-20 5:56 ` Ricardo Wurmus @ 2026-11-20 13:42 ` Arun Isaac 2026-11-20 13:45 ` Arun Isaac 2026-11-20 14:01 ` Ricardo Wurmus 0 siblings, 2 replies; 29+ messages in thread From: Arun Isaac @ 2026-11-20 13:42 UTC (permalink / raw) To: Ricardo Wurmus; +Cc: kaagum Hi Ricardo, Looking at your backtrace from earlier, you are missing not just the context-length but also the tokens used (see third frame from the bottom in the backtrace). Not sure how to mitigate this on kaagum's side. Any suggestions? We could estimate the tokens used from the number of characters in the message. But, we can't do much about the context length. Perhaps we should fall back to having a fixed threshold for the tokens used rather than computing the fraction of the context that has been used. Or, perhaps we should only ever use a fixed threshold and not bother to compute the fraction at all. This is what Pi does: https://docs.pi.dev/latest/compaction (look for "reserveTokens"). That page explains that their compaction triggers when contextTokens > contextWindow - reserveTokens Regards, Arun ^ permalink raw reply [flat|nested] 29+ messages in thread
* Re: [PATCH v2 0/5] Context compaction 2026-11-20 13:42 ` Arun Isaac @ 2026-11-20 13:45 ` Arun Isaac 2026-11-20 14:01 ` Ricardo Wurmus 1 sibling, 0 replies; 29+ messages in thread From: Arun Isaac @ 2026-11-20 13:45 UTC (permalink / raw) To: Ricardo Wurmus; +Cc: kaagum > This is what Pi does: https://docs.pi.dev/latest/compaction (look for > "reserveTokens"). That page explains that their compaction triggers > when > > contextTokens > contextWindow - reserveTokens Actually, we can't use this condition either since we don't know contextWindow. I am open to suggestions. Cheers! ^ permalink raw reply [flat|nested] 29+ messages in thread
* Re: [PATCH v2 0/5] Context compaction 2026-11-20 13:42 ` Arun Isaac 2026-11-20 13:45 ` Arun Isaac @ 2026-11-20 14:01 ` Ricardo Wurmus 2026-11-22 16:54 ` Arun Isaac 1 sibling, 1 reply; 29+ messages in thread From: Ricardo Wurmus @ 2026-11-20 14:01 UTC (permalink / raw) To: Arun Isaac; +Cc: Ricardo Wurmus, kaagum Hi Arun, > Looking at your backtrace from earlier, you are missing not just > the > context-length but also the tokens used (see third frame from > the bottom > in the backtrace). Not sure how to mitigate this on kaagum's > side. Any > suggestions? In Bifrost I see the tokens used for every request, so the information is available; I just don't know at what point is is dropped. I see that in Bifrost we can add attributes to hosted models, so I'll check with the admins to see if we can pass more model parameters through. -- Ricardo ^ permalink raw reply [flat|nested] 29+ messages in thread
* Re: [PATCH v2 0/5] Context compaction 2026-11-20 14:01 ` Ricardo Wurmus @ 2026-11-22 16:54 ` Arun Isaac 0 siblings, 0 replies; 29+ messages in thread From: Arun Isaac @ 2026-11-22 16:54 UTC (permalink / raw) To: Ricardo Wurmus; +Cc: Ricardo Wurmus, kaagum Hi Ricardo, > In Bifrost I see the tokens used for every request, so the > information is available; Can we verify the tokens used is in your LLM response? If you can share the output of the command below, that would be helpful. I am going for the second line using `sed -n 2p` since the first line only returns the list of available models. grep '^web: <-' /path/to/kaagum-trace | sed -n 2p | cut -d\ -f4- | jq .usage Here is what I see with OpenRouter. { "completion_tokens_details": { "audio_tokens": 0, "image_tokens": 0, "reasoning_tokens": 0 }, "cost_details": { "upstream_inference_completions_cost": 0.00090, "upstream_inference_prompt_cost": 0.010161, "upstream_inference_cost": 0.011061 }, "prompt_tokens_details": { "video_tokens": 0, "audio_tokens": 0, "cache_write_tokens": 1692, "cached_tokens": 0 }, "is_byok": false, "cost": 0.011061, "total_tokens": 1755, "completion_tokens": 60, "prompt_tokens": 1695 } > I see that in Bifrost we can add attributes to hosted models, so I'll > check with the admins to see if we can pass more model parameters > through. Yes, please. Thanks! Arun ^ permalink raw reply [flat|nested] 29+ messages in thread
* [PATCH v2 1/5] Support context compaction. 2026-11-13 22:46 ` strategies for context management Arun Isaac 2026-11-15 4:47 ` [PATCH v2 0/5] Context compaction Arun Isaac @ 2026-11-15 4:47 ` Arun Isaac 2026-11-15 4:47 ` [PATCH v2 2/5] Add sliding window compacter Arun Isaac ` (3 subsequent siblings) 5 siblings, 0 replies; 29+ messages in thread From: Arun Isaac @ 2026-11-15 4:47 UTC (permalink / raw) To: Arun Isaac, Ricardo Wurmus; +Cc: kaagum --- bin/kaagum | 13 +++- kaagum/compacters.scm | 26 +++++++ kaagum/tea.scm | 176 ++++++++++++++++++++++++++++++------------ 3 files changed, 164 insertions(+), 51 deletions(-) create mode 100644 kaagum/compacters.scm diff --git a/bin/kaagum b/bin/kaagum index 2c8c9ee..50fbb76 100755 --- a/bin/kaagum +++ b/bin/kaagum @@ -24,6 +24,7 @@ exec guile --no-auto-compile -e main -s "$0" "$@" (srfi srfi-26) (srfi srfi-37) (ice-9 match) + (kaagum compacters) ; for --compacter-eval expressions (kaagum config) (kaagum openai) (kaagum tea) @@ -53,6 +54,9 @@ exec guile --no-auto-compile -e main -s "$0" "$@" (option (list #\t "more-tools") #t #f (lambda (opt name arg result) (acons 'more-tools arg result))) + (option (list #\c "compacter-eval") #t #f + (lambda (opt name arg result) + (acons 'compacter-eval arg result))) (option (list "kagi-api-key-command") #t #f (lambda (opt name arg result) (acons 'kagi-api-key-command arg result))) @@ -79,6 +83,7 @@ Run kaagum AI agent. -m, --model=MODEL LLM model name to start new sessions with (default: \"anthropic/claude-opus-4.8\") -t, --more-tools=FILE scheme file providing more tools to the agent + -c, --compacter-eval=EXPR expression returning compacter (default: noop) --kagi-api-key-command=COMMAND command to run to get Kagi API key @@ -112,7 +117,8 @@ Run kaagum AI agent. invalid-option invalid-argument '((model . "anthropic/claude-opus-4.8") - (api-base-uri . "https://openrouter.ai/api"))))) + (api-base-uri . "https://openrouter.ai/api") + (compacter-eval . "noop-compacter"))))) (when (assq-ref args 'help) (print-usage program) (exit #t)) @@ -135,7 +141,10 @@ Run kaagum AI agent. '()) (if (assq-ref args 'more-tools) (load (assq-ref args 'more-tools)) - '()))))) + '())) + (eval (call-with-input-string (assq-ref args 'compacter-eval) + read) + (interaction-environment))))) (parameterize ((%kagi-api-key (and kagi-api-key-command (get-api-key kagi-api-key-command)))) ;; (trace 'kagi "Key ~a" (%kagi-api-key)) diff --git a/kaagum/compacters.scm b/kaagum/compacters.scm new file mode 100644 index 0000000..25a3281 --- /dev/null +++ b/kaagum/compacters.scm @@ -0,0 +1,26 @@ +;;; kaagum --- Tiny, security-focused AI agent in Guile +;;; Copyright © 2026 Arun Isaac <arunisaac@systemreboot.net> +;;; +;;; This file is part of kaagum. +;;; +;;; kaagum is free software: you can redistribute it and/or modify it +;;; under the terms of the GNU General Public License as published by +;;; the Free Software Foundation, either version 3 of the License, or +;;; (at your option) any later version. +;;; +;;; kaagum is distributed in the hope that it will be useful, but +;;; WITHOUT ANY WARRANTY; without even the implied warranty of +;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +;;; General Public License for more details. +;;; +;;; You should have received a copy of the GNU General Public License +;;; along with kaagum. If not, see <https://www.gnu.org/licenses/>. + +(define-module (kaagum compacters) + #:use-module (kaagum records) + #:export (noop-compacter)) + +;; The noop compacter is an identity compacter. It doesn't compact at all; it +;; returns the messages as they are. +(define* (noop-compacter messages #:key tokens context-length #:allow-other-keys) + messages) \ No newline at end of file diff --git a/kaagum/tea.scm b/kaagum/tea.scm index ca05f52..0ed8a32 100644 --- a/kaagum/tea.scm +++ b/kaagum/tea.scm @@ -67,11 +67,12 @@ #:key (input-tokens 0) (output-tokens 0) (thought-tokens 0) (cache-read-tokens 0) (cache-write-tokens 0) (cost 0) - cancelling? (messages '()) (pending-tool-calls '()) - (allowed-tools '()) (rejected-tools '())) + cancelling? (messages '()) (messages-context '()) + (pending-tool-calls '()) (allowed-tools '()) + (rejected-tools '())) (constructor cwd model input-tokens output-tokens thought-tokens cache-read-tokens cache-write-tokens cost - cancelling? messages pending-tool-calls + cancelling? messages messages-context pending-tool-calls allowed-tools rejected-tools))) (fields (cwd session-cwd lensed) (model session-model lensed) @@ -89,6 +90,7 @@ (cost session-cost lensed) (cancelling? session-cancelling? lensed) (messages session-messages lensed) + (messages-context session-messages-context lensed) (tool-calls session-tool-calls lensed) ;; List of tool names that are allowlisted for the session (allowed-tools session-allowed-tools lensed) @@ -126,6 +128,24 @@ state." (key-ref session-id) state-sessions)) +(define (state-messages-context session-id) + "Return a lens to focus on the messages in the context of session with +@var{session-id} in state." + (compose session-messages-context + (key-ref session-id) + state-sessions)) + +(define (push-message session-id message state) + "Cons @var{message} onto both messages and the messages context of session with +@var{session-id} in @var{state}." + (-> state + (push (state-messages session-id) + message + <>) + (push (state-messages-context session-id) + message + <>))) + (define (state-tool-calls session-id) "Return a lens to focus on tool calls of session with @var{session-id} in state." (compose session-tool-calls @@ -201,9 +221,11 @@ state." (key-ref session-id) state-sessions)) -(define (llm-requests session-id) +(define (llm-requests session-id models) "Return the state-monadic list of @code{<llm-request>} objects for session with -@var{session-id}." +@var{session-id}. + +@var{models} is the same as in @code{tea-loop}." (state-let* ((state (current-state))) (state-return (if (and (null? (focus (state-tool-calls session-id) @@ -211,17 +233,43 @@ state." (not (focus (state-session-cancelling? session-id) state))) ;; There are no more tool calls in flight and a cancellation is not in - ;; progress; dispatch to LLM. - (list (llm-request session-id - (focus (state-model session-id) - state) - ;; Reverse because we have been prepending new - ;; messages onto the list. - (reverse (focus (state-messages session-id) - state)))) + ;; progress; compact before dispatching to LLM. + (list (compaction-request + session-id + (focus (state-model session-id) + state) + ;; Reverse because we have been prepending new messages onto + ;; this list. + (reverse (focus (state-messages-context session-id) + state)) + (+ (focus (state-session-input-tokens session-id) + state) + (focus (state-session-output-tokens session-id) + state)) + (focus (compose model-context-length + (key-ref (focus (state-model session-id) + state))) + models))) ;; There are tool calls or a cancellation in progress; do nothing. (list))))) +(define (compaction-response-effects response) + (let ((session-id (compaction-response-session-id response))) + (state-begin + ;; Write compacted messages to state. + (state-let* ((state (current-state))) + (set-current-state (put (state-messages-context session-id) + ;; Reverse because we want to keep prepending new + ;; messages onto this list. + (reverse (compaction-response-messages response)) + state)) + ;; Dispatch compacted messages to LLM. + (state-return + (list (llm-request session-id + (focus (state-model session-id) + state) + (compaction-response-messages response)))))))) + (define-record-type* (<llm-request> llm-request llm-request?) (fields (session-id llm-request-session-id) (model llm-request-model) @@ -239,6 +287,18 @@ state." (cost llm-response-cost) (http-error? llm-response-http-error?))) +(define-record-type* (<compaction-request> compaction-request compaction-request?) + (fields (session-id compaction-request-session-id) + ;; Model name (string) + (model compaction-request-model) + (messages compaction-request-messages) + (tokens compaction-request-tokens) + (context-length compaction-request-context-length))) + +(define-record-type* (<compaction-response> compaction-response compaction-response?) + (fields (session-id compaction-response-session-id) + (messages compaction-response-messages))) + (define-record-type* (<acp-message> acp-message acp-message?) (fields (json acp-message-json lensed))) @@ -498,13 +558,13 @@ in @code{tea-loop}." (else (state-begin (state-let* ((state (current-state))) - (set-current-state (push (state-messages session-id) - ;; TODO: Allow more than one - ;; content block. - (user-message (focus (in-json 0 "text") - prompt)) - state))) - (llm-requests session-id)))))) + (set-current-state (push-message session-id + ;; TODO: Allow more than + ;; one content block. + (user-message (focus (in-json 0 "text") + prompt)) + state))) + (llm-requests session-id models)))))) ("session/cancel" (let ((session-id (focus (in "params" "sessionId") request))) @@ -665,10 +725,10 @@ session with @var{session-id}. (state-let* ((state (current-state))) (set-current-state (-> state ;; Push tool call response onto messages. - (push (state-messages session-id) - (tool-message call-id - (tool-call-parse-failure-message c)) - <>)))) + (push-message session-id + (tool-message call-id + (tool-call-parse-failure-message c)) + <>)))) ;; Notify client about invalid tool call. (state-return (list (acp-message `(("jsonrpc" . "2.0") ("method" . "session/update") @@ -836,9 +896,9 @@ in @code{tea-loop}." (llm-response-cost response) <>) ;; Push LLM response onto messages. - (push (state-messages session-id) - llm-reply - <>)))) + (push-message session-id + llm-reply + <>)))) (state-let* ((tool-call-effects (state-append-map (lambda (call-json) (tool-call-effects session-id call-json tools)) @@ -859,25 +919,26 @@ in @code{tea-loop}." ;; Else, return what we have so far. (state-return effects))) ;; Maybe dispatch LLM requests. - (state-let* ((llm-requests (llm-requests session-id))) + (state-let* ((llm-requests (llm-requests session-id models))) (state-return (append effects llm-requests))))))))) -(define (tool-call-result-effects result) - "Return the state-monadic list of effects for new tool call @var{result}." +(define (tool-call-result-effects result models) + "Return the state-monadic list of effects for new tool call @var{result}. +@var{models} is the same as in @code{tea-loop}." (let ((session-id (tool-call-result-session-id result))) (state-begin (state-let* ((state (current-state))) (set-current-state (-> state ;; Push tool call result onto messages. - (push (state-messages session-id) - (tool-call-result-message result) - <>) + (push-message session-id + (tool-call-result-message result) + <>) ;; Delete tool call from session tool call list. (alist-delete-over (state-tool-calls session-id) (tool-call-result-call-id result) <>)))) ;; Send a notification for each tool call evaluated. - (state-let* ((llm-requests (llm-requests session-id))) + (state-let* ((llm-requests (llm-requests session-id models))) (state-return (cons (acp-message `(("jsonrpc" . "2.0") ("method" . "session/update") @@ -933,9 +994,11 @@ in @code{tea-loop}." ((llm-response? message) (llm-response-effects message tools models)) ((tool-call-result? message) - (tool-call-result-effects message)))) + (tool-call-result-effects message models)) + ((compaction-response? message) + (compaction-response-effects message)))) -(define* (tea-loop state llm-base-uri llm-api-key models tools +(define* (tea-loop state llm-base-uri llm-api-key models tools compacter #:optional (events (let ((line (get-line (current-input-port)))) (and (not (eof-object? line)) (begin @@ -943,10 +1006,10 @@ in @code{tea-loop}." (list (acp-message (json-string->scm line)))))))) "Run a @acronym{TEA, The Elm Architecture} loop starting with @var{state}. -@var{llm-base-uri}, @var{llm-api-key} and @var{tools} are the same as in -@code{run-tea-loop}. @var{models} is an association list mapping model IDs to -@code{<model>} objects, the first element of which is the default model. -@var{events} is an internal recursion variable." +@var{llm-base-uri}, @var{llm-api-key}, @var{tools} and @var{compacter} are the +same as in @code{run-tea-loop}. @var{models} is an association list mapping +model IDs to @code{<model>} objects, the first element of which is the default +model. @var{events} is an internal recursion variable." ;; Read a JSON-RPC message, handle it, and loop. (when events (let-values (((effects next-state) @@ -954,18 +1017,18 @@ in @code{tea-loop}." (state-append-map (cut acp-effects <> models tools) events) state))) - (match (append-map (cut do-effect <> llm-base-uri llm-api-key tools) + (match (append-map (cut do-effect <> llm-base-uri llm-api-key tools compacter) effects) (() - (tea-loop next-state llm-base-uri llm-api-key models tools)) + (tea-loop next-state llm-base-uri llm-api-key models tools compacter)) ((events ...) - (tea-loop next-state llm-base-uri llm-api-key models tools events)))))) + (tea-loop next-state llm-base-uri llm-api-key models tools compacter events)))))) -(define (do-effect effect llm-base-uri llm-api-key tools) +(define (do-effect effect llm-base-uri llm-api-key tools compacter) "Do @var{effect}. Return list of events produced by the effect. -@var{llm-base-uri}, @var{llm-api-key} and @var{tools} are the same as in -@code{run-tea-loop}." +@var{llm-base-uri}, @var{llm-api-key}, @var{tools} and @var{compacter} are the +same as in @code{run-tea-loop}." (cond ;; Send message to client, and return the state unchanged. ((acp-message? effect) @@ -1019,20 +1082,35 @@ in @code{tea-loop}." json) 0) #f))))) + ;; Send messages to compacter for compaction; trace this if the messages were + ;; actually compacted. + ((compaction-request? effect) + (list (compaction-response + (compaction-request-session-id effect) + (compacter (compaction-request-messages effect) + #:tokens (compaction-request-tokens effect) + #:context-length (compaction-request-context-length effect) + #:llm-base-uri llm-base-uri + #:llm-api-key llm-api-key + #:model (compaction-request-model effect))))) ;; Evaluate tool, handle the result, and return the new state. ((tool-call? effect) (list (eval-tool-call effect tools))))) -(define (run-tea-loop llm-base-uri llm-api-key model tools) +(define (run-tea-loop llm-base-uri llm-api-key model tools compacter) "Run a @acronym{TEA, The Elm Architecture} loop. @var{llm-base-uri} is the base URI of the LLM provider. @var{llm-api-key} is the API key to authenticate with the LLM provider. @var{model} is the name of the model to initialize sessions with. @var{tools} is the list of tools made available to the LLM. It is an -association list matching tool names to @code{<tool>} objects." +association list matching tool names to @code{<tool>} objects. @var{compacter} +is a function that takes a list of messages and returns a compacted list of +messages to query the LLM with. The compacted messages hopefully use fewer +tokens than the original messages." (let ((models (openai-models llm-base-uri llm-api-key))) (tea-loop (state #f 0 0 '() '()) llm-base-uri llm-api-key (cons (assoc model models) (alist-delete model models)) - tools))) + tools + compacter))) -- 2.54.0 ^ permalink raw reply [flat|nested] 29+ messages in thread
* [PATCH v2 2/5] Add sliding window compacter. 2026-11-13 22:46 ` strategies for context management Arun Isaac 2026-11-15 4:47 ` [PATCH v2 0/5] Context compaction Arun Isaac 2026-11-15 4:47 ` [PATCH v2 1/5] Support context compaction Arun Isaac @ 2026-11-15 4:47 ` Arun Isaac 2026-11-15 4:47 ` [PATCH v2 3/5] Add summarizing compacter Arun Isaac ` (2 subsequent siblings) 5 siblings, 0 replies; 29+ messages in thread From: Arun Isaac @ 2026-11-15 4:47 UTC (permalink / raw) To: Arun Isaac, Ricardo Wurmus; +Cc: kaagum --- kaagum/compacters.scm | 97 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 95 insertions(+), 2 deletions(-) diff --git a/kaagum/compacters.scm b/kaagum/compacters.scm index 25a3281..4df4d19 100644 --- a/kaagum/compacters.scm +++ b/kaagum/compacters.scm @@ -17,10 +17,103 @@ ;;; along with kaagum. If not, see <https://www.gnu.org/licenses/>. (define-module (kaagum compacters) + #:use-module (srfi srfi-1) + #:use-module (srfi srfi-11) + #:use-module (srfi srfi-26) + #:use-module (ice-9 match) + #:use-module (json) + #:use-module (kaagum message) #:use-module (kaagum records) - #:export (noop-compacter)) + #:use-module (kaagum trace) + #:export (trace-compacter-in + trace-compacter-out + + noop-compacter + sliding-window-compacter)) ;; The noop compacter is an identity compacter. It doesn't compact at all; it ;; returns the messages as they are. (define* (noop-compacter messages #:key tokens context-length #:allow-other-keys) - messages) \ No newline at end of file + messages) + +(define (trace-compacter-in messages) + "Trace compacter input of @var{messages} and return it." + (trace 'compacter "<- ~a" + (scm->json-string (list->vector (map message->tree messages)))) + messages) + +(define (trace-compacter-out messages) + "Trace compacter output of @var{messages} and return it." + (trace 'compacter "-> ~a" + (scm->json-string (list->vector (map message->tree messages)))) + messages) + +(define (message-length message) + (or (and=> (message-content message) + string-length) + 0)) + +(define (nspan pred . lists) + "Like @code{span}, but where the @var{pred} takes many arguments instead of one." + (let-values (((keep-list drop-list) + (span (cut apply pred <>) + (apply map list lists)))) + (values (map first keep-list) + (map first drop-list)))) + +(define (break-messages messages tokens keep-tokens) + "Break list of @var{messages} into two lists, the second list of which +corresponds to @var{keep-tokens} number of tokens. The second list has at least +one element, even when it corresponds to more than @var{keep-tokens} number of +tokens. The @var{messages} list is only broken at a prompt turn boundary, that +is, at @code{<user-message>} type messages. + +@var{tokens} is the number of tokens @var{messages} corresponds to." + (let ((total-message-length (fold (lambda (message result) + (+ (message-length message) + result)) + 0 + messages))) + (let-values (((keep-messages drop-messages) + (nspan (lambda (message previous-message tokens-so-far) + ;; We break only at prompt turn boundaries, that is, + ;; when the previous message is a <user-message>. + ;; Since the first message has no previous message, + ;; this also means that at least one message is + ;; guaranteed to be kept. + (or (not (user-message? previous-message)) + (< tokens-so-far keep-tokens))) + (reverse messages) + (cons #f (reverse messages)) + (fold (lambda (message result) + (cons (+ (* (/ (message-length message) + total-message-length) + tokens) + (match result + (() 0) + ((head tail ...) head))) + result)) + '() + (reverse messages))))) + (values (reverse drop-messages) + (reverse keep-messages))))) + +;; Once CONTEXT-THRESHOLD fraction of the context window has been used, the +;; sliding window compacter keeps only the most recent messages corresponding to +;; KEEP-CONTEXT fraction of the context window. +(define* (sliding-window-compacter #:key (context-threshold 0.7) (keep-context 0.2)) + (lambda* (messages #:key tokens context-length #:allow-other-keys) + (if (> (/ tokens context-length) + context-threshold) + (let-values (((drop-messages keep-messages) + (break-messages messages + tokens + (* keep-context context-length)))) + (match drop-messages + ;; keep all messages + (() keep-messages) + ;; actually drop messages + (_ + (trace-compacter-in messages) + (trace-compacter-out keep-messages)))) + messages))) -- 2.54.0 ^ permalink raw reply [flat|nested] 29+ messages in thread
* [PATCH v2 3/5] Add summarizing compacter. 2026-11-13 22:46 ` strategies for context management Arun Isaac ` (2 preceding siblings ...) 2026-11-15 4:47 ` [PATCH v2 2/5] Add sliding window compacter Arun Isaac @ 2026-11-15 4:47 ` Arun Isaac 2026-11-15 4:47 ` [PATCH v2 4/5] Document context compacters Arun Isaac 2026-11-15 4:47 ` [PATCH v2 5/5] Allow user-defined " Arun Isaac 5 siblings, 0 replies; 29+ messages in thread From: Arun Isaac @ 2026-11-15 4:47 UTC (permalink / raw) To: Arun Isaac, Ricardo Wurmus; +Cc: kaagum --- kaagum/compacters.scm | 42 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/kaagum/compacters.scm b/kaagum/compacters.scm index 4df4d19..b9daf2f 100644 --- a/kaagum/compacters.scm +++ b/kaagum/compacters.scm @@ -22,14 +22,18 @@ #:use-module (srfi srfi-26) #:use-module (ice-9 match) #:use-module (json) + #:use-module (lens) + #:use-module (kaagum lens) #:use-module (kaagum message) + #:use-module (kaagum openai) #:use-module (kaagum records) #:use-module (kaagum trace) #:export (trace-compacter-in trace-compacter-out noop-compacter - sliding-window-compacter)) + sliding-window-compacter + summarizing-compacter)) ;; The noop compacter is an identity compacter. It doesn't compact at all; it ;; returns the messages as they are. @@ -117,3 +121,39 @@ is, at @code{<user-message>} type messages. (trace-compacter-in messages) (trace-compacter-out keep-messages)))) messages))) + +;; Once CONTEXT-THRESHOLD fraction of the context window has been used, the +;; summarizing compacter keeps the most recent messages corresponding to +;; KEEP-CONTEXT fraction of the context window and summarizes all the earlier +;; messages into a single message. +(define* (summarizing-compacter #:key (context-threshold 0.7) (keep-context 0.2) + (summarizer-prompt "Summarize all the conversation prior to this point into a single message.")) + (lambda* (messages #:key tokens context-length llm-base-uri llm-api-key model #:allow-other-keys) + (if (> (/ tokens context-length) + context-threshold) + (let-values (((drop-messages keep-messages) + (break-messages messages + tokens + (* keep-context context-length)))) + (match drop-messages + ;; keep all messages + (() keep-messages) + ;; no point summarizing one message, just cons it on. + ((drop-message) + (cons drop-message + keep-messages)) + ;; actually summarize + (_ + (trace-compacter-in messages) + (trace-compacter-out + (cons (tree->message + (focus (in-json "choices" 0 "message") + (openai-query llm-base-uri + llm-api-key + model + (append (map message->tree drop-messages) + `((("role" . "user") + ("content" . ,summarizer-prompt)))) + '()))) + keep-messages))))) + messages))) -- 2.54.0 ^ permalink raw reply [flat|nested] 29+ messages in thread
* [PATCH v2 4/5] Document context compacters. 2026-11-13 22:46 ` strategies for context management Arun Isaac ` (3 preceding siblings ...) 2026-11-15 4:47 ` [PATCH v2 3/5] Add summarizing compacter Arun Isaac @ 2026-11-15 4:47 ` Arun Isaac 2026-11-15 4:47 ` [PATCH v2 5/5] Allow user-defined " Arun Isaac 5 siblings, 0 replies; 29+ messages in thread From: Arun Isaac @ 2026-11-15 4:47 UTC (permalink / raw) To: Arun Isaac, Ricardo Wurmus; +Cc: kaagum --- README.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/README.md b/README.md index 67a3ad2..210089a 100644 --- a/README.md +++ b/README.md @@ -82,6 +82,37 @@ If your custom tools require other Guile packages or modules, you may provide ac "GUILE_LOAD_COMPILED_PATH" "/some/path/")) ``` +# Context compaction + +In long conversations, it is helpful to compact messages so that the context window of the model is not exceeded. kaagum supports various compaction strategies. + +## Sliding window compacter + +```scheme +(sliding-window-compacter #:key (context-threshold 0.7) (keep-context 0.2)) +``` +Once `context-threshold` fraction of the context window has been used, the sliding window compacter keeps only the most recent messages corresponding to `keep-context` fraction of the context window. + +To use this compacter, pass `--compacter-eval=(sliding-window-compacter)` to kaagum. You may also configure the compacter parameters using something like `--compacter-eval=(sliding-window-compacter #:context-threshold 0.8 #:keep-context 0.3)`. + +## Summarizing compacter + +```scheme +(summarizing-compacter #:key (context-threshold 0.7) + (keep-context 0.2) + (summarizer-prompt "Summarize all the conversation prior to this point into a single message.")) +``` +Once `context-threshold` fraction of the context window has been used, the summarizing compacter keeps the most recent messages corresponding to `keep-context` fraction of the context window and summarizes all the earlier messages into a single message. + +To use this compacter, pass `--compacter-eval=(summarizing-compacter)` to kaagum. You may also configure the compacter parameters using something like `--compacter-eval=(summarizing-compacter #:context-threshold 0.8 #:keep-context 0.3)`. + +## noop compacter + +```scheme +noop-compacter +``` +The noop compacter is an identity compacter. It doesn't compact at all; use this compacter to disable context compaction. To use this compacter, pass `--compacter-eval=noop-compacter` to kaagum. + # Contributing Please report issues or send patches to the public inbox at [kaagum@systemreboot.net](https://lists.systemreboot.net/kaagum/). -- 2.54.0 ^ permalink raw reply [flat|nested] 29+ messages in thread
* [PATCH v2 5/5] Allow user-defined context compacters. 2026-11-13 22:46 ` strategies for context management Arun Isaac ` (4 preceding siblings ...) 2026-11-15 4:47 ` [PATCH v2 4/5] Document context compacters Arun Isaac @ 2026-11-15 4:47 ` Arun Isaac 5 siblings, 0 replies; 29+ messages in thread From: Arun Isaac @ 2026-11-15 4:47 UTC (permalink / raw) To: Arun Isaac, Ricardo Wurmus; +Cc: kaagum --- README.md | 15 +++++++++++++++ bin/kaagum | 12 +++++++++--- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 210089a..19a6d39 100644 --- a/README.md +++ b/README.md @@ -113,6 +113,21 @@ noop-compacter ``` The noop compacter is an identity compacter. It doesn't compact at all; use this compacter to disable context compaction. To use this compacter, pass `--compacter-eval=noop-compacter` to kaagum. +## User-defined compacters + +kaagum also supports custom user-defined compacters. Similar to the `--more-tools` parameter, you define your custom compacter in a scheme file and pass it to kaagum using the `--compacter-file` parameter. + +A compacter is a function that accepts a list of `messages` and returns a compacted list of messages. `messages` is a list of `<user-message>`, `<assistant-message>` or `<tool-message>` records. See `kaagum/message.scm` for definitions of these record types and utilities to operate on them. + +In addition, compacters are also provided the following keyword arguments: +- **tokens:** number of tokens that correspond to all `messages` put together +- **context-length:** context length of the model in use +- **llm-base-uri:** base URI of the LLM provider +- **llm-api-key:** API key to authenticate with the LLM provider +- **model:** name of the model in use + +See definitions of built-in compacters in `kaagum/compacters.scm` for examples. + # Contributing Please report issues or send patches to the public inbox at [kaagum@systemreboot.net](https://lists.systemreboot.net/kaagum/). diff --git a/bin/kaagum b/bin/kaagum index 50fbb76..ac5ab4d 100755 --- a/bin/kaagum +++ b/bin/kaagum @@ -57,6 +57,9 @@ exec guile --no-auto-compile -e main -s "$0" "$@" (option (list #\c "compacter-eval") #t #f (lambda (opt name arg result) (acons 'compacter-eval arg result))) + (option (list "compacter-file") #t #f + (lambda (opt name arg result) + (acons 'compacter-file arg result))) (option (list "kagi-api-key-command") #t #f (lambda (opt name arg result) (acons 'kagi-api-key-command arg result))) @@ -84,6 +87,7 @@ Run kaagum AI agent. (default: \"anthropic/claude-opus-4.8\") -t, --more-tools=FILE scheme file providing more tools to the agent -c, --compacter-eval=EXPR expression returning compacter (default: noop) + --compacter-file=FILE scheme file providing compacter --kagi-api-key-command=COMMAND command to run to get Kagi API key @@ -142,9 +146,11 @@ Run kaagum AI agent. (if (assq-ref args 'more-tools) (load (assq-ref args 'more-tools)) '())) - (eval (call-with-input-string (assq-ref args 'compacter-eval) - read) - (interaction-environment))))) + (if (assq-ref args 'compacter-file) + (load (assq-ref args 'compacter-file)) + (eval (call-with-input-string (assq-ref args 'compacter-eval) + read) + (interaction-environment)))))) (parameterize ((%kagi-api-key (and kagi-api-key-command (get-api-key kagi-api-key-command)))) ;; (trace 'kagi "Key ~a" (%kagi-api-key)) -- 2.54.0 ^ permalink raw reply [flat|nested] 29+ messages in thread
* Re: strategies for context management 2026-11-06 21:28 ` Ricardo Wurmus 2026-11-07 8:15 ` Ricardo Wurmus @ 2026-11-08 1:43 ` Arun Isaac 1 sibling, 0 replies; 29+ messages in thread From: Arun Isaac @ 2026-11-08 1:43 UTC (permalink / raw) To: Ricardo Wurmus; +Cc: Ricardo Wurmus, kaagum > it would be helpful to provide a means for users to delete or edit > session messages to reduce the effective context. I don't know if > kaagum's design makes this possible or if perhaps it is something > that is not wanted due to design constraints. Strictly speaking, we couldn't provide this since the Agent Client Protocol does not provide a way for the client to delete messages. We could go our own way and implement this as a non-standard slash command, but I wonder if it is worth the effort. ^ permalink raw reply [flat|nested] 29+ messages in thread
end of thread, other threads:[~2026-11-22 16:54 UTC | newest] Thread overview: 29+ messages (download: mbox.gz / follow: Atom feed) -- links below jump to the message on this page -- 2026-11-06 8:11 strategies for context management Ricardo Wurmus 2026-11-06 14:21 ` Arun Isaac 2026-11-06 21:28 ` Ricardo Wurmus 2026-11-07 8:15 ` Ricardo Wurmus 2026-11-08 1:35 ` Arun Isaac 2026-11-08 1:36 ` [PATCH] Support context compaction Arun Isaac 2026-11-09 13:25 ` strategies for context management Ricardo Wurmus 2026-11-10 23:42 ` Arun Isaac 2026-11-13 22:41 ` [PATCH 1/4] Add message record equality comparators Arun Isaac 2026-11-13 22:41 ` [PATCH 2/4] Support context compaction Arun Isaac 2026-11-13 22:41 ` [PATCH 3/4] Add sliding window compacter Arun Isaac 2026-11-13 22:41 ` [PATCH 4/4] Allow loading compacter from file Arun Isaac 2026-11-13 22:46 ` strategies for context management Arun Isaac 2026-11-15 4:47 ` [PATCH v2 0/5] Context compaction Arun Isaac 2026-11-19 14:28 ` Ricardo Wurmus 2026-11-19 14:29 ` Ricardo Wurmus 2026-11-19 18:43 ` Arun Isaac 2026-11-20 5:39 ` Ricardo Wurmus 2026-11-20 5:56 ` Ricardo Wurmus 2026-11-20 13:42 ` Arun Isaac 2026-11-20 13:45 ` Arun Isaac 2026-11-20 14:01 ` Ricardo Wurmus 2026-11-22 16:54 ` Arun Isaac 2026-11-15 4:47 ` [PATCH v2 1/5] Support context compaction Arun Isaac 2026-11-15 4:47 ` [PATCH v2 2/5] Add sliding window compacter Arun Isaac 2026-11-15 4:47 ` [PATCH v2 3/5] Add summarizing compacter Arun Isaac 2026-11-15 4:47 ` [PATCH v2 4/5] Document context compacters Arun Isaac 2026-11-15 4:47 ` [PATCH v2 5/5] Allow user-defined " Arun Isaac 2026-11-08 1:43 ` strategies for context management Arun Isaac
This is a public inbox, see mirroring instructions for how to clone and mirror all data and code used for this inbox