Core Fundamentals ⏱ 8 min read 📁 examples/21_observability.mjs

Lesson 07: Observability, Telemetry and Abort

Instrument your AI agent pipeline with structured client events, typed error handling, pluggable API observers, and graceful request cancellation using AbortController.

1. Why This Feature Exists

Production agent applications require deep visibility into latency, network retries, rate limits, and tool execution times. Additionally, user-initiated cancellations must terminate HTTP connections immediately.

2. Key Symbols and Exports

client.on(event, handler)
Listen to api_request, api_response, api_retry, tool_start, and tool_finish events.
withApiObserver(client, observer)
Pluggable observability tap for Datadog, OpenTelemetry, or custom monitoring.
MerciError & BackendError
Typed error classes carrying HTTP status codes, error details, and error origins.
AbortController & AbortSignal
Cancel in-flight LLM calls and backoff delays cleanly without orphan requests.

3. Implementation Walkthrough

import {
    ProviderType,
    resolveProvider,
    initializeClient,
    loadCredentials,
    getDefaultModel,
    withApiObserver,
    MerciError
} from 'merci-sdk';

const PROVIDER = resolveProvider();
const { client } = await initializeClient({ provider: PROVIDER, options: loadCredentials({ provider: PROVIDER }) });

// Attach structured observer
withApiObserver(client, {
    onRequest: (req) => console.log(`[REQ] ${req.method} ${req.url} (model: ${req.model})`),
    onResponse: (res) => console.log(`[RES] Status ${res.status} (${res.latencyMs}ms)`),
    onRetry: ({ attempt, delayMs }) => console.warn(`[RETRY] Attempt ${attempt} after ${delayMs}ms`)
});

// Cancellation with AbortController
const controller = new AbortController();
setTimeout(() => controller.abort(), 250); // Abort after 250ms

try {
    const session = client.session(getDefaultModel({ provider: PROVIDER }));
    await session.run('Write a 2000-word essay on distributed systems.', {
        signal: controller.signal
    });
} catch (err) {
    if (err.name === 'AbortError' || err.code === 'ABORT_ERR') {
        console.log('Request was cancelled gracefully.');
    }
}

4. Wire and Telemetry Mechanics

Event hooks fire synchronously before and after fetch calls. When an AbortSignal is triggered, underlying socket connections are closed and active retry timers are cleared immediately.

5. Run the Example

Execute the runnable example directly from the repository root:

node examples/21_observability.mjs

Read the full example: examples/21_observability.mjs →

Expected Output: Demonstrates event logging, observer telemetry, typed error catching, and early AbortSignal cancellation.