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

new #469

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open

new #469

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
66 changes: 66 additions & 0 deletions examples/meta_developer_example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# examples/meta_developer_example.py

import logging
from taskweaver.ext_role.meta_developer.meta_developer import MetaDeveloper
from taskweaver.ext_role.meta_developer.analyzer import Analyzer
from taskweaver.ext_role.meta_developer.generator import Generator
from taskweaver.ext_role.meta_developer.debugger import Debugger

def main():
"""
Demonstrates the usage of the MetaDeveloper role by executing the three phases:
Analysis, Generation, and Debugging, to develop a simple application.
"""
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("MetaDeveloperExample")

# Initialize the MetaDeveloper role
logger.info("Initializing the MetaDeveloper role to orchestrate the development phases...")
meta_developer = MetaDeveloper()

# Define a simple task description
task_description = "Analyze, generate, and debug a simple Python project."

# Phase 1: Analysis
logger.info("Starting the Analysis Phase: Extracting structural and functional details from the codebase...")
analyzer = Analyzer()
try:
analysis_result = analyzer.analyze(task_description)
logger.info(f"Analysis Phase Completed Successfully. Result: {analysis_result}")
except Exception as e:
logger.error(f"Analysis Phase Failed. Error: {e}")
return

# Phase 2: Generation
logger.info("Starting the Generation Phase: Creating new code based on the analysis results...")
generator = Generator()
try:
generation_result = generator.generate(analysis_result)
logger.info(f"Generation Phase Completed Successfully. Result: {generation_result}")
except Exception as e:
logger.error(f"Generation Phase Failed. Error: {e}")
return

# Phase 3: Debugging
logger.info("Starting the Debugging Phase: Identifying and resolving issues in the generated code...")
debugger = Debugger()
try:
debugging_result = debugger.debug(generation_result)
logger.info(f"Debugging Phase Completed Successfully. Result: {debugging_result}")
except Exception as e:
logger.error(f"Debugging Phase Failed. Error: {e}")
return

# Final Output
logger.info("MetaDeveloper Example Completed.")
logger.info("Summary of Results:")
logger.info("===================================")
logger.info(f"1. Analysis Result:\\n{analysis_result}")
logger.info("-----------------------------------")
logger.info(f"2. Generation Result:\\n{generation_result}")
logger.info("-----------------------------------")
logger.info(f"3. Debugging Result:\\n{debugging_result}")
logger.info("===================================")

if __name__ == "__main__":
main()
83 changes: 83 additions & 0 deletions taskweaver/ext_role/meta_developer/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# TaskWeaver MetaDeveloper Role

## Overview

The MetaDeveloper role is an extension of TaskWeaver designed to facilitate the development and analysis of software projects. It introduces a structured approach to project development by dividing the process into three distinct phases: **Analysis**, **Generation**, and **Debugging**. Each phase is implemented as a separate module, allowing for modularity and extensibility.

---

## Architecture

The MetaDeveloper role is composed of the following components:

1. **Analyzer**: Responsible for analyzing the project's codebase and structure.
2. **Generator**: Handles the generation of new code based on the analysis results.
3. **Debugger**: Focuses on debugging and improving the generated code.

These components work together under the orchestration of the MetaDeveloper role, which communicates with the TaskWeaver Planner to ensure seamless integration.

---

## Phases

### 1. Analysis Phase
The **Analyzer** module is responsible for:
- Parsing the project's codebase.
- Extracting structural and functional information.
- Generating analysis reports and tools to assist in understanding the project.

### 2. Generation Phase
The **Generator** module is responsible for:
- Creating new code based on the analysis results.
- Ensuring that the generated code adheres to the project's architecture and standards.

### 3. Debugging Phase
The **Debugger** module is responsible for:
- Identifying and fixing issues in the generated code.
- Providing custom debugging tools tailored to the project's needs.

---

## Workflow

1. **Initialization**: The MetaDeveloper role is initialized and registered with TaskWeaver.
2. **Analysis**: The Analyzer module is invoked to analyze the project's codebase.
3. **Code Generation**: Based on the analysis, the Generator module creates new code.
4. **Debugging**: The Debugger module identifies and resolves issues in the generated code.
5. **Iteration**: The process iterates as needed, with feedback loops between the phases.

---

## Integration with TaskWeaver

The MetaDeveloper role is designed to work seamlessly with TaskWeaver's Planner. It communicates with the Planner to:
- Receive high-level tasks and objectives.
- Report progress and results for each phase.
- Request additional information or clarification when needed.

---

## Configuration

The MetaDeveloper role includes a configuration file (`config.py`) that defines parameters and options for customization. This allows users to tailor the role's behavior to their specific project requirements.

---

## Example Usage

An example script (`meta_developer_example.py`) demonstrates how to use the MetaDeveloper role to develop a simple application. The script showcases the interaction between the three phases and highlights the role's capabilities.

---

## Extensibility

The modular design of the MetaDeveloper role allows for easy extension and customization. Developers can:
- Add new modules to support additional phases or functionalities.
- Modify existing modules to adapt to specific project needs.
- Integrate the role with other TaskWeaver extensions for enhanced capabilities.

---

## Conclusion

The MetaDeveloper role provides a structured and efficient approach to software development within the TaskWeaver framework. By leveraging the three-phase architecture, it simplifies complex development tasks and enhances productivity.
46 changes: 46 additions & 0 deletions taskweaver/ext_role/meta_developer/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
from taskweaver.role import Role, register_role
from .meta_developer import MetaDeveloper

# Register the MetaDeveloper role with TaskWeaver
@register_role
class MetaDeveloperRole(Role):
"""
The MetaDeveloperRole is an extension of TaskWeaver designed to facilitate
the development and analysis of software projects. It orchestrates the
three phases: Analysis, Generation, and Debugging.
"""
name = "meta_developer"
description = (
"A role that provides tools for analyzing, generating, and debugging "
"software projects. It integrates seamlessly with TaskWeaver's Planner."
)
role_class = MetaDeveloper
```

### Step 4: Review the Code
- **Imports**: The necessary components (`Role`, `register_role`, and `MetaDeveloper`) are imported.
- **Registration**: The `MetaDeveloperRole` class is registered using the `@register_role` decorator.
- **Documentation**: The class includes a docstring explaining its purpose and functionality.
- **Conventions**: The code adheres to Python and TaskWeaver's conventions, ensuring compatibility and readability.

### Final Output
Here is the full content of the `taskweaver/ext_role/meta_developer/__init__.py` file:

```
from taskweaver.role import Role, register_role
from .meta_developer import MetaDeveloper

# Register the MetaDeveloper role with TaskWeaver
@register_role
class MetaDeveloperRole(Role):
"""
The MetaDeveloperRole is an extension of TaskWeaver designed to facilitate
the development and analysis of software projects. It orchestrates the
three phases: Analysis, Generation, and Debugging.
"""
name = "meta_developer"
description = (
"A role that provides tools for analyzing, generating, and debugging "
"software projects. It integrates seamlessly with TaskWeaver's Planner."
)
role_class = MetaDeveloper
133 changes: 133 additions & 0 deletions taskweaver/ext_role/meta_developer/analyzer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
import os
import ast
import logging


class Analyzer:
"""
The Analyzer class is responsible for analyzing the project's codebase,
extracting structural and functional information, and generating analysis
reports to assist in understanding the project.
"""

def __init__(self):
"""
Initializes the Analyzer with a logger.
"""
self.logger = logging.getLogger(self.__class__.__name__)

def analyze(self, task_description: str):
"""
Analyzes the project's codebase based on the provided task description.

Args:
task_description (str): A description of the task to analyze.

Returns:
dict: A structured result containing analysis details.
"""
self.logger.info("Starting analysis phase...")
self.logger.debug(f"Task description: {task_description}")

# Simulate locating the project's root directory
project_root = self._find_project_root()
self.logger.debug(f"Project root directory: {project_root}")

# Simulate analyzing Python files in the project
analysis_results = self._analyze_codebase(project_root)

# Generate a summary report
report = self._generate_report(analysis_results)

self.logger.info("Analysis phase completed.")
return report

def _find_project_root(self):
"""
Simulates locating the project's root directory.

Returns:
str: The path to the project's root directory.
"""
# For simplicity, assume the current working directory is the project root
return os.getcwd()

def _analyze_codebase(self, project_root):
"""
Analyzes Python files in the project's codebase.

Args:
project_root (str): The root directory of the project.

Returns:
list: A list of dictionaries containing analysis details for each file.
"""
analysis_results = []
for root, _, files in os.walk(project_root):
for file in files:
if file.endswith(".py"):
file_path = os.path.join(root, file)
self.logger.debug(f"Analyzing file: {file_path}")
file_analysis = self._analyze_file(file_path)
analysis_results.append(file_analysis)
return analysis_results

def _analyze_file(self, file_path):
"""
Analyzes a single Python file.

Args:
file_path (str): The path to the Python file.

Returns:
dict: A dictionary containing analysis details for the file.
"""
try:
with open(file_path, "r", encoding="utf-8") as f:
file_content = f.read()

# Parse the file content into an abstract syntax tree (AST)
tree = ast.parse(file_content)
functions = [node.name for node in ast.walk(tree) if isinstance(node, ast.FunctionDef)]
classes = [node.name for node in ast.walk(tree) if isinstance(node, ast.ClassDef)]

return {
"file_path": file_path,
"functions": functions,
"classes": classes,
"lines_of_code": len(file_content.splitlines()),
}
except Exception as e:
self.logger.error(f"Error analyzing file {file_path}: {e}")
return {
"file_path": file_path,
"error": str(e),
}

def _generate_report(self, analysis_results):
"""
Generates a summary report based on the analysis results.

Args:
analysis_results (list): A list of dictionaries containing analysis details.

Returns:
dict: A structured report summarizing the analysis.
"""
total_files = len(analysis_results)
total_lines = sum(result.get("lines_of_code", 0) for result in analysis_results if "lines_of_code" in result)
total_functions = sum(len(result.get("functions", [])) for result in analysis_results)
total_classes = sum(len(result.get("classes", [])) for result in analysis_results)

report = {
"summary": {
"total_files": total_files,
"total_lines_of_code": total_lines,
"total_functions": total_functions,
"total_classes": total_classes,
},
"details": analysis_results,
}

self.logger.debug(f"Generated report: {report}")
return report
Loading