Integration GuideBuild on ML Bridge
Complete guide for integrating with the ML Bridge platform and building decentralized ML applications.
REST API
Smart Contracts
SDKs
Integration Types
Multiple integration paths for different use cases.
💻
REST API
Simple HTTP API for basic operations like task submission and result retrieval.
🧪
Smart Contracts
Direct blockchain integration for advanced features and custom logic.
âš¡
SDKs
Language-specific libraries for JavaScript, Python, and Go developers.
Quick Start
Get up and running in three simple steps.
1Get API Credentials
curl -X POST https://api.mlbridge.net/auth/register \
-H "Content-Type: application/json" \
-d '{"email": "dev@example.com"}'2Install SDK
# JavaScript/TypeScript npm install @mlbridge/sdk # Python pip install mlbridge-sdk # Go go get github.com/mlbridge/go-sdk
3Submit Your First Task
import { MLBridge } from '@mlbridge/sdk';
const client = new MLBridge({
apiKey: 'your-api-key',
network: 'testnet'
});
const task = await client.tasks.create({
modelId: 'gpt-3.5-turbo',
input: { prompt: 'Hello, world!' }
});JavaScript/TypeScript SDK
Task Management
// Create a task
const task = await client.tasks.create({
modelId: 'model_123',
input: { text: 'Analyze this sentiment' },
computeRequirements: {
gpuMemory: '8GB',
maxExecutionTime: 300
}
});
// Wait for completion
const result = await client.tasks
.waitForCompletion(task.id);
// Cancel a task
await client.tasks.cancel(task.id);Model Operations
// List available models
const models = await client.models.list({
category: 'nlp',
verified: true
});
// Register a new model
const newModel = await client.models.register({
name: 'My Custom Model',
description: 'A fine-tuned model',
category: 'nlp',
modelFile: './model.bin',
metadata: {
framework: 'pytorch',
version: '1.0.0'
}
});Python SDK
Async/Await Support
import asyncio
from mlbridge import AsyncMLBridge
async def main():
client = AsyncMLBridge(api_key='your-key')
# Create task
task = await client.tasks.create({
'model_id': 'model_123',
'input': {'text': 'Hello world'}
})
# Wait for result
result = await client.tasks
.wait_for_completion(task['id'])
print(f"Result: {result['output']}")
asyncio.run(main())Batch Processing
# Submit multiple tasks
tasks = client.tasks.create_batch([
{'model_id': 'model_123',
'input': {'text': 'Text 1'}},
{'model_id': 'model_123',
'input': {'text': 'Text 2'}},
{'model_id': 'model_123',
'input': {'text': 'Text 3'}}
])
# Wait for all to complete
results = client.tasks.wait_for_batch(
[task['id'] for task in tasks],
timeout=600
)
for result in results:
print(result['output'])Smart Contract Integration
Contract Addresses
TaskManager
TBD
ModelRegistry
TBD
Governance
TBD
Staking
TBD
Web3 Integration
import { ethers } from 'ethers';
import TaskManagerABI from './abis/TaskManager.json';
const provider = new ethers.providers.Web3Provider(
window.ethereum
);
const signer = provider.getSigner();
const taskManager = new ethers.Contract(
'0x1234...5678',
TaskManagerABI,
signer
);
// Submit a task
const tx = await taskManager.createTask(
'model_123',
ethers.utils.formatBytes32String('input'),
ethers.utils.parseEther('0.01')
);
await tx.wait();Event Listening
// Listen for task completion
taskManager.on('TaskCompleted',
(taskId, result, cost) => {
console.log(`Task ${taskId} completed`);
console.log(`Result: ${result}`);
console.log(`Cost: ${ethers.utils
.formatEther(cost)} ETH`);
});
// Listen for new model registrations
modelRegistry.on('ModelRegistered',
(modelId, owner, metadata) => {
console.log(`New model: ${modelId}`);
console.log(`Owner: ${owner}`);
});Webhook Integration
Register Webhook
const webhook = await client.webhooks.create({
url: 'https://your-app.com/webhooks',
events: [
'task.completed',
'task.failed'
],
secret: 'your-webhook-secret'
});
console.log('Webhook ID:', webhook.id);Webhook Handler
// Express.js handler
app.post('/webhooks', (req, res) => {
const sig = req.headers['x-mlbridge-signature'];
if (!verifySignature(req.body, sig, secret)) {
return res.status(401).send('Invalid');
}
const event = req.body;
switch (event.event) {
case 'task.completed':
handleCompletion(event.data);
break;
case 'task.failed':
handleFailure(event.data);
break;
}
res.status(200).send('OK');
});Best Practices
Performance
- • Use connection pooling
- • Implement caching
- • Batch tasks when possible
- • Use webhooks over polling
Security
- • Store keys securely
- • Validate webhook signatures
- • Use HTTPS everywhere
- • Validate all inputs
Reliability
- • Implement retry logic
- • Handle timeouts gracefully
- • Monitor API usage
- • Log errors properly
Cost Optimization
- • Set cost limits
- • Choose optimal compute
- • Monitor spending
- • Use model caching
Error Handling Pattern
try {
const task = await client.tasks.create(taskData);
const result = await client.tasks.waitForCompletion(task.id);
return result;
} catch (error) {
if (error.code === 'INSUFFICIENT_BALANCE') {
throw new Error('Please add funds to your account');
} else if (error.code === 'MODEL_NOT_FOUND') {
throw new Error('The specified model does not exist');
} else if (error.code === 'RATE_LIMIT_EXCEEDED') {
await new Promise(resolve => setTimeout(resolve, 60000));
return retryOperation();
} else {
console.error('Unexpected error:', error);
throw error;
}
}Resources & Support
Documentation
- API Reference
- SDK Documentation
- Smart Contract ABIs
- Example Applications
Community
- Discord Developer Channel
- GitHub Discussions
- Stack Overflow Tag
- Developer Newsletter
Support
- Technical Support Email
- Bug Reports
- Feature Requests
- Priority Support (Enterprise)