58 lines
1.7 KiB
Go
58 lines
1.7 KiB
Go
package agentrun
|
|
|
|
// droppedOutput replaces a tool output cut to fit a history bound.
|
|
const droppedOutput = "[output dropped to fit the context window]"
|
|
|
|
// historySize is what an entry contributes to a history's size, in bytes.
|
|
func historySize(e TranscriptEntry) int {
|
|
n := len(e.Text) + len(e.Output) + len(e.Error) + len(e.Args)
|
|
for _, call := range e.ToolCalls {
|
|
n += len(call.Name) + len(call.Args)
|
|
}
|
|
return n
|
|
}
|
|
|
|
// BoundHistory returns entries cut to at most maxBytes: the system prompt and
|
|
// the run's first user message are left out because a continuation sends its
|
|
// own, then the oldest tool outputs are dropped, then the oldest entries. The
|
|
// input is not modified.
|
|
func BoundHistory(entries []TranscriptEntry, maxBytes int) []TranscriptEntry {
|
|
out := make([]TranscriptEntry, 0, len(entries))
|
|
seenUser := false
|
|
total := 0
|
|
for _, e := range entries {
|
|
switch {
|
|
case e.Kind == TranscriptSystem:
|
|
continue
|
|
case e.Kind == TranscriptUser && !seenUser:
|
|
seenUser = true
|
|
continue
|
|
}
|
|
out = append(out, e)
|
|
total += historySize(e)
|
|
}
|
|
for i := 0; i < len(out) && total > maxBytes; i++ {
|
|
if out[i].Kind != TranscriptTool || len(out[i].Output) <= len(droppedOutput) {
|
|
continue
|
|
}
|
|
total -= len(out[i].Output) - len(droppedOutput)
|
|
out[i].Output = droppedOutput
|
|
}
|
|
drop := 0
|
|
for drop < len(out) && total > maxBytes {
|
|
total -= historySize(out[drop])
|
|
drop++
|
|
}
|
|
return out[drop:]
|
|
}
|
|
|
|
// HistoryBytes is the size budget for a history sent to a model with the given
|
|
// context window in tokens: a third of the window at about four bytes a token.
|
|
// A zero window is the persistence bound.
|
|
func HistoryBytes(contextWindow int) int {
|
|
if contextWindow <= 0 {
|
|
return 256 << 10
|
|
}
|
|
return contextWindow * 4 / 3
|
|
}
|