File size: 8,217 Bytes
68d7816 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 | import type { Message } from '#/llm-adapter/contract/message';
import type { ProfileModelContext } from '#/agent/profile/profile';
import type { CompactionSource } from './types';
import { estimateTokensForMessage } from '#/llm-adapter/contract/tokens';
export interface CompactionConfig {
triggerRatio: number;
blockRatio: number;
reservedContextSize: number;
maxCompactionPerTurn: number;
maxOverflowCompactionAttempts: number;
maxRecentMessages: number;
maxRecentUserMessages: number;
maxRecentSizeRatio: number;
minOverflowReductionRatio: number;
}
export const DEFAULT_COMPACTION_CONFIG: CompactionConfig = {
triggerRatio: 0.85,
blockRatio: 0.85,
reservedContextSize: 50_000,
maxCompactionPerTurn: Infinity,
maxOverflowCompactionAttempts: 3,
maxRecentMessages: 4,
maxRecentUserMessages: Infinity,
maxRecentSizeRatio: 0.2,
minOverflowReductionRatio: 0.05,
};
export interface CompactionStrategy {
shouldCompact(usedSize: number): boolean;
shouldBlock(usedSize: number): boolean;
computeCompactCount(messages: readonly Message[], source: CompactionSource): number;
reduceCompactOnOverflow(messages: readonly Message[]): number;
readonly checkAfterStep: boolean;
readonly maxCompactionPerTurn: number;
readonly maxOverflowCompactionAttempts: number;
}
export class RuntimeCompactionStrategy implements CompactionStrategy {
constructor(
private readonly context: () => ProfileModelContext,
private readonly estimateMessage: (message: Message) => number = estimateTokensForMessage,
) { }
shouldCompact(usedSize: number): boolean {
return this.delegate().shouldCompact(usedSize);
}
shouldBlock(usedSize: number): boolean {
return this.delegate().shouldBlock(usedSize);
}
computeCompactCount(messages: readonly Message[], source: CompactionSource): number {
return this.windowDelegate().computeCompactCount(messages, source);
}
reduceCompactOnOverflow(messages: readonly Message[]): number {
return this.windowDelegate().reduceCompactOnOverflow(messages);
}
get checkAfterStep(): boolean {
return this.config().triggerRatio !== this.config().blockRatio;
}
get maxCompactionPerTurn(): number {
return DEFAULT_COMPACTION_CONFIG.maxCompactionPerTurn;
}
get maxOverflowCompactionAttempts(): number {
return DEFAULT_COMPACTION_CONFIG.maxOverflowCompactionAttempts;
}
private delegate(): DefaultCompactionStrategy {
const model = this.context();
return new DefaultCompactionStrategy(
() => model.modelCapabilities.max_input_tokens ?? model.modelCapabilities.max_context_tokens,
this.config(model),
this.estimateMessage,
);
}
private windowDelegate(): DefaultCompactionStrategy {
return new DefaultCompactionStrategy(
() => this.context().modelCapabilities.max_input_tokens ?? this.context().modelCapabilities.max_context_tokens,
DEFAULT_COMPACTION_CONFIG,
this.estimateMessage,
);
}
private config(model: ProfileModelContext = this.context()): CompactionConfig {
const triggerRatio = model.compactionTriggerRatio ?? DEFAULT_COMPACTION_CONFIG.triggerRatio;
const blockRatio = Math.max(triggerRatio, DEFAULT_COMPACTION_CONFIG.blockRatio);
return {
...DEFAULT_COMPACTION_CONFIG,
triggerRatio,
blockRatio,
reservedContextSize:
model.reservedContextSize ?? DEFAULT_COMPACTION_CONFIG.reservedContextSize,
};
}
}
export class DefaultCompactionStrategy implements CompactionStrategy {
constructor(
protected readonly maxSizeProvider: () => number,
protected readonly config: CompactionConfig = DEFAULT_COMPACTION_CONFIG,
protected readonly estimateMessage: (message: Message) => number = estimateTokensForMessage,
) { }
protected get maxSize(): number {
return this.maxSizeProvider();
}
shouldCompact(usedSize: number): boolean {
if (this.maxSize <= 0) return false;
return (
usedSize >= this.maxSize * this.config.triggerRatio ||
this.shouldUseReservedContext(usedSize)
);
}
shouldBlock(usedSize: number): boolean {
if (this.maxSize <= 0) return false;
return (
usedSize >= this.maxSize * this.config.blockRatio ||
this.shouldUseReservedContext(usedSize)
);
}
private shouldUseReservedContext(usedSize: number): boolean {
const reservedSize = this.config.reservedContextSize;
return reservedSize > 0 && reservedSize < this.maxSize && usedSize + reservedSize >= this.maxSize;
}
computeCompactCount(messages: readonly Message[], source: CompactionSource): number {
if (source === 'manual') {
for (let i = messages.length - 1; i > 0; i--) {
if (canSplitAfter(messages, i)) {
return this.fitCompactCountToWindow(messages, i + 1);
}
}
return 0;
}
let recentMessages = 1;
let recentUserMessages = 0;
let recentSize = 0;
let bestN: number | undefined;
for (; recentMessages < messages.length; recentMessages++) {
const splitIndex = messages.length - recentMessages - 1;
const m2 = messages[messages.length - recentMessages]!;
if (m2.role === 'user') {
recentUserMessages++;
}
recentSize += this.estimateMessage(m2);
if (canSplitAfter(messages, splitIndex)) {
bestN = splitIndex + 1;
}
const reachesMax = recentMessages >= this.config.maxRecentMessages
|| recentUserMessages >= this.config.maxRecentUserMessages
|| recentSize >= this.maxSize * this.config.maxRecentSizeRatio;
if (reachesMax && bestN !== undefined) {
break;
}
}
return this.fitCompactCountToWindow(messages, bestN ?? 0);
}
reduceCompactOnOverflow(messages: readonly Message[]): number {
const minReducedSize = Math.max(
1,
Math.ceil(this.maxSize * this.config.minOverflowReductionRatio),
);
let reducedSize = 0;
let bestN: number | undefined;
for (let i = messages.length - 2; i > 0; i--) {
reducedSize += this.estimateMessage(messages[i + 1]!);
if (canSplitAfter(messages, i)) {
bestN = i + 1;
if (reducedSize >= minReducedSize) {
return i + 1;
}
}
}
return bestN ?? messages.length;
}
private fitCompactCountToWindow(
messages: readonly Message[],
compactedCount: number,
): number {
if (this.maxSize <= 0 || compactedCount <= 0) {
return compactedCount;
}
let compactedSize = 0;
for (let i = 0; i < compactedCount; i++) {
compactedSize += this.estimateMessage(messages[i]!);
}
if (compactedSize <= this.maxSize) {
return compactedCount;
}
let bestN: number | undefined;
for (let n = compactedCount - 1; n > 0; n--) {
compactedSize -= this.estimateMessage(messages[n]!);
if (!canSplitAfter(messages, n - 1)) {
continue;
}
bestN = n;
if (compactedSize <= this.maxSize) {
return n;
}
}
return bestN ?? compactedCount;
}
get checkAfterStep(): boolean {
return this.config.triggerRatio !== this.config.blockRatio;
}
get maxCompactionPerTurn(): number {
return this.config.maxCompactionPerTurn;
}
get maxOverflowCompactionAttempts(): number {
return this.config.maxOverflowCompactionAttempts;
}
}
function canSplitAfter(messages: readonly Message[], index: number): boolean {
const m = messages[index];
if (m === undefined) return false;
if (m.role === 'user') return false;
if (m.role === 'assistant' && m.toolCalls.length > 0) return false;
if (messages[index + 1]?.role === 'tool') return false;
if (prefixEndsWithOpenToolExchange(messages, index)) return false;
return true;
}
function prefixEndsWithOpenToolExchange(messages: readonly Message[], index: number): boolean {
if (messages[index]?.role !== 'tool') return false;
let toolResultCount = 0;
for (let i = index; i >= 0; i--) {
const message = messages[i];
if (message === undefined) return false;
if (message.role === 'tool') {
toolResultCount++;
continue;
}
return message.role === 'assistant' && message.toolCalls.length > toolResultCount;
}
return false;
}
|