duckmesh-sdk
v1.1.4
Published
Decentralized AI inference network
Downloads
43
Readme
DuckMesh SDK
Decentralized AI Inference Marketplace
DuckMesh SDK provides a simple interface to interact with the DuckMesh decentralized AI inference network. Submit AI tasks, pay with DUCK tokens, and get verified results from a distributed network of compute providers.
Features
- 🤖 AI Inference: Submit prompts to various AI models (GPT, Claude, Llama, etc.)
- 🔒 Trustless: Cryptographically verified results with multiple verification modes
- 💰 Tokenized: Pay-per-use model with DUCK token integration
- ⚡ Fast: Optimized for low-latency AI inference
- 🛡️ Reliable: Built-in dispute resolution and redundancy
- 🌐 Decentralized: No single point of failure
Installation
npm install duckmesh-sdkyarn add duckmesh-sdkQuick Start
import { DuckMeshClient, JobSpec, VerificationMode } from 'duckmesh-sdk';
// Initialize client
const client = new DuckMeshClient(
'https://rpc.duckchain.io/', // Duckchai Mainnet RPC URL
'YOUR_PRIVATE_KEY', // Wallet private key
'0x...', // JobMarket contract address
'0x...', // DuckToken contract address
'https://uectchxh90.execute-api.us-east-1.amazonaws.com/prod' // Coordinator service URL
);
// Define your AI task
const jobSpec: JobSpec = {
prompt: "Write a haiku about blockchain technology",
maxTokens: 100,
temperature: 0.7
};
async function runInference() {
try {
// Submit job
const jobId = await client.submitJob(
'gpt-4', // Model ID
jobSpec,
1000, // Max price in DUCK tokens
VerificationMode.Redundant // Verification method
);
console.log(`Job submitted: ${jobId}`);
// Wait for result
const result = await client.waitForResult(jobId);
console.log('AI Response:', result.output);
} catch (error) {
console.error('Error:', error);
}
}
runInference();API Reference
DuckMeshClient
Constructor
new DuckMeshClient(
rpcUrl: string,
privateKey: string,
jobMarketAddress: string,
duckTokenAddress: string,
coordinatorUrl: string
)Parameters:
rpcUrl: Ethereum JSON-RPC endpoint URLprivateKey: Your wallet's private key (keep secure!)jobMarketAddress: Deployed JobMarket contract addressduckTokenAddress: DUCK token contract addresscoordinatorUrl: DuckMesh coordinator service URL
Methods
submitJob(modelId, jobSpec, maxPrice, verificationMode?, timeout?)
Submit an AI inference job to the network.
const jobId = await client.submitJob(
'gpt-3.5-turbo',
{
prompt: "Explain quantum computing",
maxTokens: 200,
temperature: 0.5
},
500, // Max 500 DUCK tokens
VerificationMode.ReferenceCheck,
3600 // 1 hour timeout
);Returns: Promise<number> - Unique job ID
waitForResult(jobId, pollInterval?)
Wait for job completion and retrieve results.
const result = await client.waitForResult(jobId, 5000); // Poll every 5 secondsReturns: Promise<InferenceResult>
getJobStatus(jobId)
Check current status of a submitted job.
const status = await client.getJobStatus(123);
console.log(status.status); // JobStatus enumReturns: Promise<JobStatusResponse>
disputeJob(jobId, reason)
Dispute a job result if unsatisfactory.
await client.disputeJob(123, "Result does not match prompt requirements");getBalance()
Get your current DUCK token balance.
const balance = await client.getBalance();
console.log(`Balance: ${balance} DUCK`);Returns: Promise<number>
Types
JobSpec
interface JobSpec {
prompt: string; // The AI prompt/input
maxTokens: number; // Maximum tokens to generate
temperature: number; // Creativity level (0-1)
modelParameters?: Record<string, any>; // Additional model-specific params
}InferenceResult
interface InferenceResult {
output: string; // AI-generated response
metadata: {
tokensUsed: number; // Actual tokens consumed
executionTime: number; // Processing time (ms)
modelVersion: string; // Model version used
};
signature: string; // Cryptographic proof
}VerificationMode
enum VerificationMode {
Redundant = 0, // Multiple providers, consensus required
ReferenceCheck = 1, // Compare against reference implementation
Attestation = 2, // Provider attestation with reputation
ZkML = 3 // Zero-knowledge machine learning proof
}JobStatus
enum JobStatus {
Pending = 0, // Waiting for provider
Assigned = 1, // Provider assigned
Completed = 2, // Result submitted
Disputed = 3, // Under dispute
Finalized = 4 // Payment processed
}Supported Models
- OpenAI:
gpt-4,gpt-3.5-turbo,text-davinci-003 - Anthropic:
claude-3-opus,claude-3-sonnet - Meta:
llama-2-70b,llama-2-13b,llama-2-7b - Google:
gemini-pro,palm-2 - Mistral:
mistral-7b,mistral-8x7b
Model availability depends on network providers
Network Configuration
Mainnet
const client = new DuckMeshClient(
'https://rpc.duckchain.io/',
process.env.PRIVATE_KEY,
'0x1234...', // JobMarket mainnet address
'0x5678...', // DUCK token mainnet address
'https://uectchxh90.execute-api.us-east-1.amazonaws.com/prod'
);Testnet
const client = new DuckMeshClient(
'https://testnet.rpc.duckchain.io/',
process.env.PRIVATE_KEY,
'0xabcd...', // JobMarket testnet address
'0xefgh...', // DUCK token testnet address
'https://uectchxh90.execute-api.us-east-1.amazonaws.com/prod'
);Examples
Text Generation
const response = await client.submitJob('gpt-3.5-turbo', {
prompt: "Write a product description for a smart water bottle",
maxTokens: 150,
temperature: 0.8
}, 300);Code Generation
const response = await client.submitJob('gpt-4', {
prompt: "Write a Python function to calculate fibonacci numbers",
maxTokens: 200,
temperature: 0.2,
modelParameters: {
stop: ["```"]
}
}, 500);Creative Writing
const response = await client.submitJob('claude-3-opus', {
prompt: "Write a short story about AI and humanity",
maxTokens: 800,
temperature: 0.9
}, 1200);Error Handling
try {
const jobId = await client.submitJob(modelId, jobSpec, maxPrice);
const result = await client.waitForResult(jobId);
} catch (error) {
if (error.message.includes('insufficient balance')) {
console.error('Not enough DUCK tokens');
} else if (error.message.includes('timeout')) {
console.error('Job timed out');
} else {
console.error('Unexpected error:', error);
}
}Security Best Practices
- Private Key Management: Never hardcode private keys. Use environment variables or secure key management.
// ✅ Good
const client = new DuckMeshClient(
process.env.RPC_URL,
process.env.PRIVATE_KEY,
// ...
);
// ❌ Bad
const client = new DuckMeshClient(
'https://...',
'0x1234567890abcdef..', // Don't do this!
// ...
);- Input Validation: Validate prompts and parameters before submission
- Error Handling: Always implement proper error handling
- Rate Limiting: Implement client-side rate limiting for production apps
Development
Prerequisites
- Node.js 16+
- TypeScript 4.5+
- Ethereum wallet with DUCK tokens
Building from Source
git clone https://github.com/Monday436326/duckmesh/sdk
cd sdk
npm install
npm run buildRunning Tests
npm testContributing
We welcome contributions! Please see our Contributing Guide for details.
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Changelog
See CHANGELOG.md for version history.
Built with 🦆 by the DuckMesh Team
