> ## Documentation Index
> Fetch the complete documentation index at: https://docs.stateset.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Developer Guide

> Everything you need to build agentic commerce with StateSet

# 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.

<Note>
  **New to StateSet?** Start with our [Quickstart Guide](/quickstart) to deploy
  your first agent, then come back here to dive deeper.
</Note>

## Why Developers Love StateSet

<CardGroup cols={3}>
  <Card title="Modern Stack" icon="layer-group">
    Built with Rust, Axum, GraphQL, and cutting-edge AI models
  </Card>

  <Card title="Developer First" icon="terminal">
    Clean APIs, comprehensive SDKs for 11 languages, and documentation that
    actually helps
  </Card>

  <Card title="Instant Deploy" icon="rocket">
    From intent to outcome in minutes, not months
  </Card>
</CardGroup>

## Getting Started

### Prerequisites

Before you begin, ensure you have:

<Tabs>
  <Tab title="Required">
    * **Node.js 22+** or **Python 3.8+**
  </Tab>

  <Tab title="Recommended">
    * **TypeScript**: For better developer experience - **Git**: For version
      control - **Docker**: For local development
  </Tab>
</Tabs>

### Installation

```bash npm theme={null}
npm install -g @stateset/cli
npm install @stateset/embedded
```

```bash python theme={null}
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

```typescript theme={null}
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

<Note>
  **🚀 Ship faster with StateSet Sandbox** Get free sandbox credits when you
  [sign up today](https://sandbox.stateset.app). No credit card required.
</Note>

### 3. Workflows: Orchestrating Multi-Step Operations

Workflows handle long-running processes that span multiple steps and systems:

```typescript theme={null}
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:

```typescript theme={null}
// 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:

```typescript theme={null}
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:

```typescript theme={null}
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:

```typescript theme={null}
// 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:

```typescript theme={null}
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:

```typescript theme={null}
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:

```typescript theme={null}
// 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

```typescript theme={null}
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

```typescript theme={null}
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

```typescript theme={null}
// 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

```typescript theme={null}
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

```typescript theme={null}
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

```typescript theme={null}
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

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

### Track Agent Performance

```typescript theme={null}
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

<CardGroup cols={3}>
  <Card title="API Reference" icon="book" href="/api-reference/introduction">
    Complete API documentation with all endpoints and parameters
  </Card>

  <Card title="SDK Guides" icon="package" href="/guides/sdk-installation">
    Language-specific guides for Node.js, Python, Ruby, and more
  </Card>

  <Card title="Best Practices" icon="check-circle" href="/guides/api-design-guidelines">
    Production-ready patterns and security considerations
  </Card>
</CardGroup>

***

<Banner>
  ### Ready to Build? Start with the [Quickstart Guide](/quickstart) or explore

  the [API Reference](/api-reference/introduction) to begin integrating StateSet
  into your application.
</Banner>
