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.
- Python
- TypeScript
- Rust
- Go
- C#
- Java
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()],
)
import { Agent } from "ish-harness";
const agent = new Agent({
name: "instrumented_assistant",
model: { provider: "openai_chat", name: "gpt-4o-mini" },
lifecycle: ({ event, context }) => {
switch (event) {
case "before_model":
case "after_model":
case "before_tool":
case "after_tool":
console.log(event, context.entity_name, context.duration_ms);
break;
case "model_error":
case "tool_error":
console.error(event, context.entity_name, context.error);
break;
}
},
});
use std::{env, io, sync::Arc};
use async_trait::async_trait;
use ish_harness::interceptors::{LifecycleContext, LifecycleEvent, LifecycleObserver};
use ish_harness::{Agent, OpenAIModel, RunnerConfig};
struct CustomObserver;
#[async_trait]
impl LifecycleObserver for CustomObserver {
async fn dispatch(
&self,
event: LifecycleEvent,
context: &mut LifecycleContext,
_chunk: Option<&str>,
) -> Result<(), String> {
match event {
LifecycleEvent::BeforeModel
| LifecycleEvent::AfterModel
| LifecycleEvent::BeforeTool
| LifecycleEvent::AfterTool => {
println!("{:?}: {} ({:?} ms)", event, context.entity_name, context.duration_ms);
}
LifecycleEvent::ModelError | LifecycleEvent::ToolError => {
eprintln!("{:?}: {:?} on {}", event, context.error, context.entity_name);
}
LifecycleEvent::ModelChunk => {}
}
Ok(())
}
}
let model = OpenAIModel::new(
"gpt-4o-mini".into(),
"https://api.openai.com/v1".into(),
env::var("OPENAI_API_KEY")?,
0.2,
);
let config = RunnerConfig {
lifecycle_observer: Some(Arc::new(CustomObserver)),
..RunnerConfig::default()
};
let agent = Agent::builder(Arc::new(model))
.name("instrumented_assistant")
.config(config)
.build()
.map_err(io::Error::other)?;
req := ish.AgentRunRequest{
AgentName: "instrumented_assistant",
Model: &ish.AgentModel{Provider: "openai_chat", Name: "gpt-4o-mini"},
UserPrompt: ish.StringPtr("Summarize system health."),
Lifecycle: func(request map[string]any) (any, bool, error) {
event, _ := request["event"].(string)
ctxMap, _ := request["context"].(map[string]any)
fmt.Printf("[%s] entity=%v duration_ms=%v\n",
event, ctxMap["entity_name"], ctxMap["duration_ms"])
return nil, false, nil
},
}
using Ish.Harness;
using var request = new AgentRunRequest
{
AgentName = "instrumented_assistant",
Model = new AgentModel { Provider = "openai_chat", Name = "gpt-4o-mini" },
UserPrompt = "Summarize system health.",
Lifecycle = req =>
{
var eventName = req.GetProperty("event").GetString();
var entity = req.GetProperty("context").GetProperty("entity_name").GetString();
Console.WriteLine($"[{eventName}] entity={entity}");
return null;
},
};
import io.github.ishharness.IshClient;
var request = new IshClient.AgentRequest(
"gpt-4o-mini",
"Answer clearly.",
"Summarize system health.")
.provider("openai_chat")
.agentName("instrumented_assistant")
.lifecycle(req -> {
String event = req.path("event").asText();
String entity = req.path("context").path("entity_name").asText();
System.out.println("[" + event + "] entity=" + entity);
return null;
});
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
| Event | When it runs | What it can do |
|---|---|---|
before_model | Before a model request | Inspect or update the messages sent to the model. |
model_chunk | As streamed text arrives | Observe partial output without blocking the run. |
after_model | After a model reply | Inspect or update the reply and proposed tool calls. |
model_error | If a model request fails | Read the error and elapsed time. |
before_tool | Before a tool runs | Check its name and arguments; allow or reject the call. |
after_tool | After a tool returns | Inspect the redacted result before it is added to context. |
tool_error | If a tool or policy check fails | Read 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.
| Field | Type | Semantics |
|---|---|---|
| Run identifiers | Text values | Connects related model and tool events |
| Source | Name and type | Identifies the agent, model, tool, subagent, or workflow |
| Input and output | Optional JSON | Carries redacted or structured data for inspection |
| Error | Optional text | Describes a failed model or tool call |
| Timing | Milliseconds | Shows start, end, and elapsed time |
metadata | JSON values | Extra 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
| Dimension | Ad-Hoc Tool Wrappers | Lifecycle Interceptors |
|---|---|---|
| Separation of Concerns | Security and telemetry mixed with business logic | Pure decoupling; tools remain clean domain code |
| Lifecycle Granularity | Only intercepts tool calls | Intercepts runs, model calls, streaming chunks, tools, and errors (before_model/before_llm, after_model/after_llm, before_tool, after_tool) |
| Composability | Complex nested decorator pyramids | Declarative pipeline via interceptors=[...] in Python or composed lifecycle observers across SDKs |
Agent lifecycle Interface
Core Topics
- Safety checks: Review prompts, tool arguments, and results; limit access to sensitive files and commands; and protect credentials.
- Monitoring: Measure model and tool use, follow a run across services, and optionally send trace records to an observability service.