mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-03 07:57:22 +00:00
Evict large tool outputs from old messages before sending to API
Add evictSeenToolOutputs following the same pattern as evictSeenImages. Tool results larger than 1 KiB that the model has already seen and responded to are replaced with a short placeholder at send time. This prevents multi-MB tool output history from being re-sent on every subsequent turn in long agentic sessions.
This commit is contained in:
1 parent
c285dbcd05
commit
ebd6fc9a10
1 file changed
+29
@@ -396,6 +396,32 @@ export class SessionManager {
|
||||
});
|
||||
};
|
||||
|
||||
// Replace large tool result content with a short summary for messages the
|
||||
// model has already seen and responded to. Like evictSeenImages, this is a
|
||||
// send-time transformation only — session.messages stays intact for the UI.
|
||||
const TOOL_OUTPUT_EVICTION_THRESHOLD = 1024; // 1 KiB
|
||||
const evictSeenToolOutputs = (msgs: OpenAI.Chat.Completions.ChatCompletionMessageParam[]): OpenAI.Chat.Completions.ChatCompletionMessageParam[] => {
|
||||
// Find the index of the last assistant message — everything before it
|
||||
// has already been seen and responded to by the model.
|
||||
let lastAssistantIdx = -1;
|
||||
for (let i = msgs.length - 1; i >= 0; i--) {
|
||||
if (msgs[i].role === 'assistant') {
|
||||
lastAssistantIdx = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (lastAssistantIdx === -1) return msgs;
|
||||
|
||||
return msgs.map((msg, idx) => {
|
||||
if (idx >= lastAssistantIdx) return msg;
|
||||
if (msg.role !== 'tool') return msg;
|
||||
if (typeof msg.content !== 'string') return msg;
|
||||
if (msg.content.length <= TOOL_OUTPUT_EVICTION_THRESHOLD) return msg;
|
||||
|
||||
return { ...msg, content: '[Previous tool output truncated]' };
|
||||
});
|
||||
};
|
||||
|
||||
// Prepare messages for AI
|
||||
// Note: User messages with image_url content parts are valid ChatCompletionMessageParam types
|
||||
// The AIMessage type includes ChatCompletionMessageParam, so this cast is safe
|
||||
@@ -403,6 +429,9 @@ export class SessionManager {
|
||||
? [{ role: 'system', content: systemPrompt }, ...session.messages]
|
||||
: session.messages) as OpenAI.Chat.Completions.ChatCompletionMessageParam[];
|
||||
|
||||
// Evict large tool outputs the model has already processed.
|
||||
messages = evictSeenToolOutputs(messages);
|
||||
|
||||
// Evict images the model has already seen (all except the last user message).
|
||||
// This is a send-time transformation only — session.messages stays intact for the UI.
|
||||
messages = evictSeenImages(messages);
|
||||
|
||||
Reference in new issue
Block a user