]> git.giacomolli.uk - onechat/blob - compactor.go
Send the end of the view in one part with the task
[onechat] / compactor.go
1 package main
2
3 import (
4         "context"
5         "errors"
6         "fmt"
7         "slices"
8         "strings"
9         "unicode/utf8"
10 )
11
12 const (
13         // compactionTries is the most calls for one node.
14         compactionTries = 5
15
16         // viewBlock is the number of view lines in one input part.
17         viewBlock = 4
18 )
19
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)
23
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, in the
28 // parts that compactionParts gives. Only the last part holds the end of the
29 // view, so compactions whose views end at different lines begin with the same
30 // parts up to their last shared block.
31 //
32 // When the line is over nodeBytes, the next try sends the same view and task,
33 // plus a note with the size of the newest line and its cut at the limit. A try
34 // never sends the model's earlier reply or reasoning back, so every try has the
35 // same cached prefix and about the same size. After at most compactionTries
36 // tries, the shortest line is the node. A few bytes over the limit is fine,
37 // because the view measures the real sizes. A call that fails before any line
38 // fails the build, and the core tries it again at the next message.
39 type Compactor struct {
40         client       *Client
41         model        ModelConfig
42         instructions string
43         tools        []Tool
44 }
45
46 // newCompactor returns the compactor of the agent name, which sends its calls
47 // through client with model.
48 func newCompactor(client *Client, name string, model ModelConfig) *Compactor {
49         return &Compactor{
50                 client:       client,
51                 model:        model,
52                 instructions: prompt(name),
53                 tools:        agentTools(),
54         }
55 }
56
57 // Summarize returns the line of the node of task.
58 func (c *Compactor) Summarize(ctx context.Context, task Task) (string, error) {
59         text, err := compactionTask(task)
60         if err != nil {
61                 return "", err
62         }
63
64         first := compactionParts(task.Context, text)
65         var lines []string
66         note := ""
67         for len(lines) < compactionTries {
68                 parts := first
69                 if note != "" {
70                         parts = append(slices.Clip(first), note)
71                 }
72
73                 var response Response
74                 response, err = c.client.Create(ctx, Request{
75                         Model:        c.model.Model,
76                         Effort:       c.model.Effort,
77                         Instructions: c.instructions,
78                         Tools:        c.tools,
79                         Input:        []any{userMessage(parts...)},
80                         Node:         &nodeKey{task.Level, task.Index},
81                 })
82                 if err != nil {
83                         break
84                 }
85
86                 line := strings.TrimSpace(response.Text)
87                 if line == "" {
88                         err = errors.New("compaction gave no line")
89                         break
90                 }
91
92                 lines = append(lines, line)
93                 if len(line) <= nodeBytes {
94                         break
95                 }
96
97                 note = tooLong(line)
98         }
99
100         if len(lines) == 0 {
101                 return "", fmt.Errorf("compact node (%d, %d): %w", task.Level, task.Index, err)
102         }
103
104         return shortest(lines), nil
105 }
106
107 // compactionParts returns the input parts of a first try for the compaction
108 // view context and the task text: the opening tag, one part for each whole
109 // block of viewBlock lines, and then one part with the rest of the lines, the
110 // closing tag, a newline, and the task. Joined, the parts are the view, a
111 // newline, and the task.
112 func compactionParts(context, task string) []string {
113         lines := strings.SplitAfter(strings.TrimPrefix(context, "<chat>\n"), "\n")
114         whole := len(lines) - 1 - (len(lines)-1)%viewBlock
115         parts := []string{"<chat>\n"}
116         for n := 0; n < whole; n += viewBlock {
117                 parts = append(parts, strings.Join(lines[n:n+viewBlock], ""))
118         }
119
120         return append(parts, strings.Join(lines[whole:], "")+"\n"+task)
121 }
122
123 // compactionTask returns the task of a build, with its input.
124 func compactionTask(task Task) (string, error) {
125         if task.Level == 0 && len(task.Input) == 1 {
126                 return fmt.Sprintf(`Compaction: compress message %d into one line of at most %d bytes
127 (about 70 words), the length of this ruler:
128 %s
129 <input>
130 %s
131 </input>`, task.Index, nodeBytes, ruler, task.Input[0]), nil
132         }
133
134         if task.Level > 0 && len(task.Input) == 2 {
135                 first := task.Index << task.Level
136                 half := 1 << (task.Level - 1)
137
138                 return fmt.Sprintf(`Compaction: merge lines %d+%d and %d+%d, adjacent, into one line of at most
139 %d bytes (about 70 words), the length of this ruler:
140 %s
141 <chat> may hold their messages, %d to %d, in more detail: take details
142 of them from there too.
143 <input>
144 %s
145 %s
146 </input>`, first, half, first+half, half, nodeBytes, ruler, first, nodeEnd(task.Level, task.Index)-1, task.Input[0], task.Input[1]), nil
147         }
148
149         return "", fmt.Errorf("node (%d, %d) has %d inputs", task.Level, task.Index, len(task.Input))
150 }
151
152 // tooLong returns the note for a line over nodeBytes: its size and its first
153 // nodeBytes bytes, which show the model where the limit cuts it.
154 func tooLong(line string) string {
155         return fmt.Sprintf(`Too long: your last line for this <input> was %d bytes,
156 over the %d-byte limit. Write the whole line again, cutting just
157 enough of the least valuable items to fit before this cut:
158 %s| <- LIMIT`, len(line), nodeBytes, cutLine(line))
159 }
160
161 // cutLine returns the first nodeBytes bytes of line, without a part of a
162 // character at the end.
163 func cutLine(line string) string {
164         if len(line) <= nodeBytes {
165                 return line
166         }
167
168         cut := line[:nodeBytes]
169         for !utf8.ValidString(cut) {
170                 cut = cut[:len(cut)-1]
171         }
172
173         return cut
174 }
175
176 // shortest returns the first of the shortest lines.
177 func shortest(lines []string) string {
178         best := lines[0]
179         for _, line := range lines[1:] {
180                 if len(line) < len(best) {
181                         best = line
182                 }
183         }
184
185         return best
186 }