feat(agents): Add on_llm_start and on_llm_end Lifecycle Hooks #987
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Motivation
Currently, the
AgentHooks
provide valuable lifecycle events for the start/end of an agent run and for tool execution (on_tool_start
/on_tool_end
). However, developers lack the ability to observe the agent's execution at the language model level.This PR introduces two new hooks,
on_llm_start
andon_llm_end
, to provide this deeper level of observability. This change enables several key use cases:Summary of Changes
src/agents/lifecycle.py
Added two new async methods,
on_llm_start
andon_llm_end
, to theAgentHooks
base class, matching the existingon_*_start
/on_*_end
pattern.src/agents/run.py
Wrapped the call to
model.get_response(...)
in_get_new_response
with invocations of the new hooks so that they fire immediately before and after each LLM call.tests/test_agent_llm_hooks.py
Added unit tests (using a mock model and spy hooks) to validate:
on_start → on_llm_start → on_llm_end → on_end
in a chat‑only run.on_start → on_llm_start → on_llm_end → on_tool_start → on_tool_end → on_llm_start → on_llm_end → on_end
.agent.hooks
isNone
.Usage Examples
1. Async Example (awaitable via
run
)2. Sync Example (blocking via
run_sync
)Note
Checklist
ruff
).