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