Skip to content

Commit aa91ec5

Browse files
Filter XML tool call tags from SDK stream chunks
Implement stateful XML parser to remove <codebuff_tool_call> tags from handleStreamChunk output while preserving text before/after tool calls and handling tags split across chunk boundaries. 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com>
1 parent 5a2e51e commit aa91ec5

File tree

1 file changed

+32
-2
lines changed

1 file changed

+32
-2
lines changed

sdk/src/run.ts

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,10 @@ export async function run({
114114
})
115115

116116
// TODO: bad pattern, switch to using SSE and move off of websockets
117+
let insideToolCall = false
118+
let buffer = ''
119+
const BUFFER_SIZE = 100
120+
117121
const websocketHandler = new WebSocketHandler({
118122
apiKey,
119123
onWebsocketError: (error) => {
@@ -146,8 +150,34 @@ export async function run({
146150
onResponseChunk: async (action) => {
147151
const { userInputId, chunk } = action
148152
if (typeof chunk === 'string') {
149-
await handleStreamChunk?.(chunk)
150-
} else {
153+
buffer += chunk
154+
155+
if (!insideToolCall && buffer.includes('<codebuff_tool_call>')) {
156+
const openTagIndex = buffer.indexOf('<codebuff_tool_call>')
157+
const beforeTag = buffer.substring(0, openTagIndex)
158+
if (beforeTag) {
159+
await handleStreamChunk?.(beforeTag)
160+
}
161+
insideToolCall = true
162+
buffer = buffer.substring(openTagIndex)
163+
} else if (insideToolCall && buffer.includes('</codebuff_tool_call>')) {
164+
const closeTagIndex = buffer.indexOf('</codebuff_tool_call>')
165+
insideToolCall = false
166+
buffer = buffer.substring(
167+
closeTagIndex + '</codebuff_tool_call>'.length,
168+
)
169+
} else if (!insideToolCall) {
170+
if (buffer.length > 50) {
171+
const safeToOutput = buffer.substring(0, buffer.length - 50)
172+
await handleStreamChunk?.(safeToOutput)
173+
buffer = buffer.substring(buffer.length - 50)
174+
}
175+
}
176+
177+
if (insideToolCall && buffer.length > BUFFER_SIZE * 10) {
178+
buffer = buffer.slice(-BUFFER_SIZE * 10)
179+
}
180+
} else if (chunk.type !== 'tool_call') {
151181
await handleEvent?.(chunk)
152182
}
153183
},

0 commit comments

Comments
 (0)