adk-python icon indicating copy to clipboard operation
adk-python copied to clipboard

Support list of callbacks for agent lifecycle hooks (before_agent_callback, after_agent_callback, etc.)

Open kaligautier opened this issue 6 months ago • 7 comments

Feature Request

Problem

In the Python SDK, agent lifecycle callback parameters (before_agent_callback, after_agent_callback, before_model_callback, etc.) accept only a single callable. When multiple concerns need to run at the same hook point (e.g., logging + data injection before an agent starts), developers are forced to write a manual composite wrapper:

async def before_portfolio_analyzer(callback_context: CallbackContext) -> None:
    log_agent_start(callback_context)
    await inject_portfolio_data(callback_context)

portfolio_analyzer = LlmAgent(
    before_agent_callback=before_portfolio_analyzer,  # manual composition
)

This adds boilerplate and breaks the "1 callback = 1 responsibility" principle.

Existing precedent in Go SDK

The Go SDK already supports lists of callbacks:

llmCfg := llmagent.Config{
    BeforeAgentCallbacks: []agent.BeforeAgentCallback{onBeforeAgent},
    AfterAgentCallbacks:  []agent.AfterAgentCallback{onAfterAgent},
    BeforeModelCallbacks: []llmagent.BeforeModelCallback{onBeforeModel},
    BeforeToolCallbacks:  []llmagent.BeforeToolCallback{onBeforeTool},
}

Proposed solution

Accept either a single callable or a list of callables for all callback parameters in Python:

portfolio_analyzer = LlmAgent(
    before_agent_callback=[log_agent_start, inject_portfolio_data],
    before_model_callback=log_before_model,  # single callable still works
)

Callbacks in the list would execute sequentially. If any callback returns a non-None value (e.g., Content to skip the agent), subsequent callbacks in the list should be skipped (short-circuit).

Benefits

  • Parity with Go SDK — consistent behavior across SDKs
  • Composability — mix and match reusable callback functions without manual wrappers
  • Single Responsibility — each callback function stays focused on one concern

Environment

  • Python SDK
  • Affects: BaseAgent (before_agent_callback, after_agent_callback) and LlmAgent (before_model_callback, after_model_callback, before_tool_callback, after_tool_callback)

kaligautier avatar May 04 '26 10:05 kaligautier

@kaligautier Thanks for the update. The request is currently being reviewed by our team, and I will let you know if anything further is needed. Thank you for your understanding.

klateefa avatar May 05 '26 05:05 klateefa

The after_agent_callback hook is exactly where post-execution accountability plugs in.

We've been building Mycelium Trails — an accountability layer for autonomous agents. The pattern is: after_agent_callback fires → agent POSTs signed trail record to Base mainnet → cryptographic receipt of what the agent did, verifiable by anyone.

Supporting a list of callbacks makes this composable: developers can chain their own after_agent_callback logic alongside a trail hook without conflicts. Today with a single callback slot, adding accountability means replacing existing logic.

The trail record structure:

# in after_agent_callback
await trails.record({
    'agent_id': agent.name,
    'action': callback_context.function_call.name,
    'claims': {
        'runtime': 'google-adk',
        'outcome': str(callback_context.function_response)
    }
})
# returns signed on-chain receipt, Base mainnet

Live system: https://argentum.rgiskard.xyz/trails/demo — would work as a drop-in after_agent_callback for any ADK agent.

giskard09 avatar May 05 '26 22:05 giskard09

Quick update on the Mycelium Trails work mentioned above.

Today we ran the first genesis transactions against this infrastructure — the creator committed via Lightning, the agent signed its own commitment autonomously on Arbitrum with no human intervention. Human and agent, same accountability mechanism, same date.

The economic coordination layer that reads those trails: github.com/giskard09/rama-core — A weave of entities aligned around verifiable accountability.

The after_agent_callback pattern above is still the cleanest integration point for ADK. Supporting a list of callbacks would make it composable without overriding existing hooks.

giskard09 avatar May 08 '26 16:05 giskard09

Following up with a working example.

The after_agent_callback pattern for tamper-evident trails in ADK:

import hashlib, struct, time, httpx
from google.adk.agents import Agent

ARGENTUM_API = "https://argentum-api.rgiskard.xyz"
AGENT_ID     = "my-adk-agent-001"

def derive_action_ref(agent_id: str, action_type: str, scope: str, ts_ms: int) -> str:
    payload = (
        agent_id.encode() + action_type.encode()
        + scope.encode() + struct.pack(">q", ts_ms)
    )
    return hashlib.sha256(payload).hexdigest()

def mycelium_trail_callback(callback_context):
    ts_ms      = int(time.time() * 1000)
    action_ref = derive_action_ref(AGENT_ID, "BUILD", callback_context.agent_name, ts_ms)
    try:
        with httpx.Client(timeout=3.0) as client:
            client.post(f"{ARGENTUM_API}/action/submit", json={
                "entity_id":   AGENT_ID,
                "entity_type": "agent",
                "action_type": "BUILD",
                "description": f"Agent: {callback_context.agent_name}",
                "nonce":       action_ref,
                "timestamp":   ts_ms // 1000,
            })
    except Exception:
        pass  # trail failure never blocks the agent

agent = Agent(
    name="compliance_agent",
    model="gemini-2.0-flash",
    after_agent_callback=mycelium_trail_callback,
)

action_ref is deterministic: SHA-256(agent_id || action_type || scope || timestamp_ms int64 big-endian). Same derivation runs across LangGraph, OpenAI Agents SDK, and AutoGen — one verifiable trail format regardless of which framework runs the agent.

For regulated deployments (EU AI Act Art. 12, FCA SYSC 9.1, Basel III/BCBS 239): https://github.com/giskard09/argentum-core

giskard09 avatar May 15 '26 13:05 giskard09

strong +1 for composable callbacks. the before/after agent lifecycle hook is exactly the right integration surface for accountability infrastructure.

we built a receipt layer that hooks into these callbacks to produce bilateral cryptographic receipts: before_agent_callback generates the pre-execution receipt (binding what the agent is authorized to do), after_agent_callback generates the post-execution receipt (binding what actually happened). both are Ed25519 signed and hash-chained.

with composable callbacks, developers can stack nobulex receipts alongside logging, data injection, and observability without writing a manual composite wrapper. each callback stays single-responsibility.

the action_ref derivation mentioned above aligns with our implementation. happy to contribute the ADK callback integration once the list-of-callbacks API lands.

repo: https://github.com/arian-gogani/nobulex

arian-gogani avatar May 17 '26 21:05 arian-gogani

Strong +1 for composable callbacks. The important part for audit/provenance use cases is not just accepting a list, but making the list semantics predictable enough that independent hooks can coexist.

A contract I would want to see specified:

order: callbacks run in declaration order
mutation: later callbacks either see prior mutations, or the API explicitly forbids mutation
short-circuit: a callback that returns a terminal response prevents later callbacks, with an inspectable reason
errors: failed callback identity and stop/continue behavior are visible
scope: before_* hooks can attach a pre-action/admission record; after_* hooks can attach result/receipt metadata

Without those rules, teams end up rebuilding one giant wrapper anyway because policy checks, redaction, telemetry, and receipt emission all need to know whether they are observing the same run state.

I am dogfooding this shape in Project Telos/forum-style ledgers, where the goal is to keep multi-agent routing and tool decisions replayable without making any one hook own the whole audit story: https://github.com/HarperZ9/forum

HarperZ9 avatar Jun 27 '26 20:06 HarperZ9

this is already supported, all six hooks take either a single callable or a list, and the list runs in order and stops at the first non-None return. open a new issue if it resurfaces.

GWeale avatar Aug 06 '26 21:08 GWeale