Easily integrate with the Omni API using our JavaScript SDK
Install the Omni JavaScript SDK using npm or yarn:
npm install @omnimoderate/sdk
Or with yarn:
yarn add @omnimoderate/sdk
First, import the SDK and create a client instance with your API key:
import { OmniClient } from '@omnimoderate/sdk';
// Create a client instance
const client = new OmniClient({
apiKey: 'your_api_key_here'
});
Here's a simple example of how to moderate text content:
// Moderate a single text item
const result = await client.moderate({
input: [
{ type: 'text', text: 'This is a sample text to moderate.' }
]
});
console.log('Moderation result:', result.flagged);
And here's how to moderate both text and images:
// Function to convert an image file to base64
async function fileToBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
}
// Moderate text and images
async function moderateMixedContent(textContent, imageFile) {
// Convert image to base64
const imageBase64 = await fileToBase64(imageFile);
const result = await client.moderate({
input: [
{ type: 'text', text: textContent },
{ type: 'image', base64: imageBase64 }
],
analyze_images: true
});
console.log('Moderation result:', result.flagged);
// Check text result
console.log('Text flagged:', result.results[0].flagged);
// Check image result
console.log('Image flagged:', result.results[1].flagged);
// Check vision analysis
if (result.vision_analysis) {
console.log('Image analysis:', result.vision_analysis[0].analysis);
}
return result;
}
The SDK automatically verifies response signatures if you provide your signature secret:
// Create a client instance with signature verification
const client = new OmniClient({
apiKey: 'your_api_key_here',
signatureSecret: 'your_signature_secret_here'
});
// The SDK will automatically verify signatures
const result = await client.moderate({
input: [
{ type: 'text', text: 'This is a sample text to moderate.' }
]
});
The SDK includes built-in retry logic for rate limit errors:
// Create a client instance with retry options
const client = new OmniClient({
apiKey: 'your_api_key_here',
retry: {
maxRetries: 3,
initialDelay: 1000, // 1 second
maxDelay: 10000 // 10 seconds
}
});
// The SDK will automatically retry rate-limited requests
const result = await client.moderate({
input: [
{ type: 'text', text: 'This is a sample text to moderate.' }
]
});
You can customize the fetch options used by the SDK:
// Create a client instance with custom fetch options
const client = new OmniClient({
apiKey: 'your_api_key_here',
fetchOptions: {
timeout: 10000, // 10 seconds
headers: {
'User-Agent': 'My Custom App/1.0'
}
}
});
Here's an example of how to integrate the SDK with a React component:
import React, { useState } from 'react';
import { OmniClient } from '@omnimoderate/sdk';
// Create a client instance
const client = new OmniClient({
apiKey: process.env.REACT_APP_OMNI_API_KEY
});
function ModerationForm() {
const [text, setText] = useState('');
const [image, setImage] = useState(null);
const [result, setResult] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const handleSubmit = async (e) => {
e.preventDefault();
setLoading(true);
setError(null);
try {
// Prepare input array
const input = [];
// Add text if provided
if (text.trim()) {
input.push({ type: 'text', text });
}
// Add image if provided
if (image) {
const reader = new FileReader();
reader.readAsDataURL(image);
const imageBase64 = await new Promise((resolve, reject) => {
reader.onload = () => resolve(reader.result);
reader.onerror = reject;
});
input.push({ type: 'image', base64: imageBase64 });
}
// Submit for moderation
const moderationResult = await client.moderate({
input,
analyze_images: true
});
setResult(moderationResult);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
return (
<div>
<h2>Content Moderation</h2>
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="text">Text:</label>
<textarea
id="text"
value={text}
onChange={(e) => setText(e.target.value)}
placeholder="Enter text to moderate"
rows={4}
/>
</div>
<div>
<label htmlFor="image">Image:</label>
<input
id="image"
type="file"
accept="image/*"
onChange={(e) => setImage(e.target.files[0])}
/>
</div>
<button type="submit" disabled={loading || (!text && !image)}>
{loading ? 'Moderating...' : 'Moderate Content'}
</button>
</form>
{error && (
<div className="error">
<p>Error: {error}</p>
</div>
)}
{result && (
<div className="result">
<h3>Moderation Result</h3>
<p>Content flagged: {result.flagged ? 'Yes' : 'No'}</p>
{result.results.map((item, index) => (
<div key={index}>
<h4>Item {index + 1}</h4>
<p>Flagged: {item.flagged ? 'Yes' : 'No'}</p>
<p>Categories:</p>
<ul>
{Object.entries(item.categories).map(([category, flagged]) => (
<li key={category}>
{category}: {flagged ? 'Yes' : 'No'} (Score: {item.category_scores[category].toFixed(2)})
</li>
))}
</ul>
</div>
))}
{result.vision_analysis && (
<div>
<h4>Vision Analysis</h4>
{result.vision_analysis.map((analysis, index) => (
<div key={index}>
<p>Image {analysis.image_index - (text ? 1 : 0) + 1}:</p>
<p>Analysis: {analysis.analysis}</p>
<p>Flagged: {analysis.flagged ? 'Yes' : 'No'}</p>
</div>
))}
</div>
)}
</div>
)}
</div>
);
}
export default ModerationForm;