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

# Deploy

> Deploy ResponseCX agents with the SDK

# Deploy an agent with the SDK

### SDK

The ResponseCX agent runtime is built on top of StateSet Cloud platform infrastructure, a deterministic workflow engine, an event-driven architecture, and state-of-the-art models.

Each agent has its own configuration and set of modules that define its behavior.

### TypeScript One-Click Deploy

Deploying an agent with the SDK is as simple as copying and pasting the code below into a file and running it.

```typescript theme={null}

import { NextRequest, NextResponse } from "next/server";
import { StateSetClient } from 'stateset-node';
import winston from 'winston';

const logger = winston.createLogger({
  level: process.env.LOG_LEVEL || 'info',
  transports: [new winston.transports.Console()]
});

// Ensure runtime is set to edge
export const config = {
  runtime: 'edge',
};

// Define interfaces for agent configuration
interface AgentAttribute {
  attribute_name: string;
  attribute_type: string;
  value?: number;
  max_value?: number;
  min_value?: number;
  category?: string;
  description?: string;
  modifiable?: boolean;
  impact?: string;
  org_id?: string;
  activated?: boolean;
  user_id?: string;
}

interface AgentRule {
  rule_name: string;
  rule_type: string;
  activated: boolean;
  description: string;
  org_id: string;
  user_id?: string;
}

interface AgentWorkflow {
  name: string;
  description: string;
  type: string;
  triggers: Trigger[];
  actions: Action[];
}

interface Trigger {
  type: string;
  event: string;
}

interface Action {
  type: string;
  config: Record<string, any>;
}

interface AgentChannel {
  name: string;
  type: string;
  config: Record<string, any>;
}

interface AgentConfiguration {
  learning_rate: number;
  memory_retention: number;
  response_threshold: number;
  auto_escalation: boolean;
  monitoring: {
    performance_tracking: boolean;
    error_logging: boolean;
    activity_history: boolean;
  };
}

// Helper function to retrieve API key securely
const getApiKey = (): string => {
  const apiKey = process.env.STATESET_API_KEY;
  if (!apiKey) {
    throw new Error('STATESET_API_KEY is not defined in environment variables.');
  }
  return apiKey;
};

// Helper function to handle batch creation
const createBatch = async (items: any[], createFn: Function, nameField: string): Promise<string[]> => {
  const creationPromises = items.map(createFn);
  const results = await Promise.allSettled(creationPromises);
  const createdIds: string[] = [];

  results.forEach((result, index) => {
    if (result.status === 'fulfilled') {
      createdIds.push(result.value.id);
    } else {
      logger.error('Failed to create item', {
        nameField,
        name: items[index][nameField],
        reason: result.reason
      });
    }
  });

  return createdIds;
};

// Main handler function
export default async function handler(req: NextRequest) {
  try {
    const apiKey = getApiKey();
    const client = new StateSetClient({ apiKey });

    // Create the base agent
    const agent = await client.agents.create({
      name: 'Order Processing Agent',
      description: 'AI Agent for handling order processing and management',
      type: 'order_processing',
      schema: {
        type: 'object',
        properties: {
          orderId: { type: 'string' },
          customerId: { type: 'string' },
          orderDetails: {
            type: 'object',
            properties: {
              items: { type: 'array' },
              totalAmount: { type: 'number' },
              shippingAddress: { type: 'object' }
            }
          }
        },
        required: ['orderId']
      },
      capabilities: [
        'order_processing',
        'customer_service',
        'inventory_management',
        'shipping_coordination'
      ]
    });

    // Define agent components
    const personalityAttributes: AgentAttribute[] = [
      {
        attribute_name: 'Efficiency',
        attribute_type: 'numeric',
        value: 90,
        max_value: 100,
        min_value: 0,
        category: 'performance',
        description: 'Speed and accuracy in processing orders',
        modifiable: true,
        impact: 'high',
        org_id: 'org_123',
        activated: true
      },
      {
        attribute_name: 'Customer Focus',
        attribute_type: 'numeric',
        value: 95,
        max_value: 100,
        min_value: 0,
        category: 'personality',
        description: 'Level of attention to customer needs',
        modifiable: true,
        impact: 'high',
        org_id: 'org_123',
        activated: true
      },
      {
        attribute_name: 'Adaptability',
        attribute_type: 'numeric',
        value: 85,
        max_value: 100,
        min_value: 0,
        category: 'personality',
        description: 'Ability to handle unexpected situations',
        modifiable: true,
        impact: 'medium',
        org_id: 'org_123',
        activated: true
      }
    ];

    const operationalRules: AgentRule[] = [
      {
        rule_name: 'Order Validation',
        rule_type: 'validation',
        activated: true,
        description: 'Validate all order details before processing',
        org_id: 'org_123'
      },
      {
        rule_name: 'Inventory Check',
        rule_type: 'process',
        activated: true,
        description: 'Verify inventory availability before order confirmation',
        org_id: 'org_123'
      },
      {
        rule_name: 'Customer Communication',
        rule_type: 'communication',
        activated: true,
        description: 'Maintain clear communication with customers throughout the process',
        org_id: 'org_123'
      },
      {
        rule_name: 'Error Handling',
        rule_type: 'exception',
        activated: true,
        description: 'Handle errors and exceptions gracefully with proper escalation',
        org_id: 'org_123'
      }
    ];

    const workflows: AgentWorkflow[] = [
      {
        name: 'Order Processing Workflow',
        description: 'Standard workflow for processing new orders',
        type: 'sequential',
        triggers: [
          {
            type: 'event',
            event: 'new_order_received'
          }
        ],
        actions: [
          {
            type: 'validate_order',
            config: { checkInventory: true }
          },
          {
            type: 'process_payment',
            config: { retryAttempts: 3 }
          },
          {
            type: 'generate_shipping_label',
            config: { carrier: 'preferred' }
          }
        ]
      }
    ];

    const channels: AgentChannel[] = [
      {
        name: 'Customer Chat',
        type: 'chat',
        config: {
          response_time: 30,
          language: 'en',
          tone: 'professional'
        }
      },
      {
        name: 'Email Notifications',
        type: 'email',
        config: {
          templates: {
            order_confirmation: true,
            shipping_update: true,
            delivery_confirmation: true
          }
        }
      }
    ];

    // Create agent components
    const attributeIds = await createBatch(personalityAttributes, (attr) => client.attributes.create({ agent_id: agent.id, ...attr }), 'attribute_name');
    const ruleIds = await createBatch(operationalRules, (rule) => client.rules.create({ agent_id: agent.id, ...rule }), 'rule_name');
    const workflowIds = await createBatch(workflows, (workflow) => client.workflows.create({ agent_id: agent.id, ...workflow }), 'name');
    const channelIds = await createBatch(channels, (channel) => client.channels.create({ agent_id: agent.id, ...channel }), 'name');

    // Define agent configuration
    const agentConfig: AgentConfiguration = {
      learning_rate: 0.1,
      memory_retention: 0.8,
      response_threshold: 0.7,
      auto_escalation: true,
      monitoring: {
        performance_tracking: true,
        error_logging: true,
        activity_history: true
      }
    };

    // Update agent with all created components
    const updatedAgent = await client.agents.update(agent.id, {
      attributes: attributeIds,
      rules: ruleIds,
      workflows: workflowIds,
      channels: channelIds,
      status: 'active',
      configuration: agentConfig
    });

    // Activate the agent
    await client.agents.setAvailable(agent.id);

    return NextResponse.json({
      status: 'success',
      message: 'Order processing agent created successfully',
      data: {
        agent_id: agent.id,
        attributes_created: attributeIds.length,
        rules_created: ruleIds.length,
        workflows_created: workflowIds.length,
        channels_created: channelIds.length,
        status: updatedAgent.status
      }
    });
  } catch (error) {
    logger.error('Error creating order processing agent', {
      message: error instanceof Error ? error.message : String(error)
    });

    return NextResponse.json({
      status: 'error',
      message: error instanceof Error ? error.message : 'An unknown error occurred',
      timestamp: new Date().toISOString(),
      details: error instanceof Error ? {
        name: error.name,
        stack: process.env.NODE_ENV === 'development' ? error.stack : undefined
      } : undefined
    }, {
      status: 500,
      headers: {
        'Content-Type': 'application/json'
      }
    });
  }
}

```

### Python One Click Deploy

Deploying an agent with the SDK is as simple as copying and pasting the code below into a file and running it.

```python theme={null}

import os
import asyncio
import logging
from stateset import StateSetClient
from fastapi import FastAPI, Request, HTTPException
from pydantic import BaseModel
from typing import List, Dict, Optional

app = FastAPI()

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Define data models
class AgentAttribute(BaseModel):
    attribute_name: str
    attribute_type: str
    value: Optional[int] = None
    max_value: Optional[int] = None
    min_value: Optional[int] = None
    category: Optional[str] = None
    description: Optional[str] = None
    modifiable: Optional[bool] = None
    impact: Optional[str] = None
    org_id: Optional[str] = None
    activated: Optional[bool] = None

class AgentRule(BaseModel):
    rule_name: str
    rule_type: str
    activated: bool
    description: str
    org_id: str

class Trigger(BaseModel):
    type: str
    event: str

class Action(BaseModel):
    type: str
    config: Dict[str, any]

class AgentWorkflow(BaseModel):
    name: str
    description: str
    type: str
    triggers: List[Trigger]
    actions: List[Action]

class AgentChannel(BaseModel):
    name: str
    type: str
    config: Dict[str, any]

class AgentConfiguration(BaseModel):
    learning_rate: float
    memory_retention: float
    response_threshold: float
    auto_escalation: bool
    monitoring: Dict[str, bool]

# Helper function to retrieve API key securely
def get_api_key() -> str:
    api_key = os.getenv('STATESET_API_KEY')
    if not api_key:
        raise ValueError('STATESET_API_KEY is not defined in environment variables.')
    return api_key

# Helper function to handle batch creation
async def create_batch(items: List[BaseModel], create_fn, name_field: str) -> List[str]:
    tasks = [create_fn(item) for item in items]
    results = await asyncio.gather(*tasks, return_exceptions=True)
    created_ids = []

    for i, result in enumerate(results):
        if isinstance(result, Exception):
            logger.error(
                "Failed to create %s: %s",
                name_field,
                getattr(items[i], name_field),
                exc_info=result,
            )
        else:
            created_ids.append(result['id'])

    return created_ids

@app.post("/create_agent")
async def create_agent():
    try:
        api_key = get_api_key()
        client = StateSetClient(api_key=api_key)

        # Create the base agent
        agent_data = {
            "name": "Order Processing Agent",
            "description": "AI Agent for handling order processing and management",
            "type": "order_processing",
            "schema": {
                "type": "object",
                "properties": {
                    "orderId": {"type": "string"},
                    "customerId": {"type": "string"},
                    "orderDetails": {
                        "type": "object",
                        "properties": {
                            "items": {"type": "array"},
                            "totalAmount": {"type": "number"},
                            "shippingAddress": {"type": "object"}
                        }
                    }
                },
                "required": ["orderId"]
            },
            "capabilities": [
                "order_processing",
                "customer_service",
                "inventory_management",
                "shipping_coordination"
            ]
        }
        agent = await client.agents.create(agent_data)

        # Define agent components
        personality_attributes = [
            AgentAttribute(
                attribute_name="Efficiency",
                attribute_type="numeric",
                value=90,
                max_value=100,
                min_value=0,
                category="performance",
                description="Speed and accuracy in processing orders",
                modifiable=True,
                impact="high",
                org_id="org_123",
                activated=True
            ),
            AgentAttribute(
                attribute_name="Customer Focus",
                attribute_type="numeric",
                value=95,
                max_value=100,
                min_value=0,
                category="personality",
                description="Level of attention to customer needs",
                modifiable=True,
                impact="high",
                org_id="org_123",
                activated=True
            ),
            AgentAttribute(
                attribute_name="Adaptability",
                attribute_type="numeric",
                value=85,
                max_value=100,
                min_value=0,
                category="personality",
                description="Ability to handle unexpected situations",
                modifiable=True,
                impact="medium",
                org_id="org_123",
                activated=True
            )
        ]

        operational_rules = [
            AgentRule(
                rule_name="Order Validation",
                rule_type="validation",
                activated=True,
                description="Validate all order details before processing",
                org_id="org_123"
            ),
            AgentRule(
                rule_name="Inventory Check",
                rule_type="process",
                activated=True,
                description="Verify inventory availability before order confirmation",
                org_id="org_123"
            ),
            AgentRule(
                rule_name="Customer Communication",
                rule_type="communication",
                activated=True,
                description="Maintain clear communication with customers throughout the process",
                org_id="org_123"
            ),
            AgentRule(
                rule_name="Error Handling",
                rule_type="exception",
                activated=True,
                description="Handle errors and exceptions gracefully with proper escalation",
                org_id="org_123"
            )
        ]

        workflows = [
            AgentWorkflow(
                name="Order Processing Workflow",
                description="Standard workflow for processing new orders",
                type="sequential",
                triggers=[
                    Trigger(type="event", event="new_order_received")
                ],
                actions=[
                    Action(type="validate_order", config={"checkInventory": True}),
                    Action(type="process_payment", config={"retryAttempts": 3}),
                    Action(type="generate_shipping_label", config={"carrier": "preferred"})
                ]
            )
        ]

        channels = [
            AgentChannel(
                name="Customer Chat",
                type="chat",
                config={
                    "response_time": 30,
                    "language": "en",
                    "tone": "professional"
                }
            ),
            AgentChannel(
                name="Email Notifications",
                type="email",
                config={
                    "templates": {
                        "order_confirmation": True,
                        "shipping_update": True,
                        "delivery_confirmation": True
                    }
                }
            )
        ]

        # Create agent components
        attribute_ids = await create_batch(personality_attributes, lambda attr: client.attributes.create(agent.id, attr.dict()), 'attribute_name')
        rule_ids = await create_batch(operational_rules, lambda rule: client.rules.create(agent.id, rule.dict()), 'rule_name')
        workflow_ids = await create_batch(workflows, lambda wf: client.workflows.create(agent.id, wf.dict()), 'name')
        channel_ids = await create_batch(channels, lambda ch: client.channels.create(agent.id, ch.dict()), 'name')

        # Define agent configuration
        agent_config = AgentConfiguration(
            learning_rate=0.1,
            memory_retention=0.8,
            response_threshold=0.7,
            auto_escalation=True,
            monitoring={
                "performance_tracking": True,
                "error_logging": True,
                "activity_history": True
            }
        )

        # Update agent with all created components
        updated_agent = await client.agents.update(agent.id, {
            "attributes": attribute_ids,
            "rules": rule_ids,
            "workflows": workflow_ids,
            "channels": channel_ids,
            "status": "active",
            "configuration": agent_config.dict()
        })

        # Activate the agent
        await client.agents.set_available(agent.id)

        return {
            "status": "success",
            "message": "Order processing agent created successfully",
            "data": {
                "agent_id": agent.id,
                "attributes_created": len(attribute_ids),
                "rules_created": len(rule_ids),
                "workflows_created": len(workflow_ids),
                "channels_created": len(channel_ids),
                "status": updated_agent['status']
            }
        }
    except Exception as error:
        logger.error('Error creating order processing agent', exc_info=error)
        raise HTTPException(status_code=500, detail=str(error))


```
