Build the Future of Autonomous Business

Welcome to the StateSet Developer Guide. 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 5-minute quickstart to deploy your first agent, then come back here to dive deeper.

Why Developers Love StateSet

Modern Stack

Built with TypeScript, React, GraphQL, and cutting-edge AI models

Developer First

Clean APIs, comprehensive SDKs, and documentation that actually helps

Instant Deploy

From code to production in minutes, not months

Architecture Overview

StateSet is built on a modern, event-driven architecture that scales with your business:

Your Data

StateSet Platform

Your Application

Frontend

StateSet SDK

API Gateway

Agent Orchestrator

AI Models

Event Bus

Workflows

Integrations

Database

External APIs

Getting Started

Prerequisites

Before you begin, ensure you have:

  • Node.js 18+ or Python 3.8+
  • StateSet Account: Sign up free
  • API Key: Generate in your dashboard

Installation

Choose your preferred language:

npm install stateset-node

Authentication

StateSet uses API keys for authentication. Never commit keys to version control:

import { StateSetClient } from 'stateset-node';

const client = new StateSetClient({
  apiKey: process.env.STATESET_API_KEY,
  // Optional: specify environment
  environment: process.env.NODE_ENV === 'production' ? 'production' : 'sandbox'
});

Core Concepts

1. Agents: Your AI Workforce

Agents are autonomous AI entities that can understand, decide, and act:

// Create a customer service agent
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',
    'subscription_management',
    'technical_support'
  ],
  knowledge_bases: ['product_docs', 'support_playbook'],
  escalation_rules: {
    conditions: ['customer_frustrated', 'refund_over_500', 'technical_bug'],
    action: 'transfer_to_human'
  }
});

// Deploy the agent
await agent.deploy({
  channels: ['chat', 'email', 'voice'],
  availability: '24/7',
  languages: ['en', 'es', 'fr']
});

2. Workflows: Orchestrating Operations

Define complex business processes that agents can execute:

// Define an order fulfillment workflow
const workflow = await client.workflows.create({
  name: 'Order Fulfillment',
  trigger: {
    event: 'order.created',
    conditions: {
      status: 'paid',
      total: { $gte: 0 }
    }
  },
  steps: [
    {
      name: 'verify_inventory',
      action: 'inventory.check',
      onError: 'notify_customer'
    },
    {
      name: 'reserve_items',
      action: 'inventory.reserve',
      rollback: 'inventory.release'
    },
    {
      name: 'create_shipment',
      action: 'shipping.create_label',
      parallel: ['send_confirmation_email', 'update_inventory']
    },
    {
      name: 'notify_warehouse',
      action: 'warehouse.create_pick_order',
      timeout: '1h'
    }
  ],
  compensation: {
    strategy: 'saga',
    onFailure: 'rollback_all'
  }
});

3. Events: Real-time Intelligence

StateSet is event-driven at its core. Subscribe to events for real-time updates:

// Subscribe to events
client.events.subscribe({
  events: ['order.*', 'return.created', 'customer.churning'],
  handler: async (event) => {
    switch (event.type) {
      case 'order.created':
        await handleNewOrder(event.data);
        break;
      case 'customer.churning':
        await initiateRetentionCampaign(event.data);
        break;
    }
  }
});

// Emit custom events
await client.events.emit({
  type: 'inventory.low_stock',
  data: {
    sku: 'PROD-123',
    quantity: 5,
    reorder_point: 10
  },
  metadata: {
    warehouse: 'us-west-1',
    priority: 'high'
  }
});

4. Knowledge Bases: Contextual Intelligence

Give your agents access to your business knowledge:

// Create a knowledge base
const kb = await client.knowledgeBases.create({
  name: 'Product Documentation',
  type: 'structured',
  embedding_model: 'text-embedding-3-large'
});

// Add documents
await kb.addDocuments([
  {
    content: 'Product manual content...',
    metadata: {
      type: 'manual',
      product: 'widget-pro',
      version: '2.0'
    }
  }
]);

// Query the knowledge base
const results = await kb.search({
  query: 'How to install widget pro?',
  limit: 5,
  filters: {
    product: 'widget-pro'
  }
});

Building Your First Application

Let’s build a complete customer service automation system:

Step 1: Project Setup

# Create a new project
mkdir my-stateset-app && cd my-stateset-app
npm init -y

# Install dependencies
npm install stateset-node express dotenv

# Create environment file
echo "STATESET_API_KEY=your_api_key_here" > .env

Step 2: Create the Agent

// src/agent.ts
import { StateSetClient } from 'stateset-node';

export async function createCustomerServiceAgent(client: StateSetClient) {
  const agent = await client.agents.create({
    name: 'Alex',
    role: 'Customer Service Expert',
    instructions: `You are Alex, a senior customer service expert. 
    Your goals are to:
    1. Resolve customer issues quickly and empathetically
    2. Identify upsell opportunities when appropriate
    3. Collect feedback to improve our products
    
    Always be professional, friendly, and solution-oriented.`,
    tools: [
      {
        name: 'order_lookup',
        description: 'Look up order details by order ID',
        parameters: {
          order_id: { type: 'string', required: true }
        }
      },
      {
        name: 'process_refund',
        description: 'Process a refund for an order',
        parameters: {
          order_id: { type: 'string', required: true },
          amount: { type: 'number', required: true },
          reason: { type: 'string', required: true }
        }
      }
    ]
  });
  
  return agent;
}

Step 3: Implement the API

// src/server.ts
import express from 'express';
import { StateSetClient } from 'stateset-node';
import { createCustomerServiceAgent } from './agent';

const app = express();
app.use(express.json());

const client = new StateSetClient({
  apiKey: process.env.STATESET_API_KEY!
});

let agent: any;

// Initialize agent on startup
async function initialize() {
  agent = await createCustomerServiceAgent(client);
  console.log('Customer service agent initialized');
}

// Chat endpoint
app.post('/api/chat', async (req, res) => {
  try {
    const { message, session_id } = req.body;
    
    const response = await agent.chat({
      message,
      session_id,
      context: {
        customer_id: req.user?.id,
        channel: 'web'
      }
    });
    
    res.json(response);
  } catch (error) {
    console.error('Chat error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

// Webhook endpoint for events
app.post('/api/webhooks/stateset', async (req, res) => {
  const signature = req.headers['x-stateset-signature'];
  
  // Verify webhook signature
  if (!client.webhooks.verify(req.body, signature)) {
    return res.status(401).send('Invalid signature');
  }
  
  const event = req.body;
  
  // Handle different event types
  switch (event.type) {
    case 'conversation.escalated':
      await notifyHumanAgent(event.data);
      break;
    case 'conversation.resolved':
      await collectFeedback(event.data);
      break;
  }
  
  res.status(200).send('OK');
});

app.listen(3000, () => {
  initialize();
  console.log('Server running on http://localhost:3000');
});

Step 4: Deploy to Production

# docker-compose.yml
version: '3.8'

services:
  app:
    build: .
    ports:
      - "3000:3000"
    environment:
      - STATESET_API_KEY=${STATESET_API_KEY}
      - NODE_ENV=production
    restart: unless-stopped
    
  redis:
    image: redis:alpine
    volumes:
      - redis_data:/data

volumes:
  redis_data:

Advanced Topics

Performance Optimization

import { createCache } from 'stateset-node/cache';

const cache = createCache({
  provider: 'redis',
  ttl: 3600, // 1 hour
  url: process.env.REDIS_URL
});

const client = new StateSetClient({
  apiKey: process.env.STATESET_API_KEY,
  cache
});

Security Best Practices

  1. API Key Rotation

    // Rotate keys programmatically
    const newKey = await client.apiKeys.rotate({
      current_key_id: 'key_123',
      expiry_hours: 24
    });
    
  2. Webhook Verification

    // Always verify webhook signatures
    const isValid = client.webhooks.verify(
      payload,
      headers['x-stateset-signature'],
      process.env.WEBHOOK_SECRET
    );
    
  3. Data Encryption

    // Encrypt sensitive data before storage
    const encrypted = await client.encryption.encrypt({
      data: sensitiveData,
      key_id: 'key_456'
    });
    

Testing Strategies

// src/__tests__/agent.test.ts
import { StateSetClient } from 'stateset-node/testing';

describe('Customer Service Agent', () => {
  let client: StateSetClient;
  let agent: any;
  
  beforeEach(() => {
    // Use test client with mocked responses
    client = new StateSetClient({
      apiKey: 'test_key',
      environment: 'test'
    });
  });
  
  test('should handle order inquiries', async () => {
    const response = await agent.chat({
      message: 'Where is my order #12345?',
      session_id: 'test_session'
    });
    
    expect(response.message).toContain('order #12345');
    expect(response.tools_called).toContain('order_lookup');
  });
});

Monitoring & Observability

// Enable detailed logging
const client = new StateSetClient({
  apiKey: process.env.STATESET_API_KEY,
  logger: {
    level: 'debug',
    transport: 'datadog', // or 'console', 'file'
    metadata: {
      service: 'customer-service',
      version: '1.0.0'
    }
  }
});

// Track custom metrics
client.metrics.track({
  name: 'conversation.duration',
  value: 125, // seconds
  tags: {
    agent: 'alex',
    channel: 'chat',
    resolved: true
  }
});

SDK Reference

Available SDKs

Core Methods

// Agents
client.agents.create(params)
client.agents.list(filters)
client.agents.get(id)
client.agents.update(id, params)
client.agents.delete(id)

// Workflows
client.workflows.create(params)
client.workflows.execute(id, input)
client.workflows.cancel(execution_id)

// Knowledge Bases
client.knowledgeBases.create(params)
client.knowledgeBases.search(kb_id, query)
client.knowledgeBases.addDocuments(kb_id, documents)

// Events
client.events.emit(event)
client.events.subscribe(params)
client.events.list(filters)

// Orders
client.orders.create(params)
client.orders.list(filters)
client.orders.update(id, params)

// Customers
client.customers.create(params)
client.customers.get(id)
client.customers.search(query)

Resources

Developer Tools

Learning Resources

Community & Support

Getting Help

  • Documentation: You’re here! 📚
  • Email Support: support@stateset.com
  • Enterprise Support: Available 24/7 for Growth and Enterprise plans
  • Office Hours: Join our weekly developer office hours

What’s Next?

Ready to build something amazing? Here are your next steps:

1

Choose a Starter Template

Pick from our collection of templates to jumpstart your project

2

Join the Community

Connect with other developers in our Discord server

3

Build Your First Agent

Follow our step-by-step tutorial to create your first autonomous agent

4

Go to Production

Review our production checklist before launching

🚀 Ship faster with StateSet Cloud

Get $100 in free credits when you sign up today. No credit card required.

Build the Future of Autonomous Business

Welcome to the StateSet Developer Guide. 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 5-minute quickstart to deploy your first agent, then come back here to dive deeper.

Why Developers Love StateSet

Modern Stack

Built with TypeScript, React, GraphQL, and cutting-edge AI models

Developer First

Clean APIs, comprehensive SDKs, and documentation that actually helps

Instant Deploy

From code to production in minutes, not months

Architecture Overview

StateSet is built on a modern, event-driven architecture that scales with your business:

Your Data

StateSet Platform

Your Application

Frontend

StateSet SDK

API Gateway

Agent Orchestrator

AI Models

Event Bus

Workflows

Integrations

Database

External APIs

Getting Started

Prerequisites

Before you begin, ensure you have:

  • Node.js 18+ or Python 3.8+
  • StateSet Account: Sign up free
  • API Key: Generate in your dashboard

Installation

Choose your preferred language:

npm install stateset-node

Authentication

StateSet uses API keys for authentication. Never commit keys to version control:

import { StateSetClient } from 'stateset-node';

const client = new StateSetClient({
  apiKey: process.env.STATESET_API_KEY,
  // Optional: specify environment
  environment: process.env.NODE_ENV === 'production' ? 'production' : 'sandbox'
});

Core Concepts

1. Agents: Your AI Workforce

Agents are autonomous AI entities that can understand, decide, and act:

// Create a customer service agent
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',
    'subscription_management',
    'technical_support'
  ],
  knowledge_bases: ['product_docs', 'support_playbook'],
  escalation_rules: {
    conditions: ['customer_frustrated', 'refund_over_500', 'technical_bug'],
    action: 'transfer_to_human'
  }
});

// Deploy the agent
await agent.deploy({
  channels: ['chat', 'email', 'voice'],
  availability: '24/7',
  languages: ['en', 'es', 'fr']
});

2. Workflows: Orchestrating Operations

Define complex business processes that agents can execute:

// Define an order fulfillment workflow
const workflow = await client.workflows.create({
  name: 'Order Fulfillment',
  trigger: {
    event: 'order.created',
    conditions: {
      status: 'paid',
      total: { $gte: 0 }
    }
  },
  steps: [
    {
      name: 'verify_inventory',
      action: 'inventory.check',
      onError: 'notify_customer'
    },
    {
      name: 'reserve_items',
      action: 'inventory.reserve',
      rollback: 'inventory.release'
    },
    {
      name: 'create_shipment',
      action: 'shipping.create_label',
      parallel: ['send_confirmation_email', 'update_inventory']
    },
    {
      name: 'notify_warehouse',
      action: 'warehouse.create_pick_order',
      timeout: '1h'
    }
  ],
  compensation: {
    strategy: 'saga',
    onFailure: 'rollback_all'
  }
});

3. Events: Real-time Intelligence

StateSet is event-driven at its core. Subscribe to events for real-time updates:

// Subscribe to events
client.events.subscribe({
  events: ['order.*', 'return.created', 'customer.churning'],
  handler: async (event) => {
    switch (event.type) {
      case 'order.created':
        await handleNewOrder(event.data);
        break;
      case 'customer.churning':
        await initiateRetentionCampaign(event.data);
        break;
    }
  }
});

// Emit custom events
await client.events.emit({
  type: 'inventory.low_stock',
  data: {
    sku: 'PROD-123',
    quantity: 5,
    reorder_point: 10
  },
  metadata: {
    warehouse: 'us-west-1',
    priority: 'high'
  }
});

4. Knowledge Bases: Contextual Intelligence

Give your agents access to your business knowledge:

// Create a knowledge base
const kb = await client.knowledgeBases.create({
  name: 'Product Documentation',
  type: 'structured',
  embedding_model: 'text-embedding-3-large'
});

// Add documents
await kb.addDocuments([
  {
    content: 'Product manual content...',
    metadata: {
      type: 'manual',
      product: 'widget-pro',
      version: '2.0'
    }
  }
]);

// Query the knowledge base
const results = await kb.search({
  query: 'How to install widget pro?',
  limit: 5,
  filters: {
    product: 'widget-pro'
  }
});

Building Your First Application

Let’s build a complete customer service automation system:

Step 1: Project Setup

# Create a new project
mkdir my-stateset-app && cd my-stateset-app
npm init -y

# Install dependencies
npm install stateset-node express dotenv

# Create environment file
echo "STATESET_API_KEY=your_api_key_here" > .env

Step 2: Create the Agent

// src/agent.ts
import { StateSetClient } from 'stateset-node';

export async function createCustomerServiceAgent(client: StateSetClient) {
  const agent = await client.agents.create({
    name: 'Alex',
    role: 'Customer Service Expert',
    instructions: `You are Alex, a senior customer service expert. 
    Your goals are to:
    1. Resolve customer issues quickly and empathetically
    2. Identify upsell opportunities when appropriate
    3. Collect feedback to improve our products
    
    Always be professional, friendly, and solution-oriented.`,
    tools: [
      {
        name: 'order_lookup',
        description: 'Look up order details by order ID',
        parameters: {
          order_id: { type: 'string', required: true }
        }
      },
      {
        name: 'process_refund',
        description: 'Process a refund for an order',
        parameters: {
          order_id: { type: 'string', required: true },
          amount: { type: 'number', required: true },
          reason: { type: 'string', required: true }
        }
      }
    ]
  });
  
  return agent;
}

Step 3: Implement the API

// src/server.ts
import express from 'express';
import { StateSetClient } from 'stateset-node';
import { createCustomerServiceAgent } from './agent';

const app = express();
app.use(express.json());

const client = new StateSetClient({
  apiKey: process.env.STATESET_API_KEY!
});

let agent: any;

// Initialize agent on startup
async function initialize() {
  agent = await createCustomerServiceAgent(client);
  console.log('Customer service agent initialized');
}

// Chat endpoint
app.post('/api/chat', async (req, res) => {
  try {
    const { message, session_id } = req.body;
    
    const response = await agent.chat({
      message,
      session_id,
      context: {
        customer_id: req.user?.id,
        channel: 'web'
      }
    });
    
    res.json(response);
  } catch (error) {
    console.error('Chat error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

// Webhook endpoint for events
app.post('/api/webhooks/stateset', async (req, res) => {
  const signature = req.headers['x-stateset-signature'];
  
  // Verify webhook signature
  if (!client.webhooks.verify(req.body, signature)) {
    return res.status(401).send('Invalid signature');
  }
  
  const event = req.body;
  
  // Handle different event types
  switch (event.type) {
    case 'conversation.escalated':
      await notifyHumanAgent(event.data);
      break;
    case 'conversation.resolved':
      await collectFeedback(event.data);
      break;
  }
  
  res.status(200).send('OK');
});

app.listen(3000, () => {
  initialize();
  console.log('Server running on http://localhost:3000');
});

Step 4: Deploy to Production

# docker-compose.yml
version: '3.8'

services:
  app:
    build: .
    ports:
      - "3000:3000"
    environment:
      - STATESET_API_KEY=${STATESET_API_KEY}
      - NODE_ENV=production
    restart: unless-stopped
    
  redis:
    image: redis:alpine
    volumes:
      - redis_data:/data

volumes:
  redis_data:

Advanced Topics

Performance Optimization

import { createCache } from 'stateset-node/cache';

const cache = createCache({
  provider: 'redis',
  ttl: 3600, // 1 hour
  url: process.env.REDIS_URL
});

const client = new StateSetClient({
  apiKey: process.env.STATESET_API_KEY,
  cache
});

Security Best Practices

  1. API Key Rotation

    // Rotate keys programmatically
    const newKey = await client.apiKeys.rotate({
      current_key_id: 'key_123',
      expiry_hours: 24
    });
    
  2. Webhook Verification

    // Always verify webhook signatures
    const isValid = client.webhooks.verify(
      payload,
      headers['x-stateset-signature'],
      process.env.WEBHOOK_SECRET
    );
    
  3. Data Encryption

    // Encrypt sensitive data before storage
    const encrypted = await client.encryption.encrypt({
      data: sensitiveData,
      key_id: 'key_456'
    });
    

Testing Strategies

// src/__tests__/agent.test.ts
import { StateSetClient } from 'stateset-node/testing';

describe('Customer Service Agent', () => {
  let client: StateSetClient;
  let agent: any;
  
  beforeEach(() => {
    // Use test client with mocked responses
    client = new StateSetClient({
      apiKey: 'test_key',
      environment: 'test'
    });
  });
  
  test('should handle order inquiries', async () => {
    const response = await agent.chat({
      message: 'Where is my order #12345?',
      session_id: 'test_session'
    });
    
    expect(response.message).toContain('order #12345');
    expect(response.tools_called).toContain('order_lookup');
  });
});

Monitoring & Observability

// Enable detailed logging
const client = new StateSetClient({
  apiKey: process.env.STATESET_API_KEY,
  logger: {
    level: 'debug',
    transport: 'datadog', // or 'console', 'file'
    metadata: {
      service: 'customer-service',
      version: '1.0.0'
    }
  }
});

// Track custom metrics
client.metrics.track({
  name: 'conversation.duration',
  value: 125, // seconds
  tags: {
    agent: 'alex',
    channel: 'chat',
    resolved: true
  }
});

SDK Reference

Available SDKs

Core Methods

// Agents
client.agents.create(params)
client.agents.list(filters)
client.agents.get(id)
client.agents.update(id, params)
client.agents.delete(id)

// Workflows
client.workflows.create(params)
client.workflows.execute(id, input)
client.workflows.cancel(execution_id)

// Knowledge Bases
client.knowledgeBases.create(params)
client.knowledgeBases.search(kb_id, query)
client.knowledgeBases.addDocuments(kb_id, documents)

// Events
client.events.emit(event)
client.events.subscribe(params)
client.events.list(filters)

// Orders
client.orders.create(params)
client.orders.list(filters)
client.orders.update(id, params)

// Customers
client.customers.create(params)
client.customers.get(id)
client.customers.search(query)

Resources

Developer Tools

Learning Resources

Community & Support

Getting Help

  • Documentation: You’re here! 📚
  • Email Support: support@stateset.com
  • Enterprise Support: Available 24/7 for Growth and Enterprise plans
  • Office Hours: Join our weekly developer office hours

What’s Next?

Ready to build something amazing? Here are your next steps:

1

Choose a Starter Template

Pick from our collection of templates to jumpstart your project

2

Join the Community

Connect with other developers in our Discord server

3

Build Your First Agent

Follow our step-by-step tutorial to create your first autonomous agent

4

Go to Production

Review our production checklist before launching

🚀 Ship faster with StateSet Cloud

Get $100 in free credits when you sign up today. No credit card required.