Manual Agent Tracing
Maximum control over your AI agent observability. Manual agent tracing gives you complete control over when and how agent executions are tracked, perfect for complex workflows, custom error handling, and integration with existing monitoring systems.
This approach provides the ultimate flexibility for sophisticated tracing requirements where automatic wrappers don’t meet your specific needs.
Manual agent tracing provides maximum flexibility but requires more code. Use it when you need custom tracing logic, complex error handling, or integration with existing monitoring systems.
How It Works
Manual agent tracing provides comprehensive control through:
- Complete control - You decide exactly what gets tracked and when
- Custom error handling - Implement sophisticated error recovery and reporting
- Integration friendly - Works seamlessly with existing monitoring and logging systems
- Performance optimization - Only trace what you need, when you need it
- Complex workflows - Handle multi-step processes with custom logic
Implementation
Python: Manual Context Management
JavaScript: Manual Control Flow
const { config, startTracing, trackNode, endTracing } = require('@handit.ai/node');
config({ apiKey: 'your-api-key' });
async function manualEcommerceAgent(userId, actionType, payload) {
// Start a new trace session
const tracingResponse = await startTracing({
agentName: 'ecommerce_agent'
});
const executionId = tracingResponse.executionId;
try {
// Step 1: User authentication and validation
const userAuth = await authenticateUser(userId);
// Track authentication
await trackNode({
input: { userId, actionType },
output: userAuth,
nodeName: 'user_authentication',
agentName: 'ecommerce_agent',
nodeType: 'tool',
executionId
});
// Step 2: Action-specific processing
let actionResult;
if (actionType === 'purchase') {
actionResult = await processPurchase(payload, userAuth);
} else if (actionType === 'recommendation') {
actionResult = await processRecommendation(payload, userAuth);
} else if (actionType === 'support') {
actionResult = await processSupport(payload, userAuth);
} else {
throw new Error(`Unknown action type: ${actionType}`);
}
// Track action processing
await trackNode({
input: { payload, userAuth },
output: actionResult,
nodeName: `${actionType}_processing`,
agentName: 'ecommerce_agent',
nodeType: 'tool',
executionId
});
// Step 3: Final result processing
const finalResult = await finalizeResult(actionResult, userAuth);
// Track final processing
await trackNode({
input: { actionResult, userAuth },
output: finalResult,
nodeName: 'result_finalization',
agentName: 'ecommerce_agent',
nodeType: 'tool',
executionId
});
// Track final result
const result = {
result: finalResult,
success: true
};
await trackNode({
input: { userId, actionType, payload },
output: result,
nodeName: 'final_response',
agentName: 'ecommerce_agent',
nodeType: 'tool',
executionId
});
return result;
} catch (error) {
// Track error
const errorResult = {
error: error.message,
success: false
};
await trackNode({
input: { userId, actionType, payload },
output: errorResult,
nodeName: 'error_handling',
agentName: 'ecommerce_agent',
nodeType: 'tool',
executionId
});
// Custom error recovery based on context
if (actionType === 'purchase') {
// Save purchase attempt for later retry
await savePurchaseAttempt(userId, payload, error.message);
return {
result: { saved: true, retryable: true },
error: error.message
};
} else {
// Return graceful error response
return {
result: { success: false, message: 'Operation failed' },
error: error.message
};
}
} finally {
// End the trace session
await endTracing({
executionId,
agentName: 'ecommerce_agent'
});
}
}
// Helper functions for different action types
async function processPurchase(payload, userAuth) {
// Validate purchase data
const validation = await validatePurchaseData(payload);
if (!validation.valid) {
throw new Error(`Purchase validation failed: ${validation.issues.join(', ')}`);
}
// Process payment
const payment = await processPayment(payload.paymentInfo, payload.amount);
return {
transactionId: payment.transactionId,
amount: payload.amount
};
}
async function processRecommendation(payload, userAuth) {
// Get user preferences
const preferences = await getUserPreferences(userAuth.userId);
// Generate recommendations
const recommendations = await generateRecommendations(preferences, payload.category);
return {
recommendations,
category: payload.category
};
}
// Additional helper functions
async function authenticateUser(userId) {
// Your authentication logic
return { success: true, tier: 'premium' };
}
async function validatePurchaseData(payload) {
// Your validation logic
return { valid: true, issues: [] };
}
async function processPayment(paymentInfo, amount) {
// Your payment processing logic
return { transactionId: 'txn_12345', success: true };
}
Advanced Patterns
Multi-Agent Orchestration
Best Practices
When to Use Manual Tracing:
Use Case | Why Manual Tracing |
---|---|
Complex error recovery | Custom error handling logic and recovery strategies |
Multi-step workflows | Dependencies between steps require custom coordination |
Existing monitoring integration | Need to integrate with current logging and monitoring systems |
Performance optimization | Selective tracing based on conditions and requirements |
Business-specific tracking | Custom metrics and tracking requirements unique to your domain |
Implementation Guidelines:
- Use consistent node names - Ensure proper correlation across all trace points
- Track both success and failure paths - Comprehensive coverage of all execution scenarios
- Include relevant context - Provide meaningful data in all traces for debugging
- Implement proper error handling - Handle tracing failures gracefully without affecting business logic
- Consider performance impact - Balance tracing detail with system performance requirements
Manual tracing requires careful error handling and context management. Make sure to properly end tracing sessions and handle all failure scenarios.
Manual agent tracing gives you the power to implement sophisticated monitoring and optimization strategies tailored to your specific use cases.
Next Steps
- Explore Agent Wrapper/Decorator for automatic tracing
- Learn about Node Wrapper/Decorator for function-level control
- Check Node Function Tracing for flexible tracking patterns