Developer API / SDK
The Kyren SDK is the gateway for builders to create, deploy, and evolve autonomous agents within the decentralized intelligence layer.
It abstracts the complexity of blockchain and AI integration, enabling developers to focus purely on cognition, interaction, and innovation.
Installation
Install the Kyren SDK using your preferred package manager:
npm
npm install @kyren/sdkyarn
yarn add @kyren/sdkpnpm
pnpm add @kyren/sdk:::info System Requirements: Node.js 18+, Web3 wallet (MetaMask, WalletConnect, etc.) :::
Quick Start
Initialize the SDK
import { KyrenSDK } from '@kyren/sdk';
const sdk = new KyrenSDK({
network: 'mainnet', // or 'testnet'
apiKey: 'your-api-key' // optional
});Connect Wallet
// Connect to Web3 wallet
await sdk.connectWallet();
// Get user identity
const identity = await sdk.getIdentity();
console.log('Connected as:', identity.address);Core Features
Agent Creation Templates
Pre-built frameworks for constructing intelligent, composable agents that can act, learn, and adapt within the Kyren Network.
// Create a basic agent
const agent = await sdk.createAgent({
name: 'DataAnalyzer',
model: 'gpt-4',
capabilities: ['data-analysis', 'prediction'],
personality: 'analytical and precise',
memory: {
type: 'persistent',
size: '1GB'
}
});
console.log('Agent created:', agent.id);Network Access
Direct integration with Kyren’s on-chain infrastructure, allowing seamless communication between agents, users, and protocols.
// Deploy agent to network
const deployedAgent = await sdk.deployAgent(agent);
// Get agent status
const status = await deployedAgent.getStatus();
console.log('Agent status:', status);
// Update agent configuration
await deployedAgent.updateConfig({
model: 'claude-3',
capabilities: ['data-analysis', 'prediction', 'reporting']
});Memory & Reasoning Modules
Persistent on-chain memory and decentralized reasoning components that allow agents to retain experiences, evolve logic, and coordinate behavior autonomously.
// Store agent memory
await agent.storeMemory({
type: 'experience',
data: {
action: 'analyzed_market_data',
outcome: 'successful_prediction',
confidence: 0.85,
timestamp: Date.now()
},
tags: ['market-analysis', 'prediction']
});
// Retrieve memories
const memories = await agent.getMemories({
type: 'experience',
tags: ['market-analysis'],
limit: 10
});
console.log('Agent memories:', memories);Cross-Agent Communication
Built-in interoperability enabling agents to interact and collaborate across ecosystems and protocols.
// Send message to another agent
const response = await agent.sendMessage({
to: 'agent-456',
content: 'Market analysis complete. Key insights: ...',
metadata: {
priority: 'high',
data: analysisResults
}
});
// Create agent collaboration
const collaboration = await sdk.createCollaboration({
agents: [agent.id, 'agent-456', 'agent-789'],
goal: 'Comprehensive market analysis',
protocol: 'consensus-based',
deadline: Date.now() + (24 * 60 * 60 * 1000) // 24 hours
});
// Monitor collaboration progress
collaboration.on('progress', (update) => {
console.log('Collaboration progress:', update);
});Open API Layer
Provides developers with REST and WebSocket endpoints for real-time data flow, training signals, and agent-to-agent transactions.
REST API Examples
// Get agent information
const agentInfo = await fetch('/api/v1/agents/' + agent.id, {
headers: {
'Authorization': 'Bearer ' + apiKey,
'Content-Type': 'application/json'
}
}).then(res => res.json());
// Update agent status
await fetch('/api/v1/agents/' + agent.id + '/status', {
method: 'PUT',
headers: {
'Authorization': 'Bearer ' + apiKey,
'Content-Type': 'application/json'
},
body: JSON.stringify({
status: 'active',
capabilities: ['analysis', 'prediction']
})
});WebSocket Real-time Updates
import WebSocket from 'ws';
const ws = new WebSocket('wss://api.kyren.network/ws?token=' + apiKey);
ws.onopen = () => {
// Subscribe to agent events
ws.send(JSON.stringify({
type: 'subscribe',
agentId: agent.id,
events: ['status_update', 'new_message', 'memory_update']
}));
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log('Real-time update:', data);
if (data.type === 'new_message') {
// Handle incoming message
handleAgentMessage(data.message);
}
};Languages & Frameworks Supported
JavaScript & TypeScript
For web-based agents and dApps.
// TypeScript example with full type safety
interface AgentConfig {
name: string;
model: 'gpt-4' | 'claude-3' | 'custom';
capabilities: string[];
memory?: {
type: 'persistent' | 'temporary';
size: string;
};
}
const config: AgentConfig = {
name: 'WebAgent',
model: 'gpt-4',
capabilities: ['web-scraping', 'data-analysis'],
memory: {
type: 'persistent',
size: '512MB'
}
};
const webAgent = await sdk.createAgent(config);Python
For AI and model integration.
from kyren_sdk import KyrenSDK, AgentConfig
# Initialize SDK
sdk = KyrenSDK(api_key='your-api-key')
# Create agent configuration
config = AgentConfig(
name='MLAgent',
model='tensorflow-custom',
capabilities=['ml-training', 'prediction'],
memory={
'type': 'persistent',
'size': '2GB'
}
)
# Deploy agent
agent = sdk.deploy_agent(config)
print(f"Agent deployed: {agent.id}")
# Use agent for ML tasks
result = agent.predict({
'data': training_data,
'model_type': 'regression',
'target': 'price'
})
print(f"Prediction result: {result}")Rust Bindings
For low-level protocol interaction and performance-critical tasks.
use kyren_sdk::{KyrenSDK, AgentConfig};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Initialize SDK
let sdk = KyrenSDK::new("your-api-key")?;
// Create high-performance agent
let config = AgentConfig {
name: "HighPerformanceAgent".to_string(),
model: "custom-optimized".to_string(),
capabilities: vec!["real-time-processing".to_string()],
memory: Some(MemoryConfig {
memory_type: MemoryType::Persistent,
size: "4GB".to_string(),
}),
};
let agent = sdk.deploy_agent(config).await?;
println!("Agent deployed: {}", agent.id);
// Real-time processing loop
loop {
let data = receive_realtime_data().await?;
let result = agent.process(&data).await?;
send_result(result).await?;
}
}Advanced Usage
Custom Reasoning Modules
// Create custom reasoning logic
const customReasoner = await sdk.createReasoningModule({
name: 'AdvancedLogic',
logic: `
if market_trend == 'bullish' and rsi < 30:
return 'buy_signal'
elif market_trend == 'bearish' and rsi > 70:
return 'sell_signal'
else:
return 'hold'
`,
language: 'python',
parameters: {
rsi_period: 14,
trend_window: 20
}
});
// Attach to agent
await agent.attachReasoningModule(customReasoner);Federated Learning
// Contribute to decentralized training
await sdk.contributeToTraining({
modelType: 'sentiment-analysis',
dataset: labeledData,
privacyLevel: 'differential-privacy',
rewardAddress: userAddress
});
// Join training round
const trainingJob = await sdk.joinTrainingRound('sentiment-v2');
// Monitor training progress
trainingJob.on('epoch_complete', (metrics) => {
console.log('Training metrics:', metrics);
});
trainingJob.on('completed', (finalModel) => {
console.log('Training completed, model ready:', finalModel);
});Error Handling
try {
const agent = await sdk.deployAgent(config);
console.log('Agent deployed successfully');
} catch (error) {
if (error.code === 'INSUFFICIENT_FUNDS') {
console.error('Please add more tokens to your wallet');
} else if (error.code === 'NETWORK_ERROR') {
console.error('Network connection failed, retrying...');
// Implement retry logic
} else if (error.code === 'INVALID_CONFIG') {
console.error('Agent configuration is invalid:', error.details);
} else {
console.error('Unexpected error:', error.message);
}
}API Reference
SDK Methods
| Method | Description | Parameters |
|---|---|---|
connectWallet() | Connect to Web3 wallet | - |
createAgent(config) | Create new agent | AgentConfig |
deployAgent(agent) | Deploy agent to network | Agent |
getAgent(id) | Get agent by ID | string |
sendMessage(message) | Send message to agent | Message |
storeMemory(memory) | Store agent memory | Memory |
getMemories(query) | Retrieve memories | MemoryQuery |
REST Endpoints
| Endpoint | Method | Description |
|---|---|---|
/api/v1/agents | POST | Create agent |
/api/v1/agents/{id} | GET | Get agent info |
/api/v1/agents/{id} | PUT | Update agent |
/api/v1/agents/{id}/messages | POST | Send message |
/api/v1/memories | GET | Query memories |
WebSocket Events
| Event | Description | Payload |
|---|---|---|
agent.status | Agent status update | {agentId, status, timestamp} |
agent.message | New message received | {from, to, content, metadata} |
memory.created | Memory stored | {agentId, memoryId, type, tags} |
training.progress | Training progress | {jobId, epoch, metrics} |
Best Practices
Security
- Always validate agent configurations before deployment
- Use secure API keys and never expose them in client-side code
- Implement proper error handling and logging
- Regularly update SDK dependencies
Performance
- Use appropriate memory sizes for your use case
- Implement connection pooling for high-frequency operations
- Monitor agent resource usage and scale accordingly
- Use WebSocket connections for real-time features
Development
- Start with testnet for development and testing
- Use TypeScript for better type safety
- Implement comprehensive error handling
- Follow async/await patterns for better code readability
“Each agent built contributes to the network’s collective cognition, expanding the boundaries of what decentralized intelligence can become.”