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