♻️ Quality: internal/compact without smells (7 → 0)
- Compact: the summary step as summaryOf (merge rule, empty summary) - Valid: pendingCalls.check per part - shrink: shrinkPart, shrinkArgs (maps.Clone), and tagged — the metadata copy shrink and withNotes both did - shrink.go and valid.go by theme Checked: shrink, Valid (6 histories) and Compact (4 summarizers, a merge, a summary alone) byte-identical old vs new (temporary golden test). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
6bd1c61 parent: 9c248b3 modified
internal/compact/compact.go +26 -57 | @@ -21,7 +21,6 @@ import ( | ||
| 21 | 21 | "encoding/json" |
| 22 | 22 | "errors" |
| 23 | 23 | "fmt" |
| 24 | - "slices" | |
| 25 | 24 | "strings" |
| 26 | 25 | "time" |
| 27 | 26 | |
| @@ -136,27 +135,10 @@ func Compact(ctx context.Context, msgs []*ai.Message, cfg config.ContextConfig, | ||
| 136 | 135 | } |
| 137 | 136 | old, recent := turns[:len(turns)-keep], turns[len(turns)-keep:] |
| 138 | 137 | |
| 139 | - // An earlier summary that is the only old turn: re-summarising a summary | |
| 140 | - // loses detail and gains nothing. | |
| 141 | - merge := IsSummary(old[0][0]) | |
| 142 | - if merge && len(old) == 1 { | |
| 143 | - return Result{}, ErrNothingToCompact | |
| 144 | - } | |
| 145 | - | |
| 146 | - oldMsgs := flatten(old) | |
| 147 | - text, err := summarize(ctx, Request(oldMsgs, cfg.Prompt, merge)) | |
| 138 | + pair, compressed, err := summaryOf(ctx, old, cfg.Prompt, summarize) | |
| 148 | 139 | if err != nil { |
| 149 | 140 | return Result{}, err |
| 150 | 141 | } |
| 151 | - if strings.TrimSpace(text) == "" { | |
| 152 | - return Result{}, errors.New("empty summary") | |
| 153 | - } | |
| 154 | - | |
| 155 | - questions := len(old) | |
| 156 | - if merge { | |
| 157 | - questions-- // the summary pair is not a question the user asked | |
| 158 | - } | |
| 159 | - pair := SummaryPair(text, len(oldMsgs), questions, commands(oldMsgs)) | |
| 160 | 142 | |
| 161 | 143 | out := make([]*ai.Message, 0, len(head)+len(pair)+len(msgs)) |
| 162 | 144 | out = append(out, head...) |
| @@ -172,7 +154,7 @@ func Compact(ctx context.Context, msgs []*ai.Message, cfg config.ContextConfig, | ||
| 172 | 154 | |
| 173 | 155 | return Result{ |
| 174 | 156 | Messages: out, |
| 175 | - Compressed: len(oldMsgs), | |
| 157 | + Compressed: compressed, | |
| 176 | 158 | Kept: len(kept), |
| 177 | 159 | Before: Estimate(msgs), |
| 178 | 160 | After: Estimate(out), |
| @@ -180,6 +162,30 @@ func Compact(ctx context.Context, msgs []*ai.Message, cfg config.ContextConfig, | ||
| 180 | 162 | }, nil |
| 181 | 163 | } |
| 182 | 164 | |
| 165 | +// summaryOf summarises the old turns into the summary pair, and says how | |
| 166 | +// many messages it replaces. An earlier summary that is the only old turn | |
| 167 | +// is left alone: re-summarising a summary loses detail and gains nothing; | |
| 168 | +// with other turns after it, it is merged into the new summary. | |
| 169 | +func summaryOf(ctx context.Context, old [][]*ai.Message, prompt string, summarize Summarizer) ([]*ai.Message, int, error) { | |
| 170 | + merge := IsSummary(old[0][0]) | |
| 171 | + if merge && len(old) == 1 { | |
| 172 | + return nil, 0, ErrNothingToCompact | |
| 173 | + } | |
| 174 | + oldMsgs := flatten(old) | |
| 175 | + text, err := summarize(ctx, Request(oldMsgs, prompt, merge)) | |
| 176 | + if err != nil { | |
| 177 | + return nil, 0, err | |
| 178 | + } | |
| 179 | + if strings.TrimSpace(text) == "" { | |
| 180 | + return nil, 0, errors.New("empty summary") | |
| 181 | + } | |
| 182 | + questions := len(old) | |
| 183 | + if merge { | |
| 184 | + questions-- // the summary pair is not a question the user asked | |
| 185 | + } | |
| 186 | + return SummaryPair(text, len(oldMsgs), questions, commands(oldMsgs)), len(oldMsgs), nil | |
| 187 | +} | |
| 188 | + | |
| 183 | 189 | // Split separates the leading system message(s) from the question turns. A |
| 184 | 190 | // turn starts at a user message and runs until the next one, so it holds the |
| 185 | 191 | // whole model ↔ tools exchange the question caused; an earlier summary pair is |
| @@ -203,43 +209,6 @@ func Split(msgs []*ai.Message) (head []*ai.Message, turns [][]*ai.Message) { | ||
| 203 | 209 | return head, turns |
| 204 | 210 | } |
| 205 | 211 | |
| 206 | -// Valid checks what an OpenAI-compatible server checks before answering: the | |
| 207 | -// history starts with the system prompt, every tool request sits in a model | |
| 208 | -// message, and every tool response answers a request seen earlier — paired by | |
| 209 | -// Ref when the server set one, by tool name otherwise (same rule as | |
| 210 | -// engine.executed). | |
| 211 | -func Valid(msgs []*ai.Message) error { | |
| 212 | - if len(msgs) == 0 || msgs[0].Role != ai.RoleSystem { | |
| 213 | - return errors.New("history does not start with the system prompt") | |
| 214 | - } | |
| 215 | - type call struct{ ref, name string } | |
| 216 | - var pending []call | |
| 217 | - for i, m := range msgs { | |
| 218 | - for _, p := range m.Content { | |
| 219 | - switch { | |
| 220 | - case p.IsToolRequest() && p.ToolRequest != nil: | |
| 221 | - if m.Role != ai.RoleModel { | |
| 222 | - return fmt.Errorf("message %d: tool request in a %s message", i, m.Role) | |
| 223 | - } | |
| 224 | - pending = append(pending, call{p.ToolRequest.Ref, p.ToolRequest.Name}) | |
| 225 | - case p.IsToolResponse() && p.ToolResponse != nil: | |
| 226 | - r := p.ToolResponse | |
| 227 | - j := slices.IndexFunc(pending, func(c call) bool { | |
| 228 | - if r.Ref != "" { | |
| 229 | - return c.ref == r.Ref | |
| 230 | - } | |
| 231 | - return c.name == r.Name | |
| 232 | - }) | |
| 233 | - if j < 0 { | |
| 234 | - return fmt.Errorf("message %d: tool response %q answers no pending request", i, r.Name) | |
| 235 | - } | |
| 236 | - pending = slices.Delete(pending, j, j+1) | |
| 237 | - } | |
| 238 | - } | |
| 239 | - } | |
| 240 | - return nil | |
| 241 | -} | |
| 242 | - | |
| 243 | 212 | // Estimate approximates the token count of a history without asking the |
| 244 | 213 | // engine: characters divided by 3.5, plus a few tokens of framing per message. |
| 245 | 214 | // |
| @@ -21,7 +21,6 @@ import ( | |||
| 21 | "encoding/json" | 21 | "encoding/json" |
| 22 | "errors" | 22 | "errors" |
| 23 | "fmt" | 23 | "fmt" |
| 24 | - "slices" | ||
| 25 | "strings" | 24 | "strings" |
| 26 | "time" | 25 | "time" |
| 27 | 26 | ||
| @@ -136,27 +135,10 @@ func Compact(ctx context.Context, msgs []*ai.Message, cfg config.ContextConfig, | |||
| 136 | } | 135 | } |
| 137 | old, recent := turns[:len(turns)-keep], turns[len(turns)-keep:] | 136 | old, recent := turns[:len(turns)-keep], turns[len(turns)-keep:] |
| 138 | 137 | ||
| 139 | - // An earlier summary that is the only old turn: re-summarising a summary | 138 | + pair, compressed, err := summaryOf(ctx, old, cfg.Prompt, summarize) |
| 140 | - // loses detail and gains nothing. | ||
| 141 | - merge := IsSummary(old[0][0]) | ||
| 142 | - if merge && len(old) == 1 { | ||
| 143 | - return Result{}, ErrNothingToCompact | ||
| 144 | - } | ||
| 145 | - | ||
| 146 | - oldMsgs := flatten(old) | ||
| 147 | - text, err := summarize(ctx, Request(oldMsgs, cfg.Prompt, merge)) | ||
| 148 | if err != nil { | 139 | if err != nil { |
| 149 | return Result{}, err | 140 | return Result{}, err |
| 150 | } | 141 | } |
| 151 | - if strings.TrimSpace(text) == "" { | ||
| 152 | - return Result{}, errors.New("empty summary") | ||
| 153 | - } | ||
| 154 | - | ||
| 155 | - questions := len(old) | ||
| 156 | - if merge { | ||
| 157 | - questions-- // the summary pair is not a question the user asked | ||
| 158 | - } | ||
| 159 | - pair := SummaryPair(text, len(oldMsgs), questions, commands(oldMsgs)) | ||
| 160 | 142 | ||
| 161 | out := make([]*ai.Message, 0, len(head)+len(pair)+len(msgs)) | 143 | out := make([]*ai.Message, 0, len(head)+len(pair)+len(msgs)) |
| 162 | out = append(out, head...) | 144 | out = append(out, head...) |
| @@ -172,7 +154,7 @@ func Compact(ctx context.Context, msgs []*ai.Message, cfg config.ContextConfig, | |||
| 172 | 154 | ||
| 173 | return Result{ | 155 | return Result{ |
| 174 | Messages: out, | 156 | Messages: out, |
| 175 | - Compressed: len(oldMsgs), | 157 | + Compressed: compressed, |
| 176 | Kept: len(kept), | 158 | Kept: len(kept), |
| 177 | Before: Estimate(msgs), | 159 | Before: Estimate(msgs), |
| 178 | After: Estimate(out), | 160 | After: Estimate(out), |
| @@ -180,6 +162,30 @@ func Compact(ctx context.Context, msgs []*ai.Message, cfg config.ContextConfig, | |||
| 180 | }, nil | 162 | }, nil |
| 181 | } | 163 | } |
| 182 | 164 | ||
| 165 | +// summaryOf summarises the old turns into the summary pair, and says how | ||
| 166 | +// many messages it replaces. An earlier summary that is the only old turn | ||
| 167 | +// is left alone: re-summarising a summary loses detail and gains nothing; | ||
| 168 | +// with other turns after it, it is merged into the new summary. | ||
| 169 | +func summaryOf(ctx context.Context, old [][]*ai.Message, prompt string, summarize Summarizer) ([]*ai.Message, int, error) { | ||
| 170 | + merge := IsSummary(old[0][0]) | ||
| 171 | + if merge && len(old) == 1 { | ||
| 172 | + return nil, 0, ErrNothingToCompact | ||
| 173 | + } | ||
| 174 | + oldMsgs := flatten(old) | ||
| 175 | + text, err := summarize(ctx, Request(oldMsgs, prompt, merge)) | ||
| 176 | + if err != nil { | ||
| 177 | + return nil, 0, err | ||
| 178 | + } | ||
| 179 | + if strings.TrimSpace(text) == "" { | ||
| 180 | + return nil, 0, errors.New("empty summary") | ||
| 181 | + } | ||
| 182 | + questions := len(old) | ||
| 183 | + if merge { | ||
| 184 | + questions-- // the summary pair is not a question the user asked | ||
| 185 | + } | ||
| 186 | + return SummaryPair(text, len(oldMsgs), questions, commands(oldMsgs)), len(oldMsgs), nil | ||
| 187 | +} | ||
| 188 | + | ||
| 183 | // Split separates the leading system message(s) from the question turns. A | 189 | // Split separates the leading system message(s) from the question turns. A |
| 184 | // turn starts at a user message and runs until the next one, so it holds the | 190 | // turn starts at a user message and runs until the next one, so it holds the |
| 185 | // whole model ↔ tools exchange the question caused; an earlier summary pair is | 191 | // whole model ↔ tools exchange the question caused; an earlier summary pair is |
| @@ -203,43 +209,6 @@ func Split(msgs []*ai.Message) (head []*ai.Message, turns [][]*ai.Message) { | |||
| 203 | return head, turns | 209 | return head, turns |
| 204 | } | 210 | } |
| 205 | 211 | ||
| 206 | -// Valid checks what an OpenAI-compatible server checks before answering: the | ||
| 207 | -// history starts with the system prompt, every tool request sits in a model | ||
| 208 | -// message, and every tool response answers a request seen earlier — paired by | ||
| 209 | -// Ref when the server set one, by tool name otherwise (same rule as | ||
| 210 | -// engine.executed). | ||
| 211 | -func Valid(msgs []*ai.Message) error { | ||
| 212 | - if len(msgs) == 0 || msgs[0].Role != ai.RoleSystem { | ||
| 213 | - return errors.New("history does not start with the system prompt") | ||
| 214 | - } | ||
| 215 | - type call struct{ ref, name string } | ||
| 216 | - var pending []call | ||
| 217 | - for i, m := range msgs { | ||
| 218 | - for _, p := range m.Content { | ||
| 219 | - switch { | ||
| 220 | - case p.IsToolRequest() && p.ToolRequest != nil: | ||
| 221 | - if m.Role != ai.RoleModel { | ||
| 222 | - return fmt.Errorf("message %d: tool request in a %s message", i, m.Role) | ||
| 223 | - } | ||
| 224 | - pending = append(pending, call{p.ToolRequest.Ref, p.ToolRequest.Name}) | ||
| 225 | - case p.IsToolResponse() && p.ToolResponse != nil: | ||
| 226 | - r := p.ToolResponse | ||
| 227 | - j := slices.IndexFunc(pending, func(c call) bool { | ||
| 228 | - if r.Ref != "" { | ||
| 229 | - return c.ref == r.Ref | ||
| 230 | - } | ||
| 231 | - return c.name == r.Name | ||
| 232 | - }) | ||
| 233 | - if j < 0 { | ||
| 234 | - return fmt.Errorf("message %d: tool response %q answers no pending request", i, r.Name) | ||
| 235 | - } | ||
| 236 | - pending = slices.Delete(pending, j, j+1) | ||
| 237 | - } | ||
| 238 | - } | ||
| 239 | - } | ||
| 240 | - return nil | ||
| 241 | -} | ||
| 242 | - | ||
| 243 | // Estimate approximates the token count of a history without asking the | 212 | // Estimate approximates the token count of a history without asking the |
| 244 | // engine: characters divided by 3.5, plus a few tokens of framing per message. | 213 | // engine: characters divided by 3.5, plus a few tokens of framing per message. |
| 245 | // | 214 | // |
modified
internal/compact/inturn.go +1 -73 | @@ -178,72 +178,6 @@ func hasToolResponse(m *ai.Message) bool { | ||
| 178 | 178 | return false |
| 179 | 179 | } |
| 180 | 180 | |
| 181 | -// shrink returns a copy of m with its long tool results and call arguments | |
| 182 | -// cut to their first line, and how many it cut; m itself when none. | |
| 183 | -func shrink(m *ai.Message) (*ai.Message, int) { | |
| 184 | - n := 0 | |
| 185 | - parts := make([]*ai.Part, len(m.Content)) | |
| 186 | - for i, p := range m.Content { | |
| 187 | - parts[i] = p | |
| 188 | - switch { | |
| 189 | - case p.IsToolResponse() && p.ToolResponse != nil: | |
| 190 | - text := jsonOf(p.ToolResponse.Output) | |
| 191 | - if len(text) > shrinkOver { | |
| 192 | - r := *p.ToolResponse | |
| 193 | - r.Output = headLine(text) | |
| 194 | - parts[i] = ai.NewToolResponsePart(&r) | |
| 195 | - n++ | |
| 196 | - } | |
| 197 | - case p.IsToolRequest() && p.ToolRequest != nil: | |
| 198 | - in, ok := p.ToolRequest.Input.(map[string]any) | |
| 199 | - if !ok { | |
| 200 | - continue | |
| 201 | - } | |
| 202 | - var cut map[string]any | |
| 203 | - for k, v := range in { | |
| 204 | - s, isText := v.(string) | |
| 205 | - if !isText || len(s) <= shrinkOver { | |
| 206 | - continue | |
| 207 | - } | |
| 208 | - if cut == nil { | |
| 209 | - cut = make(map[string]any, len(in)) | |
| 210 | - for k2, v2 := range in { | |
| 211 | - cut[k2] = v2 | |
| 212 | - } | |
| 213 | - } | |
| 214 | - cut[k] = headLine(s) | |
| 215 | - } | |
| 216 | - if cut != nil { | |
| 217 | - r := *p.ToolRequest | |
| 218 | - r.Input = cut | |
| 219 | - parts[i] = ai.NewToolRequestPart(&r) | |
| 220 | - n++ | |
| 221 | - } | |
| 222 | - } | |
| 223 | - } | |
| 224 | - if n == 0 { | |
| 225 | - return m, 0 | |
| 226 | - } | |
| 227 | - meta := map[string]any{metaKey: "shrunk"} | |
| 228 | - for k, v := range m.Metadata { | |
| 229 | - if k != metaKey { | |
| 230 | - meta[k] = v | |
| 231 | - } | |
| 232 | - } | |
| 233 | - return ai.NewMessage(m.Role, meta, parts...), n | |
| 234 | -} | |
| 235 | - | |
| 236 | -// headLine is a long text's first line (at most 200 characters) and a note | |
| 237 | -// saying what was dropped. | |
| 238 | -func headLine(s string) string { | |
| 239 | - first, _, _ := strings.Cut(s, "\n") | |
| 240 | - if len(first) > 200 { | |
| 241 | - first = first[:200] + "…" | |
| 242 | - } | |
| 243 | - lines := strings.Count(s, "\n") + 1 | |
| 244 | - return fmt.Sprintf("%s\n[mm: the rest (%d line(s), %d characters) was dropped to keep the context small — read the file or run the command again if you need it]", first, lines, len(s)) | |
| 245 | -} | |
| 246 | - | |
| 247 | 181 | // turnPrompt asks for notes on the turn's older exchanges. |
| 248 | 182 | const turnPrompt = `Everything above, after the system message, is the first part of the work |
| 249 | 183 | an agent did on ONE task, through tool calls. Write notes the same agent will |
| @@ -271,11 +205,5 @@ func withNotes(question *ai.Message, notes string, n int) *ai.Message { | ||
| 271 | 205 | own = own[:len(own)-1] |
| 272 | 206 | } |
| 273 | 207 | parts := append(append([]*ai.Part{}, own...), ai.NewTextPart("\n\n"+text)) |
| 274 | - meta := map[string]any{metaKey: "in-turn"} | |
| 275 | - for k, v := range question.Metadata { | |
| 276 | - if k != metaKey { | |
| 277 | - meta[k] = v | |
| 278 | - } | |
| 279 | - } | |
| 280 | - return ai.NewMessage(ai.RoleUser, meta, parts...) | |
| 208 | + return ai.NewMessage(ai.RoleUser, tagged(question.Metadata, "in-turn"), parts...) | |
| 281 | 209 | } |
| @@ -178,72 +178,6 @@ func hasToolResponse(m *ai.Message) bool { | |||
| 178 | return false | 178 | return false |
| 179 | } | 179 | } |
| 180 | 180 | ||
| 181 | -// shrink returns a copy of m with its long tool results and call arguments | ||
| 182 | -// cut to their first line, and how many it cut; m itself when none. | ||
| 183 | -func shrink(m *ai.Message) (*ai.Message, int) { | ||
| 184 | - n := 0 | ||
| 185 | - parts := make([]*ai.Part, len(m.Content)) | ||
| 186 | - for i, p := range m.Content { | ||
| 187 | - parts[i] = p | ||
| 188 | - switch { | ||
| 189 | - case p.IsToolResponse() && p.ToolResponse != nil: | ||
| 190 | - text := jsonOf(p.ToolResponse.Output) | ||
| 191 | - if len(text) > shrinkOver { | ||
| 192 | - r := *p.ToolResponse | ||
| 193 | - r.Output = headLine(text) | ||
| 194 | - parts[i] = ai.NewToolResponsePart(&r) | ||
| 195 | - n++ | ||
| 196 | - } | ||
| 197 | - case p.IsToolRequest() && p.ToolRequest != nil: | ||
| 198 | - in, ok := p.ToolRequest.Input.(map[string]any) | ||
| 199 | - if !ok { | ||
| 200 | - continue | ||
| 201 | - } | ||
| 202 | - var cut map[string]any | ||
| 203 | - for k, v := range in { | ||
| 204 | - s, isText := v.(string) | ||
| 205 | - if !isText || len(s) <= shrinkOver { | ||
| 206 | - continue | ||
| 207 | - } | ||
| 208 | - if cut == nil { | ||
| 209 | - cut = make(map[string]any, len(in)) | ||
| 210 | - for k2, v2 := range in { | ||
| 211 | - cut[k2] = v2 | ||
| 212 | - } | ||
| 213 | - } | ||
| 214 | - cut[k] = headLine(s) | ||
| 215 | - } | ||
| 216 | - if cut != nil { | ||
| 217 | - r := *p.ToolRequest | ||
| 218 | - r.Input = cut | ||
| 219 | - parts[i] = ai.NewToolRequestPart(&r) | ||
| 220 | - n++ | ||
| 221 | - } | ||
| 222 | - } | ||
| 223 | - } | ||
| 224 | - if n == 0 { | ||
| 225 | - return m, 0 | ||
| 226 | - } | ||
| 227 | - meta := map[string]any{metaKey: "shrunk"} | ||
| 228 | - for k, v := range m.Metadata { | ||
| 229 | - if k != metaKey { | ||
| 230 | - meta[k] = v | ||
| 231 | - } | ||
| 232 | - } | ||
| 233 | - return ai.NewMessage(m.Role, meta, parts...), n | ||
| 234 | -} | ||
| 235 | - | ||
| 236 | -// headLine is a long text's first line (at most 200 characters) and a note | ||
| 237 | -// saying what was dropped. | ||
| 238 | -func headLine(s string) string { | ||
| 239 | - first, _, _ := strings.Cut(s, "\n") | ||
| 240 | - if len(first) > 200 { | ||
| 241 | - first = first[:200] + "…" | ||
| 242 | - } | ||
| 243 | - lines := strings.Count(s, "\n") + 1 | ||
| 244 | - return fmt.Sprintf("%s\n[mm: the rest (%d line(s), %d characters) was dropped to keep the context small — read the file or run the command again if you need it]", first, lines, len(s)) | ||
| 245 | -} | ||
| 246 | - | ||
| 247 | // turnPrompt asks for notes on the turn's older exchanges. | 181 | // turnPrompt asks for notes on the turn's older exchanges. |
| 248 | const turnPrompt = `Everything above, after the system message, is the first part of the work | 182 | const turnPrompt = `Everything above, after the system message, is the first part of the work |
| 249 | an agent did on ONE task, through tool calls. Write notes the same agent will | 183 | an agent did on ONE task, through tool calls. Write notes the same agent will |
| @@ -271,11 +205,5 @@ func withNotes(question *ai.Message, notes string, n int) *ai.Message { | |||
| 271 | own = own[:len(own)-1] | 205 | own = own[:len(own)-1] |
| 272 | } | 206 | } |
| 273 | parts := append(append([]*ai.Part{}, own...), ai.NewTextPart("\n\n"+text)) | 207 | parts := append(append([]*ai.Part{}, own...), ai.NewTextPart("\n\n"+text)) |
| 274 | - meta := map[string]any{metaKey: "in-turn"} | 208 | + return ai.NewMessage(ai.RoleUser, tagged(question.Metadata, "in-turn"), parts...) |
| 275 | - for k, v := range question.Metadata { | ||
| 276 | - if k != metaKey { | ||
| 277 | - meta[k] = v | ||
| 278 | - } | ||
| 279 | - } | ||
| 280 | - return ai.NewMessage(ai.RoleUser, meta, parts...) | ||
| 281 | } | 209 | } |
added
internal/compact/shrink.go +96 -0 | new file mode 100644 | ||
| @@ -0,0 +1,96 @@ | ||
| 1 | +package compact | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "fmt" | |
| 5 | + "maps" | |
| 6 | + "strings" | |
| 7 | + | |
| 8 | + "github.com/firebase/genkit/go/ai" | |
| 9 | +) | |
| 10 | + | |
| 11 | +// shrink returns a copy of m with its long tool results and call arguments | |
| 12 | +// cut to their first line, and how many it cut; m itself when none. | |
| 13 | +func shrink(m *ai.Message) (*ai.Message, int) { | |
| 14 | + n := 0 | |
| 15 | + parts := make([]*ai.Part, len(m.Content)) | |
| 16 | + for i, p := range m.Content { | |
| 17 | + parts[i] = p | |
| 18 | + if cut, ok := shrinkPart(p); ok { | |
| 19 | + parts[i] = cut | |
| 20 | + n++ | |
| 21 | + } | |
| 22 | + } | |
| 23 | + if n == 0 { | |
| 24 | + return m, 0 | |
| 25 | + } | |
| 26 | + return ai.NewMessage(m.Role, tagged(m.Metadata, "shrunk"), parts...), n | |
| 27 | +} | |
| 28 | + | |
| 29 | +// shrinkPart is p with its long tool result or long call arguments cut, and | |
| 30 | +// whether there was anything to cut. | |
| 31 | +func shrinkPart(p *ai.Part) (*ai.Part, bool) { | |
| 32 | + switch { | |
| 33 | + case p.IsToolResponse() && p.ToolResponse != nil: | |
| 34 | + text := jsonOf(p.ToolResponse.Output) | |
| 35 | + if len(text) <= shrinkOver { | |
| 36 | + return p, false | |
| 37 | + } | |
| 38 | + r := *p.ToolResponse | |
| 39 | + r.Output = headLine(text) | |
| 40 | + return ai.NewToolResponsePart(&r), true | |
| 41 | + case p.IsToolRequest() && p.ToolRequest != nil: | |
| 42 | + cut := shrinkArgs(p.ToolRequest.Input) | |
| 43 | + if cut == nil { | |
| 44 | + return p, false | |
| 45 | + } | |
| 46 | + r := *p.ToolRequest | |
| 47 | + r.Input = cut | |
| 48 | + return ai.NewToolRequestPart(&r), true | |
| 49 | + } | |
| 50 | + return p, false | |
| 51 | +} | |
| 52 | + | |
| 53 | +// shrinkArgs is a copy of a call's arguments with its long text values cut | |
| 54 | +// to their first line, or nil when none is long (or the arguments are not | |
| 55 | +// an object). | |
| 56 | +func shrinkArgs(input any) map[string]any { | |
| 57 | + in, ok := input.(map[string]any) | |
| 58 | + if !ok { | |
| 59 | + return nil | |
| 60 | + } | |
| 61 | + var cut map[string]any | |
| 62 | + for k, v := range in { | |
| 63 | + s, isText := v.(string) | |
| 64 | + if !isText || len(s) <= shrinkOver { | |
| 65 | + continue | |
| 66 | + } | |
| 67 | + if cut == nil { | |
| 68 | + cut = maps.Clone(in) | |
| 69 | + } | |
| 70 | + cut[k] = headLine(s) | |
| 71 | + } | |
| 72 | + return cut | |
| 73 | +} | |
| 74 | + | |
| 75 | +// tagged is a message's metadata with mm's tag set to tag, the other keys | |
| 76 | +// kept. | |
| 77 | +func tagged(metadata map[string]any, tag string) map[string]any { | |
| 78 | + meta := map[string]any{metaKey: tag} | |
| 79 | + for k, v := range metadata { | |
| 80 | + if k != metaKey { | |
| 81 | + meta[k] = v | |
| 82 | + } | |
| 83 | + } | |
| 84 | + return meta | |
| 85 | +} | |
| 86 | + | |
| 87 | +// headLine is a long text's first line (at most 200 characters) and a note | |
| 88 | +// saying what was dropped. | |
| 89 | +func headLine(s string) string { | |
| 90 | + first, _, _ := strings.Cut(s, "\n") | |
| 91 | + if len(first) > 200 { | |
| 92 | + first = first[:200] + "…" | |
| 93 | + } | |
| 94 | + lines := strings.Count(s, "\n") + 1 | |
| 95 | + return fmt.Sprintf("%s\n[mm: the rest (%d line(s), %d characters) was dropped to keep the context small — read the file or run the command again if you need it]", first, lines, len(s)) | |
| 96 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,96 @@ | |||
| 1 | +package compact | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "fmt" | ||
| 5 | + "maps" | ||
| 6 | + "strings" | ||
| 7 | + | ||
| 8 | + "github.com/firebase/genkit/go/ai" | ||
| 9 | +) | ||
| 10 | + | ||
| 11 | +// shrink returns a copy of m with its long tool results and call arguments | ||
| 12 | +// cut to their first line, and how many it cut; m itself when none. | ||
| 13 | +func shrink(m *ai.Message) (*ai.Message, int) { | ||
| 14 | + n := 0 | ||
| 15 | + parts := make([]*ai.Part, len(m.Content)) | ||
| 16 | + for i, p := range m.Content { | ||
| 17 | + parts[i] = p | ||
| 18 | + if cut, ok := shrinkPart(p); ok { | ||
| 19 | + parts[i] = cut | ||
| 20 | + n++ | ||
| 21 | + } | ||
| 22 | + } | ||
| 23 | + if n == 0 { | ||
| 24 | + return m, 0 | ||
| 25 | + } | ||
| 26 | + return ai.NewMessage(m.Role, tagged(m.Metadata, "shrunk"), parts...), n | ||
| 27 | +} | ||
| 28 | + | ||
| 29 | +// shrinkPart is p with its long tool result or long call arguments cut, and | ||
| 30 | +// whether there was anything to cut. | ||
| 31 | +func shrinkPart(p *ai.Part) (*ai.Part, bool) { | ||
| 32 | + switch { | ||
| 33 | + case p.IsToolResponse() && p.ToolResponse != nil: | ||
| 34 | + text := jsonOf(p.ToolResponse.Output) | ||
| 35 | + if len(text) <= shrinkOver { | ||
| 36 | + return p, false | ||
| 37 | + } | ||
| 38 | + r := *p.ToolResponse | ||
| 39 | + r.Output = headLine(text) | ||
| 40 | + return ai.NewToolResponsePart(&r), true | ||
| 41 | + case p.IsToolRequest() && p.ToolRequest != nil: | ||
| 42 | + cut := shrinkArgs(p.ToolRequest.Input) | ||
| 43 | + if cut == nil { | ||
| 44 | + return p, false | ||
| 45 | + } | ||
| 46 | + r := *p.ToolRequest | ||
| 47 | + r.Input = cut | ||
| 48 | + return ai.NewToolRequestPart(&r), true | ||
| 49 | + } | ||
| 50 | + return p, false | ||
| 51 | +} | ||
| 52 | + | ||
| 53 | +// shrinkArgs is a copy of a call's arguments with its long text values cut | ||
| 54 | +// to their first line, or nil when none is long (or the arguments are not | ||
| 55 | +// an object). | ||
| 56 | +func shrinkArgs(input any) map[string]any { | ||
| 57 | + in, ok := input.(map[string]any) | ||
| 58 | + if !ok { | ||
| 59 | + return nil | ||
| 60 | + } | ||
| 61 | + var cut map[string]any | ||
| 62 | + for k, v := range in { | ||
| 63 | + s, isText := v.(string) | ||
| 64 | + if !isText || len(s) <= shrinkOver { | ||
| 65 | + continue | ||
| 66 | + } | ||
| 67 | + if cut == nil { | ||
| 68 | + cut = maps.Clone(in) | ||
| 69 | + } | ||
| 70 | + cut[k] = headLine(s) | ||
| 71 | + } | ||
| 72 | + return cut | ||
| 73 | +} | ||
| 74 | + | ||
| 75 | +// tagged is a message's metadata with mm's tag set to tag, the other keys | ||
| 76 | +// kept. | ||
| 77 | +func tagged(metadata map[string]any, tag string) map[string]any { | ||
| 78 | + meta := map[string]any{metaKey: tag} | ||
| 79 | + for k, v := range metadata { | ||
| 80 | + if k != metaKey { | ||
| 81 | + meta[k] = v | ||
| 82 | + } | ||
| 83 | + } | ||
| 84 | + return meta | ||
| 85 | +} | ||
| 86 | + | ||
| 87 | +// headLine is a long text's first line (at most 200 characters) and a note | ||
| 88 | +// saying what was dropped. | ||
| 89 | +func headLine(s string) string { | ||
| 90 | + first, _, _ := strings.Cut(s, "\n") | ||
| 91 | + if len(first) > 200 { | ||
| 92 | + first = first[:200] + "…" | ||
| 93 | + } | ||
| 94 | + lines := strings.Count(s, "\n") + 1 | ||
| 95 | + return fmt.Sprintf("%s\n[mm: the rest (%d line(s), %d characters) was dropped to keep the context small — read the file or run the command again if you need it]", first, lines, len(s)) | ||
| 96 | +} | ||
added
internal/compact/valid.go +60 -0 | new file mode 100644 | ||
| @@ -0,0 +1,60 @@ | ||
| 1 | +package compact | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "errors" | |
| 5 | + "fmt" | |
| 6 | + "slices" | |
| 7 | + | |
| 8 | + "github.com/firebase/genkit/go/ai" | |
| 9 | +) | |
| 10 | + | |
| 11 | +// Valid checks what an OpenAI-compatible server checks before answering: the | |
| 12 | +// history starts with the system prompt, every tool request sits in a model | |
| 13 | +// message, and every tool response answers a request seen earlier — paired by | |
| 14 | +// Ref when the server set one, by tool name otherwise (same rule as | |
| 15 | +// engine.executed). | |
| 16 | +func Valid(msgs []*ai.Message) error { | |
| 17 | + if len(msgs) == 0 || msgs[0].Role != ai.RoleSystem { | |
| 18 | + return errors.New("history does not start with the system prompt") | |
| 19 | + } | |
| 20 | + var pending pendingCalls | |
| 21 | + for i, m := range msgs { | |
| 22 | + for _, p := range m.Content { | |
| 23 | + if err := pending.check(i, m, p); err != nil { | |
| 24 | + return err | |
| 25 | + } | |
| 26 | + } | |
| 27 | + } | |
| 28 | + return nil | |
| 29 | +} | |
| 30 | + | |
| 31 | +// pendingCall is a tool request not answered yet. | |
| 32 | +type pendingCall struct{ ref, name string } | |
| 33 | + | |
| 34 | +// pendingCalls are the tool requests of a history not answered yet, in order. | |
| 35 | +type pendingCalls []pendingCall | |
| 36 | + | |
| 37 | +// check takes part p of message i: a tool request must sit in a model | |
| 38 | +// message and waits for its answer; a tool response must answer one. | |
| 39 | +func (pending *pendingCalls) check(i int, m *ai.Message, p *ai.Part) error { | |
| 40 | + switch { | |
| 41 | + case p.IsToolRequest() && p.ToolRequest != nil: | |
| 42 | + if m.Role != ai.RoleModel { | |
| 43 | + return fmt.Errorf("message %d: tool request in a %s message", i, m.Role) | |
| 44 | + } | |
| 45 | + *pending = append(*pending, pendingCall{p.ToolRequest.Ref, p.ToolRequest.Name}) | |
| 46 | + case p.IsToolResponse() && p.ToolResponse != nil: | |
| 47 | + r := p.ToolResponse | |
| 48 | + j := slices.IndexFunc(*pending, func(c pendingCall) bool { | |
| 49 | + if r.Ref != "" { | |
| 50 | + return c.ref == r.Ref | |
| 51 | + } | |
| 52 | + return c.name == r.Name | |
| 53 | + }) | |
| 54 | + if j < 0 { | |
| 55 | + return fmt.Errorf("message %d: tool response %q answers no pending request", i, r.Name) | |
| 56 | + } | |
| 57 | + *pending = slices.Delete(*pending, j, j+1) | |
| 58 | + } | |
| 59 | + return nil | |
| 60 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,60 @@ | |||
| 1 | +package compact | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "errors" | ||
| 5 | + "fmt" | ||
| 6 | + "slices" | ||
| 7 | + | ||
| 8 | + "github.com/firebase/genkit/go/ai" | ||
| 9 | +) | ||
| 10 | + | ||
| 11 | +// Valid checks what an OpenAI-compatible server checks before answering: the | ||
| 12 | +// history starts with the system prompt, every tool request sits in a model | ||
| 13 | +// message, and every tool response answers a request seen earlier — paired by | ||
| 14 | +// Ref when the server set one, by tool name otherwise (same rule as | ||
| 15 | +// engine.executed). | ||
| 16 | +func Valid(msgs []*ai.Message) error { | ||
| 17 | + if len(msgs) == 0 || msgs[0].Role != ai.RoleSystem { | ||
| 18 | + return errors.New("history does not start with the system prompt") | ||
| 19 | + } | ||
| 20 | + var pending pendingCalls | ||
| 21 | + for i, m := range msgs { | ||
| 22 | + for _, p := range m.Content { | ||
| 23 | + if err := pending.check(i, m, p); err != nil { | ||
| 24 | + return err | ||
| 25 | + } | ||
| 26 | + } | ||
| 27 | + } | ||
| 28 | + return nil | ||
| 29 | +} | ||
| 30 | + | ||
| 31 | +// pendingCall is a tool request not answered yet. | ||
| 32 | +type pendingCall struct{ ref, name string } | ||
| 33 | + | ||
| 34 | +// pendingCalls are the tool requests of a history not answered yet, in order. | ||
| 35 | +type pendingCalls []pendingCall | ||
| 36 | + | ||
| 37 | +// check takes part p of message i: a tool request must sit in a model | ||
| 38 | +// message and waits for its answer; a tool response must answer one. | ||
| 39 | +func (pending *pendingCalls) check(i int, m *ai.Message, p *ai.Part) error { | ||
| 40 | + switch { | ||
| 41 | + case p.IsToolRequest() && p.ToolRequest != nil: | ||
| 42 | + if m.Role != ai.RoleModel { | ||
| 43 | + return fmt.Errorf("message %d: tool request in a %s message", i, m.Role) | ||
| 44 | + } | ||
| 45 | + *pending = append(*pending, pendingCall{p.ToolRequest.Ref, p.ToolRequest.Name}) | ||
| 46 | + case p.IsToolResponse() && p.ToolResponse != nil: | ||
| 47 | + r := p.ToolResponse | ||
| 48 | + j := slices.IndexFunc(*pending, func(c pendingCall) bool { | ||
| 49 | + if r.Ref != "" { | ||
| 50 | + return c.ref == r.Ref | ||
| 51 | + } | ||
| 52 | + return c.name == r.Name | ||
| 53 | + }) | ||
| 54 | + if j < 0 { | ||
| 55 | + return fmt.Errorf("message %d: tool response %q answers no pending request", i, r.Name) | ||
| 56 | + } | ||
| 57 | + *pending = slices.Delete(*pending, j, j+1) | ||
| 58 | + } | ||
| 59 | + return nil | ||
| 60 | +} | ||