| 131 | } |
| 132 | |
| 133 | const select = ( |
| 134 | entries: readonly Entry[], |
| 135 | tokens: number, |
| 136 | ): { readonly head: string; readonly recent: string } | undefined => { |
| 137 | const conversation = entries |
| 138 | .filter((entry) => entry.message.type !== "compaction") |
| 139 | .map((entry) => serialize(entry.message)) |
| 140 | .filter(Boolean) |
| 141 | if (conversation.length === 0) return |
| 142 | let total = 0 |
| 143 | let split = conversation.length |
| 144 | let splitPrefix = "" |
| 145 | let splitSuffix = "" |
| 146 | for (let index = conversation.length - 1; index >= 0; index--) { |
| 147 | const next = total + Token.estimate(conversation[index]) |
| 148 | if (next > tokens) { |
| 149 | const remaining = Math.max(0, tokens - total) * 4 |
| 150 | if (remaining > 0) { |
| 151 | splitPrefix = conversation[index].slice(0, -remaining) |
| 152 | splitSuffix = conversation[index].slice(-remaining) |
| 153 | split = index + 1 |
| 154 | } |
| 155 | break |
| 156 | } |
| 157 | total = next |
| 158 | split = index |
| 159 | } |
| 160 | return { |
| 161 | head: [...conversation.slice(0, split), splitPrefix].filter(Boolean).join("\n\n"), |
| 162 | recent: [splitSuffix, ...conversation.slice(split)].filter(Boolean).join("\n\n"), |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | export const buildPrompt = (input: { readonly previousSummary?: string; readonly context: readonly string[] }) => |
| 167 | [ |