Skip to content

[FEATURE] Implement general-purpose hook/callback system #231

@zastrowm

Description

@zastrowm

Problem Statement

Several current features under consideration/design are converging on the idea that we'd like to provide a mechanism to build primative SDK objects that can hook into events of an agent to and adapt behavior (#191, #33).

Today this can be done via the callback_handler of the agent, however it has a couple flaws:

  • The default handler is to print output; adding an explict handler disables this behavior
  • Composing multiple handlers together is clunky
  • It is currently invoked for all events instead of only the ones that a caller is interesting in
  • Arguments passed into the callback_handler are untyped

Proposed Solution

Implement a general purpose hook system which is:

  • Composable: A feature can be implemented by subscribing to multiple hooks and callers do not need to provide hooks in a specific order
  • N to N: Multiple hooks can subscribe and respond to an event and a hook can subscribe to multiple events
  • Hooks can be added externally allowing tools or features to add hooks as needed and allow others to subscribe

Alternatives Solutions

  • Continue to use the callback system to intercept these events
  • Implement a system on top of async iterators which has similar functionality

Status & tasking

As of Jul 11, we've recently added the core system of hooks which allows you to observe a subset of events within the event-loop.

Current Available Events

Event Description
AgentInitializedEvent Triggered when an agent has been constructed and finished initialization at the end of Agent.init
BeforeInvocationEvent Triggered at the beginning of a new agent request (call, stream_async, or structured_output)
AfterInvocationEvent Triggered at the end of an agent request, regardless of success or failure. Uses reverse callback ordering
MessageAddedEvent Triggered when a message is added to the agent's conversation history

Experimental Events

Event Description
BeforeModelInvocationEvent Triggered before the model is invoked for inference
AfterModelInvocationEvent Triggered after model invocation completes. Uses reverse callback ordering
BeforeToolInvocationEvent Triggered before a tool is invoked
AfterToolInvocationEvent Triggered after tool invocation completes. Uses reverse callback ordering

Documentation is currently pending release, but was added via PR #130

Sub-tasks

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions