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();Python Integration Example
import requests
import json
from typing import List, Dict, Optional
class MomentizeClient:
def __init__(self, api_key: str, base_url: str = "https://api.momentize.ai"):
self.api_key = api_key
self.base_url = base_url
self.session = requests.Session()
self.session.headers.update({
'Authorization': f'Bearer {api_key}',
'Content-Type': 'application/json'
})
def analyze_conversation(self, conversation: List[Dict], session_id: str,
user_context: Optional[Dict] = None) -> Dict:
"""Analyze conversation for high-value moments"""
payload = {
'conversation': conversation,
'session_id': session_id,
'user_context': user_context or {}
}
response = self.session.post(f"{self.base_url}/v1/analyze",
json=payload)
response.raise_for_status()
return response.json()
def track_event(self, event_type: str, session_id: str,
impression_id: Optional[str] = None,
advertiser_id: Optional[str] = None,
metadata: Optional[Dict] = None) -> Dict:
"""Track user interaction events"""
payload = {
'event_type': event_type,
'session_id': session_id,
'impression_id': impression_id,
'advertiser_id': advertiser_id,
'metadata': metadata or {}
}
response = self.session.post(f"{self.base_url}/v1/events",
json=payload)
response.raise_for_status()
return response.json()
def get_stats(self) -> Dict:
"""Get analytics data"""
response = self.session.get(f"{self.base_url}/v1/stats")
response.raise_for_status()
return response.json()
# Example usage with Flask web app
from flask import Flask, request, jsonify, session
import uuid
app = Flask(__name__)
app.secret_key = 'your-secret-key'
# Initialize Momentize.ai client
momentize = MomentizeClient('your-api-key')
@app.route('/chat', methods=['POST'])
def chat_endpoint():
data = request.json
user_message = data.get('message')
# Get or create session ID
if 'session_id' not in session:
session['session_id'] = f"session_{uuid.uuid4()}"
# Get conversation history from session
conversation = session.get('conversation', [])
# Add user message
conversation.append({
'role': 'user',
'content': user_message
})
# Generate AI response (your implementation)
ai_response = generate_ai_response(user_message)
conversation.append({
'role': 'assistant',
'content': ai_response
})
# Update session
session['conversation'] = conversation
try:
# Analyze conversation with Momentize.ai
result = momentize.analyze_conversation(
conversation=conversation,
session_id=session['session_id'],
user_context={
'platform': 'web_app',
'user_ip': request.remote_addr
}
)
# Track impressions for any sponsored content
for ad in result.get('sponsored_content', []):
momentize.track_event(
event_type='impression',
session_id=session['session_id'],
impression_id=ad['impression_id'],
advertiser_id=ad['advertiser_id']
)
return jsonify({
'ai_response': ai_response,
'moments': result.get('moments_detected', []),
'sponsored_content': result.get('sponsored_content', []),
'total_value': result.get('total_estimated_value', 0)
})
except Exception as e:
print(f"Momentize.ai error: {e}")
return jsonify({
'ai_response': ai_response,
'moments': [],
'sponsored_content': []
})
@app.route('/track-click', methods=['POST'])
def track_click():
"""Track clicks on sponsored content"""
data = request.json
try:
momentize.track_event(
event_type='click',
session_id=data['session_id'],
impression_id=data['impression_id'],
advertiser_id=data['advertiser_id'],
metadata={
'click_timestamp': data.get('timestamp'),
'user_agent': request.headers.get('User-Agent')
}
)
return jsonify({'success': True})
except Exception as e:
return jsonify({'success': False, 'error': str(e)})
def generate_ai_response(message):
# Your AI implementation here
return f"I understand you're asking about: {message}"
if __name__ == '__main__':
app.run(debug=True)React Integration Example
import React, { useState, useEffect } from 'react';
import axios from 'axios';
// Custom hook for Momentize.ai integration
const useAIMoments = (apiKey) => {
const [client, setClient] = useState(null);
useEffect(() => {
const aiMomentsClient = {
analyze: async (conversation, sessionId) => {
const response = await axios.post('https://api.momentize.ai/v1/analyze', {
conversation,
session_id: sessionId
}, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
return response.data;
},
trackEvent: async (eventData) => {
await axios.post('https://api.momentize.ai/v1/events', eventData, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
}
};
setClient(aiMomentsClient);
}, [apiKey]);
return client;
};
// React Chat Component
const AIChatWidget = ({ apiKey }) => {
const [messages, setMessages] = useState([]);
const [inputValue, setInputValue] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [sessionId] = useState(`session_${Date.now()}`);
const [sponsoredContent, setSponsoredContent] = useState([]);
const aiMoments = useAIMoments(apiKey);
const sendMessage = async () => {
if (!inputValue.trim() || isLoading) return;
const userMessage = {
role: 'user',
content: inputValue,
timestamp: new Date().toISOString()
};
setMessages(prev => [...prev, userMessage]);
setInputValue('');
setIsLoading(true);
try {
// Get AI response (replace with your AI service)
const aiResponse = await getAIResponse(inputValue);
const assistantMessage = {
role: 'assistant',
content: aiResponse,
timestamp: new Date().toISOString()
};
const updatedConversation = [...messages, userMessage, assistantMessage];
setMessages(updatedConversation);
// Analyze with Momentize.ai
if (aiMoments) {
const result = await aiMoments.analyze(updatedConversation, sessionId);
if (result.sponsored_content?.length > 0) {
setSponsoredContent(result.sponsored_content);
// Track impressions
result.sponsored_content.forEach(ad => {
aiMoments.trackEvent({
event_type: 'impression',
session_id: sessionId,
impression_id: ad.impression_id,
advertiser_id: ad.advertiser_id
});
});
}
}
} catch (error) {
console.error('Chat error:', error);
} finally {
setIsLoading(false);
}
};
const handleAdClick = (ad) => {
if (aiMoments) {
aiMoments.trackEvent({
event_type: 'click',
session_id: sessionId,
impression_id: ad.impression_id,
advertiser_id: ad.advertiser_id
});
}
window.open(ad.cta_url, '_blank');
};
return (
<div className="ai-chat-widget">
<div className="chat-header">
<h3>AI Assistant</h3>
</div>
<div className="chat-messages">
{messages.map((message, index) => (
<div key={index} className={`message ${message.role}`}>
<div className="message-content">
{message.content}
</div>
</div>
))}
{sponsoredContent.map((ad, index) => (
<SponsoredContentBlock
key={index}
ad={ad}
onClick={() => handleAdClick(ad)}
/>
))}
{isLoading && (
<div className="message assistant loading">
<div className="message-content">Thinking...</div>
</div>
)}
</div>
<div className="chat-input">
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
onKeyPress={(e) => e.key === 'Enter' && sendMessage()}
placeholder="Ask me anything..."
disabled={isLoading}
/>
<button onClick={sendMessage} disabled={isLoading || !inputValue.trim()}>
Send
</button>
</div>
</div>
);
};
// Sponsored Content Component
const SponsoredContentBlock = ({ ad, onClick }) => (
<div className="sponsored-content-block">
<div className="disclosure">{ad.disclosure}</div>
<div className="ad-content">
<h4>{ad.title}</h4>
<p>{ad.description}</p>
<button onClick={onClick} className="cta-button">
{ad.cta_text}
</button>
</div>
</div>
);
// Helper function - replace with your AI service
const getAIResponse = async (message) => {
// Simulate AI response - replace with OpenAI, Claude, etc.
await new Promise(resolve => setTimeout(resolve, 1000));
return `I understand you're asking about: "${message}". How can I help you further?`;
};
export default AIChatWidget;PHP Integration Example
<?php
/**
* Momentize.ai PHP SDK
* Simple integration for PHP applications
*/
class MomentizeClient {
private $apiKey;
private $baseUrl;
public function __construct($apiKey, $baseUrl = 'https://api.momentize.ai') {
$this->apiKey = $apiKey;
$this->baseUrl = rtrim($baseUrl, '/');
}
/**
* Analyze conversation for high-value moments
*/
public function analyze($conversation, $sessionId, $userContext = []) {
$data = [
'conversation' => $conversation,
'session_id' => $sessionId,
'user_context' => $userContext
];
return $this->makeRequest('POST', '/v1/analyze', $data);
}
/**
* Track user interaction events
*/
public function trackEvent($eventType, $sessionId, $impressionId = null,
$advertiserId = null, $metadata = []) {
$data = [
'event_type' => $eventType,
'session_id' => $sessionId,
'impression_id' => $impressionId,
'advertiser_id' => $advertiserId,
'metadata' => $metadata
];
return $this->makeRequest('POST', '/v1/events', $data);
}
/**
* Get analytics data
*/
public function getStats() {
return $this->makeRequest('GET', '/v1/stats');
}
/**
* Make HTTP request to Momentize.ai API
*/
private function makeRequest($method, $endpoint, $data = null) {
$url = $this->baseUrl . $endpoint;
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . $this->apiKey,
'Content-Type: application/json',
'Accept: application/json'
],
CURLOPT_TIMEOUT => 30,
CURLOPT_CUSTOMREQUEST => $method
]);
if ($data && $method !== 'GET') {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
}
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
throw new Exception("cURL Error: " . $error);
}
$decodedResponse = json_decode($response, true);
if ($httpCode >= 400) {
$errorMsg = isset($decodedResponse['detail']) ?
$decodedResponse['detail'] :
'HTTP Error ' . $httpCode;
throw new Exception($errorMsg);
}
return $decodedResponse;
}
}
// Example: Laravel Controller Integration
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class ChatController extends Controller {
private $momentize;
public function __construct() {
$this->momentize = new MomentizeClient(config('services.momentize.api_key'));
}
public function sendMessage(Request $request) {
$message = $request->input('message');
$sessionId = $request->session()->get('ai_session_id', 'session_' . time());
$request->session()->put('ai_session_id', $sessionId);
// Get conversation history from session
$conversation = $request->session()->get('conversation', []);
// Add user message
$conversation[] = [
'role' => 'user',
'content' => $message
];
// Generate AI response (your implementation)
$aiResponse = $this->generateAIResponse($message);
$conversation[] = [
'role' => 'assistant',
'content' => $aiResponse
];
// Update session
$request->session()->put('conversation', $conversation);
try {
// Analyze with Momentize.ai
$result = $this->momentize->analyze(
$conversation,
$sessionId,
[
'platform' => 'laravel',
'user_id' => auth()->id()
]
);
// Track impressions for sponsored content
foreach ($result['sponsored_content'] ?? [] as $ad) {
$this->momentize->trackEvent(
'impression',
$sessionId,
$ad['impression_id'],
$ad['advertiser_id'],
[
'timestamp' => now()->toISOString(),
'user_agent' => $request->userAgent()
]
);
}
return response()->json([
'ai_response' => $aiResponse,
'moments' => $result['moments_detected'] ?? [],
'sponsored_content' => $result['sponsored_content'] ?? [],
'total_value' => $result['total_estimated_value'] ?? 0
]);
} catch (Exception $e) {
// Log error and return basic response
\Log::error('Momentize.ai error: ' . $e->getMessage());
return response()->json([
'ai_response' => $aiResponse,
'moments' => [],
'sponsored_content' => []
]);
}
}
public function trackClick(Request $request) {
try {
$this->momentize->trackEvent(
'click',
$request->input('session_id'),
$request->input('impression_id'),
$request->input('advertiser_id'),
[
'timestamp' => now()->toISOString(),
'user_agent' => $request->userAgent()
]
);
return response()->json(['success' => true]);
} catch (Exception $e) {
return response()->json(['success' => false, 'error' => $e->getMessage()]);
}
}
private function generateAIResponse($message) {
// Your AI implementation here
return "Thank you for your message: " . $message;
}
}
// Example: Simple PHP Chat Interface
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$momentize = new MomentizeClient('your-api-key');
$message = $_POST['message'] ?? '';
if (!isset($_SESSION['session_id'])) {
$_SESSION['session_id'] = 'session_' . time() . '_' . rand(1000, 9999);
}
if (!isset($_SESSION['conversation'])) {
$_SESSION['conversation'] = [];
}
// Add user message
$_SESSION['conversation'][] = [
'role' => 'user',
'content' => $message
];
// Generate AI response
$aiResponse = "Thanks for your message: " . $message;
$_SESSION['conversation'][] = [
'role' => 'assistant',
'content' => $aiResponse
];
try {
$result = $momentize->analyze(
$_SESSION['conversation'],
$_SESSION['session_id']
);
$sponsoredContent = $result['sponsored_content'] ?? [];
} catch (Exception $e) {
$sponsoredContent = [];
error_log('Momentize.ai error: ' . $e->getMessage());
}
header('Content-Type: application/json');
echo json_encode([
'ai_response' => $aiResponse,
'sponsored_content' => $sponsoredContent
]);
exit;
}
?>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.