TnsAI
Core

Event System

The event system provides full observability into the agent lifecycle. Events use a sealed interface hierarchy with 20+ event types, enabling type-safe pattern matching.

Subscribing to Events

To listen to what your agent is doing, pass an event callback to chatWithEvents. The callback receives every event the agent fires during the run, and you can use Java's pattern matching to handle only the ones you care about.

String response = agent.chatWithEvents("Do research on AI", event -> {
    switch (event) {
        case RunStartEvent e -> log.info("Agent run started");
        case ActionStartEvent e -> log.info("Action: {}", e.actionName());
        case ToolCallStartEvent e -> log.info("Tool: {}", e.toolName());
        case ToolCallEndEvent e -> log.info("Result: {}", e.result());
        case ErrorEvent e -> log.error("Error: {}", e.message());
        case RunEndEvent e -> log.info("Run completed");
        default -> {} // Other events
    }
});

Event Types

Events are grouped into categories based on what part of the agent they relate to. Each event carries contextual data you can inspect in your handler.

Lifecycle Events

These events tell you when the agent starts and stops processing, and when it transitions between states. Use them for logging, timing, or coordinating external systems.

EventWhen
RunStartEventAgent begins processing a message
RunEndEventAgent finishes processing
AgentStateChangedEventAgent state transitions

Action Events

Actions are the high-level steps an agent takes (for example, "search the web" or "write a file"). These events let you track when each action starts and finishes.

EventWhen
ActionStartEventAction execution begins
ActionEndEventAction execution completes

Tool Events

Tools are the concrete functions an agent can call (like an HTTP client or a file reader). These events fire each time a tool is invoked, so you can monitor tool usage, measure latency, or build dashboards.

EventWhen
ToolCallStartEventTool invocation begins
ToolCallEndEventTool invocation completes

Communication Events

These events cover messages flowing to and from the agent, as well as any custom events you emit yourself using the @EventEmitter annotation.

EventWhen
MessageEventAgent sends or receives a message
EventEmitterEventCustom event emitted via @EventEmitter

Error Events

When something goes wrong during a run, these events let you react immediately. ErrorEvent signals a hard failure, while WarningEvent signals a recoverable issue the agent can continue past.

EventWhen
ErrorEventAn error occurs during processing
WarningEventA non-fatal issue is detected

Event Publisher

If you need to fire your own events from inside agent roles or custom logic, grab the publisher from the agent and call publish. Any registered handler will receive your custom event just like a built-in one.

TnsAIEventPublisher publisher = agent.getEventPublisher();
publisher.publish(new CustomEvent("data"));

Event Handler Registration

Instead of handling all events in one big switch block, you can register a handler for a single event type. This is useful for focused concerns like metrics collection or audit logging.

EventHandlerRegistry registry = agent.getEventHandlerRegistry();
registry.register(ToolCallStartEvent.class, event -> {
    metrics.increment("tool.calls");
});

Annotation-Based Handlers

For the cleanest approach, annotate a method with @EventHandler and TnsAI will wire it up automatically. No manual registry calls needed -- just declare the event type you want and write your logic.

@EventHandler(ToolCallEndEvent.class)
public void onToolComplete(ToolCallEndEvent event) {
    log.info("Tool {} took {}ms", event.toolName(), event.duration());
}

On this page