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