Code Examples

Complete, working examples showing how to integrate Momentize.ai into your applications. Monetize the Moments in your AI apps.

JavaScript Integration Example
// npm install momentize-sdk
import { Momentize } from 'momentize-sdk';

const client = new Momentize({
  apiKey: 'your-api-key',
  baseUrl: 'https://api.momentize.ai'
});

// Example: Chatbot integration
class ChatBot {
  constructor() {
    this.conversation = [];
    this.sessionId = 'session_' + Date.now();
  }
  
  async handleUserMessage(message) {
    // Add user message
    this.conversation.push({
      role: 'user',
      content: message
    });
    
    // Get AI response (your implementation)
    const aiResponse = await this.getAIResponse(message);
    this.conversation.push({
      role: 'assistant',
      content: aiResponse
    });
    
    // Display AI response
    this.displayMessage('assistant', aiResponse);
    
    // Analyze for moments and get sponsored content
    try {
      const result = await client.analyze({
        conversation: this.conversation,
        sessionId: this.sessionId
      });
      
      // Display any sponsored content
      if (result.sponsored_content.length > 0) {
        this.displaySponsoredContent(result.sponsored_content);
      }
      
      console.log('Moments detected:', result.moments_detected);
      console.log('Estimated value:', result.total_estimated_value);
      
    } catch (error) {
      console.error('Momentize.ai error:', error);
    }
  }
  
  displaySponsoredContent(ads) {
    ads.forEach(ad => {
      const adElement = this.createAdElement(ad);
      document.querySelector('#chat-container').appendChild(adElement);
      
      // Track impression
      client.trackEvent({
        eventType: 'impression',
        sessionId: this.sessionId,
        impressionId: ad.impression_id,
        advertiserId: ad.advertiser_id
      });
    });
  }
  
  createAdElement(ad) {
    const div = document.createElement('div');
    div.className = 'sponsored-content';
    div.innerHTML = `
      <div class="disclosure">${ad.disclosure}</div>
      <h3>${ad.title}</h3>
      <p>${ad.description}</p>
      <a href="${ad.cta_url}" class="cta-button" target="_blank">
        ${ad.cta_text}
      </a>
    `;
    
    // Add click tracking
    div.querySelector('.cta-button').addEventListener('click', () => {
      client.trackEvent({
        eventType: 'click',
        sessionId: this.sessionId,
        impressionId: ad.impression_id,
        advertiserId: ad.advertiser_id
      });
    });
    
    return div;
  }
}

// Initialize chatbot
const chatbot = new ChatBot();

Key Integration Features

Conversation Analysis

  • • Real-time moment detection
  • • Confidence scoring
  • • Value estimation
  • • Context extraction

Sponsored Content

  • • FTC-compliant display
  • • Relevant ad matching
  • • Frequency capping
  • • Click-through tracking

Analytics & Events

  • • Impression tracking
  • • Click analytics
  • • Revenue reporting
  • • Performance metrics

Common Integration Patterns

1. Reactive Analysis

Analyze conversations after each exchange to detect moments and display relevant sponsored content.

User Message → AI Response → Moment Analysis → Display Sponsored Content

2. Batch Processing

Analyze multiple conversations periodically for better performance and reduced API calls.

Collect Conversations → Batch Analysis → Queue Sponsored Content → Display

3. Session-Based Tracking

Maintain session state to enable frequency capping and personalized ad delivery.

Generate Session ID → Track Conversation → Apply Frequency Limits → Show Unique Ads

Error Handling Best Practices

Graceful Degradation

  • • Never let Momentize.ai API errors break your main application flow
  • • Always provide fallback behavior when moment analysis fails
  • • Log errors for debugging but don't expose them to users
  • • Implement retry logic with exponential backoff
  • • Cache successful responses to reduce API dependency

Testing Your Integration

Test Conversations

  • • "I need to buy a laptop for work"
  • • "iPhone vs Samsung Galaxy comparison"
  • • "My computer is not working properly"
  • • "How to fix a broken screen"
  • • "Book a restaurant reservation"

Expected Moments

  • • Purchase Intent (laptop)
  • • Comparison (iPhone vs Samsung)
  • • Problem (computer not working)
  • • How To (fix screen)
  • • Booking (restaurant)

Ready to Get Started?

Choose your preferred integration approach and start monetizing your AI conversations today.