# Anges: An Open Source Autonomous Engineering Assistant
Anges is an LLM powered engineering agent system designed to be easy to use, but also highly customizable and minimalist.
## Quick Start
### Installation & First Run
```bash
# Install from PyPI
pip install anges
# Set your API key. Anges defaults to using Anthropic's Claude.
# (See configuration below to use other models like Gemini or OpenAI)
export ANTHROPIC_API_KEY=<YOUR_API_KEY_HERE>
# Run your first task
anges -q "What is the OS version?"
```
### Basic Usage
```bash
# Interactive mode (for conversational tasks)
anges -i
# Direct task execution from the command line
anges -q "List all python files in the current directory."
# Execute a task described in a file
anges -f task_description.txt
# Launch the web interface
anges ui --port 5000 --password your_password
# Help menu
anges -h
```
*A quick demonstration of Anges checking the OS and listing files.*

*A quick look of Anges UI.*

### Configurations
The default configuration is located at `anges/configs/default_config.yaml`.
You can override these settings by creating a `config.yaml` file at `~/.anges/config.yaml`.
For example, to configure the default agent to use Google's Gemini Pro:
```bash
# Create the config file to switch the default model
cat > ~/.anges/config.yaml <<EOF
agents:
default_agent:
model_name: "gemini/gemini-1.5-pro-latest"
EOF
# Export the corresponding API key
export GOOGLE_API_KEY=<YOUR_GEMINI_API_KEY>
```
### Advanced usages
* **Working Directory:** You can set the agent's working directory from the UI or CLI. This sets the default location for operations but does not enforce a strict permission boundary.
* **Prefix Command:** You can configure a prefix command (e.g., `export MY_VAR=... &&`) that will be executed before every command the agent runs. This is useful for setting up a consistent environment.
* **Default Agent vs. Orchestrator:**
* **Default Agent:** Ideal for simple, single-step tasks that a human could complete in a few minutes. It's fast and direct.
* **Orchestrator:** For complex, multi-step problems that require research, planning, and code iteration. The orchestrator agent can break down the task and delegate to other agents.
* **Event Streams:** Every action, thought process, and command is logged as a JSON file in `~/.anges/data/event_streams`. This provides full transparency and creates a valuable dataset for fine-tuning or analysis.
### Demos & Examples
* [Linux and Cloud Ops](https://demo.anges.ai/?chatId=QIVELO41)
* [Creating a Demo Website](https://demo.anges.ai/?chatId=dCg8a13M)
* [Solving a Complex Task (3-hour run)](https://demo.anges.ai/?chatId=atktkEDt)
* [Recursive Self-Invocation Testing](https://demo.anges.ai/?chatId=pyA5pYEm)
Explore more demos at **[https://demo.anges.ai](https://demo.anges.ai)**.
## Why Anges?
| Feature | **Anges** | **Gemini CLI** | **Cursor** |
| :--- | :--- | :--- | :--- |
| **Open Source** | ✅ Yes (MIT) | ✅ Yes (Apache-2.0) | ❌ No |
| **CLI Support** | ✅ Yes | ✅ Yes | ✅ Yes |
| **Web UI** | ✅ Yes | ❌ No | ❌ No |
| **Mobile Web Access** | ✅ Yes | ❌ No | ❌ No |
| **Hackable & Customizable** | ✅ Flexible (Python) | ⚠️ Forkable | ❌ Minified |
| **Multi-Agent Orchestration**| ✅ Yes | ❌ No | ❌ No |
| **Model Agnostic** | ✅ Any Model | ❌ Gemini Only | ❌ Claude/OpenAI |
### From Advisor to Assistant
We're used to LLMs being advisors—they sit behind a chat box, waiting for copy-pasted context and offering suggestions you still have to run yourself.
But what if you gave an AI **real access** to your shell, tools, and working environment? What if it could **work alongside you**, not just talk to you?
Anges turns that idea into a practical, hackable reality, giving LLMs controlled execution power while keeping engineers fully in the loop.
### Key Benefits
* **Real Automation, Not Just Advice**
Anges doesn’t just suggest commands—it runs them. It reads output, handles errors, and plans its next move. It's a doer, not a talker.
* **Model Agnostic**
Use any model you want—Claude, OpenAI, Gemini, Llama, local models—all are easily configurable. You control the brain.
* **Flexible Interfaces**
Work from your terminal, in a container, or through the web UI on your phone. Anges meets you where you are.
* **Hackable by Design**
Written in clean, modular Python. Everything is exposed and easy to modify. There are no heavy abstractions hiding the prompts or logic.
* **Built-in Orchestration**
Tackle complex tasks with a multi-agent system that can decompose problems, delegate work, and execute recursively—with zero boilerplate.
* **Transparent Event Logs**
Every command, decision, and observation is saved to a local event stream. You have a perfect, replayable audit trail of the agent's work.
### Use Cases
* **As an Engineering Assistant**
Ask it to install packages, inspect logs, restart services, or modify configuration files—all within a single, natural language query.
* **For DevOps & Maintenance**
Automate infrastructure chores like updating dependencies, cleaning up disk space, or managing your local development environment.
* **For Data & File Workflows**
Let it move, rename, clean, or parse files. Have it pipe commands together to build quick data pipelines without writing scripts.
* **For Learning & Debugging**
Watch how the agent breaks down a task and plans its execution. It’s a great way to learn new system tools or understand complex commands.
* **To Build Custom Domain Agents**
Need an agent that knows your specific codebase, product, or workflow? Fork Anges, wire in your custom logic, and create a specialized assistant.
## Core Design Concepts
### Architecture Overview
Anges follows a modular, event-driven architecture with distinct components for task interpretation, command generation, execution management, and result processing. The framework is built around four core concepts:
1. **BaseAgent Lifecycle**: Manages agent creation, initialization, and execution flow
2. **Event Stream**: Provides persistent state management and execution history
3. **Action System**: Defines extensible actions for agent capabilities
4. **Prompt Construction**: Builds contextual prompts from event history
### BaseAgent Lifecycle
The BaseAgent class serves as the foundation for all agent types in Anges, managing the complete lifecycle from initialization to task completion.
#### Agent Initialization
```python
class BaseAgent:
def __init__(
self,
parent_ids=[],
inference_func=None,
event_stream=None,
cmd_init_dir=config.agents.default_agent.cmd_init_dir,
prefix_cmd="",
interrupt_check=None,
max_consecutive_actions_to_summarize=30,
logging_level=logging.DEBUG,
auto_entitle=False,
):
```
**Key Initialization Components:**
- **Event Stream**: Creates or inherits an EventStream for state persistence
- **Inference Function**: LLM integration for decision making
- **Execution Context**: Working directory and command prefix configuration
- **Interrupt Handling**: Optional callback for graceful task interruption
- **Summarization**: Automatic event summarization for long conversations
#### Execution Flow
The agent follows a structured execution loop:
1. **Request Handling**: Processes new or follow-up requests
2. **Event Creation**: Adds request events to the event stream
3. **Decision Loop**: Continuously prompts LLM and executes actions until completion
4. **Interruption Checks**: Monitors for user interrupts or execution limits
5. **State Persistence**: Saves event stream after each significant action
```python
def run_with_new_request(self, task_description, event_stream=None):
# Initialize run configuration
run_config = self._build_run_config(task_description, event_stream)
# Add new request to event stream
self._handle_received_new_request(run_config)
while True:
# Check for interruptions
if self._check_interruption(run_config):
return event_stream
# Check execution limits
if self._check_exhausted(run_config):
return event_stream
# Get next action and execute
if self._prefict_next_event_and_handle_actions(event_stream, run_config):
return event_stream
```
### Event Stream System
The Event Stream provides persistent state management and execution history, enabling agents to maintain context across complex, multi-step tasks.
#### Event Structure
Each event captures a discrete action or state change:
```python
class Event:
def __init__(self, type, reasoning="", content="", title=None,
message="", analysis="", est_input_token=0, est_output_token=0):
self.type = type # Event classification
self.reasoning = reasoning # Agent's reasoning (visible in history)
self.content = content # Event content/results
self.message = message # User-visible message
self.analysis = analysis # Internal analysis (not shown to user)
self.created_at = datetime.now()
```
**Event Types:**
- `new_request` / `follow_up_request`: User task requests
- `action`: Shell command execution
- `edit_file`: File modification operations
- `task_completion`: Successful task completion
- `task_interrupted`: Task interruption or failure
- `agent_requested_help`: Agent requesting human assistance
- `agent_text_response`: Agent providing informational responses
#### EventStream Management
```python
class EventStream:
def __init__(self, title=None, uid=None, parent_event_stream_uids=None, agent_type=""):
self.events_list = [] # Chronological event sequence
self.event_summaries_list = [] # Summarized event ranges
self.uid = uid # Unique stream identifier
self.parent_event_stream_uids = parent_event_stream_uids # Hierarchical relationships
self.agent_settings = {} # Persistent agent configuration
```
**Key Features:**
- **Persistence**: Automatic JSON serialization to disk
- **Hierarchical Structure**: Support for parent-child agent relationships
- **Event Summarization**: Automatic summarization of long event sequences
- **Settings Management**: Persistent storage of agent configuration
#### Event Summarization
To manage long conversations, the system automatically summarizes events:
- **Task Completion Summaries**: Generated when tasks complete
- **Action Aggregation**: Summarizes sequences of related actions
- **Configurable Thresholds**: Customizable summarization triggers
### Agent Types
The system supports multiple agent types optimized for different scenarios:
#### Default Agent
**Purpose**: General-purpose task execution with full action capabilities
**Use Cases**: Complex multi-step tasks, file operations, system administration
**Actions**: All available actions (shell commands, file editing, help requests)
#### Task Executor
**Purpose**: Focused command execution with minimal overhead
**Use Cases**: Simple command execution, quick operations
**Actions**: Primarily shell commands and basic responses
#### Task Analyzer
**Purpose**: Task decomposition and analysis without execution
**Use Cases**: Planning, task breakdown, requirement analysis
**Actions**: Text responses, analysis outputs
#### Orchestrator
**Purpose**: Complex workflow management with child agent coordination
**Use Cases**: Multi-agent workflows, complex project management
**Actions**: Child agent spawning, workflow coordination
### Model Integration
Flexible LLM integration supporting multiple providers with consistent interfaces and fallback mechanisms.
#### Supported Providers
- **Claude (Anthropic)**: Primary recommendation for complex reasoning
- **OpenAI GPT**: Broad compatibility and performance
- **Google Gemini**: Alternative provider with competitive capabilities
#### Integration Architecture
```python
INFERENCE_FUNC_DICT = {
'claude': claude_inference,
'openai': openai_inference,
'gemini': gemini_inference
}
```
**Features:**
- **Unified Interface**: Consistent API across all providers
- **Configuration Management**: YAML-based model configuration
- **Error Handling**: Graceful fallback and retry mechanisms
- **Token Estimation**: Usage tracking and optimization
### Safety and Control
Built-in safeguards for command validation, execution monitoring, and error handling.
#### Execution Safeguards
- **Command Timeouts**: Configurable execution time limits
- **Working Directory Control**: Isolated execution environments
- **Command Prefixing**: Automatic command modification for safety
- **Interrupt Handling**: Graceful task termination
#### Error Management
- **Comprehensive Logging**: Detailed execution tracking
- **Error Recovery**: Automatic retry and fallback mechanisms
- **State Persistence**: Recovery from unexpected failures
- **User Notifications**: Clear error communication
## Implementation Details
### Command Line Interface
Anges provides a unified CLI with multiple operation modes:
#### Interactive Mode
```bash
anges [options]
```
### Action System
The Action system provides a modular, extensible framework for defining agent capabilities through discrete, composable actions.
#### Action Architecture
All actions inherit from the base Action class:
```python
class Action:
def __init__(self):
self.type = "" # Action identifier
self.guide_prompt = "" # LLM instruction text
self.user_visible = False # Whether action results are shown to user
self.unique_action = False # Whether action must be used alone
self.returning_action = False # Whether action terminates the execution loop
def handle_action_in_parsed_response(self, run_config, parsed_response_dict, action_json):
raise NotImplementedError("Subclasses must implement this method")
```
#### Built-in Actions
**RUN_SHELL_CMD**: Execute shell commands with timeout and background support
- **Type**: Non-visible, non-unique
- **Purpose**: System command execution
- **Features**: Timeout control, background execution, output capture
**EDIT_FILE**: Structured file operations (create, insert, replace, remove)
- **Type**: Non-visible, non-unique
- **Purpose**: File content manipulation
- **Operations**: NEW_FILE, INSERT_LINES, REMOVE_LINES, REPLACE_LINES
**TASK_COMPLETE**: Signal successful task completion
- **Type**: User-visible, unique, returning
- **Purpose**: Task termination with summary
- **Output**: Markdown-formatted completion report
**HELP_NEEDED**: Request human assistance
- **Type**: User-visible, unique, returning
- **Purpose**: Escalation when agent is blocked
- **Format**: Structured problem description with blocker, attempts, suggestions
**AGENT_TEXT_RESPONSE**: Provide informational responses
- **Type**: User-visible, unique, returning
- **Purpose**: Answer questions or provide intermediate results
- **Format**: Markdown-formatted text responses
**READ_MIME_FILES**: Analyze multimedia content
- **Type**: Non-visible, non-unique
- **Purpose**: Process images, PDFs, videos using multimodal AI
- **Capabilities**: Local files, YouTube links, content analysis
#### Action Execution Flow
1. **Prompt Construction**: Actions provide guide_prompt text for LLM instruction
2. **Response Parsing**: Agent response is validated against available actions
3. **Action Dispatch**: Appropriate action handler is called with parsed parameters
4. **Event Creation**: Action results are stored as events in the event stream
5. **State Management**: Event stream is updated and persisted
6. **Flow Control**: Returning actions terminate the execution loop
```python
def _prefict_next_event_and_handle_actions(self, event_stream, run_config):
# Get LLM response with action selection
parsed_response_dict = self._prompt_and_get_action_from_response(event_stream)
# Build action registry
registered_actions_dict = {ra.type.lower(): ra for ra in self.registered_actions}
called_actions_json = parsed_response_dict.get("actions", [])
# Handle returning actions (terminate loop)
first_action = registered_actions_dict[called_actions_json[0].get("action_type").lower()]
if first_action.returning_action:
return first_action.handle_action_in_parsed_response(run_config, parsed_response_dict, called_actions_json[0])
# Execute all non-returning actions
for action_json in called_actions_json:
action = registered_actions_dict.get(action_json.get("action_type").lower())
action.handle_action_in_parsed_response(run_config, parsed_response_dict, action_json)
return None # Continue execution loop
```
#### Action Extensibility
New actions can be easily added by:
1. **Inheriting from Action**: Implement the base class interface
2. **Defining Guide Prompts**: Provide clear LLM instructions
3. **Implementing Handlers**: Define action execution logic
4. **Registering Actions**: Add to agent's action registry
### Prompt Construction
The prompt construction system builds contextual prompts from event history, enabling agents to maintain awareness of previous actions and current state.
#### Prompt Template System
Prompts are built using a template-based approach:
```python
def construct_prompt_for_event_stream(event_stream, prompt_template=None, agent_config=None):
# Build event history string
event_stream_string = construct_events_str_with_summary(event_stream, agent_config=agent_config)
# Replace template placeholders
prompt = prompt_template.replace("PLACEHOLDER_EVENT_STREAM", event_stream_string)
# Add context-specific instructions
if event_stream.events_list and event_stream.events_list[-1].type == "edit_file":
prompt += "\n<!!The last event was a file editing operation...>"
return prompt
```
#### Event History Formatting
Events are formatted into structured text for LLM consumption:
```
## Event 1 TYPE: NEW_REQUEST
REASONING:
[Agent's reasoning for this action]
CONTENT:
[Event content - command output, file changes, etc.]
## Event 2 TYPE: ACTION
REASONING:
[Why this command was executed]
CONTENT:
[Command output and results]
```
#### Content Management
**Truncation Strategy**: Long content is truncated for older events while preserving recent context
- **Recent Events**: Full content preserved (configurable threshold)
- **Older Events**: Truncated with "...N lines omitted..." indicators
- **Summaries**: Replace ranges of events with AI-generated summaries
**Summary Integration**: Event summaries are seamlessly integrated into the prompt:
```
## Summary of Events 5 to 12
[AI-generated summary of actions and results]
## Event 13 TYPE: ACTION
[Current event details]
```
#### Template Placeholders
**PLACEHOLDER_EVENT_STREAM**: Replaced with formatted event history
**PLACEHOLDER_ACTION_INSTRUCTIONS**: Replaced with available action documentation
Example template structure:
```
# INSTRUCTION
You are an AI agent...
# EVENT STREAM
PLACEHOLDER_EVENT_STREAM
# AVAILABLE ACTIONS
PLACEHOLDER_ACTION_INSTRUCTIONS
```
#### Context Optimization
**Dynamic Content Limits**: Adjustable based on:
- Model context window size
- Task complexity requirements
- Performance considerations
**Intelligent Summarization**: Automatic summarization triggers:
- Task completion events
- Consecutive action thresholds
- Content length limits
**State Preservation**: Critical state information is preserved across summarization:
- Current working directory
- Active file modifications
- Error conditions
- User preferences
### Configuration Management
- `--port`: Port number (default: 5000)
- `--password`: Access password (required)
### Web Interface
The web interface provides a browser-based chat interface for remote agent interaction.
#### Starting the Web Interface
```bash
anges ui --port 5000 --password your_secure_password
```
#### Access Methods
- **Local**: `http://localhost:5000`
- **Remote**: `http://your_server_ip:5000`
#### Security Features
- Password-protected access
- HTTPS communication
- Secure session management with Flask-Login
- Remote access capabilities with proper authentication
#### Interface Features
- Real-time chat interface
- Task progress monitoring
- Command execution visibility
- Session management
- Multi-request support
### Migration from Legacy Interfaces
The unified CLI replaces previous separate interfaces:
| Legacy Command | New Unified Command |
|----------------|--------------------|
| `python run_web_interface.py --password pass --port 5005` | `anges ui --password pass --port 5005` |
| `python -m anges.cli_interface.cli_runner --input-file=task.txt` | `anges -f task.txt` |
*[Additional implementation details to be expanded in subsequent sub-tasks]*
## Examples
### Basic Operations
#### Interactive Task Execution
```bash
anges
# Prompt: Please enter the task description:
# Input: List all files in the current directory
```
#### Direct Task with Custom Configuration
```bash
anges -q "Find all Python files larger than 1MB" --model openai --path /project
```
#### File-Based Task Execution
```bash
# Create task file
echo "Analyze disk usage and clean up temporary files" > cleanup_task.txt
anges -f cleanup_task.txt
```
### Advanced Usage
#### Custom Agent and Model Selection
```bash
anges --agent task_analyzer --model claude --logging debug
```
#### Web Interface with Custom Configuration
```bash
anges ui --host 0.0.0.0 --port 8080 --password secure_password_123
```
#### Continuing Previous Sessions
```bash
anges --existing_stream_id previous_session_id
```
### Real-World Scenarios
#### Default Agent Usage
**Basic Default Agent Example**
```python
#!/usr/bin/env python3
"""Example: Using Default Agent for file system operations"""
from anges.agents.default_agent import DefaultAgent
from anges.agents.agent_utils.events import Event
import logging
# Create a default agent instance
agent = DefaultAgent(
cmd_init_dir="/home/user/projects",
prefix_cmd="",
logging_level=logging.INFO,
auto_entitle=True
)
# Execute a simple task
task_description = "List all Python files in the current directory and show their sizes"
print(f"Executing task: {task_description}")
# Add the task as a new request event
event = Event(event_type="NEW_REQUEST", content=task_description)
agent.event_stream.add_event(event)
# Run the agent
result = agent.run()
print(f"Task completed with status: {agent.status}")
# Access the event stream to see what happened
for event in agent.event_stream.events:
print(f"Event: {event.event_type} - {event.content[:100]}...")
```
**Default Agent with Custom Configuration**
```python
#!/usr/bin/env python3
"""Example: Default Agent with custom settings and error handling"""
from anges.agents.default_agent import DefaultAgent
from anges.agents.agent_utils.events import Event, EventStream
from anges.utils.inference_api import INFERENCE_FUNC_DICT
import logging
def interrupt_check():
"""Custom interrupt check function"""
# Add your custom interrupt logic here
return False
# Create agent with custom configuration
agent = DefaultAgent(
cmd_init_dir="/tmp/workspace",
prefix_cmd="sudo", # Run commands with sudo
interrupt_check=interrupt_check,
max_consecutive_actions_to_summarize=5,
logging_level=logging.DEBUG,
auto_entitle=False
)
# Complex file management task
task = """
Create a backup directory structure:
1. Create /tmp/backup/logs and /tmp/backup/configs
2. Copy all .log files from /var/log to /tmp/backup/logs
3. Create a summary report of copied files
4. Set appropriate permissions (755 for directories, 644 for files)
"""
try:
# Add task event
event = Event(event_type="NEW_REQUEST", content=task)
agent.event_stream.add_event(event)
# Execute the task
result = agent.run()
if agent.status == "completed":
print("✅ Backup task completed successfully")
# Save the event stream for later analysis
from anges.utils.data_handler import save_event_stream
save_event_stream(agent.event_stream, "backup_task_log.json")
else:
print(f"❌ Task failed with status: {agent.status}")
except Exception as e:
print(f"Error executing task: {e}")
# Handle errors gracefully
```
#### Orchestrator Usage
**Basic Orchestrator Example**
```python
#!/usr/bin/env python3
"""Example: Using Orchestrator for complex multi-step workflows"""
from anges.agents.orchestrator import Orchestrator
from anges.agents.agent_utils.events import Event
from anges.agents.agent_utils.agent_factory import AgentFactory, AgentConfig
import logging
# Create orchestrator with custom configuration
orchestrator = Orchestrator(
cmd_init_dir="/home/user/development",
remaining_recursive_depth=3, # Allow 3 levels of sub-agents
max_consecutive_actions_to_summarize=10,
logging_level=logging.INFO,
auto_entitle=True
)
# Complex development workflow task
complex_task = """
Set up a new Python project with the following requirements:
1. Create project directory structure (src/, tests/, docs/, requirements/)
2. Initialize git repository
3. Create virtual environment and activate it
4. Install development dependencies (pytest, black, flake8)
5. Create basic project files (setup.py, README.md, .gitignore)
6. Run initial code quality checks
7. Create first commit with initial project structure
"""
print("Starting complex project setup workflow...")
# Add the complex task
event = Event(event_type="NEW_REQUEST", content=complex_task)
orchestrator.event_stream.add_event(event)
# Execute the workflow
result = orchestrator.run()
print(f"Workflow completed with status: {orchestrator.status}")
# The orchestrator automatically manages sub-agents and coordinates the workflow
print(f"Total events processed: {len(orchestrator.event_stream.events)}")
print(f"Orchestrator UID: {orchestrator.uid}")
```
**Advanced Orchestrator with Agent Factory**
```python
#!/usr/bin/env python3
"""Example: Advanced Orchestrator usage with AgentFactory"""
from anges.agents.agent_utils.agent_factory import AgentFactory, AgentConfig, AgentType
from anges.agents.agent_utils.events import Event
from anges.utils.data_handler import save_event_stream, read_event_stream
import logging
import os
def setup_monitoring_system():
"""Set up a comprehensive monitoring system using Orchestrator"""
# Create agent configuration
config = AgentConfig(
agent_type=AgentType.ORCHESTRATOR.value,
cmd_init_dir=os.getcwd(),
prefix_cmd="",
logging_level=logging.INFO,
auto_entitle=True,
remaining_recursive_depth=4,
orchestrator_config={
'remaining_recursive_depth': 4,
'max_consecutive_actions_to_summarize': 15
}
)
# Create orchestrator using factory
factory = AgentFactory()
orchestrator = factory.create_agent(config)
# Complex monitoring setup task
monitoring_task = """
Set up a comprehensive system monitoring solution:
Phase 1: System Metrics Collection
- Install and configure system monitoring tools (htop, iotop, nethogs)
- Set up log rotation for system logs
- Create custom scripts to collect CPU, memory, and disk metrics
Phase 2: Log Analysis Setup
- Configure centralized logging
- Set up log parsing and analysis tools
- Create alerting rules for critical system events
Phase 3: Dashboard and Reporting
- Generate system health reports
- Create automated daily/weekly summary emails
- Set up real-time monitoring dashboard
Phase 4: Automation and Maintenance
- Create cron jobs for regular maintenance tasks
- Set up automated cleanup procedures
- Configure backup verification and reporting
"""
print("🚀 Starting comprehensive monitoring system setup...")
# Add the complex task
event = Event(event_type="NEW_REQUEST", content=monitoring_task)
orchestrator.event_stream.add_event(event)
# Execute the comprehensive workflow
try:
result = orchestrator.run()
if orchestrator.status == "completed":
print("✅ Monitoring system setup completed successfully!")
# Save detailed execution log
log_file = f"monitoring_setup_{orchestrator.uid}.json"
save_event_stream(orchestrator.event_stream, log_file)
print(f"📝 Execution log saved to: {log_file}")
# Print summary of actions taken
action_count = sum(1 for event in orchestrator.event_stream.events
if event.event_type == "ACTION")
print(f"📊 Total actions executed: {action_count}")
else:
print(f"❌ Setup failed with status: {orchestrator.status}")
except Exception as e:
print(f"💥 Error during setup: {e}")
return orchestrator
if __name__ == "__main__":
orchestrator = setup_monitoring_system()
```
#### Development Environment Setup
```python
#!/usr/bin/env python3
"""Example: Automated development environment setup"""
from anges.agents.agent_utils.agent_factory import AgentFactory, AgentConfig
from anges.agents.agent_utils.events import Event
def setup_dev_environment(project_name: str, tech_stack: str):
"""Set up a complete development environment for a new project"""
# Use orchestrator for complex setup
config = AgentConfig(
agent_type="orchestrator",
cmd_init_dir=f"/home/user/projects",
auto_entitle=True,
remaining_recursive_depth=3
)
factory = AgentFactory()
agent = factory.create_agent(config)
setup_task = f"""
Create a complete {tech_stack} development environment for project '{project_name}':
1. Project Structure:
- Create project directory: {project_name}
- Set up standard directory structure
- Initialize version control (git)
2. Environment Setup:
- Create and configure virtual environment
- Install base dependencies for {tech_stack}
- Set up development tools (linting, formatting, testing)
3. Configuration Files:
- Create appropriate config files (.gitignore, requirements.txt, etc.)
- Set up CI/CD configuration templates
- Create development documentation templates
4. Initial Code:
- Create basic project structure with example code
- Set up testing framework with sample tests
- Create initial documentation
5. Verification:
- Run initial tests to verify setup
- Check code quality tools are working
- Validate all dependencies are correctly installed
"""
event = Event(event_type="NEW_REQUEST", content=setup_task)
agent.event_stream.add_event(event)
print(f"🔧 Setting up {tech_stack} development environment for '{project_name}'...")
result = agent.run()
return agent.status == "completed"
# Example usage
if __name__ == "__main__":
success = setup_dev_environment("my-web-app", "Python Flask")
if success:
print("✅ Development environment setup completed!")
else:
print("❌ Setup failed. Check logs for details.")
```
#### Log Analysis and Monitoring
```python
#!/usr/bin/env python3
"""Example: Automated log analysis and monitoring"""
from anges.agents.default_agent import DefaultAgent
from anges.agents.agent_utils.events import Event
import logging
from datetime import datetime
def analyze_system_logs():
"""Analyze system logs for issues and generate reports"""
agent = DefaultAgent(
cmd_init_dir="/var/log",
logging_level=logging.INFO,
auto_entitle=True
)
analysis_task = f"""
Perform comprehensive system log analysis for {datetime.now().strftime('%Y-%m-%d')}:
1. Error Detection:
- Scan system logs for ERROR, CRITICAL, and FATAL messages
- Identify recurring error patterns
- Extract relevant timestamps and context
2. Security Analysis:
- Check authentication logs for failed login attempts
- Look for suspicious network activity
- Identify potential security threats
3. Performance Monitoring:
- Analyze resource usage patterns
- Identify performance bottlenecks
- Check for memory or disk space issues
4. Report Generation:
- Create summary report with findings
- Generate recommendations for issues found
- Save detailed analysis to /tmp/log_analysis_report.txt
5. Alerting:
- If critical issues found, create alert file
- Prepare notification content for system administrators
"""
event = Event(event_type="NEW_REQUEST", content=analysis_task)
agent.event_stream.add_event(event)
print("📊 Starting system log analysis...")
result = agent.run()
if agent.status == "completed":
print("✅ Log analysis completed successfully")
return True
else:
print(f"❌ Log analysis failed: {agent.status}")
return False
if __name__ == "__main__":
analyze_system_logs()
```
#### Performance Optimization Workflows
```python
#!/usr/bin/env python3
"""Example: Automated performance optimization workflow"""
from anges.agents.orchestrator import Orchestrator
from anges.agents.agent_utils.events import Event
import logging
def optimize_system_performance():
"""Run comprehensive system performance optimization"""
orchestrator = Orchestrator(
cmd_init_dir="/",
remaining_recursive_depth=3,
logging_level=logging.INFO,
auto_entitle=True
)
optimization_task = """
Perform comprehensive system performance optimization:
Phase 1: System Analysis
- Analyze current system performance metrics
- Identify resource bottlenecks (CPU, memory, disk, network)
- Check running processes and services
- Analyze system startup time and services
Phase 2: Cleanup Operations
- Clean temporary files and caches
- Remove old log files and rotate current ones
- Clean package manager caches
- Remove orphaned packages and dependencies
Phase 3: Configuration Optimization
- Optimize system swappiness settings
- Configure I/O scheduler for better performance
- Adjust network buffer sizes if needed
- Optimize filesystem mount options
Phase 4: Service Optimization
- Disable unnecessary startup services
- Optimize database configurations if present
- Configure web server settings for better performance
- Set up proper caching mechanisms
Phase 5: Monitoring Setup
- Install performance monitoring tools
- Set up automated performance tracking
- Create performance baseline measurements
- Schedule regular optimization maintenance
Phase 6: Verification and Reporting
- Run performance benchmarks before and after
- Generate detailed optimization report
- Create recommendations for future improvements
- Set up alerting for performance degradation
"""
event = Event(event_type="NEW_REQUEST", content=optimization_task)
orchestrator.event_stream.add_event(event)
print("🚀 Starting system performance optimization workflow...")
result = orchestrator.run()
return orchestrator.status == "completed"
if __name__ == "__main__":
success = optimize_system_performance()
if success:
print("✅ Performance optimization completed!")
else:
print("❌ Optimization workflow failed.")
```
---
*This documentation is part of an ongoing improvement initiative. Additional technical details, architecture diagrams, and comprehensive examples will be added in subsequent updates.*
Raw data
{
"_id": null,
"home_page": "https://github.com/anges-ai/anges",
"name": "anges",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.8",
"maintainer_email": null,
"keywords": "ai, agent, orchestration, automation, framework, llm, openai, anthropic, google, vertexai, workflow, event-driven, multi-agent, assistant, custom-actions, plugin-system, ai-automation",
"author": "Anges Team",
"author_email": "me@anges.ai",
"download_url": "https://files.pythonhosted.org/packages/1e/38/62f5040441dae76e489761b2e509ec0587fd94432c0b92b678de7fc12c34/anges-0.1.0.tar.gz",
"platform": null,
"description": "# Anges: An Open Source Autonomous Engineering Assistant\n\nAnges is an LLM powered engineering agent system designed to be easy to use, but also highly customizable and minimalist.\n\n## Quick Start\n\n### Installation & First Run\n\n```bash\n# Install from PyPI\npip install anges\n\n# Set your API key. Anges defaults to using Anthropic's Claude.\n# (See configuration below to use other models like Gemini or OpenAI)\nexport ANTHROPIC_API_KEY=<YOUR_API_KEY_HERE>\n\n# Run your first task\nanges -q \"What is the OS version?\"\n```\n\n### Basic Usage\n\n```bash\n# Interactive mode (for conversational tasks)\nanges -i\n\n# Direct task execution from the command line\nanges -q \"List all python files in the current directory.\"\n\n# Execute a task described in a file\nanges -f task_description.txt\n\n# Launch the web interface\nanges ui --port 5000 --password your_password\n\n# Help menu\nanges -h\n```\n\n*A quick demonstration of Anges checking the OS and listing files.*\n\n\n*A quick look of Anges UI.*\n\n\n### Configurations\n\nThe default configuration is located at `anges/configs/default_config.yaml`.\n\nYou can override these settings by creating a `config.yaml` file at `~/.anges/config.yaml`.\n\nFor example, to configure the default agent to use Google's Gemini Pro:\n\n```bash\n# Create the config file to switch the default model\ncat > ~/.anges/config.yaml <<EOF\nagents:\n default_agent:\n model_name: \"gemini/gemini-1.5-pro-latest\"\nEOF\n\n# Export the corresponding API key\nexport GOOGLE_API_KEY=<YOUR_GEMINI_API_KEY>\n```\n\n### Advanced usages\n\n * **Working Directory:** You can set the agent's working directory from the UI or CLI. This sets the default location for operations but does not enforce a strict permission boundary.\n\n * **Prefix Command:** You can configure a prefix command (e.g., `export MY_VAR=... &&`) that will be executed before every command the agent runs. This is useful for setting up a consistent environment.\n\n * **Default Agent vs. Orchestrator:**\n\n * **Default Agent:** Ideal for simple, single-step tasks that a human could complete in a few minutes. It's fast and direct.\n * **Orchestrator:** For complex, multi-step problems that require research, planning, and code iteration. The orchestrator agent can break down the task and delegate to other agents.\n\n * **Event Streams:** Every action, thought process, and command is logged as a JSON file in `~/.anges/data/event_streams`. This provides full transparency and creates a valuable dataset for fine-tuning or analysis.\n\n### Demos & Examples\n\n * [Linux and Cloud Ops](https://demo.anges.ai/?chatId=QIVELO41)\n * [Creating a Demo Website](https://demo.anges.ai/?chatId=dCg8a13M)\n * [Solving a Complex Task (3-hour run)](https://demo.anges.ai/?chatId=atktkEDt)\n * [Recursive Self-Invocation Testing](https://demo.anges.ai/?chatId=pyA5pYEm)\n\nExplore more demos at **[https://demo.anges.ai](https://demo.anges.ai)**.\n\n\n## Why Anges?\n\n| Feature | **Anges** | **Gemini CLI** | **Cursor** |\n| :--- | :--- | :--- | :--- |\n| **Open Source** | \u2705 Yes (MIT) | \u2705 Yes (Apache-2.0) | \u274c No |\n| **CLI Support** | \u2705 Yes | \u2705 Yes | \u2705 Yes |\n| **Web UI** | \u2705 Yes | \u274c No | \u274c No |\n| **Mobile Web Access** | \u2705 Yes | \u274c No | \u274c No |\n| **Hackable & Customizable** | \u2705 Flexible (Python) | \u26a0\ufe0f Forkable | \u274c Minified |\n| **Multi-Agent Orchestration**| \u2705 Yes | \u274c No | \u274c No |\n| **Model Agnostic** | \u2705 Any Model | \u274c Gemini Only | \u274c Claude/OpenAI |\n\n### From Advisor to Assistant\n\nWe're used to LLMs being advisors\u2014they sit behind a chat box, waiting for copy-pasted context and offering suggestions you still have to run yourself.\n\nBut what if you gave an AI **real access** to your shell, tools, and working environment? What if it could **work alongside you**, not just talk to you?\n\nAnges turns that idea into a practical, hackable reality, giving LLMs controlled execution power while keeping engineers fully in the loop.\n\n### Key Benefits\n\n * **Real Automation, Not Just Advice**\n Anges doesn\u2019t just suggest commands\u2014it runs them. It reads output, handles errors, and plans its next move. It's a doer, not a talker.\n\n * **Model Agnostic**\n Use any model you want\u2014Claude, OpenAI, Gemini, Llama, local models\u2014all are easily configurable. You control the brain.\n\n * **Flexible Interfaces**\n Work from your terminal, in a container, or through the web UI on your phone. Anges meets you where you are.\n\n * **Hackable by Design**\n Written in clean, modular Python. Everything is exposed and easy to modify. There are no heavy abstractions hiding the prompts or logic.\n\n * **Built-in Orchestration**\n Tackle complex tasks with a multi-agent system that can decompose problems, delegate work, and execute recursively\u2014with zero boilerplate.\n\n * **Transparent Event Logs**\n Every command, decision, and observation is saved to a local event stream. You have a perfect, replayable audit trail of the agent's work.\n\n### Use Cases\n\n * **As an Engineering Assistant**\n Ask it to install packages, inspect logs, restart services, or modify configuration files\u2014all within a single, natural language query.\n\n * **For DevOps & Maintenance**\n Automate infrastructure chores like updating dependencies, cleaning up disk space, or managing your local development environment.\n\n * **For Data & File Workflows**\n Let it move, rename, clean, or parse files. Have it pipe commands together to build quick data pipelines without writing scripts.\n\n * **For Learning & Debugging**\n Watch how the agent breaks down a task and plans its execution. It\u2019s a great way to learn new system tools or understand complex commands.\n\n * **To Build Custom Domain Agents**\n Need an agent that knows your specific codebase, product, or workflow? Fork Anges, wire in your custom logic, and create a specialized assistant.\n\n## Core Design Concepts\n\n### Architecture Overview\n\nAnges follows a modular, event-driven architecture with distinct components for task interpretation, command generation, execution management, and result processing. The framework is built around four core concepts:\n\n1. **BaseAgent Lifecycle**: Manages agent creation, initialization, and execution flow\n2. **Event Stream**: Provides persistent state management and execution history\n3. **Action System**: Defines extensible actions for agent capabilities\n4. **Prompt Construction**: Builds contextual prompts from event history\n\n### BaseAgent Lifecycle\n\nThe BaseAgent class serves as the foundation for all agent types in Anges, managing the complete lifecycle from initialization to task completion.\n\n#### Agent Initialization\n\n```python\nclass BaseAgent:\n def __init__(\n self,\n parent_ids=[],\n inference_func=None,\n event_stream=None,\n cmd_init_dir=config.agents.default_agent.cmd_init_dir,\n prefix_cmd=\"\",\n interrupt_check=None,\n max_consecutive_actions_to_summarize=30,\n logging_level=logging.DEBUG,\n auto_entitle=False,\n ):\n```\n\n**Key Initialization Components:**\n- **Event Stream**: Creates or inherits an EventStream for state persistence\n- **Inference Function**: LLM integration for decision making\n- **Execution Context**: Working directory and command prefix configuration\n- **Interrupt Handling**: Optional callback for graceful task interruption\n- **Summarization**: Automatic event summarization for long conversations\n\n#### Execution Flow\n\nThe agent follows a structured execution loop:\n\n1. **Request Handling**: Processes new or follow-up requests\n2. **Event Creation**: Adds request events to the event stream\n3. **Decision Loop**: Continuously prompts LLM and executes actions until completion\n4. **Interruption Checks**: Monitors for user interrupts or execution limits\n5. **State Persistence**: Saves event stream after each significant action\n\n```python\ndef run_with_new_request(self, task_description, event_stream=None):\n # Initialize run configuration\n run_config = self._build_run_config(task_description, event_stream)\n \n # Add new request to event stream\n self._handle_received_new_request(run_config)\n \n while True:\n # Check for interruptions\n if self._check_interruption(run_config):\n return event_stream\n \n # Check execution limits\n if self._check_exhausted(run_config):\n return event_stream\n \n # Get next action and execute\n if self._prefict_next_event_and_handle_actions(event_stream, run_config):\n return event_stream\n```\n\n### Event Stream System\n\nThe Event Stream provides persistent state management and execution history, enabling agents to maintain context across complex, multi-step tasks.\n\n#### Event Structure\n\nEach event captures a discrete action or state change:\n\n```python\nclass Event:\n def __init__(self, type, reasoning=\"\", content=\"\", title=None, \n message=\"\", analysis=\"\", est_input_token=0, est_output_token=0):\n self.type = type # Event classification\n self.reasoning = reasoning # Agent's reasoning (visible in history)\n self.content = content # Event content/results\n self.message = message # User-visible message\n self.analysis = analysis # Internal analysis (not shown to user)\n self.created_at = datetime.now()\n```\n\n**Event Types:**\n- `new_request` / `follow_up_request`: User task requests\n- `action`: Shell command execution\n- `edit_file`: File modification operations\n- `task_completion`: Successful task completion\n- `task_interrupted`: Task interruption or failure\n- `agent_requested_help`: Agent requesting human assistance\n- `agent_text_response`: Agent providing informational responses\n\n#### EventStream Management\n\n```python\nclass EventStream:\n def __init__(self, title=None, uid=None, parent_event_stream_uids=None, agent_type=\"\"):\n self.events_list = [] # Chronological event sequence\n self.event_summaries_list = [] # Summarized event ranges\n self.uid = uid # Unique stream identifier\n self.parent_event_stream_uids = parent_event_stream_uids # Hierarchical relationships\n self.agent_settings = {} # Persistent agent configuration\n```\n\n**Key Features:**\n- **Persistence**: Automatic JSON serialization to disk\n- **Hierarchical Structure**: Support for parent-child agent relationships\n- **Event Summarization**: Automatic summarization of long event sequences\n- **Settings Management**: Persistent storage of agent configuration\n\n#### Event Summarization\n\nTo manage long conversations, the system automatically summarizes events:\n\n- **Task Completion Summaries**: Generated when tasks complete\n- **Action Aggregation**: Summarizes sequences of related actions\n- **Configurable Thresholds**: Customizable summarization triggers\n\n### Agent Types\n\nThe system supports multiple agent types optimized for different scenarios:\n\n#### Default Agent\n**Purpose**: General-purpose task execution with full action capabilities\n**Use Cases**: Complex multi-step tasks, file operations, system administration\n**Actions**: All available actions (shell commands, file editing, help requests)\n\n#### Task Executor\n**Purpose**: Focused command execution with minimal overhead\n**Use Cases**: Simple command execution, quick operations\n**Actions**: Primarily shell commands and basic responses\n\n#### Task Analyzer\n**Purpose**: Task decomposition and analysis without execution\n**Use Cases**: Planning, task breakdown, requirement analysis\n**Actions**: Text responses, analysis outputs\n\n#### Orchestrator\n**Purpose**: Complex workflow management with child agent coordination\n**Use Cases**: Multi-agent workflows, complex project management\n**Actions**: Child agent spawning, workflow coordination\n\n### Model Integration\n\nFlexible LLM integration supporting multiple providers with consistent interfaces and fallback mechanisms.\n\n#### Supported Providers\n- **Claude (Anthropic)**: Primary recommendation for complex reasoning\n- **OpenAI GPT**: Broad compatibility and performance\n- **Google Gemini**: Alternative provider with competitive capabilities\n\n#### Integration Architecture\n```python\nINFERENCE_FUNC_DICT = {\n 'claude': claude_inference,\n 'openai': openai_inference, \n 'gemini': gemini_inference\n}\n```\n\n**Features:**\n- **Unified Interface**: Consistent API across all providers\n- **Configuration Management**: YAML-based model configuration\n- **Error Handling**: Graceful fallback and retry mechanisms\n- **Token Estimation**: Usage tracking and optimization\n\n### Safety and Control\n\nBuilt-in safeguards for command validation, execution monitoring, and error handling.\n\n#### Execution Safeguards\n- **Command Timeouts**: Configurable execution time limits\n- **Working Directory Control**: Isolated execution environments\n- **Command Prefixing**: Automatic command modification for safety\n- **Interrupt Handling**: Graceful task termination\n\n#### Error Management\n- **Comprehensive Logging**: Detailed execution tracking\n- **Error Recovery**: Automatic retry and fallback mechanisms\n- **State Persistence**: Recovery from unexpected failures\n- **User Notifications**: Clear error communication\n## Implementation Details\n\n### Command Line Interface\n\nAnges provides a unified CLI with multiple operation modes:\n\n#### Interactive Mode\n```bash\nanges [options]\n```\n### Action System\n\nThe Action system provides a modular, extensible framework for defining agent capabilities through discrete, composable actions.\n\n#### Action Architecture\n\nAll actions inherit from the base Action class:\n\n```python\nclass Action:\n def __init__(self):\n self.type = \"\" # Action identifier\n self.guide_prompt = \"\" # LLM instruction text\n self.user_visible = False # Whether action results are shown to user\n self.unique_action = False # Whether action must be used alone\n self.returning_action = False # Whether action terminates the execution loop\n\n def handle_action_in_parsed_response(self, run_config, parsed_response_dict, action_json):\n raise NotImplementedError(\"Subclasses must implement this method\")\n```\n\n#### Built-in Actions\n\n**RUN_SHELL_CMD**: Execute shell commands with timeout and background support\n- **Type**: Non-visible, non-unique\n- **Purpose**: System command execution\n- **Features**: Timeout control, background execution, output capture\n\n**EDIT_FILE**: Structured file operations (create, insert, replace, remove)\n- **Type**: Non-visible, non-unique \n- **Purpose**: File content manipulation\n- **Operations**: NEW_FILE, INSERT_LINES, REMOVE_LINES, REPLACE_LINES\n\n**TASK_COMPLETE**: Signal successful task completion\n- **Type**: User-visible, unique, returning\n- **Purpose**: Task termination with summary\n- **Output**: Markdown-formatted completion report\n\n**HELP_NEEDED**: Request human assistance\n- **Type**: User-visible, unique, returning\n- **Purpose**: Escalation when agent is blocked\n- **Format**: Structured problem description with blocker, attempts, suggestions\n\n**AGENT_TEXT_RESPONSE**: Provide informational responses\n- **Type**: User-visible, unique, returning\n- **Purpose**: Answer questions or provide intermediate results\n- **Format**: Markdown-formatted text responses\n\n**READ_MIME_FILES**: Analyze multimedia content\n- **Type**: Non-visible, non-unique\n- **Purpose**: Process images, PDFs, videos using multimodal AI\n- **Capabilities**: Local files, YouTube links, content analysis\n\n#### Action Execution Flow\n\n1. **Prompt Construction**: Actions provide guide_prompt text for LLM instruction\n2. **Response Parsing**: Agent response is validated against available actions\n3. **Action Dispatch**: Appropriate action handler is called with parsed parameters\n4. **Event Creation**: Action results are stored as events in the event stream\n5. **State Management**: Event stream is updated and persisted\n6. **Flow Control**: Returning actions terminate the execution loop\n\n```python\ndef _prefict_next_event_and_handle_actions(self, event_stream, run_config):\n # Get LLM response with action selection\n parsed_response_dict = self._prompt_and_get_action_from_response(event_stream)\n \n # Build action registry\n registered_actions_dict = {ra.type.lower(): ra for ra in self.registered_actions}\n called_actions_json = parsed_response_dict.get(\"actions\", [])\n \n # Handle returning actions (terminate loop)\n first_action = registered_actions_dict[called_actions_json[0].get(\"action_type\").lower()]\n if first_action.returning_action:\n return first_action.handle_action_in_parsed_response(run_config, parsed_response_dict, called_actions_json[0])\n \n # Execute all non-returning actions\n for action_json in called_actions_json:\n action = registered_actions_dict.get(action_json.get(\"action_type\").lower())\n action.handle_action_in_parsed_response(run_config, parsed_response_dict, action_json)\n \n return None # Continue execution loop\n```\n\n#### Action Extensibility\n\nNew actions can be easily added by:\n1. **Inheriting from Action**: Implement the base class interface\n2. **Defining Guide Prompts**: Provide clear LLM instructions\n3. **Implementing Handlers**: Define action execution logic\n4. **Registering Actions**: Add to agent's action registry\n\n### Prompt Construction\n\nThe prompt construction system builds contextual prompts from event history, enabling agents to maintain awareness of previous actions and current state.\n\n#### Prompt Template System\n\nPrompts are built using a template-based approach:\n\n```python\ndef construct_prompt_for_event_stream(event_stream, prompt_template=None, agent_config=None):\n # Build event history string\n event_stream_string = construct_events_str_with_summary(event_stream, agent_config=agent_config)\n \n # Replace template placeholders\n prompt = prompt_template.replace(\"PLACEHOLDER_EVENT_STREAM\", event_stream_string)\n \n # Add context-specific instructions\n if event_stream.events_list and event_stream.events_list[-1].type == \"edit_file\":\n prompt += \"\\n<!!The last event was a file editing operation...>\"\n \n return prompt\n```\n\n#### Event History Formatting\n\nEvents are formatted into structured text for LLM consumption:\n\n```\n## Event 1 TYPE: NEW_REQUEST\nREASONING:\n[Agent's reasoning for this action]\nCONTENT:\n[Event content - command output, file changes, etc.]\n\n## Event 2 TYPE: ACTION \nREASONING:\n[Why this command was executed]\nCONTENT:\n[Command output and results]\n```\n\n#### Content Management\n\n**Truncation Strategy**: Long content is truncated for older events while preserving recent context\n- **Recent Events**: Full content preserved (configurable threshold)\n- **Older Events**: Truncated with \"...N lines omitted...\" indicators\n- **Summaries**: Replace ranges of events with AI-generated summaries\n\n**Summary Integration**: Event summaries are seamlessly integrated into the prompt:\n\n```\n## Summary of Events 5 to 12\n[AI-generated summary of actions and results]\n\n## Event 13 TYPE: ACTION\n[Current event details]\n```\n\n#### Template Placeholders\n\n**PLACEHOLDER_EVENT_STREAM**: Replaced with formatted event history\n**PLACEHOLDER_ACTION_INSTRUCTIONS**: Replaced with available action documentation\n\nExample template structure:\n```\n# INSTRUCTION\nYou are an AI agent...\n\n# EVENT STREAM\nPLACEHOLDER_EVENT_STREAM\n\n# AVAILABLE ACTIONS\nPLACEHOLDER_ACTION_INSTRUCTIONS\n```\n\n#### Context Optimization\n\n**Dynamic Content Limits**: Adjustable based on:\n- Model context window size\n- Task complexity requirements \n- Performance considerations\n\n**Intelligent Summarization**: Automatic summarization triggers:\n- Task completion events\n- Consecutive action thresholds\n- Content length limits\n\n**State Preservation**: Critical state information is preserved across summarization:\n- Current working directory\n- Active file modifications\n- Error conditions\n- User preferences\n\n### Configuration Management\n- `--port`: Port number (default: 5000)\n- `--password`: Access password (required)\n\n### Web Interface\n\nThe web interface provides a browser-based chat interface for remote agent interaction.\n\n#### Starting the Web Interface\n```bash\nanges ui --port 5000 --password your_secure_password\n```\n\n#### Access Methods\n- **Local**: `http://localhost:5000`\n- **Remote**: `http://your_server_ip:5000`\n\n#### Security Features\n- Password-protected access\n- HTTPS communication\n- Secure session management with Flask-Login\n- Remote access capabilities with proper authentication\n\n#### Interface Features\n- Real-time chat interface\n- Task progress monitoring\n- Command execution visibility\n- Session management\n- Multi-request support\n\n### Migration from Legacy Interfaces\n\nThe unified CLI replaces previous separate interfaces:\n\n| Legacy Command | New Unified Command |\n|----------------|--------------------|\n| `python run_web_interface.py --password pass --port 5005` | `anges ui --password pass --port 5005` |\n| `python -m anges.cli_interface.cli_runner --input-file=task.txt` | `anges -f task.txt` |\n\n*[Additional implementation details to be expanded in subsequent sub-tasks]*\n\n## Examples\n\n### Basic Operations\n\n#### Interactive Task Execution\n```bash\nanges\n# Prompt: Please enter the task description:\n# Input: List all files in the current directory\n```\n\n#### Direct Task with Custom Configuration\n```bash\nanges -q \"Find all Python files larger than 1MB\" --model openai --path /project\n```\n\n#### File-Based Task Execution\n```bash\n# Create task file\necho \"Analyze disk usage and clean up temporary files\" > cleanup_task.txt\nanges -f cleanup_task.txt\n```\n\n### Advanced Usage\n\n#### Custom Agent and Model Selection\n```bash\nanges --agent task_analyzer --model claude --logging debug\n```\n\n#### Web Interface with Custom Configuration\n```bash\nanges ui --host 0.0.0.0 --port 8080 --password secure_password_123\n```\n\n#### Continuing Previous Sessions\n```bash\nanges --existing_stream_id previous_session_id\n```\n\n### Real-World Scenarios\n\n#### Default Agent Usage\n\n**Basic Default Agent Example**\n```python\n#!/usr/bin/env python3\n\"\"\"Example: Using Default Agent for file system operations\"\"\"\n\nfrom anges.agents.default_agent import DefaultAgent\nfrom anges.agents.agent_utils.events import Event\nimport logging\n\n# Create a default agent instance\nagent = DefaultAgent(\n cmd_init_dir=\"/home/user/projects\",\n prefix_cmd=\"\",\n logging_level=logging.INFO,\n auto_entitle=True\n)\n\n# Execute a simple task\ntask_description = \"List all Python files in the current directory and show their sizes\"\nprint(f\"Executing task: {task_description}\")\n\n# Add the task as a new request event\nevent = Event(event_type=\"NEW_REQUEST\", content=task_description)\nagent.event_stream.add_event(event)\n\n# Run the agent\nresult = agent.run()\nprint(f\"Task completed with status: {agent.status}\")\n\n# Access the event stream to see what happened\nfor event in agent.event_stream.events:\n print(f\"Event: {event.event_type} - {event.content[:100]}...\")\n```\n\n**Default Agent with Custom Configuration**\n```python\n#!/usr/bin/env python3\n\"\"\"Example: Default Agent with custom settings and error handling\"\"\"\n\nfrom anges.agents.default_agent import DefaultAgent\nfrom anges.agents.agent_utils.events import Event, EventStream\nfrom anges.utils.inference_api import INFERENCE_FUNC_DICT\nimport logging\n\ndef interrupt_check():\n \"\"\"Custom interrupt check function\"\"\"\n # Add your custom interrupt logic here\n return False\n\n# Create agent with custom configuration\nagent = DefaultAgent(\n cmd_init_dir=\"/tmp/workspace\",\n prefix_cmd=\"sudo\", # Run commands with sudo\n interrupt_check=interrupt_check,\n max_consecutive_actions_to_summarize=5,\n logging_level=logging.DEBUG,\n auto_entitle=False\n)\n\n# Complex file management task\ntask = \"\"\"\nCreate a backup directory structure:\n1. Create /tmp/backup/logs and /tmp/backup/configs\n2. Copy all .log files from /var/log to /tmp/backup/logs\n3. Create a summary report of copied files\n4. Set appropriate permissions (755 for directories, 644 for files)\n\"\"\"\n\ntry:\n # Add task event\n event = Event(event_type=\"NEW_REQUEST\", content=task)\n agent.event_stream.add_event(event)\n \n # Execute the task\n result = agent.run()\n \n if agent.status == \"completed\":\n print(\"\u2705 Backup task completed successfully\")\n \n # Save the event stream for later analysis\n from anges.utils.data_handler import save_event_stream\n save_event_stream(agent.event_stream, \"backup_task_log.json\")\n \n else:\n print(f\"\u274c Task failed with status: {agent.status}\")\n \nexcept Exception as e:\n print(f\"Error executing task: {e}\")\n # Handle errors gracefully\n```\n\n#### Orchestrator Usage\n\n**Basic Orchestrator Example**\n```python\n#!/usr/bin/env python3\n\"\"\"Example: Using Orchestrator for complex multi-step workflows\"\"\"\n\nfrom anges.agents.orchestrator import Orchestrator\nfrom anges.agents.agent_utils.events import Event\nfrom anges.agents.agent_utils.agent_factory import AgentFactory, AgentConfig\nimport logging\n\n# Create orchestrator with custom configuration\norchestrator = Orchestrator(\n cmd_init_dir=\"/home/user/development\",\n remaining_recursive_depth=3, # Allow 3 levels of sub-agents\n max_consecutive_actions_to_summarize=10,\n logging_level=logging.INFO,\n auto_entitle=True\n)\n\n# Complex development workflow task\ncomplex_task = \"\"\"\nSet up a new Python project with the following requirements:\n1. Create project directory structure (src/, tests/, docs/, requirements/)\n2. Initialize git repository\n3. Create virtual environment and activate it\n4. Install development dependencies (pytest, black, flake8)\n5. Create basic project files (setup.py, README.md, .gitignore)\n6. Run initial code quality checks\n7. Create first commit with initial project structure\n\"\"\"\n\nprint(\"Starting complex project setup workflow...\")\n\n# Add the complex task\nevent = Event(event_type=\"NEW_REQUEST\", content=complex_task)\norchestrator.event_stream.add_event(event)\n\n# Execute the workflow\nresult = orchestrator.run()\n\nprint(f\"Workflow completed with status: {orchestrator.status}\")\n\n# The orchestrator automatically manages sub-agents and coordinates the workflow\nprint(f\"Total events processed: {len(orchestrator.event_stream.events)}\")\nprint(f\"Orchestrator UID: {orchestrator.uid}\")\n```\n\n**Advanced Orchestrator with Agent Factory**\n```python\n#!/usr/bin/env python3\n\"\"\"Example: Advanced Orchestrator usage with AgentFactory\"\"\"\n\nfrom anges.agents.agent_utils.agent_factory import AgentFactory, AgentConfig, AgentType\nfrom anges.agents.agent_utils.events import Event\nfrom anges.utils.data_handler import save_event_stream, read_event_stream\nimport logging\nimport os\n\ndef setup_monitoring_system():\n \"\"\"Set up a comprehensive monitoring system using Orchestrator\"\"\"\n \n # Create agent configuration\n config = AgentConfig(\n agent_type=AgentType.ORCHESTRATOR.value,\n cmd_init_dir=os.getcwd(),\n prefix_cmd=\"\",\n logging_level=logging.INFO,\n auto_entitle=True,\n remaining_recursive_depth=4,\n orchestrator_config={\n 'remaining_recursive_depth': 4,\n 'max_consecutive_actions_to_summarize': 15\n }\n )\n \n # Create orchestrator using factory\n factory = AgentFactory()\n orchestrator = factory.create_agent(config)\n \n # Complex monitoring setup task\n monitoring_task = \"\"\"\n Set up a comprehensive system monitoring solution:\n \n Phase 1: System Metrics Collection\n - Install and configure system monitoring tools (htop, iotop, nethogs)\n - Set up log rotation for system logs\n - Create custom scripts to collect CPU, memory, and disk metrics\n \n Phase 2: Log Analysis Setup\n - Configure centralized logging\n - Set up log parsing and analysis tools\n - Create alerting rules for critical system events\n \n Phase 3: Dashboard and Reporting\n - Generate system health reports\n - Create automated daily/weekly summary emails\n - Set up real-time monitoring dashboard\n \n Phase 4: Automation and Maintenance\n - Create cron jobs for regular maintenance tasks\n - Set up automated cleanup procedures\n - Configure backup verification and reporting\n \"\"\"\n \n print(\"\ud83d\ude80 Starting comprehensive monitoring system setup...\")\n \n # Add the complex task\n event = Event(event_type=\"NEW_REQUEST\", content=monitoring_task)\n orchestrator.event_stream.add_event(event)\n \n # Execute the comprehensive workflow\n try:\n result = orchestrator.run()\n \n if orchestrator.status == \"completed\":\n print(\"\u2705 Monitoring system setup completed successfully!\")\n \n # Save detailed execution log\n log_file = f\"monitoring_setup_{orchestrator.uid}.json\"\n save_event_stream(orchestrator.event_stream, log_file)\n print(f\"\ud83d\udcdd Execution log saved to: {log_file}\")\n \n # Print summary of actions taken\n action_count = sum(1 for event in orchestrator.event_stream.events \n if event.event_type == \"ACTION\")\n print(f\"\ud83d\udcca Total actions executed: {action_count}\")\n \n else:\n print(f\"\u274c Setup failed with status: {orchestrator.status}\")\n \n except Exception as e:\n print(f\"\ud83d\udca5 Error during setup: {e}\")\n \n return orchestrator\n\nif __name__ == \"__main__\":\n orchestrator = setup_monitoring_system()\n```\n\n#### Development Environment Setup\n\n```python\n#!/usr/bin/env python3\n\"\"\"Example: Automated development environment setup\"\"\"\n\nfrom anges.agents.agent_utils.agent_factory import AgentFactory, AgentConfig\nfrom anges.agents.agent_utils.events import Event\n\ndef setup_dev_environment(project_name: str, tech_stack: str):\n \"\"\"Set up a complete development environment for a new project\"\"\"\n \n # Use orchestrator for complex setup\n config = AgentConfig(\n agent_type=\"orchestrator\",\n cmd_init_dir=f\"/home/user/projects\",\n auto_entitle=True,\n remaining_recursive_depth=3\n )\n \n factory = AgentFactory()\n agent = factory.create_agent(config)\n \n setup_task = f\"\"\"\n Create a complete {tech_stack} development environment for project '{project_name}':\n \n 1. Project Structure:\n - Create project directory: {project_name}\n - Set up standard directory structure\n - Initialize version control (git)\n \n 2. Environment Setup:\n - Create and configure virtual environment\n - Install base dependencies for {tech_stack}\n - Set up development tools (linting, formatting, testing)\n \n 3. Configuration Files:\n - Create appropriate config files (.gitignore, requirements.txt, etc.)\n - Set up CI/CD configuration templates\n - Create development documentation templates\n \n 4. Initial Code:\n - Create basic project structure with example code\n - Set up testing framework with sample tests\n - Create initial documentation\n \n 5. Verification:\n - Run initial tests to verify setup\n - Check code quality tools are working\n - Validate all dependencies are correctly installed\n \"\"\"\n \n event = Event(event_type=\"NEW_REQUEST\", content=setup_task)\n agent.event_stream.add_event(event)\n \n print(f\"\ud83d\udd27 Setting up {tech_stack} development environment for '{project_name}'...\")\n result = agent.run()\n \n return agent.status == \"completed\"\n\n# Example usage\nif __name__ == \"__main__\":\n success = setup_dev_environment(\"my-web-app\", \"Python Flask\")\n if success:\n print(\"\u2705 Development environment setup completed!\")\n else:\n print(\"\u274c Setup failed. Check logs for details.\")\n```\n\n#### Log Analysis and Monitoring\n\n```python\n#!/usr/bin/env python3\n\"\"\"Example: Automated log analysis and monitoring\"\"\"\n\nfrom anges.agents.default_agent import DefaultAgent\nfrom anges.agents.agent_utils.events import Event\nimport logging\nfrom datetime import datetime\n\ndef analyze_system_logs():\n \"\"\"Analyze system logs for issues and generate reports\"\"\"\n \n agent = DefaultAgent(\n cmd_init_dir=\"/var/log\",\n logging_level=logging.INFO,\n auto_entitle=True\n )\n \n analysis_task = f\"\"\"\n Perform comprehensive system log analysis for {datetime.now().strftime('%Y-%m-%d')}:\n \n 1. Error Detection:\n - Scan system logs for ERROR, CRITICAL, and FATAL messages\n - Identify recurring error patterns\n - Extract relevant timestamps and context\n \n 2. Security Analysis:\n - Check authentication logs for failed login attempts\n - Look for suspicious network activity\n - Identify potential security threats\n \n 3. Performance Monitoring:\n - Analyze resource usage patterns\n - Identify performance bottlenecks\n - Check for memory or disk space issues\n \n 4. Report Generation:\n - Create summary report with findings\n - Generate recommendations for issues found\n - Save detailed analysis to /tmp/log_analysis_report.txt\n \n 5. Alerting:\n - If critical issues found, create alert file\n - Prepare notification content for system administrators\n \"\"\"\n \n event = Event(event_type=\"NEW_REQUEST\", content=analysis_task)\n agent.event_stream.add_event(event)\n \n print(\"\ud83d\udcca Starting system log analysis...\")\n result = agent.run()\n \n if agent.status == \"completed\":\n print(\"\u2705 Log analysis completed successfully\")\n return True\n else:\n print(f\"\u274c Log analysis failed: {agent.status}\")\n return False\n\nif __name__ == \"__main__\":\n analyze_system_logs()\n```\n\n#### Performance Optimization Workflows\n\n```python\n#!/usr/bin/env python3\n\"\"\"Example: Automated performance optimization workflow\"\"\"\n\nfrom anges.agents.orchestrator import Orchestrator\nfrom anges.agents.agent_utils.events import Event\nimport logging\n\ndef optimize_system_performance():\n \"\"\"Run comprehensive system performance optimization\"\"\"\n \n orchestrator = Orchestrator(\n cmd_init_dir=\"/\",\n remaining_recursive_depth=3,\n logging_level=logging.INFO,\n auto_entitle=True\n )\n \n optimization_task = \"\"\"\n Perform comprehensive system performance optimization:\n \n Phase 1: System Analysis\n - Analyze current system performance metrics\n - Identify resource bottlenecks (CPU, memory, disk, network)\n - Check running processes and services\n - Analyze system startup time and services\n \n Phase 2: Cleanup Operations\n - Clean temporary files and caches\n - Remove old log files and rotate current ones\n - Clean package manager caches\n - Remove orphaned packages and dependencies\n \n Phase 3: Configuration Optimization\n - Optimize system swappiness settings\n - Configure I/O scheduler for better performance\n - Adjust network buffer sizes if needed\n - Optimize filesystem mount options\n \n Phase 4: Service Optimization\n - Disable unnecessary startup services\n - Optimize database configurations if present\n - Configure web server settings for better performance\n - Set up proper caching mechanisms\n \n Phase 5: Monitoring Setup\n - Install performance monitoring tools\n - Set up automated performance tracking\n - Create performance baseline measurements\n - Schedule regular optimization maintenance\n \n Phase 6: Verification and Reporting\n - Run performance benchmarks before and after\n - Generate detailed optimization report\n - Create recommendations for future improvements\n - Set up alerting for performance degradation\n \"\"\"\n \n event = Event(event_type=\"NEW_REQUEST\", content=optimization_task)\n orchestrator.event_stream.add_event(event)\n \n print(\"\ud83d\ude80 Starting system performance optimization workflow...\")\n result = orchestrator.run()\n \n return orchestrator.status == \"completed\"\n\nif __name__ == \"__main__\":\n success = optimize_system_performance()\n if success:\n print(\"\u2705 Performance optimization completed!\")\n else:\n print(\"\u274c Optimization workflow failed.\")\n```\n---\n\n*This documentation is part of an ongoing improvement initiative. Additional technical details, architecture diagrams, and comprehensive examples will be added in subsequent updates.*\n",
"bugtrack_url": null,
"license": null,
"summary": "Anges - An LLM Powered Engineering Agent System",
"version": "0.1.0",
"project_urls": {
"Bug Tracker": "https://github.com/anges-ai/anges/issues",
"Documentation": "https://github.com/anges-ai/anges/tree/main/docs",
"Examples": "https://github.com/anges-ai/anges/tree/main/examples",
"Homepage": "https://github.com/anges-ai/anges",
"Source": "https://github.com/anges-ai/anges"
},
"split_keywords": [
"ai",
" agent",
" orchestration",
" automation",
" framework",
" llm",
" openai",
" anthropic",
" google",
" vertexai",
" workflow",
" event-driven",
" multi-agent",
" assistant",
" custom-actions",
" plugin-system",
" ai-automation"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "9773d338a994ab72976bf97741c0723db2f92fb090b9baa2958a0074809a3a39",
"md5": "73f6c1a9010f3ef07d5abb48c33a43c0",
"sha256": "d269cad8ebddadf56ab4fdd0c5fad38a63f6da5b44ecb35dc91799e30c426f43"
},
"downloads": -1,
"filename": "anges-0.1.0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "73f6c1a9010f3ef07d5abb48c33a43c0",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.8",
"size": 138293,
"upload_time": "2025-07-22T04:19:13",
"upload_time_iso_8601": "2025-07-22T04:19:13.910428Z",
"url": "https://files.pythonhosted.org/packages/97/73/d338a994ab72976bf97741c0723db2f92fb090b9baa2958a0074809a3a39/anges-0.1.0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "1e3862f5040441dae76e489761b2e509ec0587fd94432c0b92b678de7fc12c34",
"md5": "fa6c937e750e2bd26e8cf840cd37dadb",
"sha256": "70df79f2948273a105f243cc885143a6b17c54de9f4d7791ca22e6e65515ea3d"
},
"downloads": -1,
"filename": "anges-0.1.0.tar.gz",
"has_sig": false,
"md5_digest": "fa6c937e750e2bd26e8cf840cd37dadb",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.8",
"size": 1011056,
"upload_time": "2025-07-22T04:19:15",
"upload_time_iso_8601": "2025-07-22T04:19:15.192950Z",
"url": "https://files.pythonhosted.org/packages/1e/38/62f5040441dae76e489761b2e509ec0587fd94432c0b92b678de7fc12c34/anges-0.1.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-07-22 04:19:15",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "anges-ai",
"github_project": "anges",
"travis_ci": false,
"coveralls": false,
"github_actions": false,
"requirements": [
{
"name": "pytest",
"specs": [
[
">=",
"6.0.0"
]
]
},
{
"name": "vertexai",
"specs": [
[
">=",
"1.0.0"
]
]
},
{
"name": "openai",
"specs": [
[
">=",
"1.0.0"
]
]
},
{
"name": "anthropic",
"specs": [
[
">=",
"0.3.0"
]
]
},
{
"name": "pandas",
"specs": [
[
">=",
"1.3.0"
]
]
},
{
"name": "datasets",
"specs": [
[
">=",
"2.0.0"
]
]
},
{
"name": "argparse",
"specs": []
},
{
"name": "Flask",
"specs": [
[
">=",
"2.0.0"
]
]
},
{
"name": "flask-cors",
"specs": [
[
">=",
"3.0.0"
]
]
},
{
"name": "flask-login",
"specs": [
[
">=",
"0.6.0"
]
]
},
{
"name": "google-generativeai",
"specs": [
[
">=",
"0.3.0"
]
]
},
{
"name": "google.genai",
"specs": []
},
{
"name": "python-dotenv",
"specs": [
[
">=",
"0.19.0"
]
]
},
{
"name": "requests",
"specs": [
[
">=",
"2.25.0"
]
]
},
{
"name": "pytest-cov",
"specs": [
[
">=",
"2.12.0"
]
]
},
{
"name": "black",
"specs": [
[
">=",
"21.0.0"
]
]
},
{
"name": "flake8",
"specs": [
[
">=",
"3.9.0"
]
]
},
{
"name": "mypy",
"specs": [
[
">=",
"0.910"
]
]
},
{
"name": "sphinx",
"specs": [
[
">=",
"4.0.0"
]
]
},
{
"name": "sphinx-rtd-theme",
"specs": [
[
">=",
"1.0.0"
]
]
}
],
"lcname": "anges"
}