DragonFire Semantic Network Integration Examples
Explore practical examples of integrating the DragonFire Semantic Network into various application types, from web and mobile apps to server-side systems and IoT devices.
Overview
These integration examples demonstrate how to effectively implement the DragonFire Semantic Network across different platforms and use cases. Each example includes code samples, architectural considerations, and best practices for optimal implementation.
Integration Requirements
- DragonFire SDK: Appropriate SDK for your platform (JavaScript, Python, Java, etc.)
- API Access: Valid API key from the Developer Dashboard
- Network Access: Connection to DragonFire services
- Understanding: Familiarity with the Semantic Network concepts
Web Application Integration
This example demonstrates integrating DragonFire into a modern React web application:
// Install SDK
// npm install @dragonfire/client
// Initialize in your application
import { DragonFireClient } from '@dragonfire/client';
// Create client instance
const dragonfire = new DragonFireClient({
endpoint: 'api.dragonfire1.com',
region: 'us-east',
timeSync: true
});
// Initialize at app startup
async function initializeDragonFire() {
try {
await dragonfire.initialize();
console.log('DragonFire client initialized');
return true;
} catch (error) {
console.error('Failed to initialize DragonFire:', error);
return false;
}
}
// User authentication
async function authenticateUser(email, password) {
try {
// Using the user port (100-199) for authentication
const authResult = await dragonfire.execute(`
AUTHENTICATE(100)
.WITH({
email: "${email}",
password: "${password}"
})
.REMEMBER(true)
`);
if (authResult.success) {
// Store token in secure storage
localStorage.setItem('df_auth_token', authResult.token);
// Set token for future requests
dragonfire.setAuthToken(authResult.token);
return {
authenticated: true,
user: authResult.user
};
}
} catch (error) {
console.error('Authentication error:', error);
return { authenticated: false, error };
}
}
// Fetch user data
async function fetchUserProfile() {
try {
// Using data operations port (200-299)
const profile = await dragonfire.execute(`
GET(210)
.SELECT("profile")
.INCLUDE(["preferences", "history"])
`);
return profile;
} catch (error) {
console.error('Error fetching profile:', error);
throw error;
}
}
// Update user preferences
async function updatePreferences(preferences) {
try {
const result = await dragonfire.execute(`
UPDATE(210)
.SELECT("profile")
.SET({ preferences: ${JSON.stringify(preferences)} })
`);
return result.success;
} catch (error) {
console.error('Error updating preferences:', error);
throw error;
}
}
// React Hook for DragonFire integration
import { useState, useEffect } from 'react';
import { DragonFireClient } from '@dragonfire/client';
// Custom hook for DragonFire operations
export function useDragonFire() {
const [client, setClient] = useState(null);
const [status, setStatus] = useState('initializing');
const [error, setError] = useState(null);
useEffect(() => {
const initClient = async () => {
try {
// Create and initialize client
const dragonfire = new DragonFireClient({
endpoint: 'api.dragonfire1.com',
region: 'us-east',
timeSync: true
});
// Restore authentication if available
const token = localStorage.getItem('df_auth_token');
if (token) {
dragonfire.setAuthToken(token);
}
// Initialize
await dragonfire.initialize();
setClient(dragonfire);
setStatus('ready');
} catch (err) {
setError(err);
setStatus('error');
}
};
initClient();
// Cleanup function
return () => {
if (client) {
client.disconnect();
}
};
}, []);
return {
client,
status,
error,
isReady: status === 'ready',
execute: async (command) => {
if (status !== 'ready') {
throw new Error('DragonFire client not ready');
}
return client.execute(command);
}
};
}
// Usage in a component
function UserProfile() {
const { isReady, execute } = useDragonFire();
const [profile, setProfile] = useState(null);
useEffect(() => {
if (isReady) {
// Fetch user profile data
execute(`
GET(210)
.SELECT("profile")
.INCLUDE(["preferences"])
`)
.then(data => setProfile(data))
.catch(err => console.error('Error fetching profile:', err));
}
}, [isReady, execute]);
if (!isReady) return Loading...;
if (!profile) return Loading profile...;
return (
{profile.name}
Email: {profile.email}
execute(`
UPDATE(210)
.SELECT("profile")
.SET({ preferences: ${JSON.stringify(newPrefs)} })
`)}
/>
);
}
Mobile App Integration
This example shows how to integrate DragonFire into a React Native mobile application:
// React Native integration example
import React, { useEffect, useState } from 'react';
import { View, Text, Button, AsyncStorage } from 'react-native';
import { DragonFireClient } from '@dragonfire/client-react-native';
// Initialize DragonFire client
const dragonfire = new DragonFireClient({
endpoint: 'api.dragonfire1.com',
region: 'us-east',
offlineSupport: true, // Enable offline capabilities
persistentStorage: true // Use AsyncStorage for persistence
});
// Main component
export default function App() {
const [isReady, setIsReady] = useState(false);
const [userData, setUserData] = useState(null);
useEffect(() => {
async function initializeClient() {
try {
// Restore session if available
const token = await AsyncStorage.getItem('df_auth_token');
if (token) {
dragonfire.setAuthToken(token);
}
await dragonfire.initialize();
setIsReady(true);
// Register for sync events
dragonfire.on('sync-complete', () => {
console.log('Data synchronized with server');
});
// Load user data if authenticated
if (dragonfire.isAuthenticated()) {
loadUserData();
}
} catch (error) {
console.error('Initialization error:', error);
}
}
initializeClient();
}, []);
async function loadUserData() {
try {
const userData = await dragonfire.execute(`
GET(210)
.SELECT("profile")
.INCLUDE(["preferences"])
`);
setUserData(userData);
} catch (error) {
console.error('Error loading user data:', error);
}
}
async function handleLogin() {
try {
// Show login UI and get credentials
const { email, password } = await showLoginUI();
const authResult = await dragonfire.execute(`
AUTHENTICATE(100)
.WITH({
email: "${email}",
password: "${password}"
})
.REMEMBER(true)
`);
if (authResult.success) {
await AsyncStorage.setItem('df_auth_token', authResult.token);
await loadUserData();
}
} catch (error) {
console.error('Login error:', error);
}
}
if (!isReady) {
return Initializing... ;
}
return (
{userData ? (
) : (
Please log in to continue
)}
);
}
Server-Side Integration
This example demonstrates integrating DragonFire into a Node.js server application:
// Node.js server integration
const express = require('express');
const { DragonFireClient } = require('@dragonfire/client-node');
const app = express();
app.use(express.json());
// Initialize DragonFire client
const dragonfire = new DragonFireClient({
endpoint: 'api.dragonfire1.com',
region: 'us-east',
serviceKey: process.env.DRAGONFIRE_SERVICE_KEY,
highPerformance: true // Enable high-throughput mode
});
// Initialize on startup
async function initializeServices() {
try {
await dragonfire.initialize();
console.log('DragonFire services initialized');
} catch (error) {
console.error('Failed to initialize DragonFire:', error);
process.exit(1);
}
}
// Authentication middleware
function requireAuth(req, res, next) {
const token = req.headers.authorization?.split(' ')[1];
if (!token) {
return res.status(401).json({ error: 'Authentication required' });
}
try {
// Verify token with DragonFire
const verifyResult = dragonfire.execute(`
VERIFY(100)
.TOKEN("${token}")
`);
if (verifyResult.valid) {
req.user = verifyResult.user;
next();
} else {
res.status(401).json({ error: 'Invalid token' });
}
} catch (error) {
res.status(500).json({ error: 'Authentication error' });
}
}
// API routes
app.get('/api/user/profile', requireAuth, async (req, res) => {
try {
const userId = req.user.id;
const profile = await dragonfire.execute(`
GET(210)
.SELECT("profile")
.WHERE(id = "${userId}")
.INCLUDE(["preferences", "settings"])
`);
res.json(profile);
} catch (error) {
res.status(500).json({ error: 'Failed to fetch profile' });
}
});
app.post('/api/transactions', requireAuth, async (req, res) => {
try {
const { amount, targetAccount, currency } = req.body;
const userId = req.user.id;
// Execute financial transaction
const result = await dragonfire.execute(`
CREATE(300)
.TRANSACTION("transfer")
.WITH({
userId: "${userId}",
amount: ${amount},
currency: "${currency}",
targetAccount: "${targetAccount}"
})
`);
res.json({
success: true,
transactionId: result.transactionId
});
} catch (error) {
res.status(500).json({
error: 'Transaction failed',
details: error.message
});
}
});
// Start server
initializeServices().then(() => {
app.listen(3000, () => {
console.log('Server running on port 3000');
});
});
Financial Application
This example showcases DragonFire integration for a financial application with real-time updates:
// Financial application integration
import { DragonFireClient } from '@dragonfire/client';
import { setupRealTimeUpdates } from '@dragonfire/realtime';
class FinancialAppService {
constructor() {
this.dragonfire = new DragonFireClient({
endpoint: 'api.dragonfire1.com',
region: 'us-east',
timeSync: true
});
this.subscriptions = [];
}
async initialize(authToken) {
try {
// Set authentication token
this.dragonfire.setAuthToken(authToken);
// Initialize the client
await this.dragonfire.initialize();
// Setup real-time updates
this.realtime = setupRealTimeUpdates(this.dragonfire);
console.log('Financial service initialized');
return true;
} catch (error) {
console.error('Initialization error:', error);
return false;
}
}
// Get account balances
async getAccountBalances() {
return this.dragonfire.execute(`
GET(300)
.BALANCES()
.FORMAT("DETAILED")
`);
}
// Get recent transactions
async getRecentTransactions(days = 30) {
return this.dragonfire.execute(`
GET(300)
.TRANSACTIONS()
.FILTER(date > now().subtract(days, "days"))
.SORT(date DESC)
.LIMIT(100)
`);
}
// Create a transfer
async createTransfer(sourceAccount, targetAccount, amount, description) {
return this.dragonfire.execute(`
CREATE(300)
.TRANSACTION("transfer")
.WITH({
sourceAccount: "${sourceAccount}",
targetAccount: "${targetAccount}",
amount: ${amount},
description: "${description}"
})
`);
}
// Subscribe to balance updates
subscribeToBalanceUpdates(accountId, callback) {
const subscription = this.realtime.subscribe({
port: 300,
event: "BALANCE_CHANGED",
filter: `accountId = "${accountId}"`,
callback: (data) => {
callback({
accountId: data.accountId,
newBalance: data.balance,
change: data.change,
timestamp: data.timestamp
});
}
});
this.subscriptions.push(subscription);
return subscription.id;
}
// Subscribe to transaction alerts
subscribeToTransactionAlerts(threshold, callback) {
const subscription = this.realtime.subscribe({
port: 300,
event: "TRANSACTION_CREATED",
filter: `amount > ${threshold}`,
callback: (data) => {
callback({
transactionId: data.id,
amount: data.amount,
type: data.type,
timestamp: data.timestamp
});
}
});
this.subscriptions.push(subscription);
return subscription.id;
}
// Clean up subscriptions
cleanup() {
this.subscriptions.forEach(sub => {
this.realtime.unsubscribe(sub.id);
});
this.subscriptions = [];
this.dragonfire.disconnect();
}
}
// Usage example
async function setupFinancialApp() {
const financialService = new FinancialAppService();
await financialService.initialize(userToken);
// Get account data
const balances = await financialService.getAccountBalances();
const transactions = await financialService.getRecentTransactions();
// Update UI with data
updateBalancesUI(balances);
updateTransactionsUI(transactions);
// Setup real-time updates
financialService.subscribeToBalanceUpdates("primary-account", (update) => {
// Update balance display in real-time
updateBalanceDisplay(update.accountId, update.newBalance);
showBalanceChangeNotification(update.change);
});
// Setup large transaction alerts
financialService.subscribeToTransactionAlerts(1000, (alert) => {
showLargeTransactionAlert(alert);
});
// Clean up on page unload
window.addEventListener('beforeunload', () => {
financialService.cleanup();
});
}
AI System Integration
This example demonstrates using DragonFire's knowledge operations for AI integration:
// AI system integration
import { DragonFireClient } from '@dragonfire/client';
import { VectorUtils } from '@dragonfire/vector';
class AIAssistantService {
constructor() {
this.dragonfire = new DragonFireClient({
endpoint: 'api.dragonfire1.com',
region: 'us-east',
timeSync: true
});
this.vectorUtils = new VectorUtils();
}
async initialize(apiKey) {
try {
this.dragonfire.setApiKey(apiKey);
await this.dragonfire.initialize();
console.log('AI Assistant service initialized');
return true;
} catch (error) {
console.error('Initialization error:', error);
return false;
}
}
// Convert text to embedding vector
async textToVector(text) {
return this.dragonfire.execute(`
COMPUTE(500)
.EMBEDDING("${text}")
.MODEL("semantic-v2")
.DIMENSIONS(1536)
`);
}
// Find similar content
async findSimilarContent(queryVector, collectionName, limit = 5) {
return this.dragonfire.execute(`
SEARCH(500)
.COLLECTION("${collectionName}")
.VECTOR(${JSON.stringify(queryVector)})
.LIMIT(${limit})
.THRESHOLD(0.75)
`);
}
// Generate response
async generateResponse(prompt, context = [], options = {}) {
const defaultOptions = {
maxTokens: 500,
temperature: 0.7,
topP: 0.95
};
const mergedOptions = { ...defaultOptions, ...options };
return this.dragonfire.execute(`
GENERATE(500)
.TEXT()
.FROM("${prompt}")
.WITH_CONTEXT(${JSON.stringify(context)})
.MAX_TOKENS(${mergedOptions.maxTokens})
.TEMPERATURE(${mergedOptions.temperature})
.TOP_P(${mergedOptions.topP})
`);
}
// Store knowledge
async storeKnowledge(collection, documents) {
// Process documents in batches
const batches = this.vectorUtils.batchDocuments(documents, 10);
for (const batch of batches) {
await this.dragonfire.execute(`
STORE(500)
.COLLECTION("${collection}")
.DOCUMENTS(${JSON.stringify(batch)})
.WITH_EMBEDDINGS(true)
`);
}
return { success: true, count: documents.length };
}
// Process conversation
async processConversation(userMessage, conversationHistory) {
try {
// Convert message to vector for semantic search
const messageVector = await this.textToVector(userMessage);
// Find relevant information
const relevantInfo = await this.findSimilarContent(
messageVector,
"knowledge-base"
);
// Prepare context for generation
const context = relevantInfo.map(item => item.content);
// Generate response
const response = await this.generateResponse(
userMessage,
context,
{ temperature: 0.8 }
);
return {
response: response.text,
sources: relevantInfo.map(item => item.metadata),
confidence: response.confidence
};
} catch (error) {
console.error('Error processing conversation:', error);
throw error;
}
}
}
// Usage example
async function setupAIAssistant() {
const assistant = new AIAssistantService();
await assistant.initialize(API_KEY);
// Handle user message
document.getElementById('send-button').addEventListener('click', async () => {
const userMessage = document.getElementById('user-input').value;
const conversationHistory = getConversationHistory();
// Display user message
addMessageToChat('user', userMessage);
// Show typing indicator
showTypingIndicator();
try {
// Process with AI
const result = await assistant.processConversation(
userMessage,
conversationHistory
);
// Hide typing indicator
hideTypingIndicator();
// Display assistant response
addMessageToChat('assistant', result.response);
// Add sources if available
if (result.sources && result.sources.length > 0) {
displaySources(result.sources);
}
} catch (error) {
hideTypingIndicator();
addMessageToChat('system', 'Sorry, I encountered an error processing your request.');
}
});
}
IoT Integration
This example demonstrates integrating DragonFire with IoT devices:
// IoT integration example - Node.js
const { DragonFireIoTClient } = require('@dragonfire/iot-client');
const { SensorDataCollector } = require('./sensors');
// Create IoT-optimized client
const dragonfire = new DragonFireIoTClient({
endpoint: 'iot.dragonfire1.com',
region: 'us-east',
deviceId: process.env.DEVICE_ID,
deviceKey: process.env.DEVICE_KEY,
connectionOptions: {
// Optimized for low-bandwidth, intermittent connections
compressionLevel: 'maximum',
batchSize: 50,
maxRetries: 10,
retryInterval: 5000
}
});
// Initialize sensor collection
const sensorCollector = new SensorDataCollector({
temperature: true,
humidity: true,
motion: true,
light: true,
sampleRate: 60000 // 1 minute
});
// Setup connection with backoff retry
async function connectWithRetry(maxAttempts = 10) {
let attempts = 0;
while (attempts < maxAttempts) {
try {
console.log(`Connection attempt ${attempts + 1}...`);
await dragonfire.connect();
console.log('Connected to DragonFire IoT service');
return true;
} catch (error) {
attempts++;
const delay = Math.min(30000, Math.pow(2, attempts) * 1000);
console.log(`Connection failed, retrying in ${delay / 1000}s...`);
await new Promise(resolve => setTimeout(resolve, delay));
}
}
console.error('Failed to connect after maximum attempts');
return false;
}
// Initialize the system
async function initialize() {
try {
// Connect to DragonFire
const connected = await connectWithRetry();
if (!connected) {
console.error('Unable to establish connection. Running in offline mode.');
}
// Start sensor collection
sensorCollector.start();
// Register for device commands
dragonfire.on('command', handleDeviceCommand);
// Set up data transmission
setInterval(transmitSensorData, 60000);
// Report device status
await reportDeviceStatus('online');
} catch (error) {
console.error('Initialization error:', error);
}
}
// Transmit collected sensor data
async function transmitSensorData() {
try {
const sensorData = sensorCollector.getCollectedData();
if (sensorData.length === 0) {
return;
}
// Use the Storage port (400-499) for IoT data
await dragonfire.execute(`
STORE(400)
.DATA("sensors")
.BATCH(${JSON.stringify(sensorData)})
.WITH_TIMESTAMP(true)
.DEVICE_ID("${process.env.DEVICE_ID}")
`);
// Clear transmitted data
sensorCollector.clearCollectedData();
console.log(`Transmitted ${sensorData.length} sensor readings`);
} catch (error) {
console.error('Error transmitting sensor data:', error);
// Store data locally if transmission fails
sensorCollector.storeLocally();
}
}
// Handle device commands from DragonFire
function handleDeviceCommand(command) {
console.log('Received command:', command);
switch (command.action) {
case 'restart':
console.log('Restarting device...');
setTimeout(() => process.exit(0), 1000);
break;
case 'configure':
console.log('Updating configuration...');
updateDeviceConfiguration(command.config);
break;
case 'update_sampling':
console.log('Updating sampling rate...');
sensorCollector.updateSampleRate(command.rate);
break;
default:
console.log('Unknown command:', command);
}
}
// Report device status
async function reportDeviceStatus(status) {
try {
await dragonfire.execute(`
UPDATE(400)
.DEVICE("${process.env.DEVICE_ID}")
.STATUS("${status}")
.WITH({
battery: ${sensorCollector.getBatteryLevel()},
firmware: "${process.env.FIRMWARE_VERSION}",
uptime: ${process.uptime()}
})
`);
} catch (error) {
console.error('Error reporting device status:', error);
}
}
// Start the system
initialize();