Lifecycle Hooks

Using lifecycle hooks to monitor and debug agent execution.

Using Lifecycle Hooks to Monitor Agent Execution

Lifecycle hooks allow you to plug in your custom logging or processing steps upon key lifecycle events during the agent.run() method, such as function calls and remote service interactions.

This feature is particularly useful when you want to display the details of these events in a human-readable format to your end users in your web application, or to your agent developers if you offers a platform for your customers to build and observe agents.

lifecycle_hook.py

import json

from rich.console import Console

from oci.addons.adk import Agent, AgentClient
from oci.addons.adk.tool.prebuilt import CalculatorToolkit
from oci.addons.adk.run.types import RequiredAction, PerformedAction

# A callback function that is called when a required action is fulfilled
def handle_fulfilled_required_action(required_action: RequiredAction, performed_action: PerformedAction):
    # Implement your custom logging or processing here
    # Access the required action and performed action objects to get the details
    pass

# A callback function that is called when a remote service is invoked
def handle_invoked_remote_service(chat_request, chat_response):
    # Implement your custom logging or processing here
    # Access the chat request and response objects to get the details
    pass

def main():

    client = AgentClient(
        auth_type="api_key",
        profile="DEFAULT",
        region="us-chicago-1"
    )

    agent = Agent(
        client=client,
        agent_endpoint_id="ocid1.genaiagentendpoint...",
        instructions="You're a helpful assistant that can perform calculations.",
        tools=[CalculatorToolkit()]
    )

    agent.setup()

    input = "What's the square root of 475695037565?"
    response = agent.run(
        input,
        max_steps=6,
        on_fulfilled_required_action=handle_fulfilled_required_action,
        on_invoked_remote_service=handle_invoked_remote_service,
    )

    response.pretty_print()

if __name__ == "__main__":
    main()

Currently the ADK supports two lifecycle hooks:

  • on_fulfilled_required_action: This hook is called after a required action is fulfilled, such as a function tool is invoked.
  • on_invoked_remote_service: This hook is called when the remote agent service API is invoked.