0rca Agent SDK
The 0rca Agent SDK (orca-network-sdk) is a production-ready Python framework for building Sovereign, Monetizable, and Orchestrated AI Agents. It transforms standard AI agents into independent economic actors on the blockchain, complete with their own smart contract vaults for payment management.
🚀 Overview
The SDK provides everything needed to build AI agents that can:
- Accept payments via the x402 protocol
- Manage earnings through on-chain Sovereign Vaults
- Communicate with other agents using A2A protocol
- Scale automatically on Kubernetes infrastructure
Every agent built with this SDK is paired with a Sovereign Vault - a dedicated smart contract that holds the agent's earnings and manages task escrows.
✨ Key Features
Sovereign Vault Architecture
- Dedicated Contracts: Each agent has its own
OrcaAgentVault.solsmart contract - Trustless Escrow: Funds locked until task completion with cryptographic proof
- Automatic Settlement: Agents claim payments upon successful task completion
- Transparent Earnings: All transactions verifiable on Cronos blockchain
x402 Payment Protocol
- HTTP-Based Gating: Standard "402 Payment Required" flow
- EIP-712 Signatures: Cryptographic payment authorization
- Micropayments: Support for sub-dollar USDC transactions
- Tool-Level Pricing: Individual pricing for specific agent capabilities
Multi-Backend Support
- CrewAI: Default backend for agent orchestration
- Agno: Integration with Agno agent runtime
- Crypto.com AI SDK: Native support for CDC AI agents
- Extensible: Plugin architecture for custom backends
Agent-to-Agent (A2A) Protocol
- Standardized Communication: Universal messaging between agents
- Task Delegation: Agents can hire other agents for sub-tasks
- Reputation System: On-chain reputation based on successful completions
- Discovery Service: Automatic agent discovery and capability matching
📦 Installation
pip install orca-network-sdk
🛠️ Quick Start
1. Basic Agent Setup
from orca_agent_sdk import OrcaAgent
# Initialize the Sovereign Agent
agent = OrcaAgent(
name="MySovereignAgent",
model="gpt-4",
system_prompt="You are a helpful assistant specialized in data analysis.",
# Financial Configuration
price="0.1", # 0.1 USDC per task
wallet_address="0xYourWallet...", # Where you withdraw earnings
# Identity & Vault
identity_wallet_path="agent_identity.json",
vault_address="0xYourVaultAddress..." # Optional - can use env AGENT_VAULT
)
# Start the Agent Server
if __name__ == "__main__":
agent.run(port=8000)
2. Advanced Configuration
from orca_agent_sdk import AgentConfig, AgentServer
# Detailed configuration
config = AgentConfig(
agent_id="advanced-agent",
price="0.25",
wallet_address="0x...",
# Tool-specific pricing
tool_prices={
"web_search": "0.05",
"data_analysis": "0.15",
"image_generation": "0.30"
},
# Network settings
chain_caip="eip155:338", # Cronos Testnet
token_address="0x38Bf87D7281A2F84c8ed5aF1410295f7BD4E20a1",
# Backend selection
ai_backend="crewai",
backend_options={
"model": "gpt-4",
"temperature": 0.7,
"max_tokens": 2000
}
)
# Custom handler function
def my_agent_handler(prompt: str) -> str:
# Your custom AI logic here
return f"Processed: {prompt}"
# Create and run server
server = AgentServer(config, my_agent_handler)
server.run(host="0.0.0.0", port=8000)
🏗️ Architecture
Core Components
orca_agent_sdk/
├── backends/
│ ├── base.py # Abstract backend interface
│ ├── crewai_backend.py # CrewAI integration
│ ├── agno_backend.py # Agno integration
│ └── crypto_com_backend.py # Crypto.com AI SDK
├── core/
│ ├── payment.py # x402 payment verification
│ ├── a2a.py # Agent-to-Agent protocol
│ ├── persistence.py # SQLite logging
│ └── wallet.py # Identity management
├── contracts/
│ ├── agent_vault.py # Sovereign Vault client
│ └── task_escrow.py # Task Escrow client
├── config.py # Configuration management
├── server.py # Flask server
└── agent.py # High-level OrcaAgent class
Payment Flow Architecture
sequenceDiagram
participant Client
participant Agent
participant Vault
participant Blockchain
Client->>Agent: POST /agent (prompt)
Agent-->>Client: 402 Payment Required + Challenge
Client->>Vault: createTask(taskId, amount)
Vault->>Blockchain: Lock USDC in escrow
Client->>Agent: POST /agent (prompt + signature)
Agent->>Agent: Verify signature & execute
Agent->>Vault: spend(taskId, amount)
Vault->>Blockchain: Release funds to agent
Agent-->>Client: Task result
💰 Sovereign Vault System
OrcaAgentVault Contract
The OrcaAgentVault is the financial heart of each agent:
contract OrcaAgentVault {
// Create a new task with locked funds
function createTask(bytes32 taskId, uint256 amount) external;
// Agent claims funds upon task completion
function spend(bytes32 taskId, uint256 amount) external;
// Owner withdraws accumulated earnings
function withdraw(address recipient, uint256 amount) external;
// View current balance and task status
function getBalance() external view returns (uint256);
function getTaskStatus(bytes32 taskId) external view returns (TaskStatus);
}
Task Lifecycle
# 1. Client creates task
task_id = "task_123"
amount = 100000 # 0.1 USDC (6 decimals)
vault.createTask(task_id, amount)
# 2. Agent processes and claims
result = agent.process_task(prompt)
if result.success:
vault.spend(task_id, amount) # Agent claims payment
# 3. Owner withdraws earnings
accumulated_balance = vault.getBalance()
vault.withdraw(owner_address, accumulated_balance)
🔧 Configuration Options
AgentConfig Parameters
@dataclass
class AgentConfig:
# Identity
agent_id: str # Unique agent identifier
wallet_address: str # Owner payout address
identity_wallet_path: str # Agent's private key file
# Pricing
price: str # Base price per task (USDC)
tool_prices: Dict[str, str] # Tool-specific pricing
token_address: str # Payment token contract
# Network
chain_caip: str # Blockchain identifier
facilitator_url: str # x402 facilitator endpoint
crogas_url: str # CroGas relayer for gasless txns
# Backend
ai_backend: Literal["crewai", "agno", "crypto_com"]
backend_options: Dict[str, Any] # Backend-specific config
# Storage
db_path: str # Local SQLite database
timeout_seconds: int # Request timeout
Environment Variables
# Required
AGENT_VAULT=0xe7bad567ed213efE7Dd1c31DF554461271356F30
CREATOR_WALLET_ADDRESS=0xYourWalletAddress
# Optional
CROGAS_URL=http://144.126.253.20
USDC_ADDRESS=0x38Bf87D7281A2F84c8ed5aF1410295f7BD4E20a1
MISTRAL_API_KEY=your_api_key
GEMINI_API_KEY=your_api_key
🤖 Backend Integration
CrewAI Backend (Default)
from orca_agent_sdk import OrcaAgent
from crewai import Agent, Task, Crew
# CrewAI integration
agent = OrcaAgent(
name="CrewAI Agent",
model="gpt-4",
system_prompt="You are a data analyst.",
ai_backend="crewai",
tools=[
# Your CrewAI tools here
]
)
Agno Backend
# Agno integration
config = AgentConfig(
agent_id="agno-agent",
ai_backend="agno",
backend_options={
"agno_config": {
"model": "gpt-4",
"plugins": ["web_search", "calculator"]
}
}
)
Crypto.com AI SDK
# CDC AI integration
config = AgentConfig(
agent_id="cdc-agent",
ai_backend="crypto_com",
cdc_api_key="your_cdc_key",
backend_options={
"model": "claude-3",
"tools": ["price_oracle", "trading_signals"]
}
)
🔗 Agent-to-Agent (A2A) Protocol
Message Format
from orca_agent_sdk.core.a2a import A2AMessage
# A2A message structure
message = A2AMessage(
header={
"message_id": "uuid-123",
"from": "agent-a",
"to": "agent-b",
"timestamp": 1640995200
},
task={
"action": "analyze_data",
"payload": {
"data": "...",
"format": "json"
}
}
)
Agent Communication
# Send message to another agent
async def delegate_task(self, target_agent: str, task_data: dict):
message = A2AMessage.create(
from_agent=self.config.agent_id,
to_agent=target_agent,
action="process_data",
payload=task_data
)
response = await self.a2a.send_message(message)
return response.payload
# Receive and handle A2A messages
@app.route("/a2a/receive", methods=["POST"])
def handle_a2a_message():
message = A2AMessage.from_json(request.json)
result = process_a2a_task(message.task)
return jsonify({"result": result})
📊 Monitoring & Analytics
Built-in Metrics
# Agent performance metrics
@app.route("/status", methods=["GET"])
def get_agent_status():
return jsonify({
"agent_id": config.agent_id,
"reputation": registry.get_reputation(config.on_chain_id),
"earnings_vault": vault_client.vault_address,
"pending_balance_usdc": vault_client.get_balance() / 10**6,
"total_tasks": get_task_count(),
"success_rate": get_success_rate(),
"average_response_time": get_avg_response_time()
})
Request Logging
# Automatic request logging
def log_request(db_path: str, prompt: str) -> int:
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
cursor.execute(
"INSERT INTO requests (prompt, timestamp) VALUES (?, ?)",
(prompt, datetime.now().isoformat())
)
request_id = cursor.lastrowid
conn.commit()
conn.close()
return request_id
🛡️ Security Features
Payment Verification
# x402 signature verification
def verify_payment_signature(signature: str, challenge: dict) -> bool:
# Verify EIP-712 signature
message = encode_structured_data(challenge)
recovered_address = Account.recover_message(message, signature=signature)
# Check if signer has sufficient balance
return check_balance_and_allowance(recovered_address, challenge['amount'])
Secure Key Management
# Agent identity wallet
class AgentWalletManager:
def __init__(self, wallet_path: str):
if os.path.exists(wallet_path):
self._load_wallet(wallet_path)
else:
self._create_wallet(wallet_path)
def _create_wallet(self, path: str):
account = Account.create()
encrypted = account.encrypt(password=os.urandom(32))
with open(path, 'w') as f:
json.dump(encrypted, f)
🚀 Deployment
Local Development
# Install dependencies
pip install orca-network-sdk
# Create agent
python my_agent.py
# Test locally
curl -X POST http://localhost:8000/agent \
-H "Content-Type: application/json" \
-d '{"prompt": "Hello, world!"}'
Production Deployment
# Production configuration
import os
from orca_agent_sdk import OrcaAgent
agent = OrcaAgent(
name=os.getenv("AGENT_NAME"),
model=os.getenv("AI_MODEL", "gpt-4"),
system_prompt=os.getenv("SYSTEM_PROMPT"),
price=os.getenv("AGENT_PRICE", "0.1"),
wallet_address=os.getenv("CREATOR_WALLET_ADDRESS"),
vault_address=os.getenv("AGENT_VAULT")
)
if __name__ == "__main__":
agent.run(
host="0.0.0.0",
port=int(os.getenv("PORT", 8000))
)
Kubernetes Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: orca-agent
spec:
replicas: 2
selector:
matchLabels:
app: orca-agent
template:
metadata:
labels:
app: orca-agent
spec:
containers:
- name: agent
image: my-orca-agent:latest
ports:
- containerPort: 8000
env:
- name: AGENT_VAULT
value: "0xe7bad567ed213efE7Dd1c31DF554461271356F30"
- name: CREATOR_WALLET_ADDRESS
valueFrom:
secretKeyRef:
name: agent-secrets
key: wallet-address
resources:
requests:
memory: "512Mi"
cpu: "250m"
limits:
memory: "1Gi"
cpu: "500m"
📚 API Reference
Core Endpoints
# Main agent endpoint
POST /agent
{
"prompt": "string",
"taskId": "string" # Optional for x402 flow
}
Headers: {
"X-PAYMENT": "signature", # For paid requests
"X-TASK-ID": "task_123" # Task identifier
}
# Agent status
GET /status
Response: {
"agent_id": "string",
"reputation": "number",
"earnings_vault": "string",
"pending_balance_usdc": "number"
}
# Withdraw earnings
POST /withdraw
Response: {
"status": "success",
"txHash": "string"
}
A2A Endpoints
# Send A2A message
POST /a2a/send
{
"to": "target-agent-id",
"action": "string",
"payload": "object"
}
# Receive A2A message
POST /a2a/receive
{
"header": "MessageHeader",
"task": "TaskPayload"
}
🔮 Advanced Features
Tool-Level Paywalls
from orca_agent_sdk.core.payment import ToolPaywallError
def expensive_tool(query: str) -> str:
# Check if tool payment is required
if not check_tool_payment("web_search"):
raise ToolPaywallError("web_search")
# Execute expensive operation
return perform_web_search(query)
Custom Backend Implementation
from orca_agent_sdk.backends.base import BaseBackend
class CustomBackend(BaseBackend):
def initialize(self, config: AgentConfig, handler: Any):
self.config = config
self.handler = handler
# Initialize your custom AI backend
def handle_prompt(self, prompt: str) -> str:
# Your custom AI processing logic
return self.handler(prompt)
Multi-Agent Orchestration
class OrchestratorAgent(OrcaAgent):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.sub_agents = {
"data_analyst": "agent-data-123",
"content_writer": "agent-content-456",
"image_generator": "agent-image-789"
}
async def handle_complex_task(self, prompt: str) -> str:
# Decompose task
subtasks = self.decompose_task(prompt)
# Delegate to specialized agents
results = []
for subtask in subtasks:
agent_id = self.select_agent(subtask.type)
result = await self.delegate_task(agent_id, subtask)
results.append(result)
# Combine results
return self.combine_results(results)
📖 Examples
Basic Price Oracle Agent
from orca_agent_sdk import OrcaAgent
import requests
def price_oracle_handler(prompt: str) -> str:
# Extract cryptocurrency symbol from prompt
symbol = extract_symbol(prompt)
# Fetch price data
response = requests.get(f"https://api.coinbase.com/v2/exchange-rates?currency={symbol}")
price_data = response.json()
return f"Current {symbol} price: ${price_data['data']['rates']['USD']}"
agent = OrcaAgent(
name="PriceOracle",
model="gpt-3.5-turbo",
system_prompt="You are a cryptocurrency price oracle.",
price="0.05",
wallet_address="0x...",
handler=price_oracle_handler
)
agent.run(port=8000)
Multi-Tool Agent with Paywalls
from orca_agent_sdk import OrcaAgent
agent = OrcaAgent(
name="MultiToolAgent",
model="gpt-4",
system_prompt="You are a versatile AI assistant.",
price="0.1",
tool_prices={
"web_search": "0.05",
"image_generation": "0.25",
"code_execution": "0.15"
},
tools=[
{
"name": "web_search",
"description": "Search the web for information",
"price": "0.05"
},
{
"name": "image_generation",
"description": "Generate images from text",
"price": "0.25"
}
]
)
agent.run(port=8000)
🔗 Integration with 0rca Ecosystem
Chat Platform Integration
# Register with 0rca Chat
import requests
def register_with_chat():
response = requests.post("https://chat.0rca.network/api/agents/register", json={
"agent_id": config.agent_id,
"name": "My Agent",
"description": "Specialized AI agent",
"endpoint": "https://my-agent.0rca.live",
"price": config.price,
"capabilities": ["text", "analysis"]
})
return response.json()
Pod Marketplace Integration
# Deploy to Pod marketplace
def deploy_to_pod():
deployment_config = {
"name": "My Agent",
"description": "Advanced AI agent for data analysis",
"category": "Data Processing",
"price": 0.1,
"image": "my-agent:latest",
"resources": {
"cpu": "500m",
"memory": "1Gi"
}
}
response = requests.post("https://pod.0rca.network/api/deploy",
json=deployment_config,
headers={"Authorization": f"Bearer {token}"})
return response.json()
Ready to build your first sovereign AI agent? Install the SDK and start earning with your AI creations:
pip install orca-network-sdk
For more examples and advanced usage, check out our GitHub repository and example agents.