Observability
Observability helps answer three questions: what did the agent do, how long did each step take, and how much did model usage cost? ISH can record a timeline of model and tool activity, collect usage and timing totals, send run details to a monitoring service, and enforce configured limits. You can enable only the pieces your application needs. A trace is the connected timeline for one run; each timed item in that timeline is called a span by common monitoring tools.
- Python
- TypeScript
- Rust
- Go
- C#
- Java
from ish import Agent, BaseInterceptor, LifecycleContext, MetricsInterceptor
class PerformanceLogger(BaseInterceptor):
async def after_tool(self, ctx: LifecycleContext) -> None:
if ctx.duration_ms is not None:
print(f"Tool '{ctx.entity_name}' executed in {ctx.duration_ms:.2f} ms")
metrics = MetricsInterceptor()
agent = Agent(
name="profiled_assistant",
model="gpt-4o-mini",
interceptors=[metrics, PerformanceLogger()],
)
# After running the agent:
print(metrics.metrics)
import { Agent, IshClient, MetricsInterceptor } from "ish-harness";
const client = new IshClient();
const metrics = new MetricsInterceptor(client);
const agent = new Agent({
name: "profiled_assistant",
model: { provider: "openai_chat", name: "gpt-4o-mini" },
lifecycle: (req) => {
metrics.onLifecycle(req);
if (req.event === "after_tool" && req.context.duration_ms != null) {
console.log(`Tool '${req.context.entity_name}' executed in ${req.context.duration_ms.toFixed(2)} ms`);
}
},
});
const result = await agent.run("Check workspace status.");
console.log(metrics.snapshot(), result.total_tokens);
metrics.close();
client.close();
use std::sync::{Arc, Mutex};
use async_trait::async_trait;
use ish_harness::interceptors::{LifecycleContext, LifecycleEvent, LifecycleObserver};
use ish_harness::MetricsAccumulator;
struct RustMetricsObserver(Arc<Mutex<MetricsAccumulator>>);
#[async_trait]
impl LifecycleObserver for RustMetricsObserver {
async fn dispatch(
&self,
event: LifecycleEvent,
context: &mut LifecycleContext,
_chunk: Option<&str>,
) -> Result<(), String> {
let mut acc = self.0.lock().unwrap();
match event {
LifecycleEvent::AfterModel | LifecycleEvent::AfterTool => {
let entity_type = format!("{:?}", context.entity_type).to_lowercase();
acc.record_call(&entity_type, context.duration_ms);
if event == LifecycleEvent::AfterTool {
if let Some(ms) = context.duration_ms {
println!("Tool '{}' executed in {:.2} ms", context.entity_name, ms);
}
}
}
LifecycleEvent::ModelError | LifecycleEvent::ToolError => acc.record_error(),
_ => {}
}
Ok(())
}
}
let metrics = Arc::new(Mutex::new(MetricsAccumulator::default()));
let observer = Arc::new(RustMetricsObserver(metrics.clone()));
let snapshot = metrics.lock().unwrap().snapshot();
println!("Calls recorded: {:?}", snapshot.calls);
metrics, err := ish.NewMetricsInterceptor(client)
if err != nil {
panic(err)
}
defer metrics.Close()
result, err := client.RunAgent(ish.AgentRunRequest{
AgentName: "profiled_assistant",
Model: &ish.AgentModel{Provider: "openai_chat", Name: "gpt-4o-mini"},
UserPrompt: ish.StringPtr("Check workspace status."),
Lifecycle: metrics.OnLifecycle,
})
if err != nil {
panic(err)
}
snapshot, err := metrics.Snapshot()
fmt.Println("Result:", result, "Metrics:", snapshot)
using Ish.Harness;
using var client = new IshClient();
using var metrics = new MetricsInterceptor(client);
using var request = new AgentRunRequest
{
AgentName = "profiled_assistant",
Model = new AgentModel { Provider = "openai_chat", Name = "gpt-4o-mini" },
UserPrompt = "Check workspace status.",
Lifecycle = req =>
{
metrics.OnLifecycle(req);
return null;
},
};
var result = client.Run(request);
Console.WriteLine($"Snapshot: {metrics.Snapshot()}, Result: {result}");
import io.github.ishharness.IshClient;
import io.github.ishharness.MetricsInterceptor;
try (var metrics = new MetricsInterceptor(client);
var request = new IshClient.AgentRequest(
"gpt-4o-mini",
"Report concise status.",
"Check workspace status.")
.provider("openai_chat")
.agentName("profiled_assistant")
.lifecycle(req -> {
metrics.onLifecycle(req);
return null;
})) {
var result = client.runAgent(request);
System.out.println("Metrics: " + metrics.snapshot() + ", Result: " + result);
}
Trace privacy, run budgets
Control repeated calls
Use repeated-call detection to stop a run that keeps making the same tool call. Use cost limits when the model or provider supplies enough pricing information to estimate spend; ISH rejects incomplete or invalid cost data rather than treating it as zero.
| Control | Purpose |
|---|---|
| Repeated-call detection | Stops identical tool calls from looping |
max_cost_usd | Caps estimated model cost for a run |
max_total_tokens | Caps token use across model calls |
Measure latency
All six SDKs provide a shared metrics collector alongside custom per-event timing hooks. It records model and tool calls, errors, usage, and elapsed time:
Set model call limits
To prevent infinite loops when an agent struggles with a tricky task, configure the built-in max_turns / MaxTurns limit on the agent runner or enforce a dynamic quota inside before_llm / before_model:
- Python
- TypeScript
- Rust
- Go
- C#
- Java
from ish import Agent, BaseInterceptor, LifecycleContext
class ModelCallBudgetGuardrail(BaseInterceptor):
def __init__(self, max_calls: int = 5):
self.max_calls = max_calls
self.calls = 0
async def before_llm(self, ctx: LifecycleContext) -> None:
self.calls += 1
if self.calls > self.max_calls:
raise RuntimeError(
f"Execution aborted: exceeded model call budget of {self.max_calls}."
)
agent = Agent(
name="bounded_assistant",
model="gpt-4o-mini",
max_turns=5,
interceptors=[ModelCallBudgetGuardrail(max_calls=5)],
)
import { Agent } from "ish-harness";
let modelCalls = 0;
const maxCalls = 5;
const agent = new Agent({
name: "bounded_assistant",
model: { provider: "openai_chat", name: "gpt-4o-mini" },
max_turns: 5,
lifecycle: ({ event }) => {
if (event === "before_model") {
modelCalls += 1;
if (modelCalls > maxCalls) {
throw new Error(`Execution aborted: exceeded model call budget of ${maxCalls}.`);
}
}
},
});
use std::sync::atomic::{AtomicUsize, Ordering};
use async_trait::async_trait;
use ish_harness::interceptors::{LifecycleContext, LifecycleEvent, LifecycleObserver};
struct ModelCallBudgetGuardrail {
max_calls: usize,
calls: AtomicUsize,
}
#[async_trait]
impl LifecycleObserver for ModelCallBudgetGuardrail {
async fn dispatch(
&self,
event: LifecycleEvent,
_context: &mut LifecycleContext,
_chunk: Option<&str>,
) -> Result<(), String> {
if event == LifecycleEvent::BeforeModel {
let count = self.calls.fetch_add(1, Ordering::SeqCst) + 1;
if count > self.max_calls {
return Err(format!(
"Execution aborted: exceeded model call budget of {}.",
self.max_calls
));
}
}
Ok(())
}
}
calls := 0
const maxCalls = 5
req := ish.AgentRunRequest{
AgentName: "bounded_assistant",
Model: &ish.AgentModel{Provider: "openai_chat", Name: "gpt-4o-mini"},
MaxTurns: ish.IntPtr(5),
UserPrompt: ish.StringPtr("Analyze dependencies."),
Lifecycle: func(request map[string]any) (any, bool, error) {
if request["event"] == "before_model" {
calls++
if calls > maxCalls {
return nil, false, fmt.Errorf("exceeded model call budget of %d", maxCalls)
}
}
return nil, false, nil
},
}
using Ish.Harness;
int calls = 0;
const int maxCalls = 5;
using var request = new AgentRunRequest
{
AgentName = "bounded_assistant",
Model = new AgentModel { Provider = "openai_chat", Name = "gpt-4o-mini" },
MaxTurns = 5,
UserPrompt = "Analyze dependencies.",
Lifecycle = req =>
{
if (req.GetProperty("event").GetString() == "before_model" && ++calls > maxCalls)
{
throw new InvalidOperationException($"Exceeded model call budget of {maxCalls}.");
}
return null;
},
};
import io.github.ishharness.IshClient;
import java.util.concurrent.atomic.AtomicInteger;
var calls = new AtomicInteger();
final int maxCalls = 5;
try (var request = new IshClient.AgentRequest(
"gpt-4o-mini",
"Answer concisely.",
"Analyze dependencies.")
.provider("openai_chat")
.agentName("bounded_assistant")
.maxTurns(5)
.lifecycle(req -> {
if ("before_model".equals(req.path("event").asText())
&& calls.incrementAndGet() > maxCalls) {
throw new IllegalStateException("Exceeded model call budget of " + maxCalls);
}
return null;
})) {
var result = client.runAgent(request);
}
Send run details to monitoring tools
ish can send run timelines to Langfuse and other services that accept the
OpenTelemetry format, a common format for monitoring data. The monitoring
service stores and displays the run details it receives. You can inspect the
order and timing of model and tool activity without changing the agent's model
or tools.
trace_export_data setting | What gets sent | When to use it |
|---|---|---|
"none" | Omits prompt, tool input, and result values from exported details | When those values may contain sensitive information |
"digest" (default) | Sends short previews; long text and large lists are shortened | For routine troubleshooting with limited detail |
"full" | Sends complete prompt, tool input, and result values | Only when full content is needed and the destination is trusted |

Example trace detail from the Langfuse tracing guide. The screenshot illustrates Langfuse's interface; data shown is not produced by ISH.
Key Capabilities
- Run order and timing: exported records show the order and duration of model and tool activity.
- Input and output detail: the
trace_export_datasetting controls how much prompt, tool input, and result content is sent. - Context activity: context tool calls can appear in the timeline when they emit activity events. The default
digestmode may omit some stored values.
The default trace_export_data="digest" shortens long values but can still
send complete short values. It does not guarantee that sensitive information is
hidden. Choose "none" when exported prompt, tool input, and result content
must be excluded. Choose "full" only when the destination is trusted and you
need complete values for debugging.
Configuration Example
Set your Langfuse project credentials and host in the environment:
export LANGFUSE_PUBLIC_KEY="pk-lf-..."
export LANGFUSE_SECRET_KEY="sk-lf-..."
export LANGFUSE_HOST="https://cloud.langfuse.com"
- Python
- TypeScript
- Rust
- Go
- C#
- Java
import asyncio
from ish import Agent, OTelGenAIInterceptor
async def main() -> None:
interceptor = OTelGenAIInterceptor(
preset="langfuse",
service_name="finance-workflow",
trace_export_data="digest",
)
agent = Agent(
name="financial_analyst",
model="gpt-4o",
interceptors=[interceptor],
)
result = await agent.run("Analyze Q4 performance and save key metrics.")
print(result.content)
asyncio.run(main())
import { Agent, IshClient, OTelGenAIInterceptor } from "ish-harness";
const client = new IshClient();
const interceptor = new OTelGenAIInterceptor(client, {
preset: "langfuse",
serviceName: "finance-workflow",
traceExportData: "digest",
});
const agent = new Agent({
name: "financial_analyst",
model: { provider: "openai_chat", name: "gpt-4o" },
lifecycle: (req) => interceptor.onLifecycle(req),
});
const result = await agent.run("Analyze Q4 performance and save key metrics.");
console.log(result.content);
client.close();
Rust applications can configure the same metrics and monitoring behavior. See the Rust API reference for the exact types and method signatures.
otel, err := ish.NewOTelInterceptor(
client,
ish.OTelInterceptorOptions{
ServiceName: "finance-workflow",
TraceExportData: "digest",
},
true, // enable GenAI span attributes
"langfuse", // exporter preset
"", // read LANGFUSE_PUBLIC_KEY from env
"", // read LANGFUSE_SECRET_KEY from env
)
if err != nil {
panic(err)
}
result, err := client.RunAgent(ish.AgentRunRequest{
AgentName: "financial_analyst",
Model: &ish.AgentModel{Provider: "openai_chat", Name: "gpt-4o"},
UserPrompt: ish.StringPtr("Analyze Q4 performance and save key metrics."),
Lifecycle: otel.OnLifecycle,
})
if err != nil {
panic(err)
}
fmt.Println(result)
using Ish.Harness;
using var client = new IshClient();
var otel = new OTelGenAIInterceptor(
client,
new OTelInterceptorOptions(
ServiceName: "finance-workflow",
TraceExportData: "digest"),
preset: "langfuse");
using var request = new AgentRunRequest
{
AgentName = "financial_analyst",
Model = new AgentModel { Provider = "openai_chat", Name: "gpt-4o" },
UserPrompt = "Analyze Q4 performance and save key metrics.",
Lifecycle = otel.OnLifecycle,
};
var result = client.Run(request);
Console.WriteLine(result);
import io.github.ishharness.IshClient;
import io.github.ishharness.OTelGenAIInterceptor;
import io.github.ishharness.OTelInterceptor;
import java.util.Map;
var otel = new OTelGenAIInterceptor(
client,
new OTelInterceptor.Options(null, "finance-workflow", Map.of(), "digest", false, false),
"langfuse",
null,
null);
try (var request = new IshClient.AgentRequest(
"gpt-4o",
"Analyze financial performance accurately.",
"Analyze Q4 performance and save key metrics.")
.provider("openai_chat")
.agentName("financial_analyst")
.lifecycle(otel::onLifecycle)) {
var result = client.runAgent(request);
System.out.println(result);
}
Exporter Presets (otel.resolve_exporter)
| Preset | Default Endpoint | Authentication Header |
|---|---|---|
"langfuse" | {LANGFUSE_HOST}/api/public/otel/v1/traces (defaults LANGFUSE_HOST to http://localhost:3000) | HTTP Basic auth (LANGFUSE_PUBLIC_KEY / LANGFUSE_SECRET_KEY) |
"langtrace" | https://api.langtrace.ai/api/trace | x-api-key |
"phoenix" | http://localhost:6006/v1/traces | None by default |
| Default monitoring collector | http://localhost:4318/v1/traces | Custom headers if configured |
Set LANGFUSE_PUBLIC_KEY, LANGFUSE_SECRET_KEY, and LANGFUSE_HOST in the environment before running the Langfuse example above. See Langfuse's OpenTelemetry setup guide for region endpoints and project-key details.