Skip to main content

Agent lifecycle

Lifecycle hooks let an application observe or change an agent run before or after a model or tool call. They are useful for logging, limits, and application-specific checks. The Python hook method names before_llm and after_llm are compatibility names; event-based callbacks in all SDKs use before_model and after_model.

from ish import Agent, BaseInterceptor, LifecycleContext


class CustomInterceptor(BaseInterceptor):
async def before(self, ctx: LifecycleContext) -> None:
"""Called when the agent run begins."""

async def before_llm(self, ctx: LifecycleContext) -> None:
"""Called before the model provider is invoked."""

async def after_llm(self, ctx: LifecycleContext) -> None:
"""Called after the model provider returns messages or tool calls."""

async def before_tool(self, ctx: LifecycleContext) -> None:
"""Called before a tool function executes. May mutate ctx.input_payload or raise."""

async def after_tool(self, ctx: LifecycleContext) -> None:
"""Called after a tool function completes."""

async def on_error(self, ctx: LifecycleContext) -> None:
"""Called if a model or tool invocation errors."""


agent = Agent(
name="instrumented_assistant",
model="gpt-4o-mini",
interceptors=[CustomInterceptor()],
)

All six SDKs expose lifecycle hooks for model calls, tool calls, and agent runs. Hooks receive a shared event context. When hooks are enabled, the runtime runs relevant tool calls in sequence so policy and observer callbacks see a predictable order.

Where lifecycle hooks run​

Lifecycle events​

EventWhen it runsWhat it can do
before_modelBefore a model requestInspect or update the messages sent to the model.
model_chunkAs streamed text arrivesObserve partial output without blocking the run.
after_modelAfter a model replyInspect or update the reply and proposed tool calls.
model_errorIf a model request failsRead the error and elapsed time.
before_toolBefore a tool runsCheck its name and arguments; allow or reject the call.
after_toolAfter a tool returnsInspect the redacted result before it is added to context.
tool_errorIf a tool or policy check failsRead the error and elapsed time.

Data available to a hook​

Each hook receives a shared event record with the information needed to inspect the run. The runtime records the event's timing and links related model and tool events to the same run.

FieldTypeSemantics
Run identifiersText valuesConnects related model and tool events
SourceName and typeIdentifies the agent, model, tool, subagent, or workflow
Input and outputOptional JSONCarries redacted or structured data for inspection
ErrorOptional textDescribes a failed model or tool call
TimingMillisecondsShows start, end, and elapsed time
metadataJSON valuesExtra information supplied by your application

Choose a hook​

When to Use Interceptors​

  • Security & Content Moderation: Inspecting prompts or tool arguments for dangerous commands (e.g. rm -rf, SQL injections, prompt injections) before tool execution.
  • Latency & Cost Monitoring: Measuring exact millisecond durations and token counts of LLM calls and tool operations.
  • Rate Limiting & Governance: Enforcing maximum model-call quotas or budgets before the agent runs away with expensive recursive calls.

Hooks, tool wrappers​

DimensionAd-Hoc Tool WrappersLifecycle Interceptors
Separation of ConcernsSecurity and telemetry mixed with business logicPure decoupling; tools remain clean domain code
Lifecycle GranularityOnly intercepts tool callsIntercepts runs, model calls, streaming chunks, tools, and errors (before_model/before_llm, after_model/after_llm, before_tool, after_tool)
ComposabilityComplex nested decorator pyramidsDeclarative pipeline via interceptors=[...] in Python or composed lifecycle observers across SDKs

Agent lifecycle Interface​


Core Topics​

  1. Safety checks: Review prompts, tool arguments, and results; limit access to sensitive files and commands; and protect credentials.
  2. Monitoring: Measure model and tool use, follow a run across services, and optionally send trace records to an observability service.