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
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.mjsRead the full example: examples/21_observability.mjs →