@humanjudge/grandjury-js
v1.0.2
Published
HumanJudge SDK for AI evaluation session tracking and human feedback management
Maintainers
Readme
grandjury-js by HumanJudge
Professional session tracking and evaluation management for the HumanJudge platform.
Quick Start
CDN Integration (Recommended)
Replace manual session tracking code with professional SDK:
<!-- Simple CDN integration -->
<script src="https://grandjury.xyz/sdk/grandjury.min.js"></script>
<script>
GrandJury.init({
projectId: 'proj_your_project_id'
});
</script>Auto-initialization via Data Attributes
<script
src="https://grandjury.xyz/sdk/grandjury.min.js"
data-grandjury-project-id="proj_your_project_id"
data-grandjury-debug="false">
</script>NPM Installation
npm install @humanjudge/grandjury-jsimport GrandJury from '@humanjudge/grandjury-js';
GrandJury.init({
projectId: process.env.GRANDJURY_PROJECT_ID
});Features
✅ Professional Session Management: Automatic session ID generation and persistence
✅ Cross-Tab Support: Session sharing across browser tabs
✅ Chrome Extension Integration: Seamless detection by GrandJury Chrome extension
✅ Langfuse Integration: Built-in helpers for trace correlation
✅ Offline Support: Event queuing with automatic retry
✅ Graceful Degradation: Fallback when APIs fail
✅ TypeScript Support: Complete type definitions
✅ CDN Ready: Optimized for fast loading
API Reference
Initialization
GrandJury.init(config)Parameters:
config.projectId(string, required): Project ID in format'proj_abc123_xyz'config.apiEndpoint(string, optional): API endpoint overrideconfig.sessionMetadata(object, optional): Session metadataconfig.autoStart(boolean, optional): Auto-start session (default: true)config.enableDebug(boolean, optional): Enable debug logging (default: false)
Session Management
// Start session (automatic with autoStart: true)
const sessionId = await GrandJury.startSession({
user_type: 'premium',
app_section: 'chat'
});
// Get current session ID
const sessionId = GrandJury.getSessionId();
// Stop session
await GrandJury.stopSession();Event Tracking
// Track custom events
GrandJury.track('user_interaction', {
action: 'button_click',
element: 'submit_feedback'
});
// Track AI interactions (automatic with Langfuse integration)
GrandJury.track('ai_generation', {
model: 'gpt-4',
response_time: 1500,
cost: 0.008
});Langfuse Integration
// Wrap Langfuse trace for correlation
const enhancedTrace = GrandJury.langfuse.wrapTrace(langfuseTrace);
// Track generation automatically
GrandJury.langfuse.trackGeneration(langfuseGeneration);Utility Methods
// Check if SDK is ready
if (GrandJury.isReady()) {
// SDK is initialized and ready
}
// Get SDK version
console.log(GrandJury.version); // "1.0.0"
// Clean up resources
GrandJury.destroy();Chrome Extension Integration
The SDK automatically sets global variables for Chrome extension compatibility:
// Available after initialization
window.grandjurySessionId // Current session ID
window.grandjuryConfig // SDK configurationListen for SDK ready events:
window.addEventListener('grandjury:ready', (event) => {
const { sessionId, config, version } = event.detail;
console.log('GrandJury SDK ready:', sessionId);
});Integration Examples
Basic Web Application
<!DOCTYPE html>
<html>
<head>
<script src="https://grandjury.xyz/sdk/grandjury.min.js"></script>
</head>
<body>
<script>
GrandJury.init({
projectId: 'proj_my_app_123',
enableDebug: true
}).then(() => {
console.log('Session started:', GrandJury.getSessionId());
// Track user interactions
document.addEventListener('click', (event) => {
GrandJury.track('user_click', {
element: event.target.tagName,
url: window.location.href
});
});
});
</script>
</body>
</html>React Application
import { useEffect } from 'react';
import GrandJury from '@humanjudge/grandjury-js';
function App() {
useEffect(() => {
GrandJury.init({
projectId: process.env.REACT_APP_GRANDJURY_PROJECT_ID,
sessionMetadata: {
framework: 'react',
version: '18.2.0'
}
});
return () => {
GrandJury.destroy();
};
}, []);
const handleUserAction = () => {
GrandJury.track('form_submission', {
form_type: 'contact',
completion_time: performance.now()
});
};
return <div>Your app content</div>;
}Langfuse Integration
import { Langfuse } from 'langfuse';
import GrandJury from '@humanjudge/grandjury-js';
// Initialize both services
await GrandJury.init({ projectId: 'proj_my_app_123' });
const langfuse = new Langfuse({
publicKey: 'your_public_key',
secretKey: 'your_secret_key'
});
// Create trace with automatic correlation
const trace = langfuse.trace({ name: 'user_query' });
const enhancedTrace = GrandJury.langfuse.wrapTrace(trace);
// Generate AI response
const generation = enhancedTrace.generation({
name: 'ai_response',
model: 'gpt-4',
input: userQuery,
output: aiResponse
});
// Track generation for evaluation
GrandJury.langfuse.trackGeneration(generation);Error Handling
The SDK includes comprehensive error handling and graceful degradation:
try {
await GrandJury.init({
projectId: 'proj_invalid_id'
});
} catch (error) {
console.error('SDK initialization failed:', error);
// SDK will provide fallback functionality
}
// Graceful fallback when APIs fail
GrandJury.track('important_event', data);
// ^ Events are queued and retried automaticallySecurity
Integrity Verification
Use integrity hashes for CDN security:
<script
src="https://grandjury.xyz/sdk/grandjury.min.js"
integrity="sha384-[hash-will-be-generated]"
crossorigin="anonymous">
</script>CORS Configuration
The SDK works across all origins. Configure your project settings to restrict domains if needed.
Performance
- SDK Size: ~15KB minified + gzipped
- Load Time: <500ms from CDN
- Memory Usage: <2MB including session data
- API Calls: Minimal - only session start/stop and event batching
Browser Support
- Chrome 80+
- Firefox 75+
- Safari 13+
- Edge 80+
- Mobile browsers (iOS Safari, Chrome Mobile)
Troubleshooting
Common Issues
SDK not loading:
// Check if SDK loaded successfully
if (typeof window.GrandJury === 'undefined') {
console.error('GrandJury SDK failed to load');
// Use fallback session tracking
}Session not persisting across tabs:
// Verify sessionStorage is available
if (typeof sessionStorage === 'undefined') {
console.warn('sessionStorage not available, sessions may not persist');
}API calls failing:
GrandJury.init({
projectId: 'proj_your_id',
enableDebug: true // Enable to see detailed error logs
});Debug Mode
Enable debug logging to troubleshoot issues:
GrandJury.init({
projectId: 'proj_your_id',
enableDebug: true
});
// Check console for detailed logs:
// - Session start/stop events
// - API call results
// - Event tracking status
// - Error detailsMigration from Manual Tracking
Replace this manual approach:
// OLD: Manual session tracking
window.grandjurySessionId = 'session_' + Date.now() + '_' + Math.random().toString(36);
fetch('/api/v1/extension/sessions/start', {
method: 'POST',
body: JSON.stringify({ session_id: window.grandjurySessionId })
});With professional SDK:
// NEW: Professional SDK
GrandJury.init({
projectId: 'proj_your_project_id'
});
// Session automatically started and managedSupport
- Documentation: https://humanjudge.com/docs/integration
- Email Support: [email protected]
License
MIT License - see LICENSE file for details.
Changelog
v1.0.0 (2025-09-29)
- Initial release
- Professional session management
- Chrome extension integration
- Langfuse helpers
- Event tracking with retry logic
- TypeScript definitions
- CDN distribution
