12 // compactorTries is the most calls for one node.
13 const compactorTries = 5
15 // compactorBlock is the number of view lines in one block message.
16 const compactorBlock = 4
18 // compactorRuler shows the model the size limit of a line. Models cannot count
19 // bytes, and a sample line as the ruler gets its content copied.
20 var compactorRuler = strings.Repeat("-", nodeBytes)
22 // newCompactor returns the compactor of an agent, which sends its calls through
23 // client with model. instructions gives the system prompt of the agent at each
24 // build, so a build sends the same prompt as the turns of that time.
25 func newCompactor(client *ModelClient, instructions func() (string, error), model ModelConfig) *Compactor {
29 instructions: instructions,
34 // Compactor builds the nodes of one agent with a model. A compaction is a call
35 // like a turn, with the same system prompt and tools, so it reads them from the
36 // prompt cache of the turns. The tools are never called. After them come the
37 // compaction view up to the node and the task, as the user messages that
38 // compactorTexts gives. Each whole block of compactorBlock view lines is its
39 // own message, and the last message holds the rest of the lines and the task.
40 // The backend reads a cache entry only at a message end of a request, so a
41 // compaction whose view begins with the same lines as an earlier one begins
42 // with the same block messages.
44 // When the line is over nodeBytes, the next try sends the same messages, plus
45 // one more user message with a note with the size of the newest line and its
46 // cut at the limit. A try never sends the model's earlier reply or reasoning
47 // back, so every try begins with the whole earlier try and has about the same
48 // size. After at most compactorTries tries, the shortest line is the node. A
49 // few bytes over the limit is fine, because the view measures the real sizes. A
50 // call that fails before any line fails the build, and the core tries it again
51 // at the next message.
52 type Compactor struct {
55 instructions func() (string, error)
59 // Summarize returns the line of the node of task.
60 func (c *Compactor) Summarize(ctx context.Context, task Task) (string, error) {
61 text, err := compactorTask(task)
66 instructions, err := c.instructions()
72 for _, message := range compactorTexts(task.Context, text) {
73 first = append(first, modelUserMessage(message))
78 for len(lines) < compactorTries {
81 input = append(slices.Clip(first), modelUserMessage(note))
84 var response ModelResponse
85 response, err = c.client.Create(ctx, ModelRequest{
87 Effort: c.model.Effort,
88 Instructions: instructions,
91 Node: &NodeKey{task.Level, task.Index},
97 line := strings.TrimSpace(response.Text)
99 err = errors.New("compaction gave no line")
103 lines = append(lines, line)
104 if len(line) <= nodeBytes {
108 note = compactorTooLong(line)
115 return compactorShortest(lines), nil
118 // compactorTask returns the task of a build, with its input.
119 func compactorTask(task Task) (string, error) {
120 if task.Level == 0 && len(task.Input) == 1 {
121 return fmt.Sprintf(`Compaction: compress message %d into one line of at most %d bytes
122 (about 70 words), the length of this ruler:
126 </input>`, task.Index, nodeBytes, compactorRuler, task.Input[0]), nil
129 if task.Level > 0 && len(task.Input) == 2 {
130 first := task.Index << task.Level
131 half := 1 << (task.Level - 1)
133 return fmt.Sprintf(`Compaction: merge lines %d+%d and %d+%d, adjacent, into one line of at most
134 %d bytes (about 70 words), the length of this ruler:
136 <chat> may hold their messages, %d to %d, in more detail: take details
137 of them from there too.
141 </input>`, first, half, first+half, half, nodeBytes, compactorRuler, first, nodeEnd(task.Level, task.Index)-1, task.Input[0], task.Input[1]), nil
144 return "", fmt.Errorf("node (%d, %d) has %d inputs", task.Level, task.Index, len(task.Input))
147 // compactorTexts returns the texts of the user messages of a first try for the
148 // compaction view and the task text. Each whole block of compactorBlock lines,
149 // counted from the first line of the view, is one message. The last message
150 // holds the rest of the lines, the closing tag, a newline, and the task. The
151 // first message starts with the opening tag. Joined, the texts are the view, a
152 // newline, and the task.
153 func compactorTexts(view, task string) []string {
154 body := strings.TrimSuffix(strings.TrimPrefix(view, "<chat>\n"), "</chat>")
155 lines := strings.SplitAfter(body, "\n")
156 lines = lines[:len(lines)-1]
157 whole := len(lines) - len(lines)%compactorBlock
160 for n := 0; n < whole; n += compactorBlock {
161 texts = append(texts, viewMessage(n == 0, lines[n:n+compactorBlock]))
164 return append(texts, viewMessage(whole == 0, lines[whole:])+"</chat>\n"+task)
167 // compactorTooLong returns the note for a line over nodeBytes: its size and its
168 // first nodeBytes bytes, which show the model where the limit cuts it.
169 func compactorTooLong(line string) string {
170 return fmt.Sprintf(`Too long: your last line for this <input> was %d bytes,
171 over the %d-byte limit. Write the whole line again, cutting just
172 enough of the least valuable items to fit before this cut:
173 %s| <- LIMIT`, len(line), nodeBytes, compactorCutLine(line))
176 // compactorShortest returns the first of the compactorShortest lines.
177 func compactorShortest(lines []string) string {
179 for _, line := range lines[1:] {
180 if len(line) < len(best) {
188 // compactorCutLine returns the first nodeBytes bytes of line, without a part of
189 // a character at the end.
190 func compactorCutLine(line string) string {
191 if len(line) <= nodeBytes {
195 cut := line[:nodeBytes]
196 for !utf8.ValidString(cut) {
197 cut = cut[:len(cut)-1]