feat(agent): add post-turn stop callback

This commit is contained in:
Mario Zechner
2026-05-02 00:49:22 +02:00
parent a44622670f
commit 73b7b2c564
5 changed files with 152 additions and 1 deletions

View File

@@ -112,6 +112,20 @@ The `beforeToolCall` hook runs after `tool_execution_start` and validated argume
Tools can also return `terminate: true` to hint that the automatic follow-up LLM call should be skipped. The loop only stops early when every finalized tool result in that batch sets `terminate: true`. Mixed batches continue normally.
Low-level loop callers can set `shouldStopAfterTurn` to stop gracefully after the current turn completes:
```typescript
const stream = agentLoop(prompts, context, {
model,
convertToLlm,
shouldStopAfterTurn: async ({ message, toolResults, context, newMessages }) => {
return shouldCompactBeforeNextTurn(context.messages);
},
});
```
`shouldStopAfterTurn` runs after `turn_end` is emitted and after the assistant response and any tool executions have completed normally. If it returns `true`, the loop emits `agent_end` and exits before polling steering or follow-up queues, and before starting another LLM call. It does not abort the provider stream, does not cancel running tools, and does not alter the assistant message stop reason.
When you use the `Agent` class, assistant `message_end` processing is treated as a barrier before tool preflight begins. That means `beforeToolCall` sees agent state that already includes the assistant message that requested the tool call.
### continue() Event Sequence