Skip to content

ivyinautumn/AutoGen_codeagent

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ€– AutoGen Multi-Agent Code Generation System

A production-ready multi-agent system for intelligent code generation, quality analysis, and optimization using AutoGen and Chainlit.

🎯 Overview

This system demonstrates advanced multi-agent collaboration patterns for code development workflows, featuring:

  • πŸ§‘β€πŸ’» Code Generator Agent: Creates high-quality code from natural language requirements
  • πŸ” Code Quality Analyzer Agent: Performs comprehensive static analysis and security checks
  • ⚑ Code Optimizer Agent: Automatically fixes issues and applies optimizations
  • πŸ‘€ User Proxy Agent: Handles approval workflows with intuitive web interface

✨ Features

Core Capabilities

  • Multi-language Support: Python, JavaScript, TypeScript, Java, Go
  • Comprehensive Analysis: Static analysis, complexity metrics, security scanning
  • Automated Optimization: Style fixing, performance improvements, refactoring
  • Quality Assurance: Built-in validation and testing recommendations
  • User Approval Workflows: Interactive approval process with Chainlit UI

Analysis Tools Integration

  • pylint: Python static analysis and code quality checks
  • flake8: Style guide enforcement and error detection
  • bandit: Security vulnerability detection
  • radon: Code complexity and maintainability metrics
  • black + isort: Automated code formatting

Model Support

  • η™Ύη‚Όε€§ζ¨‘εž‹ (Bailian/DashScope): Default model provider
  • OpenAI GPT: Alternative model support
  • Custom Models: Configurable model backends

πŸš€ Quick Start

Prerequisites

  • Python 3.9+ (recommended: Python 3.11)
  • Virtual Environment (recommended)
  • η™Ύη‚Όε€§ζ¨‘εž‹ API Key or other supported model API

1. Installation

# Clone the repository
git clone <repository-url>
cd context-engineering-intro

# Create and activate virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt

2. Configuration

# Copy environment template
cp .env.example .env

# Edit .env with your API keys and settings
nano .env  # or use your preferred editor

Required environment variables:

# η™Ύη‚Όε€§ζ¨‘εž‹ Configuration
BAILIAN_API_KEY=bsk-your-api-key-here
BAILIAN_MODEL=qwen-max
BAILIAN_ENDPOINT=https://dashscope.aliyuncs.com/api/v1/

# Application Settings
CHAINLIT_PORT=8000
CHAINLIT_HOST=localhost
DEBUG_MODE=true

3. Model Configuration

Create or update model_config.yaml:

# η™Ύη‚Όε€§ζ¨‘εž‹ Configuration
provider: autogen_ext.models.openai.OpenAIChatCompletionClient
config:
  model: qwen-max
  api_key: ${BAILIAN_API_KEY}
  base_url: ${BAILIAN_ENDPOINT}

4. Run the Application

# Start the Chainlit application
chainlit run app.py -h

# Visit http://localhost:8000 in your browser

πŸ“‹ Usage Guide

Basic Workflow

  1. Start a Request: Choose a starter prompt or describe your code requirements
  2. Review Generation: The Code Generator creates initial code with self-validation
  3. Quality Analysis: The Code Reviewer performs comprehensive analysis
  4. Optimization: The Code Optimizer applies improvements and fixes
  5. User Approval: Review and approve the final code

Example Requests

Simple Function

Create a Python function to calculate fibonacci numbers with error handling

Complex Application

Build a Python Flask REST API for user authentication with:
- JWT token management
- Password hashing with bcrypt  
- Rate limiting
- Comprehensive error handling
- Unit tests

Algorithm Implementation

Implement a binary search tree in Python with:
- Insert, delete, search operations
- Tree balancing
- In-order traversal
- Comprehensive docstrings and type hints

Approval Workflow

During the process, you'll see action buttons:

  • βœ… Approve Final Code: Accept and complete the workflow
  • πŸ‘ Approve & Continue: Accept current step and proceed
  • πŸ”„ Request Changes: Specify modifications needed
  • ❌ Reject: Reject current output

Special Commands

  • help or /help: Show usage instructions
  • history or /history: View code generation history
  • reset or /reset: Clear session data

πŸ—οΈ Architecture

System Components

β”œβ”€β”€ agents/                 # Specialized agent implementations
β”‚   β”œβ”€β”€ code_generator.py   # Code generation with validation
β”‚   β”œβ”€β”€ code_reviewer.py    # Quality analysis and reporting
β”‚   β”œβ”€β”€ code_optimizer.py   # Automated fixing and optimization
β”‚   └── user_proxy.py       # User interaction and approval
β”œβ”€β”€ tools/                  # Analysis and utility tools
β”‚   β”œβ”€β”€ code_analysis.py    # Static analysis integration
β”‚   β”œβ”€β”€ complexity_analyzer.py # Complexity metrics
β”‚   β”œβ”€β”€ security_scanner.py # Security vulnerability detection
β”‚   └── code_formatter.py   # Code formatting utilities
β”œβ”€β”€ models/                 # Pydantic data models
β”‚   β”œβ”€β”€ code_request.py     # Code generation requests
β”‚   β”œβ”€β”€ analysis_result.py  # Analysis results and metrics
β”‚   └── optimization_result.py # Optimization outcomes
β”œβ”€β”€ prompts/                # Agent system messages
β”‚   β”œβ”€β”€ code_generator_prompts.py
β”‚   β”œβ”€β”€ code_reviewer_prompts.py
β”‚   └── code_optimizer_prompts.py
β”œβ”€β”€ config/                 # Configuration management
β”‚   └── settings.py         # Environment and tool settings
└── app.py                  # Main Chainlit application

Agent Coordination

The system uses AutoGen's RoundRobinGroupChat for agent coordination:

  1. Code Generator β†’ Creates initial code with self-validation
  2. Code Reviewer β†’ Analyzes quality, security, complexity
  3. Code Optimizer β†’ Applies fixes and improvements
  4. User Proxy β†’ Handles approval and feedback

πŸ”§ Development

Setting Up Development Environment

# Install development dependencies
pip install -r requirements.txt

# Install pre-commit hooks (optional)
pre-commit install

# Run code quality checks
ruff check .
mypy .
black --check .

Running Tests

# Run all tests
pytest tests/ -v

# Run with coverage
pytest tests/ -v --cov=agents --cov=tools --cov-report=term-missing

# Run specific test
pytest tests/test_code_generator.py -v

Code Quality Standards

  • Style: PEP8 compliance with black formatting
  • Type Safety: Comprehensive type hints with mypy
  • Documentation: Google-style docstrings for all functions
  • Testing: Minimum 80% test coverage
  • Security: Bandit security scanning

πŸ› οΈ Configuration

Analysis Tools Configuration

Create optional configuration files:

# Pylint configuration
config/pylint.rc

# Flake8 configuration  
config/setup.cfg

# Bandit configuration
config/bandit.yaml

Quality Thresholds

Customize quality thresholds in .env:

MIN_MAINTAINABILITY_INDEX=70.0
MAX_COMPLEXITY_SCORE=5.0
MAX_SECURITY_ISSUES=0
MAX_STYLE_VIOLATIONS=5

Supported Languages

Current support includes:

  • Python (Full support)
  • JavaScript/TypeScript (Basic support)
  • Java (Basic support)
  • Go (Basic support)

🚨 Troubleshooting

Common Issues

Model Configuration Error

❌ Configuration Error - Model configuration file not found

Solution: Ensure model_config.yaml exists with valid configuration

API Key Issues

❌ Authentication failed

Solution: Check your API key in .env file and ensure it's valid

Analysis Tool Errors

❌ Pylint execution failed

Solution: Ensure analysis tools are installed: pip install pylint flake8 bandit radon

Port Already in Use

❌ Port 8000 is already in use

Solution: Change port in .env or kill existing process

Performance Optimization

For better performance:

  1. Use faster model variants (e.g., qwen-turbo vs qwen-max)
  2. Adjust quality thresholds for faster analysis
  3. Enable caching for repeated requests
  4. Use virtual environment for better dependency isolation

Debugging

Enable debug mode in .env:

DEBUG_MODE=true

Check application logs for detailed error information.

πŸ“ˆ Advanced Usage

Custom Agent Prompts

Modify prompts in prompts/ directory to customize agent behavior:

  • code_generator_prompts.py - Code generation instructions
  • code_reviewer_prompts.py - Quality analysis criteria
  • code_optimizer_prompts.py - Optimization strategies

Integration with CI/CD

Use the analysis tools in your CI/CD pipeline:

# Quality gate script
python -c "
from tools.code_analysis import analyze_code_quality
import asyncio
result = asyncio.run(analyze_code_quality(open('code.py').read()))
exit(0 if result['passed'] else 1)
"

Custom Model Providers

Add support for custom models by modifying model_config.yaml:

provider: custom_provider.CustomChatClient
config:
  model: custom-model
  api_key: ${CUSTOM_API_KEY}
  endpoint: ${CUSTOM_ENDPOINT}

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit changes (git commit -m 'Add amazing feature')
  4. Push to branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Development Guidelines

  • Follow PEP8 style guidelines
  • Add comprehensive tests for new features
  • Update documentation for API changes
  • Ensure all quality checks pass
  • Add type hints for all functions

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ™ Acknowledgments

  • AutoGen Team - For the excellent multi-agent framework
  • Chainlit Team - For the intuitive web interface framework
  • Alibaba Cloud - For η™Ύη‚Όε€§ζ¨‘εž‹ API services
  • Python Community - For the amazing analysis tools ecosystem

πŸ“ž Support

  • Documentation: Check this README and inline code documentation
  • Issues: Report bugs and feature requests via GitHub Issues
  • Community: Join discussions in GitHub Discussions
  • API Reference: See AutoGen and Chainlit official documentation

Built with ❀️ using AutoGen, Chainlit, and η™Ύη‚Όε€§ζ¨‘εž‹

About

A intelligent code agent based on context engineering template and AutoGen framework

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages