Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Self healing and workspace update agent #663

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 34 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1737,7 +1737,7 @@ Documentation is located here at: [docs.swarms.world](https://docs.swarms.world)
-----

## Folder Structure
The swarms package has been meticlously crafted for extreme use-ability and understanding, the swarms package is split up into various modules such as `swarms.agents` that holds pre-built agents, `swarms.structs`Β that holds a vast array of structures like `Agent` and multi agent structures. The 3 most important are `structs`, `models`, and `agents`.
The swarms package has been meticlously crafted for extreme use-ability and understanding, the swarms package is split up into various modules such as `swarms.agents` that holds pre-built agents, `swarms.structs` that holds a vast array of structures like `Agent` and multi agent structures. The 3 most important are `structs`, `models`, and `agents`.

```sh
β”œβ”€β”€ __init__.py
Expand Down Expand Up @@ -1786,3 +1786,36 @@ Join our growing community around the world, for real-time support, ideas, and d
# License

GNU AFFERO GENERAL PUBLIC LICENSE

### Self-Healing Agent
The Self-Healing Agent is a specialized agent that can automatically detect, analyze, and fix runtime errors in your code using LLM-based analysis. It provides structured error analysis and generates fixes in JSON format.

```python
from swarms.agents import SelfHealingAgent

# Initialize the self-healing agent
agent = SelfHealingAgent(
model_name="gpt-4",
max_retries=3,
verbose=True
)

# Example usage with error handling
try:
result = some_function_that_might_fail()
except Exception as e:
# Agent will analyze the error and propose fixes
fix = agent.analyze_and_fix(e)
print(f"Error Analysis: {fix['analysis']}")
print(f"Proposed Fix: {fix['solution']}")
```

**Key Features:**
- Runtime error detection and analysis
- LLM-powered error understanding
- Structured JSON output with error analysis and solutions
- Automatic code fix generation
- Configurable retry attempts
- Detailed error context tracking

For more details, see the [Self-Healing Agent Documentation](docs/swarms/agents/self_healing_agent.md).
1 change: 1 addition & 0 deletions docs/mkdocs.yml
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
docs_dir: '.' # replace with the correct path if your documentation files are not in the same directory as mkdocs.yml

Check warning on line 1 in docs/mkdocs.yml

View workflow job for this annotation

GitHub Actions / yaml-lint

1:1 [document-start] missing document start "---"

Check failure on line 1 in docs/mkdocs.yml

View workflow job for this annotation

GitHub Actions / yaml-lint

1:81 [line-length] line too long (118 > 80 characters)
site_name: Swarms
site_url: https://docs.swarms.world
site_author: Swarms
site_description: The Enterprise-Grade Production-Ready Multi-Agent Orchestration Framework

Check failure on line 5 in docs/mkdocs.yml

View workflow job for this annotation

GitHub Actions / yaml-lint

5:81 [line-length] line too long (91 > 80 characters)
repo_name: kyegomez/swarms
repo_url: https://github.com/kyegomez/swarms
edit_uri: https://github.com/kyegomez/swarms/tree/main/docs
Expand All @@ -13,9 +13,9 @@
- search
- git-authors
- mkdocs-jupyter:
kernel_name: python3

Check failure on line 16 in docs/mkdocs.yml

View workflow job for this annotation

GitHub Actions / yaml-lint

16:9 [indentation] wrong indentation: expected 6 but found 8
execute: false
include_source: True

Check warning on line 18 in docs/mkdocs.yml

View workflow job for this annotation

GitHub Actions / yaml-lint

18:25 [truthy] truthy value should be one of [false, true]
include_requirejs: true
- mkdocstrings:
default_handler: python
Expand Down Expand Up @@ -137,10 +137,10 @@
- pymdownx.tilde
nav:
- Home:
- Overview: "index.md"

Check failure on line 140 in docs/mkdocs.yml

View workflow job for this annotation

GitHub Actions / yaml-lint

140:5 [indentation] wrong indentation: expected 6 but found 4
# - The Vision: "swarms/framework/vision.md"
# - Docker Setup: "swarms/install/docker_setup.md"
- Our Goal; The Ultimate Multi-Agent LLM Framework for Developers: "swarms/concept/vision.md"

Check failure on line 143 in docs/mkdocs.yml

View workflow job for this annotation

GitHub Actions / yaml-lint

143:81 [line-length] line too long (97 > 80 characters)
- Swarm Ecosystem: "swarms/concept/swarm_ecosystem.md"
- Onboarding:
- Installation: "swarms/install/install.md"
Expand All @@ -149,7 +149,7 @@
- Swarms CLI: "swarms/cli/main.md"
# - Swarms + Docker:
- Swarms Framework Architecture: "swarms/concept/framework_architecture.md"
# - Prelimary:

Check warning on line 152 in docs/mkdocs.yml

View workflow job for this annotation

GitHub Actions / yaml-lint

152:5 [comments-indentation] comment not indented like content
# - 80/20 Rule For Agents: "swarms/prompting/8020.md"
- Managing Prompts in Production: "swarms/prompts/main.md"
- Agents:
Expand All @@ -159,6 +159,7 @@
- Complete Agent API: "swarms/structs/agent.md"
- OpenAI Assistant: "swarms/agents/openai_assistant.md"
- Create and Run Agents from YAML: "swarms/agents/create_agents_yaml.md"
- Self Healing Agent: "swarms/agents/self_healing_agent.md"
- Integrating External Agents from Griptape, Langchain, etc: "swarms/agents/external_party_agents.md"
- Tools:
- Overview: "swarms/tools/main.md"
Expand Down Expand Up @@ -251,7 +252,7 @@
- Edit Agents: "swarms_platform/agents/edit_agent.md"
- Telemetry API:
- PUT: "swarms_platform/telemetry/index.md"
# - Tools API:

Check warning on line 255 in docs/mkdocs.yml

View workflow job for this annotation

GitHub Actions / yaml-lint

255:5 [comments-indentation] comment not indented like content
# - Overview: "swarms_platform/tools_api.md"
# - Add Tools: "swarms_platform/fetch_tools.md"
- Guides:
Expand Down
181 changes: 181 additions & 0 deletions docs/swarms/agents/self_healing_agent.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
# Self-Healing Agent Documentation

The Self-Healing Agent is a specialized agent designed to automatically detect, analyze, and fix runtime errors in your code using LLM-based analysis. It provides structured error analysis and generates fixes in JSON format.

## Overview

The Self-Healing Agent uses advanced language models to:
1. Analyze runtime errors and exceptions
2. Understand the error context and root cause
3. Generate potential fixes in a structured format
4. Apply fixes automatically when possible

## Installation

The Self-Healing Agent is included in the main swarms package:

```bash
pip install -U swarms
```

## Basic Usage

```python
from swarms.agents import SelfHealingAgent

# Initialize the agent
agent = SelfHealingAgent(
model_name="gpt-4", # The LLM model to use
max_retries=3, # Maximum number of fix attempts
verbose=True # Enable detailed logging
)

# Example usage with error handling
try:
result = some_function_that_might_fail()
except Exception as e:
fix = agent.analyze_and_fix(e)
print(f"Error Analysis: {fix['analysis']}")
print(f"Proposed Fix: {fix['solution']}")
```

## API Reference

### SelfHealingAgent Class

#### Constructor Parameters

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| model_name | str | "gpt-4" | The name of the LLM model to use |
| max_retries | int | 3 | Maximum number of fix attempts |
| verbose | bool | False | Enable detailed logging |
| system_prompt | str | None | Custom system prompt for the LLM |
| temperature | float | 0.7 | Temperature for LLM responses |

#### Methods

##### analyze_and_fix(error: Exception) -> dict
Analyzes an error and generates potential fixes.

**Parameters:**
- error (Exception): The caught exception to analyze

**Returns:**
A dictionary containing:
```json
{
"error_type": "str", // Type of the error
"analysis": "str", // Detailed error analysis
"context": "str", // Error context
"solution": "str", // Proposed fix in code form
"confidence": float, // Confidence score (0-1)
"metadata": {} // Additional error metadata
}
```

##### apply_fix(fix: dict) -> bool
Attempts to apply a generated fix.

**Parameters:**
- fix (dict): The fix dictionary returned by analyze_and_fix()

**Returns:**
- bool: True if fix was successfully applied, False otherwise

## Error Output Format

The agent provides structured error analysis in JSON format:

```json
{
"error_type": "ZeroDivisionError",
"analysis": "Attempted division by zero in calculation",
"context": "Error occurred in calculate_average() at line 45",
"solution": "Add a check for zero denominator:\nif denominator != 0:\n result = numerator/denominator\nelse:\n raise ValueError('Denominator cannot be zero')",
"confidence": 0.95,
"metadata": {
"file": "calculator.py",
"line": 45,
"function": "calculate_average"
}
}
```

## Best Practices

1. **Error Context**: Always provide as much context as possible when catching errors
2. **Validation**: Review proposed fixes before applying them automatically
3. **Logging**: Enable verbose mode during development for detailed insights
4. **Model Selection**: Use GPT-4 for complex errors, GPT-3.5-turbo for simpler cases
5. **Retry Strategy**: Configure max_retries based on your use case

## Examples

### Basic Error Handling

```python
from swarms.agents import SelfHealingAgent

agent = SelfHealingAgent()

def process_data(data):
try:
result = data['key']['nested_key']
return result
except Exception as e:
fix = agent.analyze_and_fix(e)
if fix['confidence'] > 0.8:
print(f"Applying fix: {fix['solution']}")
return agent.apply_fix(fix)
else:
print(f"Low confidence fix, manual review needed: {fix['analysis']}")
return None
```

### Custom System Prompt

```python
agent = SelfHealingAgent(
system_prompt="""You are an expert Python developer specializing in
fixing data processing errors. Focus on data validation and type checking
in your solutions."""
)
```

### Batch Error Processing

```python
def process_batch(items):
results = []
errors = []

for item in items:
try:
result = process_item(item)
results.append(result)
except Exception as e:
errors.append((item, e))

# Process all errors at once
if errors:
fixes = [agent.analyze_and_fix(e) for _, e in errors]
return results, fixes
```

## Error Types Handled

The Self-Healing Agent can handle various types of runtime errors including:

- Syntax Errors
- Type Errors
- Index Errors
- Key Errors
- Attribute Errors
- Value Errors
- Import Errors
- And more...

## Contributing

We welcome contributions to improve the Self-Healing Agent! Please see our [Contributing Guidelines](../../CONTRIBUTING.md) for more information.
Loading
Loading