Skip to content

Commit f3c479f

Browse files
committed
Append tool error messages after all the tool results to not break anthropic schema
1 parent 4b2b83b commit f3c479f

File tree

1 file changed

+6
-2
lines changed

1 file changed

+6
-2
lines changed

packages/agent-runtime/src/tools/stream-parser.ts

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,7 @@ export async function processStream(
253253

254254
let messageId: string | null = null
255255
let hadToolCallError = false
256+
const errorMessages: Message[] = []
256257
while (true) {
257258
if (signal.aborted) {
258259
break
@@ -277,8 +278,10 @@ export async function processStream(
277278
onResponseChunk(chunk)
278279

279280
hadToolCallError = true
280-
// Add error message to assistant messages so the agent can see what went wrong and retry
281-
assistantMessages.push(
281+
// Collect error messages to add AFTER all tool results
282+
// This ensures proper message ordering for Anthropic's API which requires
283+
// tool results to immediately follow the assistant message with tool calls
284+
errorMessages.push(
282285
userMessage(
283286
withSystemTags(
284287
`Error during tool call: ${chunk.message}. Please check the tool name and arguments and try again.`,
@@ -297,6 +300,7 @@ export async function processStream(
297300
...expireMessages(agentState.messageHistory, 'agentStep'),
298301
...assistantMessages,
299302
...toolResultsToAddAfterStream,
303+
...errorMessages, // Error messages must come AFTER tool results for proper API ordering
300304
])
301305

302306
if (!signal.aborted) {

0 commit comments

Comments
 (0)