AgentSea

Concept

Observability

Log, measure and trace agent runs with the logging, metrics and tracing classes in @lov3kaizen/agentsea-core.

01Overview

Core provides three building blocks:

Logger
Structured logging on top of winston, to the console and optionally a file.
MetricsCollector / globalMetrics
Records one entry per agent run, with latency, tokens and success. Summarizes and notifies subscribers.
Tracer / globalTracer
Spans with attributes, events and durations, grouped by trace ID.

Note

The agent does not record metrics or spans on its own. Wrap the calls you want measured, as the examples below do.

02Logging

TS
import { Logger } from '@lov3kaizen/agentsea-core';

const logger = new Logger({
  level: 'info',           // 'error' | 'warn' | 'info' | 'debug'
  format: 'json',          // 'json' | 'simple' (applies to the file)
  filename: './logs/app.log', // optional file output
  console: true,           // default; set false to skip the console
});

logger.error('Failed to connect', { error: 'timeout' });
logger.warn('Rate limit approaching', { usage: 95 });
logger.info('Agent executed', { agentName: 'chat-agent' });
logger.debug('Tool called', { toolName: 'calculator' });

// A child logger adds fixed fields to every entry
const requestLogger = logger.child({ requestId: 'req-42' });
requestLogger.info('Starting run');

Logging an agent run:

TS
import { Agent, Logger } from '@lov3kaizen/agentsea-core';

const logger = new Logger({ level: 'info' });

async function runAgent(agent: Agent, prompt: string, context: AgentContext) {
  logger.info('Agent run started', {
    agentName: agent.config.name,
    conversationId: context.conversationId,
  });
  try {
    const response = await agent.execute(prompt, context);
    logger.info('Agent run completed', {
      agentName: agent.config.name,
      tokensUsed: response.metadata.tokensUsed,
      toolCalls: response.toolCalls?.length ?? 0,
    });
    return response;
  } catch (error) {
    logger.error('Agent run failed', {
      agentName: agent.config.name,
      error: error instanceof Error ? error.message : String(error),
    });
    throw error;
  }
}

03Metrics

A metric is an AgentMetrics record: agentName, latencyMs, tokensUsed, success, an optional error, and a timestamp. Record one per run:

TS
import { Agent, AgentContext, globalMetrics } from '@lov3kaizen/agentsea-core';

async function executeWithMetrics(agent: Agent, prompt: string, context: AgentContext) {
  const startedAt = Date.now();
  try {
    const response = await agent.execute(prompt, context);
    globalMetrics.record({
      agentName: agent.config.name,
      latencyMs: Date.now() - startedAt,
      tokensUsed: response.metadata.tokensUsed,
      success: true,
      timestamp: new Date(),
    });
    return response;
  } catch (error) {
    globalMetrics.record({
      agentName: agent.config.name,
      latencyMs: Date.now() - startedAt,
      tokensUsed: 0,
      success: false,
      error: error instanceof Error ? error.message : String(error),
      timestamp: new Date(),
    });
    throw error;
  }
}

Read the recorded metrics:

getStats(agentName?)
Returns totalCalls, successRate, avgLatency, totalTokens and errors. Without a name, it covers all agents.
getAll()
Returns a copy of every recorded metric.
getByAgent(name)
Returns the metrics for one agent.
getByTimeRange(start, end)
Returns the metrics recorded in a time window.
subscribe(listener)
Calls the listener for each new metric. Returns an unsubscribe function.
clear()
Removes all recorded metrics.
TS
const stats = globalMetrics.getStats('chat-agent');
console.log(stats.totalCalls, stats.successRate, stats.avgLatency, stats.totalTokens);

04Tracing

startSpan(name, context?) returns a span and a context. Pass that context to a child span to nest it under the parent:

TS
import { globalTracer } from '@lov3kaizen/agentsea-core';

const { span: runSpan, context: runContext } = globalTracer.startSpan('agent-run');
globalTracer.setAttributes(runSpan.spanId, { agentName: 'chat-agent', userId: '12345' });

try {
  const response = await agent.execute(prompt, context);

  // A child span for a tool call, nested under the run
  const { span: toolSpan } = globalTracer.startSpan('tool-call', runContext);
  globalTracer.setAttributes(toolSpan.spanId, { toolName: 'calculator' });
  globalTracer.endSpan(toolSpan.spanId);

  globalTracer.addEvent(runSpan.spanId, 'completed', { tokensUsed: response.metadata.tokensUsed });
  globalTracer.endSpan(runSpan.spanId);

  // All spans in the trace, and the run's duration in milliseconds
  const spans = globalTracer.getTrace(runSpan.traceId);
  console.log(spans.length, globalTracer.getSpanDuration(runSpan.spanId));
} catch (error) {
  globalTracer.endSpan(runSpan.spanId, error instanceof Error ? error : new Error(String(error)));
  throw error;
}
startSpan(name, context?)
Starts a span. Returns { span, context }.
endSpan(spanId, error?)
Ends a span. Passing an error marks it failed.
setAttributes(spanId, attributes)
Attaches key/value pairs to a span.
addEvent(spanId, name, attributes?)
Adds a timestamped event to a span.
getSpan(spanId), getTrace(traceId)
Returns one span, or every span in a trace.
getSpanDuration(spanId)
Returns the duration in milliseconds once the span has ended.
export(), clear()
Returns all spans, or clears them.

05Forwarding to monitoring

Core has no built-in exporter for Prometheus, DataDog or other systems. To send metrics out, subscribe to globalMetrics and forward each record with your own client:

TS
import { globalMetrics } from '@lov3kaizen/agentsea-core';

const unsubscribe = globalMetrics.subscribe((metric) => {
  // Send to your monitoring client here
  sendToMonitoring({
    name: 'agent.run',
    agent: metric.agentName,
    latencyMs: metric.latencyMs,
    tokens: metric.tokensUsed,
    success: metric.success,
  });

  if (metric.latencyMs > 5000) {
    console.warn(`Slow run: ${metric.agentName} took ${metric.latencyMs} ms`);
  }
});

// Call unsubscribe() to stop forwarding

06Performance monitoring

Check the summary on an interval and log anything out of range:

TS
import { globalMetrics, Logger } from '@lov3kaizen/agentsea-core';

const logger = new Logger({ level: 'info' });

setInterval(() => {
  const stats = globalMetrics.getStats();

  if (stats.avgLatency > 5000) {
    logger.warn('High average latency', { avgLatency: stats.avgLatency });
  }

  const errorRate = stats.totalCalls > 0 ? stats.errors / stats.totalCalls : 0;
  if (errorRate > 0.05) {
    logger.error('High error rate', { errorRate });
  }

  logger.info('Performance summary', { ...stats, errorRate });
}, 60_000); // once a minute

08Best practices

  • Log levels: use error for failures, info for important events and debug for detail.
  • Context: include agent names and conversation IDs. Use child() for fields that repeat.
  • Metric names and fields: use the same agent names everywhere so records can be grouped.
  • Bound memory: globalMetrics and the tracer keep records in memory. Forward them and call clear() on a schedule in long-running processes.
  • Alerts: alert on error rate and latency, not on single failures.

09Next steps