FiberWise Node.js SDK (v1.0.0)
Complete Node.js and browser SDK for the FiberWise Platform.
Installation
The Node.js SDK is included with your Fiberwise installation. Reference it locally in your apps:
# Navigate to the SDK directory
cd fiber-sdk-nodejs
# Install dependencies
npm install
💡 Requirements
- Node.js 14+ or modern browser
- ES6 support
Quick Start
Basic Setup (JavaScript/ES Modules)
import FiberWise from 'fiberwise';
// Initialize with configuration
const fiber = new Fiberwise({
baseUrl: 'https://api.fiberwise.ai/api/v1',
apiKey: 'your-api-key',
appId: 'your-app-id'
});
// Example usage
async function main() {
try {
// List data items
const users = await fiber.data.listItems('users');
console.log('Users:', users);
// Run a function
const result = await fiber.functions.activate('processData', { param: 'value' });
// Real-time communication
fiber.realtime.on('message', (msg) => {
console.log('Received message:', msg);
});
await fiber.realtime.connect();
} catch (error) {
console.error('Realtime connection error:', error);
throw error; // Re-throw to allow caller to handle
}
}
main();
Basic Setup (CommonJS)
const FiberWise = require('fiberwise');
// Initialize with configuration
const fiber = new Fiberwise({
baseUrl: 'https://api.fiberwise.ai/api/v1',
apiKey: process.env.FIBERWISE_API_KEY,
appId: process.env.FIBERWISE_APP_ID
});
// Example usage
async function main() {
try {
// Get app details
const app = await fiber.apps.getDetails();
console.log('App:', app.name);
// Stream agent responses
const controller = await fiber.agents.activateStreaming(
'chat-agent',
{ message: 'Hello' },
{},
{},
{
onMessage: (chunk) => console.log('Stream chunk:', chunk),
onComplete: (result) => console.log('Stream completed:', result),
onError: (error) => console.error('Stream error:', error)
}
);
// Close stream when done
setTimeout(() => {
try {
controller.close();
} catch (closeError) {
console.error('Error closing stream:', closeError);
}
}, 5000);
} catch (error) {
console.error('Agent activation error:', error);
throw error;
}
}
main();
Core Components
1. FiberApp - Main SDK Entry Point
import { FiberApp, FiberConfig } from '@fiberwise/sdk';
interface FiberConfig {
baseUrl: string;
apiKey: string;
appId?: string;
agentApiKey?: string;
sessionId?: string;
useLocal?: boolean;
}
// Production configuration
const productionConfig: FiberConfig = {
baseUrl: 'https://api.fiberwise.ai/api/v1',
apiKey: 'fw_1234567890abcdef1234567890abcdef',
appId: 'my-node-app',
sessionId: 'session_abc123'
};
// Development configuration
const devConfig: FiberConfig = {
appId: 'my-dev-app',
useLocal: true
};
const fiber = new FiberApp(productionConfig);
// Access services
const agents = fiber.agents; // 🤖 Agent management
const data = fiber.data; // 📊 Dynamic data storage
const storage = fiber.storage; // 📁 File storage
const realtime = fiber.realtime; // ⚡ Real-time messaging
const oauth = fiber.oauth; // 🔐 OAuth management
2. Agent Management
// List and filter agents
const agents = await fiber.agents.list({
page: 1,
pageSize: 25,
orderBy: 'created',
orderDirection: 'DESC',
activeOnly: true
});
// Get specific agent
const agent = await fiber.agents.get('agent-123');
console.log(`Agent: ${agent.name} (${agent.agentType})`);
// Create new agent
const newAgent = await fiber.agents.create({
name: 'Content Analyzer',
description: 'Analyzes content for key insights',
systemPrompt: 'You are a content analysis expert.',
model: 'gpt-4',
temperature: 0.7,
maxTokens: 1000,
tools: [
{
type: 'function',
function: {
name: 'analyze_sentiment',
description: 'Analyze text sentiment',
parameters: {
type: 'object',
properties: {
text: { type: 'string' }
}
}
}
}
]
});
// Activate agent
const result = await fiber.agents.activate(newAgent.id, {
text: 'This is amazing technology!',
analysis_type: 'comprehensive'
});
console.log('Analysis result:', result.output);
3. Streaming Responses
// Stream agent responses with callbacks
const stream = await fiber.agents.activateStreaming(
'agent-123',
{ prompt: 'Write a story about AI' },
{
onMessage: (chunk) => {
try {
process.stdout.write(chunk);
} catch (writeError) {
console.error('Error writing chunk:', writeError);
}
},
onComplete: (result) => {
console.log('\nStream completed successfully:', result);
},
onError: (error) => {
console.error('Stream encountered an error:', error);
throw error; // Re-throw to propagate
}
}
);
// Alternative: async iterator approach
for await (const chunk of stream) {
process.stdout.write(chunk);
}
4. Dynamic Data Operations
// Key-value operations
fiber.data.set('userPreferences', {
theme: 'dark',
language: 'en',
notifications: true
});
const preferences = fiber.data.get('userPreferences');
const theme = fiber.data.get('theme', 'light'); // with default
// Structured data models
const userInteraction = await fiber.data.create('user_interactions', {
userId: 'user-12345',
action: 'chat_message',
content: 'Hello, AI assistant!',
timestamp: new Date().toISOString(),
metadata: {
sessionId: 'session-789',
source: 'web_app'
}
});
// Query data
const recentInteractions = await fiber.data.query('user_interactions', {
filters: {
userId: 'user-12345',
action: 'chat_message'
},
orderBy: 'timestamp',
orderDirection: 'DESC',
limit: 10
});
5. File Storage
import fs from 'fs';
// Upload file
const fileBuffer = fs.readFileSync('document.pdf');
const fileUrl = await fiber.storage.upload({
file: fileBuffer,
filename: 'document.pdf',
contentType: 'application/pdf',
metadata: { category: 'docs', userId: 'user-123' }
});
// Store data as file
await fiber.storage.store('report_2024', {
results: [1, 2, 3],
summary: 'Analysis complete'
}, { type: 'json_report' });
// Retrieve files
const fileData = await fiber.storage.retrieve('report_2024');
const downloadUrl = await fiber.storage.getUrl('document.pdf');
// List files
const files = await fiber.storage.list({
prefix: 'reports/',
limit: 20
});
Browser Testing Integration
Node.js Testing with Playwright
import { test, expect } from '@playwright/test';
import FiberWise from 'fiberwise';
// Integration test combining browser automation and SDK
test('complete agent workflow test', async ({ page }) => {
// Initialize SDK
const fiber = new Fiberwise({
baseUrl: 'http://localhost:6701',
apiKey: 'test-api-key'
});
try {
// Step 1: Create test agent via SDK
const agent = await fiber.agents.create({
name: 'Test Chat Agent',
description: 'Agent for browser testing',
systemPrompt: 'You are a helpful test assistant.',
model: 'gpt-3.5-turbo'
});
// Step 2: Test agent creation in browser
await page.goto('http://localhost:6701/agents');
// Verify agent appears in UI
await expect(page.locator(`text=${agent.name}`)).toBeVisible();
// Step 3: Test agent activation through UI
await page.click(`[data-agent-id="${agent.id}"]`);
await page.fill('#message-input', 'Hello, test agent!');
await page.click('#send-button');
// Step 4: Verify response
await expect(page.locator('.agent-response')).toBeVisible();
// Step 5: Validate via SDK
const activationResult = await fiber.agents.activate(agent.id, {
message: 'SDK validation test'
});
expect(activationResult.status).toBe('success');
} catch (error) {
console.error('Test failed:', error);
throw error;
} finally {
// Clean up resources if needed
try {
if (fiber.realtime && fiber.realtime.isConnected) {
await fiber.realtime.disconnect();
}
} catch (cleanupError) {
console.error('Cleanup error:', cleanupError);
}
}
});
Automated Testing Workflow
// automated-test-runner.ts
import { spawn } from 'child_process';
import FiberWise from 'fiberwise';
import fs from 'fs/promises';
/**
* @typedef {Object} TestScript
* @property {string} script_name
* @property {string} description
* @property {Object} settings
* @property {boolean} settings.headless
* @property {number} settings.slow_motion
* @property {boolean} settings.video_recording
* @property {Array