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.
| Event | When |
|---|---|
RunStartEvent | Agent begins processing a message |
RunEndEvent | Agent finishes processing |
AgentStateChangedEvent | Agent 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.
| Event | When |
|---|---|
ActionStartEvent | Action execution begins |
ActionEndEvent | Action 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.
| Event | When |
|---|---|
ToolCallStartEvent | Tool invocation begins |
ToolCallEndEvent | Tool 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.
| Event | When |
|---|---|
MessageEvent | Agent sends or receives a message |
EventEmitterEvent | Custom 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.
| Event | When |
|---|---|
ErrorEvent | An error occurs during processing |
WarningEvent | A 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());
}Error Handling
TnsAI.Core provides a structured exception hierarchy rooted in `TnsAIException`. Every exception carries an error code, retryability flag, and suggested retry parameters, enabling automated recovery decisions across the framework.
Knowledge Base & RAG
TnsAI provides a built-in Retrieval-Augmented Generation (RAG) system through the `KnowledgeBase` interface, `Document` model, and `@KnowledgeSource` annotation. Agents can retrieve relevant context from vector databases, files, URLs, or in-memory stores before making LLM calls.