Skip to content

Commit 0aa0031

Browse files
committed
prune reasoning for anthropic models
1 parent fb78038 commit 0aa0031

File tree

1 file changed

+30
-9
lines changed

1 file changed

+30
-9
lines changed

index.ts

Lines changed: 30 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -67,17 +67,18 @@ const plugin: Plugin = (async (ctx) => {
6767
if (body.messages && Array.isArray(body.messages)) {
6868
cacheToolParameters(body.messages)
6969

70+
// Check for tool messages in both formats:
71+
// 1. OpenAI style: role === 'tool'
72+
// 2. Anthropic style: role === 'user' with content containing tool_result
7073
const toolMessages = body.messages.filter((m: any) => {
71-
if (m.role === 'tool') return true;
72-
if (m.role === 'assistant') {
73-
if (Array.isArray(m.content)) {
74-
for (const part of m.content) {
75-
if (part.type === 'tool_use') return true;
76-
}
74+
if (m.role === 'tool') return true
75+
if (m.role === 'user' && Array.isArray(m.content)) {
76+
for (const part of m.content) {
77+
if (part.type === 'tool_result') return true
7778
}
7879
}
79-
return false;
80-
});
80+
return false
81+
})
8182

8283
const allSessions = await ctx.client.session.list()
8384
const allPrunedIds = new Set<string>()
@@ -94,17 +95,37 @@ const plugin: Plugin = (async (ctx) => {
9495
let replacedCount = 0
9596

9697
body.messages = body.messages.map((m: any) => {
98+
// OpenAI style: role === 'tool' with tool_call_id
9799
if (m.role === 'tool' && allPrunedIds.has(m.tool_call_id?.toLowerCase())) {
98100
replacedCount++
99101
return {
100102
...m,
101103
content: '[Output removed to save context - information superseded or no longer needed]'
102104
}
103105
}
106+
107+
// Anthropic style: role === 'user' with content array containing tool_result
108+
if (m.role === 'user' && Array.isArray(m.content)) {
109+
let messageModified = false
110+
const newContent = m.content.map((part: any) => {
111+
if (part.type === 'tool_result' && allPrunedIds.has(part.tool_use_id?.toLowerCase())) {
112+
messageModified = true
113+
replacedCount++
114+
return {
115+
...part,
116+
content: '[Output removed to save context - information superseded or no longer needed]'
117+
}
118+
}
119+
return part
120+
})
121+
if (messageModified) {
122+
return { ...m, content: newContent }
123+
}
124+
}
125+
104126
return m
105127
})
106128

107-
console.log(replacedCount);
108129
if (replacedCount > 0) {
109130
logger.info("fetch", "Replaced pruned tool outputs", {
110131
replaced: replacedCount,

0 commit comments

Comments
 (0)