]> git.giacomolli.uk - onechat/blob - compactor.go
Log the start and the length of each subagent run
[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 // compactorTries is the most calls for one node.
13 const compactorTries = 5
14
15 // compactorBlock is the number of view lines in one block message.
16 const compactorBlock = 4
17
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)
21
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 {
26         return &Compactor{
27                 client:       client,
28                 model:        model,
29                 instructions: instructions,
30                 tools:        promptTools(),
31         }
32 }
33
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.
43 //
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 {
53         client       *ModelClient
54         model        ModelConfig
55         instructions func() (string, error)
56         tools        []ModelTool
57 }
58
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)
62         if err != nil {
63                 return "", err
64         }
65
66         instructions, err := c.instructions()
67         if err != nil {
68                 return "", err
69         }
70
71         var first []any
72         for _, message := range compactorTexts(task.Context, text) {
73                 first = append(first, modelUserMessage(message))
74         }
75
76         var lines []string
77         note := ""
78         for len(lines) < compactorTries {
79                 input := first
80                 if note != "" {
81                         input = append(slices.Clip(first), modelUserMessage(note))
82                 }
83
84                 var response ModelResponse
85                 response, err = c.client.Create(ctx, ModelRequest{
86                         Model:        c.model.Model,
87                         Effort:       c.model.Effort,
88                         Instructions: instructions,
89                         Tools:        c.tools,
90                         Input:        input,
91                         Node:         &NodeKey{task.Level, task.Index},
92                 })
93                 if err != nil {
94                         break
95                 }
96
97                 line := strings.TrimSpace(response.Text)
98                 if line == "" {
99                         err = errors.New("compaction gave no line")
100                         break
101                 }
102
103                 lines = append(lines, line)
104                 if len(line) <= nodeBytes {
105                         break
106                 }
107
108                 note = compactorTooLong(line)
109         }
110
111         if len(lines) == 0 {
112                 return "", err
113         }
114
115         return compactorShortest(lines), nil
116 }
117
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:
123 %s
124 <input>
125 %s
126 </input>`, task.Index, nodeBytes, compactorRuler, task.Input[0]), nil
127         }
128
129         if task.Level > 0 && len(task.Input) == 2 {
130                 first := task.Index << task.Level
131                 half := 1 << (task.Level - 1)
132
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:
135 %s
136 <chat> may hold their messages, %d to %d, in more detail: take details
137 of them from there too.
138 <input>
139 %s
140 %s
141 </input>`, first, half, first+half, half, nodeBytes, compactorRuler, first, nodeEnd(task.Level, task.Index)-1, task.Input[0], task.Input[1]), nil
142         }
143
144         return "", fmt.Errorf("node (%d, %d) has %d inputs", task.Level, task.Index, len(task.Input))
145 }
146
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
158
159         var texts []string
160         for n := 0; n < whole; n += compactorBlock {
161                 texts = append(texts, viewMessage(n == 0, lines[n:n+compactorBlock]))
162         }
163
164         return append(texts, viewMessage(whole == 0, lines[whole:])+"</chat>\n"+task)
165 }
166
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))
174 }
175
176 // compactorShortest returns the first of the compactorShortest lines.
177 func compactorShortest(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 }
187
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 {
192                 return line
193         }
194
195         cut := line[:nodeBytes]
196         for !utf8.ValidString(cut) {
197                 cut = cut[:len(cut)-1]
198         }
199
200         return cut
201 }