feat(agents): Add on_llm_start and on_llm_end Lifecycle Hooks #987
+232
−0
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
This is a focused contribution with the following changes:
src/agents/lifecycle.py
: Added two new async method definitions,on_llm_start
andon_llm_end
, to theAgentHooks
base class. The naming convention aligns with the existingon_..._start
/on_..._end
pattern.src/agents/run.py
: Inserted calls to these new hooks withinAgentRunner._get_new_response
, directly wrapping themodel.get_response()
call to ensure accurate timing and data capture.tests/test_agent_llm_hooks.py
: Added a new unit test file that validates the new functionality. It uses a mock model and a spy hook class to verify:agent.hooks
isNone
.Usage Example
Here is how a developer could use the new hooks:
Checklist
ruff
).