Integration GuideBuild on ML Bridge
Complete guide for integrating with the ML Bridge platform and building decentralized ML applications.
Integration Types
Multiple integration paths for different use cases.
REST API (Planned)
HTTP API for basic operations (planned for future release).
Smart Contracts
Direct blockchain integration for advanced features and custom logic.
SDKs (Planned)
Language-specific libraries planned for JavaScript, Python, and Go.
Quick Start
Get up and running in three simple steps.
import { ConnectButton } from '@rainbow-me/rainbowkit';
import { useAccount } from 'wagmi';
// In your component
const { address, isConnected } = useAccount();
// RainbowKit provides the connect button
<ConnectButton />import { createPublicClient, http } from 'viem';
import { baseSepolia } from 'viem/chains';
const client = createPublicClient({
chain: baseSepolia,
transport: http(),
});
const model = await client.readContract({
address: '0xC383...cCb',
abi: modelRegistryAbi,
functionName: 'getModel',
args: [modelId],
});import { useWriteContract } from 'wagmi';
const { writeContract } = useWriteContract();
await writeContract({
address: '0xE54f...FF7A',
abi: taskManagerAbi,
functionName: 'createTask',
args: [modelId, inputCid, reward],
value: reward,
});JavaScript/TypeScript SDK
SDK packages are planned for future release. Currently, interact with ML Bridge via smart contracts using viem/wagmi.
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 (using IPFS CID)
const newModel = await client.models.register({
name: 'My Custom Model',
description: 'A fine-tuned model',
category: 'nlp',
ipfsCid: 'QmYwAPJzv5CZsnAzt8auVTLMk3NJT...',
metadata: {
framework: 'pytorch',
version: '1.0.0'
}
});Python SDK
SDK packages are planned for future release. Currently, interact with ML Bridge via smart contracts using viem/wagmi.
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 (Base Sepolia)
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
Webhook integration is planned for future release. Currently, interact with ML Bridge via smart contracts using viem/wagmi.
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)