MCPcopy Index your code
hub / github.com/coder/coder / tryCompact

Function tryCompact

coderd/x/chatd/chatloop/compaction.go:89–181  ·  view source on GitHub ↗

tryCompact checks whether context usage exceeds the compaction threshold and, if so, generates and persists a summary. Returns (true, nil) when compaction was performed, (false, nil) when not needed, and (false, err) on failure.

(
	ctx context.Context,
	model fantasy.LanguageModel,
	compaction *CompactionOptions,
	contextLimitFallback int64,
	stepUsage fantasy.Usage,
	stepMetadata fantasy.ProviderMetadata,
	allMessages []fantasy.Message,
)

Source from the content-addressed store, hash-verified

87// (true, nil) when compaction was performed, (false, nil) when not
88// needed, and (false, err) on failure.
89func tryCompact(
90 ctx context.Context,
91 model fantasy.LanguageModel,
92 compaction *CompactionOptions,
93 contextLimitFallback int64,
94 stepUsage fantasy.Usage,
95 stepMetadata fantasy.ProviderMetadata,
96 allMessages []fantasy.Message,
97) (bool, error) {
98 config, ok := normalizedCompactionConfig(compaction)
99 if !ok {
100 return false, nil
101 }
102
103 contextTokens := contextTokensFromUsage(stepUsage)
104 if contextTokens <= 0 {
105 return false, nil
106 }
107
108 metadataLimit := extractContextLimit(stepMetadata)
109 contextLimit := resolveContextLimit(
110 metadataLimit.Int64,
111 config.ContextLimit,
112 contextLimitFallback,
113 )
114
115 usagePercent, compact := shouldCompact(
116 contextTokens, contextLimit, config.ThresholdPercent,
117 )
118 if !compact {
119 return false, nil
120 }
121
122 // Publish the "Summarizing..." tool-call indicator so
123 // connected clients see activity during summary generation.
124 if config.PublishMessagePart != nil && config.ToolCallID != "" {
125 config.PublishMessagePart(
126 codersdk.ChatMessageRoleAssistant,
127 codersdk.ChatMessageToolCall(config.ToolCallID, config.ToolName, nil),
128 )
129 }
130
131 summary, err := generateCompactionSummary(
132 ctx, model, allMessages, config,
133 )
134 if err != nil {
135 return false, err
136 }
137 if summary == "" {
138 // Publish a tool-result error so connected clients
139 // see the compaction failure.
140 publishCompactionError(config, "compaction produced an empty summary")
141 return false, xerrors.New("compaction produced an empty summary")
142 }
143
144 systemSummary := strings.TrimSpace(
145 config.SystemSummaryPrefix + "\n\n" + summary,
146 )

Callers 2

RunFunction · 0.85
tryCompactOnExitFunction · 0.85

Calls 12

ChatMessageToolCallFunction · 0.92
ChatMessageToolResultFunction · 0.92
contextTokensFromUsageFunction · 0.85
extractContextLimitFunction · 0.85
resolveContextLimitFunction · 0.85
shouldCompactFunction · 0.85
publishCompactionErrorFunction · 0.85
NewMethod · 0.65
ErrorfMethod · 0.45
MarshalMethod · 0.45

Tested by

no test coverage detected