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

# Agents Quickstart

> This guide will walk you through creating and managing Agents on ResponseCX.

## Prerequisites

Before you begin creating agents, ensure you have:

<CardGroup cols={2}>
  <Card title="Account & Access" icon="user-check">
    * A StateSet account ([Sign up here](https://StateSet.com/sign-up))
    * API credentials from the [StateSet Dashboard](https://app.StateSet.com/settings/api-keys)
    * ResponseCX enabled in your workspace
  </Card>

  <Card title="Technical Setup" icon="code">
    * Node.js 16+ installed on your development machine
    * Basic understanding of REST APIs and JavaScript/TypeScript
    * Text editor or IDE for code development
  </Card>
</CardGroup>

<Card title="Domain Knowledge" icon="brain">
  * Understanding of conversational AI concepts and customer service workflows
  * Access to your customer support systems (if planning integrations)
  * Knowledge of your brand voice and customer interaction requirements
</Card>

## What are Agents?

In ResponseCX, an Agent is an autonomous conversational AI that can interact with your customers. You can customize its name, personality, and instructions to fit your business needs. Agents can be used in chat sessions to provide support, answer questions, and guide users.

## Creating an Agent

You can create an agent through the ResponseCX dashboard or using the SDK.

### Using the Dashboard

1. Navigate to the **Agents** section of the ResponseCX dashboard.
2. Click the **Add New Agent** button.
3. Fill in the agent's details:
   * **Name:** A recognizable name for your agent (e.g., "Support Bot").
   * **Description:** A brief summary of the agent's purpose.
   * **Type:** The type of agent. For most use cases, you'll use `Conversational AI Agent`.
   * **Voice Model:** The voice your agent will use for voice interactions. `Asteria` is a popular choice.
4. Click **Add Agent** to save your new agent.

### Using the SDK

Here's how to create an agent using our SDKs with proper error handling:

<Tabs>
  <Tab title="Node.js">
    ```javascript theme={null}
    import { StateSetClient } from 'StateSet-node';
    import winston from 'winston';

    // Configure logger
    const logger = winston.createLogger({
      level: 'info',
      format: winston.format.json(),
      transports: [new winston.transports.Console()]
    });

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

    async function createAgent() {
      try {
        const agent = await client.agents.create({
          name: "My SDK Agent",
          description: "This agent was created via the SDK.",
          type: "Conversational AI Agent",
          role: "E-commerce Assistant",
          instructions: "You are a friendly and helpful assistant for an online store.",
          goal: "Help customers find products and answer questions about their orders.",
          voice_model: "Asteria",
        });

        logger.info('Agent created successfully', { 
          agentId: agent.id, 
          name: agent.name 
        });
        
        return agent;
      } catch (error) {
        logger.error('Failed to create agent', { 
          error: error.message,
          stack: error.stack 
        });
        throw error;
      }
    }

    // Usage
    const agent = await createAgent();
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    import os
    import logging
    from StateSet import StateSetClient

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

    # Initialize the client
    client = StateSetClient(api_key=os.getenv('STATESET_API_KEY'))

    def create_agent():
        try:
            agent = client.agents.create(
                name="My SDK Agent",
                description="This agent was created via the SDK.",
                type="Conversational AI Agent",
                role="E-commerce Assistant",
                instructions="You are a friendly and helpful assistant for an online store.",
                goal="Help customers find products and answer questions about their orders.",
                voice_model="Asteria"
            )
            
            logger.info(f'Agent created successfully: {agent.id} - {agent.name}')
            return agent
            
        except Exception as error:
            logger.error(f'Failed to create agent: {str(error)}')
            raise

    # Usage
    agent = create_agent()
    ```
  </Tab>

  <Tab title="Ruby">
    ```ruby theme={null}
    require 'StateSet'
    require 'logger'

    # Configure logging
    logger = Logger.new(STDOUT)
    logger.level = Logger::INFO

    # Configure client
    StateSet.configure do |config|
      config.api_key = ENV['STATESET_API_KEY']
    end

    def create_agent
      agent = StateSet::Agent.create(
        name: "My SDK Agent",
        description: "This agent was created via the SDK.",
        type: "Conversational AI Agent",
        role: "E-commerce Assistant",
        instructions: "You are a friendly and helpful assistant for an online store.",
        goal: "Help customers find products and answer questions about their orders.",
        voice_model: "Asteria"
      )
      
      logger.info "Agent created successfully: #{agent.id} - #{agent.name}"
      agent
      
    rescue => error
      logger.error "Failed to create agent: #{error.message}"
      raise
    end

    # Usage
    agent = create_agent
    ```
  </Tab>

  <Tab title="PHP">
    ```php theme={null}
    <?php
    require_once 'vendor/autoload.php';

    use StateSet\StateSetClient;
    use Monolog\Logger;
    use Monolog\Handler\StreamHandler;

    // Configure logging
    $logger = new Logger('StateSet');
    $logger->pushHandler(new StreamHandler('php://stdout', Logger::INFO));

    // Initialize the client
    $client = new StateSetClient([
        'api_key' => $_ENV['STATESET_API_KEY']
    ]);

    function createAgent($client, $logger) {
        try {
            $agent = $client->agents->create([
                'name' => 'My SDK Agent',
                'description' => 'This agent was created via the SDK.',
                'type' => 'Conversational AI Agent',
                'role' => 'E-commerce Assistant',
                'instructions' => 'You are a friendly and helpful assistant for an online store.',
                'goal' => 'Help customers find products and answer questions about their orders.',
                'voice_model' => 'Asteria'
            ]);
            
            $logger->info('Agent created successfully', [
                'agent_id' => $agent['id'],
                'name' => $agent['name']
            ]);
            
            return $agent;
            
        } catch (Exception $error) {
            $logger->error('Failed to create agent', [
                'error' => $error->getMessage()
            ]);
            throw $error;
        }
    }

    // Usage
    $agent = createAgent($client, $logger);
    ?>
    ```
  </Tab>

  <Tab title="cURL">
    ```bash theme={null}
    # Create an agent using cURL
    curl -X POST "https://api.StateSet.com/v1/agents" \
      -H "Authorization: Bearer $STATESET_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "name": "My SDK Agent",
        "description": "This agent was created via the SDK.",
        "type": "Conversational AI Agent",
        "role": "E-commerce Assistant",
        "instructions": "You are a friendly and helpful assistant for an online store.",
        "goal": "Help customers find products and answer questions about their orders.",
        "voice_model": "Asteria"
      }' | jq '.'

    # Save the response to get the agent ID
    AGENT_ID=$(curl -s -X POST "https://api.StateSet.com/v1/agents" \
      -H "Authorization: Bearer $STATESET_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "name": "My SDK Agent",
        "description": "This agent was created via the SDK.",
        "type": "Conversational AI Agent",
        "role": "E-commerce Assistant",
        "instructions": "You are a friendly and helpful assistant for an online store.",
        "goal": "Help customers find products and answer questions about their orders.",
        "voice_model": "Asteria"
      }' | jq -r '.id')

    echo "Agent created with ID: $AGENT_ID"
    ```
  </Tab>
</Tabs>

**Agent Properties:**

* `name` (string, required): The name of the agent.
* `description` (string): A short description of the agent.
* `type` (string): The type of agent.
* `role` (string): The role you want the agent to adopt (e.g., "Customer Support Agent").
* `instructions` (string): Specific instructions for the agent on how to behave. This is where you define its personality and operational guidelines.
* `goal` (string): The primary objective for the agent in conversations.
* `voice_model` (string): The voice model for text-to-speech.

## Managing Agents

You can view, update, and delete your agents.

### Listing Agents

Retrieve a list of all your agents with pagination support:

```javascript theme={null}
async function listAgents(page = 1, limit = 10) {
  try {
    const agents = await client.agents.list({
      page,
      limit,
      sort: 'created_at:desc'
    });
    
    return {
      agents: agents.data,
      totalCount: agents.total,
      hasMore: agents.has_more
    };
  } catch (error) {
    logger.error('Failed to list agents:', error);
    throw new Error('Unable to retrieve agents at this time');
  }
}
```

## Updating an Agent

You can update an agent's properties in the dashboard or through the SDK.

### Using the Dashboard

1. In the **Agents** list, click the **Update** button for the agent you want to modify.
2. Change the desired fields in the agent editor.
3. Click **Save** to apply the changes.

### Using the SDK

```javascript theme={null}
async function updateAgent(agentId, updates) {
  try {
    const updatedAgent = await client.agents.update({
      id: agentId,
      ...updates
    });

    // Audit trail for compliance
    await auditLog.record({
      action: 'agent.updated',
      agentId: agentId,
      changes: updates,
      timestamp: new Date()
    });

    return {
      success: true,
      agent: updatedAgent,
      message: 'Agent updated successfully'
    };
  } catch (error) {
    if (error.code === 'AGENT_NOT_FOUND') {
      throw new Error('Agent not found');
    }
    
    logger.error('Failed to update agent:', error);
    throw error;
  }
}

// Example usage
const updates = {
  name: "My Updated Agent Name",
  description: "Updated description with new capabilities",
  instructions: "You are now specialized in technical support..."
};

await updateAgent(agentId, updates);
```

## Deleting an Agent

You can delete an agent from the dashboard or via the SDK. Deleting an agent is permanent and cannot be undone.

```javascript theme={null}
async function deleteAgent(agentId) {
  try {
    // Check if agent has active conversations
    const activeConversations = await client.conversations.list({
      agent_id: agentId,
      status: 'active'
    });
    
    if (activeConversations.total > 0) {
      throw new Error('Cannot delete agent with active conversations');
    }
    
    // Archive agent data before deletion (for compliance)
    await archiveAgentData(agentId);
    
    // Delete the agent
    await client.agents.delete({ id: agentId });
    
    return {
      success: true,
      message: 'Agent deleted successfully'
    };
  } catch (error) {
    logger.error('Failed to delete agent:', error);
    throw error;
  }
}
```

## Best Practices

### 1. Agent Instructions

Be specific and clear in your instructions:

```javascript theme={null}
const goodInstructions = `You are a friendly customer support agent for Acme Store.
- Always greet customers warmly
- Ask clarifying questions before providing solutions
- Never share customer personal information
- Escalate to human support for refund requests over $100`;

const poorInstructions = "Help customers";
```

### 2. Error Handling

Always implement robust error handling:

```javascript theme={null}
async function safeAgentOperation(operation) {
  const maxRetries = 3;
  let lastError;
  
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await operation();
    } catch (error) {
      lastError = error;
      
      // Don't retry on client errors
      if (error.status >= 400 && error.status < 500) {
        throw error;
      }
      
      // Exponential backoff
      await new Promise(resolve => setTimeout(resolve, Math.pow(2, i) * 1000));
    }
  }
  
  throw lastError;
}
```

### 3. Monitoring Agent Performance

Track your agent's effectiveness:

```javascript theme={null}
async function getAgentMetrics(agentId, timeframe = '7d') {
  const metrics = await client.agents.getMetrics({
    id: agentId,
    timeframe
  });
  
  return {
    conversationCount: metrics.total_conversations,
    satisfactionScore: metrics.avg_satisfaction,
    resolutionRate: metrics.resolution_rate,
    avgResponseTime: metrics.avg_response_time_ms
  };
}
```

## Next Steps

Now that you've created an agent, you can start using it in your application. Here are some things you might want to do next:

* **Create a Chat:** Learn how to initiate a chat session with your new agent.
* **Explore advanced features:** Dive into more complex agent capabilities like using functions and knowledge bases.

For more information on how to use Agents, please reach out at [support@StateSet.com](mailto:support@StateSet.com)
