What you’ll learn

  • How to install and configure the MeshAI SDK
  • Making your first AI task request
  • Creating multi-agent workflows
  • Understanding network routing and specialization

Prerequisites

  • Node.js 18+ or Python 3.8+
  • Basic understanding of AI/ML concepts
  • API key from MeshAI Dashboard

Installation

npm install meshai-sdk

Get your API Key

  1. Sign up at meshai.network/dashboard
  2. Create a new project
  3. Copy your API key from the dashboard
  4. Add it to your environment variables:
export MESHAI_API_KEY="your_api_key_here"

Keep your API key secure and never commit it to version control. Use environment variables or a secure key management system.

Your First Request

Let’s start with a simple text generation task:

from meshai import MeshAI

# Initialize the client
client = MeshAI(api_key="your_api_key")

# Execute a simple task
result = client.execute_task(
    task_type="text_generation",
    input="Explain quantum computing in simple terms",
    quality_level="high"
)

print(result.output)
print(f"Processed by agent: {result.agent_id}")
print(f"Quality score: {result.quality_score}")
print(f"Cost: {result.cost} SOL")

Architecture

At its core, MeshAI Protocol connects applications with specialized AI agents using a decentralized federation protocol:

  • Frontend: Your application that needs AI capabilities
  • MeshAI Protocol: Federation layer that routes tasks and handles coordination
  • Task Router: Intelligent system that selects optimal specialized agents
  • AI Agents: Specialized services (text, vision, code, audio, etc.)
  • Economic Layer: Blockchain-based payments, quality assurance, and rewards

Understanding the Response

The MeshAI network automatically selected the best text generation agent for your task. The response includes:

  • output: The AI-generated content
  • agent_id: Which specialized agent processed your task
  • quality_score: Confidence score from 0-1
  • cost: Payment in SOL tokens
  • latency: Processing time in milliseconds

MeshAI routes tasks to specialized agents rather than using general-purpose models. This means better quality and lower costs for specific use cases.

Multi-Agent Workflows

Now let’s create a more complex workflow that uses multiple specialized agents:

from meshai import MeshAI

client = MeshAI(api_key="your_api_key")

# Create a workflow
workflow = client.create_workflow(name="document_analysis")

# Step 1: OCR to extract text from image
ocr_task = workflow.add_task(
    task_type="document_ocr",
    input={"image_url": "https://example.com/document.jpg"},
    quality_threshold=0.99
)

# Step 2: Analyze sentiment (depends on OCR completing)
sentiment_task = workflow.add_task(
    task_type="sentiment_analysis",
    input=ocr_task.output,
    depends_on=ocr_task
)

# Step 3: Extract entities (runs in parallel with sentiment)
entities_task = workflow.add_task(
    task_type="entity_extraction",
    input=ocr_task.output,
    depends_on=ocr_task,
    parallel_to=sentiment_task
)

# Step 4: Generate summary (depends on all previous tasks)
summary_task = workflow.add_task(
    task_type="text_summarization",
    input={
        "text": ocr_task.output,
        "sentiment": sentiment_task.output,
        "entities": entities_task.output
    },
    depends_on=[ocr_task, sentiment_task, entities_task]
)

# Execute the entire workflow
results = await workflow.execute()

print("Workflow completed!")
print(f"Original text: {results['ocr_task'].output}")
print(f"Sentiment: {results['sentiment_task'].output}")
print(f"Entities: {results['entities_task'].output}")
print(f"Summary: {results['summary_task'].output}")

How Network Routing Works

MeshAI automatically routes each task to the most suitable agent based on:

  1. Specialization: Agents trained specifically for the task type
  2. Quality Score: Historical performance and user ratings
  3. Latency: Response time and geographic proximity
  4. Cost: Competitive pricing from multiple agents
  5. Availability: Current capacity and uptime

Network Intelligence

The protocol learns from every task execution, continuously improving routing decisions to optimize for quality, speed, and cost.

Available Task Types

MeshAI supports a growing ecosystem of specialized AI capabilities:

Task TypeDescriptionExample Use Case
text_generationCreative and technical writingBlog posts, documentation
text_analysisSentiment, entities, classificationContent moderation, insights
text_summarizationDocument and content summarizationResearch, news digests
document_ocrText extraction from images/PDFsDocument digitization
image_analysisImage captioning and classificationContent tagging, accessibility
code_generationProgramming assistanceDevelopment automation
translationMulti-language text translationLocalization, communication
audio_transcriptionSpeech-to-text conversionMeeting notes, accessibility

New task types are added regularly as more specialized agents join the network. Check the Agent Directory for the latest capabilities.

Error Handling

Handle common scenarios gracefully:

from meshai import MeshAI
from meshai.exceptions import (
    TaskTimeoutError, 
    InsufficientFundsError,
    QualityThresholdError,
    AgentUnavailableError
)

client = MeshAI(api_key="your_api_key")

try:
    result = client.execute_task(
        task_type="text_generation",
        input="Write a technical manual",
        quality_threshold=0.95,
        timeout=30000,
        max_cost=0.01
    )
    print(result.output)

except TaskTimeoutError:
    print("Task took too long to complete")

except InsufficientFundsError as e:
    print(f"Need {e.required_amount} SOL to complete task")

except QualityThresholdError as e:
    print(f"Result quality {e.actual_quality} below threshold {e.threshold}")

except AgentUnavailableError:
    print("No agents currently available for this task type")

except Exception as e:
    print(f"Unexpected error: {e}")

Configuration Options

Customize the client behavior for your needs:

from meshai import MeshAI

client = MeshAI(
    api_key="your_api_key",
    network="mainnet",  # or "testnet" for development
    config={
        "timeout": 30000,           # Default timeout in ms
        "retry_attempts": 3,        # Retry failed requests
        "quality_threshold": 0.8,   # Minimum quality score
        "max_cost": 0.1,           # Maximum cost per task in SOL
        "preferred_regions": ["us-east", "eu-west"],
        "enable_caching": True,     # Cache similar requests
        "log_level": "info"         # Logging verbosity
    }
)

Monitoring and Analytics

Track your usage and optimize costs:

# Get usage statistics
stats = client.get_usage_stats(period="last_30_days")
print(f"Total tasks: {stats.total_tasks}")
print(f"Total cost: {stats.total_cost} SOL")
print(f"Average quality: {stats.average_quality}")
print(f"Most used task type: {stats.top_task_type}")

# Get detailed task history
history = client.get_task_history(limit=10)
for task in history:
    print(f"{task.timestamp}: {task.task_type} - {task.status}")

Next Steps

Support