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

# Agents (Alpha)

> Autonomous AI workers powered by LLMs

<Note>
  Agents are currently in private alpha and subject to change. If you would like to them out, please reach out to [re-factor Support](mailto:support@psci-labs.com).
</Note>

## Motivation

Agents in re-factor are autonomous AI workers that can understand complex instructions, make decisions, and execute tasks using available tools and resources. They represent a powerful way to automate sophisticated workflows while maintaining human-like reasoning capabilities.

## Basic Features

An agent in re-factor consists of several core components:

1. A `system` message that defines the agent's role, capabilities, and constraints
2. Access to a specific set of [tools](/core-concepts/tools) that the agent can use
3. A memory system that maintains context across interactions
4. Built-in error handling and recovery mechanisms

## Enhanced Features

#### Tool Integration

Agents can be configured with access to specific tools, allowing them to:

<CodeGroup>
  ```typescript example.ts theme={null}
  import { Agent } from '@re-factor/sdk';

  const agent = new Agent({
      system: "You are a data analysis assistant",
      tools: [{
          name: "query_database",
          description: "Query the sales database",
          handler: async (query) => {
              // Database query implementation
          }
      }]
  });

  const result = await agent.execute(
      "Analyze our sales data for Q4 2024"
  );
  ```

  ```python example.py theme={null}
  from refactor.agents import Agent

  agent = Agent(
      system="You are a data analysis assistant",
      tools=[{
          "name": "query_database",
          "description": "Query the sales database",
          "handler": lambda query: # Database query implementation
      }]
  )

  result = await agent.execute(
      "Analyze our sales data for Q4 2024"
  )
  ```
</CodeGroup>

#### Memory Management

Agents maintain context through a sophisticated memory system that includes:

* Short-term conversation memory
* Long-term knowledge storage
* Tool execution history
* Previous decision contexts

This enables agents to maintain coherent conversations and build upon previous interactions:

```typescript theme={null}
const memory = agent.getMemory();
console.log(memory.getConversationHistory());
console.log(memory.getToolExecutions());
```

#### Error Handling

Agents come with built-in error handling capabilities:

* Automatic retry mechanisms for failed tool executions
* Graceful degradation when encountering limitations
* Clear error reporting and recovery suggestions
* Ability to ask for human intervention when needed

#### Monitoring and Observability

Every agent provides detailed insights into its operation:

* Real-time execution tracking
* Decision-making logs
* Tool usage statistics
* Performance metrics

## Schema

Agents in re-factor are defined using Zod schemas for type safety and validation:

```typescript theme={null}
const AgentSchema = {
    // Metadata
    name: string,
    description?: string,
    tags?: string[],
    version?: string,
    created?: Date,
    updated?: Date,

    // Core Components
    system: string,
    tools?: Tool[],
    memory?: {
        type: 'none' | 'conversation' | 'long_term',
        config?: Record<string, any>
    },
    errorHandling?: {
        maxRetries?: number,
        retryDelay?: number,
        fallbackBehavior?: 'ask_human' | 'skip' | 'abort'
    }
}
```

### Example Usage

<CodeGroup>
  ```typescript example.ts theme={null}
  import { Agent, Tool } from '@re-factor/sdk';

  const agent = {
      name: 'data_analyst',
      description: 'AI agent for data analysis tasks',
      version: '1.0.0',
      system: 'You are a data analysis expert who helps users understand their data.',
      tools: [{
          name: 'query_database',
          handler: async (query: string) => {
              // Database query implementation
          },
          inputSchema: z.string(),
          outputSchema: z.array(z.record(z.string(), z.any()))
      }],
      memory: {
          type: 'conversation',
          config: {
              maxMessages: 50
          }
      },
      errorHandling: {
          maxRetries: 3,
          retryDelay: 1000,
          fallbackBehavior: 'ask_human'
      }
  };
  ```

  ```python example.py theme={null}
  from refactor import Agent, Tool

  agent = {
      "name": "data_analyst",
      "description": "AI agent for data analysis tasks",
      "version": "1.0.0",
      "system": "You are a data analysis expert who helps users understand their data.",
      "tools": [{
          "name": "query_database",
          "handler": lambda query: None,  # Database query implementation
          "inputSchema": "string",
          "outputSchema": "array"
      }],
      "memory": {
          "type": "conversation",
          "config": {
              "maxMessages": 50
          }
      },
      "errorHandling": {
          "maxRetries": 3,
          "retryDelay": 1000,
          "fallbackBehavior": "ask_human"
      }
  }
  ```
</CodeGroup>

## Best Practices

When working with agents in re-factor:

1. Define clear and specific system messages
2. Limit tool access to only what's necessary
3. Implement proper error handling
4. Monitor agent performance and resource usage
5. Set appropriate timeout and retry limits
6. Document agent capabilities and limitations

For more information on implementing agents in your applications, refer to our [SDK documentation](/sdk).
