Skip to main content

Build the Future of Commerce

Welcome to the StateSet Documentation. Whether you’re building your first AI agent or architecting a complex autonomous system, this guide will help you harness the full power of StateSet’s platform.
New to StateSet? Start with our Quickstart Guide to deploy your first agent, then come back here to dive deeper.

Why Developers Love StateSet

Modern Stack

Built with Rust, Axum, GraphQL, and cutting-edge AI models

Developer First

Clean APIs, comprehensive SDKs for 11 languages, and documentation that actually helps

Instant Deploy

From intent to outcome in minutes, not months

Getting Started

Prerequisites

Before you begin, ensure you have:
  • Node.js 22+ or Python 3.8+

Installation

npm
npm install -g @stateset/cli
npm install @stateset/embedded
python
pip install stateset-embedded

Core Concepts

1. Agents: Your AI Workforce

Agents are autonomous AI entities that can understand, decide, and act on behalf of your business. Each agent has:
  • Role & Personality: Define its behavior and communication style
  • Capabilities: Specific skills like order management, support, or analytics
  • Knowledge Base: Access to your business documents and processes
  • Integrations: Connections to external systems and APIs
const agent = await client.agents.create({
  name: "Support Specialist",
  role: "Senior Customer Success Manager",
  personality: {
    traits: ["empathetic", "solution-oriented", "professional"],
    tone: "friendly yet professional",
  },
  capabilities: ["order_management", "refund_processing", "technical_support"],
  knowledge_bases: ["product_docs", "support_playbook"],
});

2. Sandboxes: Orchestrating Agentic Operations

Sandboxes are isolated environments that allow you to run your AI Agents in a safe and controlled manner. They provide:
  • Secure Execution: Run code and tools without affecting production
  • Resource Management: Control compute and memory allocation
  • Network Isolation: Isolate external calls and webhooks
  • State Management: Track agent decisions and outcomes
🚀 Ship faster with StateSet Sandbox Get free sandbox credits when you sign up today. No credit card required.

3. Workflows: Orchestrating Multi-Step Operations

Workflows handle long-running processes that span multiple steps and systems:
const workflow = await client.workflows.create({
  name: "Order Fulfillment",
  trigger: { event: "order.created" },
  steps: [
    {
      name: "Check Inventory",
      action: "inventory.check",
      timeout: "30s",
    },
    {
      name: "Process Payment",
      action: "payment.process",
      retry: { max: 3 },
    },
    {
      name: "Create Shipment",
      action: "shipping.create_label",
    },
    {
      name: "Notify Customer",
      action: "customer.notify",
      template: "order_confirmation",
    },
  ],
});

4. Events: Real-Time Business Signals

StateSet emits events for every meaningful state change:
// Subscribe to order events
client.events.subscribe({
  events: ["order.*"],
  handler: async (event) => {
    switch (event.type) {
      case "order.created":
        await handleNewOrder(event.data);
        break;
      case "order.paid":
        await triggerFulfillment(event.data);
        break;
      case "order.shipped":
        await sendTrackingUpdate(event.data);
        break;
    }
  },
});

Essential SDK Methods

Injecting Messages

Send messages to agents or conversations:
await client.messages.send({
  to: "agent_id",
  body: "Customer is asking about order status",
  context: {
    orderId: "ord_12345",
    customerId: "cust_67890",
  },
});

Handling Conversations

Manage multi-turn conversations:
const conversation = await client.conversations.create({
  participants: [
    { id: "agent_id", role: "agent" },
    { id: "customer_id", role: "customer" },
  ],
  metadata: {
    source: "web",
    campaign: "summer_sale",
  },
});

// Stream responses
const stream = await conversation.stream();
for await (const message of stream) {
  console.log("Agent says:", message.content);
}

Managing Knowledge Base

Upload and query documents:
// Create knowledge base
const kb = await client.knowledgeBases.create({
  name: "Product Documentation",
  agent_id: "agent_id",
});

// Upload documents
await kb.uploadDocument("./product-guide.pdf");
await kb.uploadDocument("./faq.md");

// Query knowledge
const results = await kb.query({
  question: "What is your return policy?",
  top_k: 3,
});

Architecture Patterns

Pattern 1: Agent + Integration

Connect agents to your existing systems:
await agent.addIntegration({
  type: "webhook",
  name: "order_lookup",
  endpoint: "https://api.yourstore.com/orders",
  authentication: {
    type: "api_key",
    key: process.env.STORE_API_KEY,
  },
  operations: ["read", "update"],
});

Pattern 2: Event-Driven Workflow

React to business events automatically:
client.events.subscribe({
  events: ["inventory.low_stock"],
  handler: async (event) => {
    // Trigger restocking
    await client.workflows.trigger("restock", {
      sku: event.data.sku,
      quantity: event.data.reorder_point * 2,
    });

    // Notify procurement team
    await client.notifications.send({
      to: "procurement_team",
      message: `Low stock alert for ${event.data.sku}`,
    });
  },
});

Pattern 3: Multi-Agent Orchestration

Coordinate multiple specialized agents:
// Create specialized agents
const salesAgent = await client.agents.create({
  name: "Sales Specialist",
  role: "Sales Representative",
  capabilities: ["lead_qualification", "product_recommendation", "pricing"],
});

const supportAgent = await client.agents.create({
  name: "Support Specialist",
  role: "Customer Support",
  capabilities: ["troubleshooting", "returns", "faq"],
});

// Route based on intent
async function routeIntent(customerMessage) {
  const intent = await client.intents.detect({
    message: customerMessage,
  });

  if (intent.category === "sales") {
    return salesAgent;
  } else if (intent.category === "support") {
    return supportAgent;
  } else {
    return await escalateToHuman();
  }
}

Error Handling Best Practices

Graceful Degradation

try {
  const result = await client.agents.execute({
    agentId: "agent_id",
    action: "process_order",
    data: orderData,
  });
} catch (error) {
  if (error.code === "TIMEOUT") {
    // Retry with exponential backoff
    await retry(orderData, { maxAttempts: 3, backoff: "exponential" });
  } else if (error.code === "RATE_LIMIT") {
    // Queue for later processing
    await queue.push({ action: "process_order", data: orderData });
  } else {
    // Log and escalate
    logger.error("Agent execution failed", { error, orderData });
    await notifyTeam({ error, orderData });
  }
}

Retry Strategies

async function withRetry(operation, options = {}) {
  const {
    maxAttempts = 3,
    backoff = "exponential",
    initialDelay = 1000,
  } = options;

  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    try {
      return await operation();
    } catch (error) {
      if (attempt === maxAttempts || !isRetryable(error)) {
        throw error;
      }

      const delay =
        backoff === "exponential"
          ? initialDelay * Math.pow(2, attempt - 1)
          : initialDelay * attempt;

      await sleep(delay);
    }
  }
}

Performance Optimization

Batch Operations

// Process multiple items efficiently
const orders = await client.orders.list({ limit: 100 });

const results = await Promise.allSettled(
  orders.map((order) =>
    client.agent.execute({
      agentId: "agent_id",
      action: "process_order",
      data: order,
    }),
  ),
);

// Handle results
results.forEach((result) => {
  if (result.status === "fulfilled") {
    logger.info("Order processed", result.value);
  } else {
    logger.error("Order failed", result.reason);
  }
});

Caching Strategy

import { LRUCache } from "lru-cache";

const cache = new LRUCache({
  max: 1000,
  ttl: 1000 * 60 * 15, // 15 minutes
});

async function getCachedData(key, fetcher) {
  const cached = cache.get(key);
  if (cached) return cached;

  const data = await fetcher();
  cache.set(key, data);
  return data;
}

Testing

Unit Testing Agents

describe("Order Agent", () => {
  it("should process new orders", async () => {
    const mockOrder = {
      items: [{ sku: "prod_123", quantity: 2 }],
      total: 99.99,
    };

    const result = await agent.process(mockOrder);

    expect(result.status).toBe("success");
    expect(result.orderId).toBeDefined();
  });

  it("should handle low inventory", async () => {
    const mockOrder = {
      items: [{ sku: "out_of_stock_123", quantity: 10 }],
    };

    const result = await agent.process(mockOrder);

    expect(result.status).toBe("failed");
    expect(result.error).toContain("insufficient inventory");
  });
});

Integration Testing

describe("Order Workflow Integration", () => {
  it("should fulfill order end-to-end", async () => {
    // Create order
    const order = await client.orders.create({
      customer_id: "test_customer",
      items: [{ sku: "test_product", quantity: 1 }],
    });

    // Wait for workflow completion
    await client.events.wait({
      event: "order.fulfilled",
      orderId: order.id,
      timeout: 30000,
    });

    // Verify fulfillment
    const fulfillment = await client.fulfillments.get(order.id);
    expect(fulfillment.tracking_number).toBeDefined();
  });
});

Monitoring & Debugging

Enable Debug Logging

const client = new StateSetClient({
  apiKey: process.env.STATESET_API_KEY,
  logger: {
    level: "debug",
    format: "json",
  },
});

Track Agent Performance

const metrics = await client.agents.getMetrics({
  agent_id: "agent_id",
  period: "24h",
  metrics: [
    "messages_sent",
    "response_time",
    "resolution_rate",
    "customer_satisfaction",
  ],
});

console.log("Average response time:", metrics.response_time.avg);
console.log("Resolution rate:", metrics.resolution_rate * 100, "%");

Next Steps