]> git.giacomolli.uk - onechat/blob - compactor.go
0089002a4838b057303e210c62a34b434b486ae0
[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 // compactorRuler shows the model the size limit of a line. Models cannot count
16 // bytes, and a sample line as the ruler gets its content copied.
17 var compactorRuler = strings.Repeat("-", nodeBytes)
18
19 // newCompactor returns the compactor of an agent, which sends its calls through
20 // client with model. instructions gives the system prompt of the agent at each
21 // build, so a build sends the same prompt as the turns of that time.
22 func newCompactor(client *ModelClient, instructions func() (string, error), model ModelConfig) *Compactor {
23 return &Compactor{
24 client: client,
25 model: model,
26 instructions: instructions,
27 tools: promptTools(),
28 }
29 }
30
31 // Compactor builds the nodes of one agent with a model. A compaction is a call
32 // like a turn, with the same system prompt and tools, so it reads them from the
33 // prompt cache of the turns. The tools are never called. After them comes one
34 // user message with the compaction view up to the node, its closing tag, a
35 // newline, and the task.
36 //
37 // When the line is over nodeBytes, the next try sends the same message, plus
38 // one more user message with a note with the size of the newest line and its
39 // cut at the limit. A try never sends the model's earlier reply or reasoning
40 // back, so every try begins with the same view and task and has about the same
41 // size. After at most compactorTries tries, the shortest line is the node. A
42 // few bytes over the limit is fine, because the view measures the real sizes. A
43 // call that fails before any line fails the build, and the core tries it again
44 // at the next message.
45 type Compactor struct {
46 client *ModelClient
47 model ModelConfig
48 instructions func() (string, error)
49 tools []ModelTool
50 }
51
52 // Summarize returns the line of the node of task.
53 func (c *Compactor) Summarize(ctx context.Context, task Task) (string, error) {
54 text, err := compactorTask(task)
55 if err != nil {
56 return "", err
57 }
58
59 instructions, err := c.instructions()
60 if err != nil {
61 return "", err
62 }
63
64 first := []any{modelUserMessage(task.Context + "\n" + text)}
65
66 var lines []string
67
68 note := ""
69 for len(lines) < compactorTries {
70 input := first
71 if note != "" {
72 input = append(slices.Clip(first), modelUserMessage(note))
73 }
74
75 var response ModelResponse
76
77 response, err = c.client.Create(ctx, ModelRequest{
78 Model: c.model.Model,
79 Effort: c.model.Effort,
80 Instructions: instructions,
81 Tools: c.tools,
82 Input: input,
83 Node: &NodeKey{task.Level, task.Index},
84 })
85 if err != nil {
86 break
87 }
88
89 line := strings.TrimSpace(response.Text)
90 if line == "" {
91 err = errors.New("compaction gave no line")
92 break
93 }
94
95 lines = append(lines, line)
96 if len(line) <= nodeBytes {
97 break
98 }
99
100 note = compactorTooLong(line)
101 }
102
103 if len(lines) == 0 {
104 return "", err
105 }
106
107 return compactorShortest(lines), nil
108 }
109
110 // compactorTask returns the task of a build, with its input.
111 func compactorTask(task Task) (string, error) {
112 if task.Level == 0 && len(task.Input) == 1 {
113 return fmt.Sprintf(`Compaction: compress message %d into one line of at most %d bytes
114 (about 70 words), the length of this ruler:
115 %s
116 <input>
117 %s
118 </input>`, task.Index, nodeBytes, compactorRuler, task.Input[0]), nil
119 }
120
121 if task.Level > 0 && len(task.Input) == 2 {
122 first := task.Index << task.Level
123 half := 1 << (task.Level - 1)
124
125 return fmt.Sprintf(`Compaction: merge lines %d+%d and %d+%d, adjacent, into one line of at most
126 %d bytes (about 70 words), the length of this ruler:
127 %s
128 <chat> may hold their messages, %d to %d, in more detail: take details
129 of them from there too.
130 <input>
131 %s
132 %s
133 </input>`, first, half, first+half, half, nodeBytes, compactorRuler, first, nodeEnd(task.Level, task.Index)-1, task.Input[0], task.Input[1]), nil
134 }
135
136 return "", fmt.Errorf("node (%d, %d) has %d inputs", task.Level, task.Index, len(task.Input))
137 }
138
139 // compactorTooLong returns the note for a line over nodeBytes: its size and its
140 // first nodeBytes bytes, which show the model where the limit cuts it.
141 func compactorTooLong(line string) string {
142 return fmt.Sprintf(`Too long: your last line for this <input> was %d bytes,
143 over the %d-byte limit. Write the whole line again, cutting just
144 enough of the least valuable items to fit before this cut:
145 %s| <- LIMIT`, len(line), nodeBytes, compactorCutLine(line))
146 }
147
148 // compactorShortest returns the first of the compactorShortest lines.
149 func compactorShortest(lines []string) string {
150 best := lines[0]
151 for _, line := range lines[1:] {
152 if len(line) < len(best) {
153 best = line
154 }
155 }
156
157 return best
158 }
159
160 // compactorCutLine returns the first nodeBytes bytes of line, without a part of
161 // a character at the end.
162 func compactorCutLine(line string) string {
163 if len(line) <= nodeBytes {
164 return line
165 }
166
167 cut := line[:nodeBytes]
168 for !utf8.ValidString(cut) {
169 cut = cut[:len(cut)-1]
170 }
171
172 return cut
173 }