13 // compactionTries is the most calls for one node.
16 // viewBlock is the number of view lines in one input part.
20 // ruler shows the model the size limit of a line. Models cannot count bytes,
21 // and a sample line as the ruler gets its content copied.
22 var ruler = strings.Repeat("-", nodeBytes)
24 // Compactor builds the nodes of one agent with a model. A compaction is a call
25 // like a turn, with the same system prompt and tools, so it reads them from the
26 // prompt cache of the turns. The tools are never called. After them comes one
27 // user message with the compaction view up to the node and the task. The view
28 // goes in parts of viewBlock lines, as viewParts gives them, so compactions
29 // whose views end at different lines still send the same first parts.
31 // When the line is over nodeBytes, the next try sends the same view and task,
32 // plus a note with the size of the newest line and its cut at the limit. A try
33 // never sends the model's earlier reply or reasoning back, so every try has the
34 // same cached prefix and about the same size. After at most compactionTries
35 // tries, the shortest line is the node. A few bytes over the limit is fine,
36 // because the view measures the real sizes. A call that fails before any line
37 // fails the build, and the core tries it again at the next message.
38 type Compactor struct {
45 // newCompactor returns the compactor of the agent name, which sends its calls
46 // through client with model.
47 func newCompactor(client *Client, name string, model ModelConfig) *Compactor {
51 instructions: prompt(name),
56 // Summarize returns the line of the node of task.
57 func (c *Compactor) Summarize(ctx context.Context, task Task) (string, error) {
58 view := viewParts(task.Context)
59 text, err := compactionTask(task)
66 for len(lines) < compactionTries {
67 parts := slices.Concat(view, []string{text})
69 parts = append(parts, note)
73 response, err = c.client.Create(ctx, Request{
75 Effort: c.model.Effort,
76 Instructions: c.instructions,
78 Input: []any{userMessage(parts...)},
79 Node: &nodeKey{task.Level, task.Index},
85 line := strings.TrimSpace(response.Text)
87 err = errors.New("compaction gave no line")
91 lines = append(lines, line)
92 if len(line) <= nodeBytes {
100 return "", fmt.Errorf("compact node (%d, %d): %w", task.Level, task.Index, err)
103 return shortest(lines), nil
106 // viewParts returns the parts of the compaction view context: the opening tag,
107 // one part for each whole block of viewBlock lines, and the rest of the lines
108 // with the closing tag and a newline. Joined, the parts are context and a
110 func viewParts(context string) []string {
111 lines := strings.SplitAfter(strings.TrimPrefix(context, "<chat>\n"), "\n")
112 whole := len(lines) - 1 - (len(lines)-1)%viewBlock
113 parts := []string{"<chat>\n"}
114 for n := 0; n < whole; n += viewBlock {
115 parts = append(parts, strings.Join(lines[n:n+viewBlock], ""))
118 return append(parts, strings.Join(lines[whole:], "")+"\n")
121 // compactionTask returns the task of a build, with its input.
122 func compactionTask(task Task) (string, error) {
123 if task.Level == 0 && len(task.Input) == 1 {
124 return fmt.Sprintf(`Compaction: compress message %d into one line of at most %d bytes
125 (about 70 words), the length of this ruler:
129 </input>`, task.Index, nodeBytes, ruler, task.Input[0]), nil
132 if task.Level > 0 && len(task.Input) == 2 {
133 first := task.Index << task.Level
134 half := 1 << (task.Level - 1)
136 return fmt.Sprintf(`Compaction: merge lines %d+%d and %d+%d, adjacent, into one line of at most
137 %d bytes (about 70 words), the length of this ruler:
139 <chat> may hold their messages, %d to %d, in more detail: take details
140 of them from there too.
144 </input>`, first, half, first+half, half, nodeBytes, ruler, first, nodeEnd(task.Level, task.Index)-1, task.Input[0], task.Input[1]), nil
147 return "", fmt.Errorf("node (%d, %d) has %d inputs", task.Level, task.Index, len(task.Input))
150 // tooLong returns the note for a line over nodeBytes: its size and its first
151 // nodeBytes bytes, which show the model where the limit cuts it.
152 func tooLong(line string) string {
153 return fmt.Sprintf(`Too long: your last line for this <input> was %d bytes,
154 over the %d-byte limit. Write the whole line again, cutting just
155 enough of the least valuable items to fit before this cut:
156 %s| <- LIMIT`, len(line), nodeBytes, cutLine(line))
159 // cutLine returns the first nodeBytes bytes of line, without a part of a
160 // character at the end.
161 func cutLine(line string) string {
162 if len(line) <= nodeBytes {
166 cut := line[:nodeBytes]
167 for !utf8.ValidString(cut) {
168 cut = cut[:len(cut)-1]
174 // shortest returns the first of the shortest lines.
175 func shortest(lines []string) string {
177 for _, line := range lines[1:] {
178 if len(line) < len(best) {