]> git.giacomolli.uk - onechat/blob - compactor.go
fe8a00ffd8c3df5038117400cf0b8de6f7b9a437
[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. 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.
30 //
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 {
39 client *Client
40 model ModelConfig
41 instructions string
42 tools []Tool
43 }
44
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 {
48 return &Compactor{
49 client: client,
50 model: model,
51 instructions: prompt(name),
52 tools: agentTools(),
53 }
54 }
55
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)
60 if err != nil {
61 return "", err
62 }
63
64 var lines []string
65 note := ""
66 for len(lines) < compactionTries {
67 parts := slices.Concat(view, []string{text})
68 if note != "" {
69 parts = append(parts, note)
70 }
71
72 var response Response
73 response, err = c.client.Create(ctx, Request{
74 Model: c.model.Model,
75 Effort: c.model.Effort,
76 Instructions: c.instructions,
77 Tools: c.tools,
78 Input: []any{userMessage(parts...)},
79 Node: &nodeKey{task.Level, task.Index},
80 })
81 if err != nil {
82 break
83 }
84
85 line := strings.TrimSpace(response.Text)
86 if line == "" {
87 err = errors.New("compaction gave no line")
88 break
89 }
90
91 lines = append(lines, line)
92 if len(line) <= nodeBytes {
93 break
94 }
95
96 note = tooLong(line)
97 }
98
99 if len(lines) == 0 {
100 return "", fmt.Errorf("compact node (%d, %d): %w", task.Level, task.Index, err)
101 }
102
103 return shortest(lines), nil
104 }
105
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
109 // newline.
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], ""))
116 }
117
118 return append(parts, strings.Join(lines[whole:], "")+"\n")
119 }
120
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:
126 %s
127 <input>
128 %s
129 </input>`, task.Index, nodeBytes, ruler, task.Input[0]), nil
130 }
131
132 if task.Level > 0 && len(task.Input) == 2 {
133 first := task.Index << task.Level
134 half := 1 << (task.Level - 1)
135
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:
138 %s
139 <chat> may hold their messages, %d to %d, in more detail: take details
140 of them from there too.
141 <input>
142 %s
143 %s
144 </input>`, first, half, first+half, half, nodeBytes, ruler, first, nodeEnd(task.Level, task.Index)-1, task.Input[0], task.Input[1]), nil
145 }
146
147 return "", fmt.Errorf("node (%d, %d) has %d inputs", task.Level, task.Index, len(task.Input))
148 }
149
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))
157 }
158
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 {
163 return line
164 }
165
166 cut := line[:nodeBytes]
167 for !utf8.ValidString(cut) {
168 cut = cut[:len(cut)-1]
169 }
170
171 return cut
172 }
173
174 // shortest returns the first of the shortest lines.
175 func shortest(lines []string) string {
176 best := lines[0]
177 for _, line := range lines[1:] {
178 if len(line) < len(best) {
179 best = line
180 }
181 }
182
183 return best
184 }