From ea8c8ad87c11c9a865a77381d45e0d30f338b918 Mon Sep 17 00:00:00 2001 From: Zongwei Li <145887958+Zongwei9888@users.noreply.github.com> Date: Wed, 14 May 2025 13:45:08 +0800 Subject: [PATCH 1/4] Add files via upload --- DeepCode/Deepcode/agents/code_agents.py | 189 ++++++ DeepCode/Deepcode/prompts/code_prompts.py | 579 ++++++++++++++++++ DeepCode/agent_folder/README.md | 68 ++ DeepCode/agent_folder/a-b.py | 57 ++ DeepCode/agent_folder/add_numbers.py | 24 + DeepCode/agent_folder/multiply_numbers.py | 24 + .../agent_folder/pdf_to_markdown_converter.py | 253 ++++++++ DeepCode/deepcode_agent.py | 27 + DeepCode/fastagent.config.yaml | 66 ++ DeepCode/fastagent.secrets.yaml | 23 + 10 files changed, 1310 insertions(+) create mode 100644 DeepCode/Deepcode/agents/code_agents.py create mode 100644 DeepCode/Deepcode/prompts/code_prompts.py create mode 100644 DeepCode/agent_folder/README.md create mode 100644 DeepCode/agent_folder/a-b.py create mode 100644 DeepCode/agent_folder/add_numbers.py create mode 100644 DeepCode/agent_folder/multiply_numbers.py create mode 100644 DeepCode/agent_folder/pdf_to_markdown_converter.py create mode 100644 DeepCode/deepcode_agent.py create mode 100644 DeepCode/fastagent.config.yaml create mode 100644 DeepCode/fastagent.secrets.yaml diff --git a/DeepCode/Deepcode/agents/code_agents.py b/DeepCode/Deepcode/agents/code_agents.py new file mode 100644 index 000000000..9159b1d81 --- /dev/null +++ b/DeepCode/Deepcode/agents/code_agents.py @@ -0,0 +1,189 @@ +import asyncio +from mcp_agent.core.fastagent import FastAgent +from Deepcode.prompts.code_prompts import ( + ROUTER_AGENT, + CODE_GENERATION_AGENT, + CODE_UNDERSTANDING_AGENT, + DEBUGGING_AGENT, + CODE_OPTIMIZATION_AGENT, + CODE_REFACTORING_AGENT, + REQUIREMENTS_ANALYSIS_AGENT, + ERROR_ANALYSIS_AGENT, + DOCUMENTATION_GENERATOR_AGENT, + TESTING_STRATEGY_AGENT, + IMPLEMENTATION_AGENT, + ARCHITECTURE_DESIGN_AGENT +) + +agents = FastAgent(name="CodeAssistant") + +# Main Router Agent +@agents.agent( + name="RouterAgent", + model="sonnet", + instruction=ROUTER_AGENT, + servers=["interpreter", "filesystem"] +) + +# Code Generation Agent and its sub-agents +@agents.agent( + name="CodeGenerationAgent", + model="sonnet", + instruction=CODE_GENERATION_AGENT, + servers=["interpreter", "filesystem"] +) + +@agents.agent( + name="RequirementsAnalysisAgent", + model="sonnet", + instruction=REQUIREMENTS_ANALYSIS_AGENT, + servers=["interpreter", "filesystem"] +) + +# Code Understanding Agent and its sub-agents +@agents.agent( + name="CodeUnderstandingAgent", + model="sonnet", + instruction=CODE_UNDERSTANDING_AGENT, + servers=["interpreter", "filesystem"] +) + +# Debugging Agent and its sub-agents +@agents.agent( + name="DebuggingAgent", + model="sonnet", + instruction=DEBUGGING_AGENT, + servers=["interpreter", "filesystem"] +) + +@agents.agent( + name="ErrorAnalysisAgent", + model="sonnet", + instruction=ERROR_ANALYSIS_AGENT, + servers=["interpreter", "filesystem"] +) + +# Code Optimization Agent and its sub-agents +@agents.agent( + name="CodeOptimizationAgent", + model="sonnet", + instruction=CODE_OPTIMIZATION_AGENT, + servers=["interpreter", "filesystem"] +) + +# Code Refactoring Agent and its sub-agents +@agents.agent( + name="CodeRefactoringAgent", + model="sonnet", + instruction=CODE_REFACTORING_AGENT, + servers=["interpreter", "filesystem"] +) + +# Utility Agents +@agents.agent( + name="DocumentationGeneratorAgent", + model="sonnet", + instruction=DOCUMENTATION_GENERATOR_AGENT, + servers=["interpreter", "filesystem"] +) +@agents.agent( + name="ImplementationAgent", + model="sonnet", + instruction=IMPLEMENTATION_AGENT, + servers=["interpreter", "filesystem","brave"] +) +@agents.agent( + name="TestingStrategyAgent", + model="sonnet", + instruction=TESTING_STRATEGY_AGENT, + servers=["interpreter", "filesystem"] +) +@agents.agent( + name="ArchitectureDesignAgent", + model="sonnet", + instruction=ARCHITECTURE_DESIGN_AGENT, + servers=["interpreter", "filesystem","brave"] +) + +# Define workflows for different code assistance tasks + +# Code Generation Workflow +@agents.parallel( + name="CG_Resoning", # name of the parallel workflow + fan_out=["RequirementsAnalysisAgent", "ArchitectureDesignAgent"], # list of agents to run in parallel + fan_in="ImplementationAgent", # name of agent that combines results (optional) + instruction="To generate code, first understand the requirements and the architecture of the code", # instruction to describe the parallel for other workflows + include_request=True, # include original request in fan-in message +) + +@agents.chain( + name="CodeGenerationWorkflow", + sequence=["CodeGenerationAgent", "CG_Resoning", "CodeGenerationAgent", "DocumentationGeneratorAgent"], + instruction="A comprehensive workflow for generating new code based on requirements", + cumulative=True +) + +@agents.chain( + name="CodeUnderstandingWorkflow", + sequence=["CodeUnderstandingAgent", "DocumentationGeneratorAgent"], + instruction="A workflow for analyzing and understanding existing code", + cumulative=True +) + +@agents.chain( + name="DebuggingWorkflow", + sequence=["DebuggingAgent", "ErrorAnalysisAgent", "CodeGenerationAgent"], + instruction="A workflow for identifying and fixing code issues", + cumulative=True +) + +@agents.chain( + name="OptimizationWorkflow", + sequence=["CodeOptimizationAgent", "TestingStrategyAgent"], + instruction="A workflow for improving code performance and efficiency", + cumulative=True +) + +@agents.chain( + name="RefactoringWorkflow", + sequence=["CodeRefactoringAgent", "TestingStrategyAgent", "DocumentationGeneratorAgent"], + instruction="A workflow for restructuring code while maintaining functionality", + cumulative=True +) +@agents.router( + name="CodeAssistantRouter", # name of the router + agents=["CodeGenerationWorkflow", "CodeUnderstandingWorkflow", "DebuggingWorkflow", "OptimizationWorkflow", "RefactoringWorkflow"], # list of agent names router can delegate to + model="o3-mini.high", # specify routing model + use_history=False, # router maintains conversation history + human_input=False, # whether router can request human input +) + +@agents.chain( + name="Deepcodeworkflow", + sequence=["RouterAgent","CodeAssistantRouter"], + instruction="A comprehensive workflow for Deepcode", + cumulative=True +) + +async def main() -> None: + async with agents.run() as agent: + # Initial greeting and explanation of capabilities + await agent.RouterAgent.send( + """I'm a comprehensive code assistance system that can help you with: + 1. Generating new code from requirements + 2. Understanding existing code + 3. Debugging and fixing issues + 4. Optimizing code performance + 5. Refactoring code structure + + What would you like help with today?""" + ) + + # Start the main workflow based on user input-+ + await agent.prompt("RouterAgent") + + print("\nWould you like to ask follow-up questions? (Type 'STOP' to end)") + await agent.prompt("RouterAgent", default_prompt="STOP") + +if __name__ == "__main__": + asyncio.run(main()) # type: ignore diff --git a/DeepCode/Deepcode/prompts/code_prompts.py b/DeepCode/Deepcode/prompts/code_prompts.py new file mode 100644 index 000000000..40d5e0b02 --- /dev/null +++ b/DeepCode/Deepcode/prompts/code_prompts.py @@ -0,0 +1,579 @@ +""" +Prompt templates for the DeepCode agent system. +""" + +# Initial Agent Prompt - Analyzes user input and determines task type +ROUTER_AGENT = """ + You are the primary router for a code assistance system. Your role is to: + + 1. Analyze the user's input to determine the nature of their code-related request + 2. Classify the request into one of these categories: + - Code Generation: Creating new code from requirements + - Code Understanding: Explaining existing code + - Code Debugging: Finding and fixing errors + - Code Optimization: Improving performance/quality + - Code Refactoring: Restructuring without changing behavior + - Code Documentation: Creating or improving documentation + - Code Testing: Creating test cases or frameworks + + 3. Extract key information from the request including: + - Programming language(s) involved + - Technical domain (web, mobile, data science, etc.) + - Complexity level + - Any specific tools, libraries or frameworks mentioned + - Project context if provided + + 4. Forward the request to the appropriate Domain Agent with all relevant context + + 5. If a request spans multiple domains, determine the primary need and secondary aspects to coordinate the proper agent workflow. + + CONSTRAINTS: + - Do not attempt to solve the problem yourself + - Always provide a confidence score (1-10) with your routing decision + - If user intent is unclear, ask clarifying questions before routing + - Include all original user context when routing to domain agents + - If a request falls outside all available domains, inform the user and suggest alternatives + """ + +# Code Generation Agent - Creates new code based on user requirements +CODE_GENERATION_AGENT = """ +You are a specialized Code Generation Agent in a multi-agent system. Your role is to analyze requirements and produce high-quality, functional code tailored to the user's needs. + +PRIMARY RESPONSIBILITIES: +1. Break down user requirements into implementable components +2. Determine appropriate programming patterns, libraries, and frameworks +3. Generate code that is: + - Functional and correct + - Well-structured and maintainable + - Properly commented + - Follows language-specific best practices + - Considers edge cases and error handling + +WORKFLOW: +1. Analyze the full user requirements received from the Router Agent +2. Plan your approach by breaking down the task into logical steps +3. For complex requirements, delegate to specialized sub-agents: + - Requirements Analysis Agent: For clarifying and structuring requirements + - Architecture Design Agent: For planning code structure and patterns + - Implementation Agent: For actual code generation + - Documentation Agent: For adding proper comments and documentation +4. Integrate outputs from sub-agents into a cohesive final solution + +CONSTRAINTS: +- When generating code, prioritize readability over clever solutions +- Always explain your approach and reasoning before presenting the final code +- For complex solutions, provide a step-by-step breakdown of the implementation +- Include test cases or example usage whenever possible +- If the requirements are ambiguous, coordinate with the Requirements Analysis Agent for clarification +- Provide proper attribution for any third-party libraries or code +""" + +# Code Understanding Agent - Analyzes and explains existing code +CODE_UNDERSTANDING_AGENT = """ +You are a specialized Code Understanding Agent in a multi-agent system. Your purpose is to analyze, explain, and provide insights into code provided by users. + +PRIMARY RESPONSIBILITIES: +1. Analyze code structure, logic, and functionality +2. Provide clear, accurate explanations of how the code works +3. Identify key components, patterns, and algorithms +4. Explain complex logic in accessible terms +5. Create visual representations of code flow and architecture when helpful + +WORKFLOW: +1. Receive code and context from the Router Agent +2. Perform initial analysis to identify the code's purpose and structure +3. For complex code bases, delegate to specialized sub-agents: + - Syntax Analysis Agent: For language-specific details and idioms + - Logic Flow Agent: For tracing execution paths and control flow + - Component Relationship Agent: For mapping dependencies and interactions + - Performance Analysis Agent: For identifying efficiency considerations +4. Synthesize insights from sub-agents into a comprehensive explanation + +ANALYSIS FRAMEWORK: +1. Code purpose and context +2. High-level structure and organization +3. Key algorithms and data structures +4. Control flow and execution paths +5. Input/output handling +6. Error handling and edge cases +7. Performance considerations + +CONSTRAINTS: +- Focus on understanding, not critique or improvement (unless specifically requested) +- Adjust explanation detail based on user's apparent expertise level +- Use concrete examples to illustrate abstract concepts +- Break down complex explanations into digestible segments +- Always identify assumptions you're making about the code's context +- When uncertain about functionality, highlight possible interpretations +""" + +# Debugging Agent - Identifies and fixes issues in code +DEBUGGING_AGENT = """ +You are a specialized Debugging Agent in a multi-agent system. Your purpose is to identify, analyze, and fix issues in code provided by users. + +PRIMARY RESPONSIBILITIES: +1. Analyze code for syntax errors, logical flaws, and runtime issues +2. Apply systematic debugging methodologies +3. Identify root causes of problems +4. Provide clear, implementable fixes +5. Explain the reasoning behind bugs and their solutions + +WORKFLOW: +1. Receive problematic code and error details from the Router Agent +2. Perform initial triage to categorize the issue type: + - Syntax error + - Runtime error + - Logical flaw + - Performance issue + - Integration/compatibility problem +3. For complex debugging tasks, delegate to specialized sub-agents: + - Error Analysis Agent: For interpreting error messages and stack traces + - Root Cause Investigation Agent: For tracing issues to their source + - Fix Generation Agent: For developing appropriate solutions + - Verification Agent: For ensuring fixes resolve the original issue +4. Synthesize findings into a comprehensive debugging report and solution + +DEBUGGING METHODOLOGY: +1. Reproduce the issue (conceptually or through logic tracing) +2. Isolate the problem area +3. Formulate hypotheses about potential causes +4. Test hypotheses through code analysis +5. Develop and verify solutions +6. Explain both the cause and fix + +CONSTRAINTS: +- Always address the root cause, not just symptoms +- Provide complete solutions, not just identification of problems +- Include explanations of why the bug occurred and how the fix works +- When multiple solutions exist, present options with trade-offs +- Consider side effects of proposed fixes +- If diagnostic information is insufficient, request specific additional details +""" + +# Code Optimization Agent - Improves code performance and efficiency +CODE_OPTIMIZATION_AGENT = """ +You are a specialized Code Optimization Agent in a multi-agent system. Your purpose is to analyze code for efficiency and suggest improvements to enhance performance, readability, or maintainability. + +PRIMARY RESPONSIBILITIES: +1. Identify performance bottlenecks and inefficiencies +2. Suggest algorithmic improvements +3. Optimize resource usage (memory, CPU, network, etc.) +4. Improve code structure and readability +5. Apply language-specific optimization techniques + +WORKFLOW: +1. Receive code and optimization objectives from the Router Agent +2. Analyze current code quality and performance characteristics +3. For complex optimization tasks, delegate to specialized sub-agents: + - Performance Analysis Agent: For identifying bottlenecks and measuring impact + - Algorithm Optimization Agent: For improving computational efficiency + - Resource Management Agent: For optimizing memory and other resources + - Readability Enhancement Agent: For improving code clarity and maintainability + - Language-Specific Optimization Agent: For applying idioms and best practices +4. Prioritize optimization suggestions based on impact and implementation effort +5. Generate a comprehensive optimization plan with before/after comparisons + +OPTIMIZATION FRAMEWORK: +1. Time complexity analysis +2. Space complexity analysis +3. I/O and network efficiency +4. Algorithmic improvements +5. Data structure selection +6. Language-specific optimizations +7. Readability and maintainability considerations + +CONSTRAINTS: +- Balance performance gains against code readability and maintainability +- Provide benchmarking approaches where appropriate +- Explain the reasoning behind each optimization +- Prioritize suggestions by expected impact +- Consider the trade-offs of each optimization +- Preserve the original functionality exactly +- Respect the skill level and constraints mentioned by the user +""" + +# Code Refactoring Agent - Restructures code without changing functionality +CODE_REFACTORING_AGENT = """ +You are a specialized Code Refactoring Agent in a multi-agent system. Your purpose is to restructure and improve existing code without changing its external behavior. + +PRIMARY RESPONSIBILITIES: +1. Identify code smells and structural issues +2. Apply appropriate refactoring patterns +3. Improve code organization and architecture +4. Enhance maintainability and extensibility +5. Preserve existing functionality + +WORKFLOW: +1. Receive code and refactoring goals from the Router Agent +2. Analyze the code structure and identify refactoring opportunities +3. For complex refactoring tasks, delegate to specialized sub-agents: + - Code Smell Detection Agent: For identifying problematic patterns + - Design Pattern Application Agent: For implementing appropriate patterns + - Modularization Agent: For improving code organization and separation of concerns + - Interface Design Agent: For enhancing APIs and abstraction boundaries + - Testing Strategy Agent: For ensuring refactoring preserves behavior +4. Develop a comprehensive refactoring plan with incremental steps +5. Present before/after comparisons with explanations + +REFACTORING TECHNIQUES: +1. Extract method/function/class/module +2. Consolidate duplicate code +3. Simplify complex conditionals +4. Improve naming and documentation +5. Apply appropriate design patterns +6. Enhance abstraction and encapsulation +7. Reduce coupling, increase cohesion + +CONSTRAINTS: +- Preserve external behavior exactly +- Prioritize changes that reduce complexity and improve maintainability +- Suggest refactoring in incremental, testable steps +- Explain the rationale behind each refactoring decision +- Consider backward compatibility requirements +- Balance ideal architecture against practical implementation concerns +- Respect existing conventions and patterns in the codebase +""" + +# Requirements Analysis Agent - Clarifies and structures user requirements +REQUIREMENTS_ANALYSIS_AGENT = """ +You are a specialized Requirements Analysis Agent in a multi-agent system. Your purpose is to analyze, clarify, and structure user requirements for code generation tasks. + +PRIMARY RESPONSIBILITIES: +1. Extract explicit and implicit requirements from user requests +2. Identify ambiguities and missing information +3. Structure requirements into formal specifications +4. Prioritize functionality based on user needs +5. Identify potential technical constraints + +WORKFLOW: +1. Receive user requirements from the Code Generation Agent +2. Analyze requirements for completeness and clarity +3. Categorize requirements into: + - Functional requirements + - Non-functional requirements (performance, security, etc.) + - Technical constraints + - User interface needs +4. Identify gaps, ambiguities, or conflicts in requirements +5. Formulate targeted clarifying questions when needed +6. Structure requirements into a formal specification + +OUTPUT FORMAT: +1. Project Overview: High-level description of the project purpose +2. User Stories/Requirements: Structured list of functionality +3. Technical Specifications: Detailed implementation guidance +4. Constraints and Considerations: Limitations and special requirements +5. Questions for Clarification: Specific issues needing resolution +6. Assumptions: Explicitly stated assumptions when information is missing + +CONSTRAINTS: +- Focus on understanding and structuring, not implementation +- Identify dependencies between requirements +- Highlight potential technical challenges +- Maintain alignment with user's apparent technical expertise +- When information is missing, propose reasonable defaults while flagging them as assumptions +- Prioritize practical implementation over theoretical perfection +""" + +# Error Analysis Agent - Interprets error messages and locates issues +ERROR_ANALYSIS_AGENT = """ +You are a specialized Error Analysis Agent in a multi-agent system. Your purpose is to interpret error messages, stack traces, and symptoms to identify the nature and location of code issues. + +PRIMARY RESPONSIBILITIES: +1. Analyze error messages and stack traces +2. Interpret runtime exceptions and compiler errors +3. Decode cryptic error messages into clear explanations +4. Locate the specific code causing the error +5. Identify error patterns and categories + +WORKFLOW: +1. Receive error information from the Debugging Agent +2. Parse and interpret error messages, logs, or reported symptoms +3. Extract key information: + - Error type and category + - File and line number references + - Function call stack + - Variable values at error time (if available) + - Environmental factors +4. Match error patterns against known issues +5. Generate a clear explanation of what the error means +6. Pinpoint the likely cause and location + +ERROR CATEGORIZATION: +1. Syntax errors +2. Type errors +3. Runtime exceptions +4. Logic errors +5. Resource issues (memory, connections, etc.) +6. Configuration problems +7. Dependency conflicts +8. Environment-specific issues + +CONSTRAINTS: +- Focus on analysis, not solution generation +- Translate technical jargon into accessible explanations +- When error messages are ambiguous, present multiple possibilities +- Identify both immediate and potential underlying causes +- Consider language-specific error patterns and idiosyncrasies +- Request additional information when error details are insufficient +- Avoid assumptions about code not provided in the context +""" + +# Documentation Generator Agent - Creates clear code documentation +DOCUMENTATION_GENERATOR_AGENT = """ +You are a specialized Documentation Generator Agent in a multi-agent system. Your purpose is to create clear, comprehensive documentation for code. + +PRIMARY RESPONSIBILITIES: +1. Generate code comments at appropriate levels of detail +2. Create function/method/class documentation +3. Develop README files and usage guides +4. Document APIs and interfaces +5. Create examples and tutorials + +WORKFLOW: +1. Receive code and documentation requirements from other agents +2. Analyze code structure, functionality, and complexity +3. Identify documentation needs based on: + - Code complexity + - Public vs. private interfaces + - User expertise level + - Documentation standards for the language/framework +4. Generate appropriate documentation using language-specific formats (JSDoc, Docstring, etc.) +5. Create supplementary materials (usage examples, diagrams) when needed + +DOCUMENTATION GUIDELINES: +1. Function/method documentation should include: + - Purpose description + - Parameter details (name, type, purpose) + - Return value information + - Exceptions/errors that may be thrown + - Usage examples for complex cases +2. Class/module documentation should include: + - Overview and purpose + - Initialization requirements + - Public interface description + - Usage patterns +3. README documentation should include: + - Project overview + - Installation instructions + - Basic usage examples + - Configuration options + - Common troubleshooting + +CONSTRAINTS: +- Balance comprehensiveness with clarity and brevity +- Follow language and framework documentation conventions +- Prioritize documenting public interfaces over internal implementation +- Use consistent terminology and formatting +- Include examples for complex functionality +- Avoid redundant documentation +- Focus on the "why" for complex code, not just the "what" +""" + +# Testing Strategy Agent - Develops testing approaches and test cases +TESTING_STRATEGY_AGENT = """ +# Testing Strategy Agent Instruction + +You are a specialized Testing Strategy Agent in a multi-agent system. Your purpose is to develop testing approaches and generate test cases for code. + +PRIMARY RESPONSIBILITIES: +1. Design comprehensive testing strategies +2. Generate unit, integration, and system test cases +3. Create test fixtures and mock objects +4. Identify edge cases and error conditions +5. Develop test coverage analysis + +WORKFLOW: +1. Receive code and testing requirements from other agents +2. Analyze code structure, functionality, and potential failure points +3. Determine appropriate testing levels and methods: + - Unit testing + - Integration testing + - System testing + - Performance testing + - Security testing +4. Generate test cases and supporting code +5. Provide coverage analysis and testing recommendations + +TEST CASE DEVELOPMENT: +1. Happy path tests (expected normal usage) +2. Edge case tests (boundary conditions) +3. Error case tests (invalid inputs, resource failures) +4. Performance tests (for optimized code) +5. Regression tests (for refactored code) + +OUTPUT FORMAT: +1. Testing Strategy Overview +2. Test Case Specifications +3. Test Code Implementation +4. Mock/Fixture Setup +5. Coverage Analysis +6. Testing Recommendations + +CONSTRAINTS: +- Balance thoroughness with practical implementation effort +- Use appropriate testing frameworks for the language/platform +- Focus on testability and isolation of components +- Consider both positive and negative test cases +- Prioritize tests based on risk and complexity +- Use automation-friendly testing approaches +- Include documentation for complex test setups +""" +# Implementation Agent Design + + +# Implementation Agent - Translates design specifications into working code +IMPLEMENTATION_AGENT = """ +You are a specialized Implementation Agent in a multi-agent system. Your purpose is to transform architecture and requirements documentation into efficient, working code that meets specifications. + +PRIMARY RESPONSIBILITIES: +1. Convert architectural designs and requirements into executable code +2. Implement functionality according to specified patterns and best practices +3. Generate code that balances readability, efficiency, and maintainability +4. Apply appropriate error handling and input validation +5. Ensure code adheres to language-specific conventions and standards + +WORKFLOW: +1. Receive requirements analysis and architectural design documents +2. Analyze the design specifications to understand: + - Core functionality requirements + - Data structures and their relationships + - Algorithms and processing logic + - Interface specifications + - Error handling requirements +3. Break down implementation into logical components +4. Implement each component following the architectural guidelines +5. Apply appropriate patterns, idioms, and best practices +6. Include necessary error handling and validation +7. Generate comprehensive inline documentation + +IMPLEMENTATION GUIDELINES: +1. Code Structure: + - Modular organization following the architecture + - Clear separation of concerns + - Consistent naming conventions + - Logical file/component organization + +2. Code Quality: + - Write DRY (Don't Repeat Yourself) code + - Ensure performant implementation + - Balance between abstraction and simplicity + - Implement robust error handling + - Consider edge cases and potential failures + +3. Language-Specific Considerations: + - Follow language idioms and conventions + - Use appropriate built-in features and libraries + - Apply language-specific optimization techniques + - Follow community-standard style guidelines + +OUTPUT FORMAT: +1. Code Implementation: + - Complete, working code snippets + - Properly formatted and indented + - With appropriate comments + - Organized by component/module + +2. Implementation Notes: + - Key decisions made during implementation + - Any deviations from the architecture (with justification) + - Potential areas for future refinement + +CONSTRAINTS: +- Strictly adhere to the provided architectural design +- Focus on implementing only what's specified in the requirements +- Balance ideal patterns with practical implementation needs +- Prioritize correctness over premature optimization +- Consider maintainability and readability as first-class concerns +- When multiple implementation approaches exist, choose the most appropriate one for the context and explain your reasoning +- Include only necessary dependencies +- Ensure code is secure and handles edge cases gracefully +""" +# Architecture Design Agent - Creates software design blueprints from requirements +ARCHITECTURE_DESIGN_AGENT = """ +# Architecture Design Agent Instruction + +You are a specialized Architecture Design Agent in a multi-agent system. Your purpose is to transform analyzed requirements into a clear, implementable software architecture that balances technical excellence with practical considerations. + +PRIMARY RESPONSIBILITIES: +1. Transform requirements into a coherent technical architecture +2. Design component structures, relationships, and interactions +3. Select appropriate design patterns, frameworks, and technologies +4. Balance quality attributes (scalability, performance, security, maintainability) +5. Provide clear guidance for implementation + +WORKFLOW: +1. Receive structured requirements from the Requirements Analysis Agent +2. Analyze requirements to identify architectural drivers: + - Core functional needs + - Critical quality attributes + - Technical constraints + - Integration requirements + - Scaling expectations +3. Design the appropriate architecture: + - System-level structure and components + - Communication patterns and interfaces + - Data models and state management + - Error handling and resilience approaches + - Security mechanisms +4. Create architectural diagrams and documentation +5. Validate the architecture against requirements +6. Provide detailed guidance for implementation + +ARCHITECTURAL DESIGN FRAMEWORKS: +1. Component Structure: + - Identify core components and their responsibilities + - Define component boundaries and interfaces + - Establish communication patterns between components + - Design hierarchical relationships where appropriate + +2. Data Architecture: + - Data storage and persistence strategies + - Data models and schemas + - Data flow and transformation + - Caching and performance optimization + +3. Integration Architecture: + - External system interfaces + - API design principles + - Authentication and authorization schemes + - Error handling and fault tolerance + +4. Technology Selection: + - Frameworks and libraries + - Programming languages (considering requirements) + - Tools and platforms + - Third-party services and components + +OUTPUT FORMAT: +1. Architecture Overview: + - High-level description of the architecture + - Key design decisions and rationale + - Visual representation (component diagrams, etc.) + +2. Component Specifications: + - Detailed description of each component + - Component responsibilities and boundaries + - Interface definitions + - Internal structure where relevant + +3. Technology Stack: + - Selected technologies with justification + - Version constraints and compatibility considerations + - Implementation recommendations + +4. Implementation Guidance: + - Design patterns to apply + - Code organization recommendations + - Critical considerations for developers + +CONSTRAINTS: +- Balance ideal architecture with practical implementation needs +- Consider the scale and complexity of the project in your design +- Prioritize architectures that suit the specified programming languages and environments +- Design for appropriate levels of flexibility without overengineering +- Be explicit about architectural trade-offs and decisions +- Consider resource constraints mentioned in requirements +- Ensure architecture supports all functional and quality requirements +- Provide designs that guide implementation without being overly prescriptive +- When uncertain about requirements impact, provide options with tradeoffs +""" \ No newline at end of file diff --git a/DeepCode/agent_folder/README.md b/DeepCode/agent_folder/README.md new file mode 100644 index 000000000..f41493732 --- /dev/null +++ b/DeepCode/agent_folder/README.md @@ -0,0 +1,68 @@ +# PDF to Markdown Converter + +## Overview +This Python script provides a comprehensive tool for converting PDF files to Markdown format. It offers two conversion methods: basic and advanced. + +## Features +- Basic text extraction from PDFs +- Advanced text extraction with formatting +- Batch conversion of multiple PDFs +- Logging support +- Error handling + +## Prerequisites +- Python 3.7+ +- PyPDF2 library + +## Installation +```bash +pip install PyPDF2 +``` + +## Usage + +### Basic Conversion +```python +from pdf_to_markdown_converter import PDFToMarkdownConverter + +# Create converter instance +converter = PDFToMarkdownConverter() + +# Convert a single PDF using basic method +converter.basic_pdf_to_markdown('document.pdf') +``` + +### Advanced Conversion +```python +# Convert a single PDF using advanced method +converter.advanced_pdf_to_markdown('document.pdf', 'output.md') +``` + +### Batch Conversion +```python +# Convert all PDFs in a directory +converter.batch_convert('/path/to/pdf/directory') +``` + +## Conversion Methods +1. **Basic Method**: Simple text extraction +2. **Advanced Method**: + - Adds page numbers as headers + - Attempts to format headers + - Identifies potential list items + +## Limitations +- May not perfectly preserve complex formatting +- Limited support for images and tables +- Works best with text-heavy PDFs + +## Troubleshooting +- Ensure PDFs are text-based +- Check file permissions +- Verify PyPDF2 is correctly installed + +## Contributing +Contributions are welcome! Please submit pull requests or open issues on the repository. + +## License +[Insert your license information here] \ No newline at end of file diff --git a/DeepCode/agent_folder/a-b.py b/DeepCode/agent_folder/a-b.py new file mode 100644 index 000000000..0b7d323c9 --- /dev/null +++ b/DeepCode/agent_folder/a-b.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +""" +File: a-b.py +Description: A simple Python script that performs subtraction between two numbers. +""" + +def subtract(a, b): + """ + Subtracts b from a and returns the result. + + Args: + a (number): The first number (minuend) + b (number): The second number (subtrahend) + + Returns: + number: The difference between a and b (a - b) + """ + return a - b + +def get_numeric_input(prompt): + """ + Helper function to get valid numeric input from the user. + + Args: + prompt (str): The input prompt to display to the user + + Returns: + float: The validated numeric input + """ + while True: + try: + value = float(input(prompt)) + return value + except ValueError: + print("Error: Please enter a valid number.") + +def main(): + """ + Main function that handles user interaction and displays results. + """ + print("Subtraction Calculator (a - b)") + print("-" * 30) + + a = get_numeric_input("Enter the value of a: ") + b = get_numeric_input("Enter the value of b: ") + + result = subtract(a, b) + print(f"\nResult: {a} - {b} = {result}") + + # Handle integer vs. float display format for cleaner output + if result == int(result): + print(f"\nResult: {a} - {b} = {int(result)}") + else: + print(f"\nResult: {a} - {b} = {result}") + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/DeepCode/agent_folder/add_numbers.py b/DeepCode/agent_folder/add_numbers.py new file mode 100644 index 000000000..4011c55d3 --- /dev/null +++ b/DeepCode/agent_folder/add_numbers.py @@ -0,0 +1,24 @@ +def add_numbers(a, b): + """ + A function that adds two numbers and returns the result. + + Args: + a: The first number + b: The second number + + Returns: + The sum of a and b + """ + return a + b + +# Example usage +if __name__ == "__main__": + # Get input from user + a = float(input("Enter the first number (a): ")) + b = float(input("Enter the second number (b): ")) + + # Calculate the sum + result = add_numbers(a, b) + + # Display the result + print(f"The sum of {a} + {b} = {result}") \ No newline at end of file diff --git a/DeepCode/agent_folder/multiply_numbers.py b/DeepCode/agent_folder/multiply_numbers.py new file mode 100644 index 000000000..3e2088100 --- /dev/null +++ b/DeepCode/agent_folder/multiply_numbers.py @@ -0,0 +1,24 @@ +def multiply_numbers(a, b): + """ + A function that multiplies two numbers and returns the result. + + Args: + a: The first number + b: The second number + + Returns: + The product of a and b + """ + return a * b + +# Example usage +if __name__ == "__main__": + # Get input from user + a = float(input("Enter the first number (a): ")) + b = float(input("Enter the second number (b): ")) + + # Calculate the product + result = multiply_numbers(a, b) + + # Display the result + print(f"The product of {a} * {b} = {result}") \ No newline at end of file diff --git a/DeepCode/agent_folder/pdf_to_markdown_converter.py b/DeepCode/agent_folder/pdf_to_markdown_converter.py new file mode 100644 index 000000000..7cf523161 --- /dev/null +++ b/DeepCode/agent_folder/pdf_to_markdown_converter.py @@ -0,0 +1,253 @@ +#!/usr/bin/env python3 +""" +PDF to Markdown Converter + +A comprehensive tool for converting PDF files to Markdown format. + +Dependencies: +- PyPDF2 +- python-docx (optional) + +Install dependencies: +pip install PyPDF2 +""" + +import os +import re +import logging +from typing import Optional, List, Union + +try: + import PyPDF2 +except ImportError: + print("Please install PyPDF2: pip install PyPDF2") + raise + +class PDFToMarkdownConverter: + def __init__(self, log_level=logging.INFO): + """ + Initialize the PDF to Markdown converter. + + Args: + log_level (int): Logging level (default: logging.INFO) + """ + # Configure logging + logging.basicConfig( + level=log_level, + format='%(asctime)s - %(levelname)s: %(message)s' + ) + self.logger = logging.getLogger(__name__) + + def basic_pdf_to_markdown( + self, + pdf_path: str, + output_path: Optional[str] = None + ) -> Optional[str]: + """ + Basic PDF to Markdown conversion. + + Args: + pdf_path (str): Path to the input PDF file + output_path (str, optional): Path to save the output Markdown file + + Returns: + str: Path to the generated Markdown file or None if conversion fails + """ + try: + # Validate input file + self._validate_pdf_file(pdf_path) + + # Determine output path + if output_path is None: + output_path = os.path.splitext(pdf_path)[0] + '.md' + + # Extract text from PDF + with open(pdf_path, 'rb') as file: + pdf_reader = PyPDF2.PdfReader(file) + markdown_content = [] + + for page in pdf_reader.pages: + page_text = page.extract_text() + markdown_content.append(page_text) + + # Combine pages + full_markdown = '\n\n'.join(markdown_content) + + # Write to Markdown file + with open(output_path, 'w', encoding='utf-8') as md_file: + md_file.write(full_markdown) + + self.logger.info(f"Basic Markdown file created: {output_path}") + return output_path + + except Exception as e: + self.logger.error(f"Error in basic PDF to Markdown conversion: {e}") + return None + + def advanced_pdf_to_markdown( + self, + pdf_path: str, + output_path: Optional[str] = None + ) -> Optional[str]: + """ + Advanced PDF to Markdown conversion with formatting. + + Args: + pdf_path (str): Path to the input PDF file + output_path (str, optional): Path to save the output Markdown file + + Returns: + str: Path to the generated Markdown file or None if conversion fails + """ + try: + # Validate input file + self._validate_pdf_file(pdf_path) + + # Determine output path + if output_path is None: + output_path = os.path.splitext(pdf_path)[0] + '.md' + + # Extract and format text from PDF + with open(pdf_path, 'rb') as file: + pdf_reader = PyPDF2.PdfReader(file) + markdown_content = [] + + for page_num, page in enumerate(pdf_reader.pages, 1): + # Extract text + page_text = page.extract_text() + + # Add page numbers as headers + page_header = f"\n## Page {page_num}\n" + + # Identify potential headers and list items + formatted_text = self._format_markdown_text(page_text) + + # Combine page header and formatted text + markdown_page = page_header + formatted_text + markdown_content.append(markdown_page) + + # Join pages + full_markdown = '\n\n'.join(markdown_content) + + # Write to Markdown file + with open(output_path, 'w', encoding='utf-8') as md_file: + md_file.write(full_markdown) + + self.logger.info(f"Advanced Markdown file created: {output_path}") + return output_path + + except Exception as e: + self.logger.error(f"Error in advanced PDF to Markdown conversion: {e}") + return None + + def _validate_pdf_file(self, pdf_path: str) -> None: + """ + Validate the input PDF file. + + Args: + pdf_path (str): Path to the PDF file + + Raises: + FileNotFoundError: If the file does not exist + ValueError: If the file is not a PDF + """ + if not os.path.exists(pdf_path): + raise FileNotFoundError(f"PDF file not found: {pdf_path}") + + if not pdf_path.lower().endswith('.pdf'): + raise ValueError("Input file must be a PDF") + + def _format_markdown_text(self, text: str) -> str: + """ + Apply basic Markdown formatting to the text. + + Args: + text (str): Input text to format + + Returns: + str: Formatted Markdown text + """ + # Convert potential headers (lines starting with capital letters) + text = re.sub(r'^([A-Z][^\n]{10,})$', r'### \1', text, flags=re.MULTILINE) + + # Identify potential list items + text = re.sub(r'^(\s*[-•*])', r'- ', text, flags=re.MULTILINE) + + # Remove excessive whitespace + text = re.sub(r'\n{3,}', '\n\n', text) + + return text + + def batch_convert( + self, + input_dir: str, + output_dir: Optional[str] = None, + conversion_method: str = 'advanced' + ) -> List[str]: + """ + Batch convert PDF files in a directory to Markdown. + + Args: + input_dir (str): Directory containing PDF files + output_dir (str, optional): Directory to save Markdown files + conversion_method (str): 'basic' or 'advanced' conversion method + + Returns: + List of converted Markdown file paths + """ + # Validate input directory + if not os.path.isdir(input_dir): + raise ValueError(f"Invalid input directory: {input_dir}") + + # Create output directory if not specified + if output_dir is None: + output_dir = os.path.join(input_dir, 'markdown_output') + os.makedirs(output_dir, exist_ok=True) + + # Find PDF files + pdf_files = [ + f for f in os.listdir(input_dir) + if f.lower().endswith('.pdf') + ] + + converted_files = [] + + # Convert each PDF file + for pdf_file in pdf_files: + pdf_path = os.path.join(input_dir, pdf_file) + md_filename = os.path.splitext(pdf_file)[0] + '.md' + md_path = os.path.join(output_dir, md_filename) + + try: + if conversion_method == 'basic': + result = self.basic_pdf_to_markdown(pdf_path, md_path) + else: + result = self.advanced_pdf_to_markdown(pdf_path, md_path) + + if result: + converted_files.append(result) + except Exception as e: + self.logger.error(f"Failed to convert {pdf_file}: {e}") + + self.logger.info(f"Batch conversion complete. Converted {len(converted_files)} files.") + return converted_files + +def main(): + """ + Main function to demonstrate PDF to Markdown conversion. + """ + converter = PDFToMarkdownConverter() + + # Example usage instructions + print("PDF to Markdown Converter") + print("------------------------") + print("Usage examples:") + print("1. Convert a single PDF (basic method):") + print(" converter.basic_pdf_to_markdown('document.pdf')") + print("\n2. Convert a single PDF (advanced method):") + print(" converter.advanced_pdf_to_markdown('document.pdf', 'output.md')") + print("\n3. Batch convert PDFs in a directory:") + print(" converter.batch_convert('/path/to/pdf/directory')") + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/DeepCode/deepcode_agent.py b/DeepCode/deepcode_agent.py new file mode 100644 index 000000000..4a3066f0d --- /dev/null +++ b/DeepCode/deepcode_agent.py @@ -0,0 +1,27 @@ +import asyncio + +from mcp_agent.core.fastagent import FastAgent +from Deepcode.agents.code_agents import * +# from rich import print + +# agents = FastAgent(name="Researcher Agent") + + + +async def main() -> None: + research_prompt = """ +Produce an investment report for the company Eutelsat. The final report should be saved in the filesystem in markdown format, and +contain at least the following: +1 - A brief description of the company +2 - Current financial position (find data, create and incorporate charts) +3 - A PESTLE analysis +4 - An investment thesis for the next 3 years. Include both 'buy side' and 'sell side' arguments, and a final +summary and recommendation. +Todays date is 15 February 2025. Include the main data sources consulted in presenting the report.""" # noqa: F841 + + async with agents.run() as agent: + await agent.CodeAssistAgent.prompt() + + +if __name__ == "__main__": + asyncio.run(main()) # type: ignore diff --git a/DeepCode/fastagent.config.yaml b/DeepCode/fastagent.config.yaml new file mode 100644 index 000000000..5988b726c --- /dev/null +++ b/DeepCode/fastagent.config.yaml @@ -0,0 +1,66 @@ +# +# Please edit this configuration file to match your environment (on Windows). +# Examples in comments below - check/change the paths. +# +# + +execution_engine: asyncio +logger: + type: console + level: error + truncate_tools: true + +mcp: + servers: + brave: + # On windows replace the command and args line to use `node` and the absolute path to the server. + # Use `npm i -g @modelcontextprotocol/server-brave-search` to install the server globally. + # Use `npm -g root` to find the global node_modules path.` + # command: "node" + # args: ["c:/Program Files/nodejs/node_modules/@modelcontextprotocol/server-brave-search/dist/index.js"] + command: "npx" + args: ["-y", "@modelcontextprotocol/server-brave-search"] + env: + # You can also place your BRAVE_API_KEY in the fastagent.secrets.yaml file. + BRAVE_API_KEY: "BSANqscKbm32rSDleDiDPK6uyFXOHrm" + filesystem: + # On windows update the command and arguments to use `node` and the absolute path to the server. + # Use `npm i -g @modelcontextprotocol/server-filesystem` to install the server globally. + # Use `npm -g root` to find the global node_modules path.` + # command: "node" + # args: ["c:/Program Files/nodejs/node_modules/@modelcontextprotocol/server-filesystem/dist/index.js","./agent_folder"] + command: "npx" + args: ["-y", "@modelcontextprotocol/server-filesystem", "./agent_folder/"] + interpreter: + command: "docker" + args: [ + "run", + "-i", + "--rm", + "--pull=always", + "-v", + "./agent_folder:/mnt/data/", + # Docker needs the absolute path on Windows (e.g. "x:/fastagent/agent_folder:/mnt/data/") + # "./agent_folder:/mnt/data/", + "ghcr.io/evalstate/mcp-py-repl:latest", + ] + roots: + - uri: "file://./agent_folder/" + name: "agent_folder" + server_uri_alias: "file:///mnt/data/" + fetch: + command: "uvx" + args: ["mcp-server-fetch"] + sequential: + command: "npx" + args: ["-y","@modelcontextprotocol/server-sequential-thinking"] + +# webmcp: +# command: "node" +# args: ["/home/ssmith/.webmcp/server.cjs"] +# env: +# WEBMCP_SERVER_TOKEN: 96e22896d8143fc1d61fec09208fc5ed + + + + diff --git a/DeepCode/fastagent.secrets.yaml b/DeepCode/fastagent.secrets.yaml new file mode 100644 index 000000000..02d9043b3 --- /dev/null +++ b/DeepCode/fastagent.secrets.yaml @@ -0,0 +1,23 @@ +# FastAgent Secrets Configuration +# WARNING: Keep this file secure and never commit to version control + +# Alternatively set OPENAI_API_KEY, ANTHROPIC_API_KEY or other environment variables. +# Keys in the configuration file override environment variables. + +openai: + api_key: "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" + +anthropic: + api_key: "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" +# deepseek: +# api_key: +# openrouter: +# api_key: + + +# Example of setting an MCP Server environment variable +mcp: + servers: + brave: + env: + BRAVE_API_KEY: "BSANqscKbm32rSDleDiDPK6uyFXOHrm" From e939912c8bf9eb758caf11c80e28f03be9d487d8 Mon Sep 17 00:00:00 2001 From: zrguo <49157727+LarFii@users.noreply.github.com> Date: Wed, 14 May 2025 13:54:41 +0800 Subject: [PATCH 2/4] Add lint workflow --- .github/ISSUE_TEMPLATE/bug_report.yml | 61 ++++++++++++++++++++++ .github/ISSUE_TEMPLATE/config.yml | 1 + .github/ISSUE_TEMPLATE/feature_request.yml | 26 +++++++++ .github/ISSUE_TEMPLATE/question.yml | 26 +++++++++ .github/dependabot.yml | 11 ++++ .github/pull_request_template.md | 32 ++++++++++++ .github/workflows/linting.yaml | 30 +++++++++++ 7 files changed, 187 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE/bug_report.yml create mode 100644 .github/ISSUE_TEMPLATE/config.yml create mode 100644 .github/ISSUE_TEMPLATE/feature_request.yml create mode 100644 .github/ISSUE_TEMPLATE/question.yml create mode 100644 .github/dependabot.yml create mode 100644 .github/pull_request_template.md create mode 100644 .github/workflows/linting.yaml diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 000000000..780a2008a --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,61 @@ +name: Bug Report +description: File a bug report +title: "[Bug]:" +labels: ["bug", "triage"] + +body: + - type: checkboxes + id: existingcheck + attributes: + label: Do you need to file an issue? + description: Please help us manage our time by avoiding duplicates and common bugs with the steps below. + options: + - label: I have searched the existing issues and this bug is not already filed. + - label: I believe this is a legitimate bug, not just a question or feature request. + - type: textarea + id: description + attributes: + label: Describe the bug + description: A clear and concise description of what the bug is. + placeholder: What went wrong? + - type: textarea + id: reproduce + attributes: + label: Steps to reproduce + description: Steps to reproduce the behavior. + placeholder: How can we replicate the issue? + - type: textarea + id: expected_behavior + attributes: + label: Expected Behavior + description: A clear and concise description of what you expected to happen. + placeholder: What should have happened? + - type: textarea + id: configused + attributes: + label: LightRAG Config Used + description: The LightRAG configuration used for the run. + placeholder: The settings content or LightRAG configuration + value: | + # Paste your config here + - type: textarea + id: screenshotslogs + attributes: + label: Logs and screenshots + description: If applicable, add screenshots and logs to help explain your problem. + placeholder: Add logs and screenshots here + - type: textarea + id: additional_information + attributes: + label: Additional Information + description: | + - LightRAG Version: e.g., v0.1.1 + - Operating System: e.g., Windows 10, Ubuntu 20.04 + - Python Version: e.g., 3.8 + - Related Issues: e.g., #1 + - Any other relevant information. + value: | + - LightRAG Version: + - Operating System: + - Python Version: + - Related Issues: diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 000000000..3ba13e0ce --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1 @@ +blank_issues_enabled: false diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 000000000..3c127d59c --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,26 @@ +name: Feature Request +description: File a feature request +labels: ["enhancement"] +title: "[Feature Request]:" + +body: + - type: checkboxes + id: existingcheck + attributes: + label: Do you need to file a feature request? + description: Please help us manage our time by avoiding duplicates and common feature request with the steps below. + options: + - label: I have searched the existing feature request and this feature request is not already filed. + - label: I believe this is a legitimate feature request, not just a question or bug. + - type: textarea + id: feature_request_description + attributes: + label: Feature Request Description + description: A clear and concise description of the feature request you would like. + placeholder: What this feature request add more or improve? + - type: textarea + id: additional_context + attributes: + label: Additional Context + description: Add any other context or screenshots about the feature request here. + placeholder: Any additional information diff --git a/.github/ISSUE_TEMPLATE/question.yml b/.github/ISSUE_TEMPLATE/question.yml new file mode 100644 index 000000000..26fed23d9 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/question.yml @@ -0,0 +1,26 @@ +name: Question +description: Ask a general question +labels: ["question"] +title: "[Question]:" + +body: + - type: checkboxes + id: existingcheck + attributes: + label: Do you need to ask a question? + description: Please help us manage our time by avoiding duplicates and common questions with the steps below. + options: + - label: I have searched the existing question and discussions and this question is not already answered. + - label: I believe this is a legitimate question, not just a bug or feature request. + - type: textarea + id: question + attributes: + label: Your Question + description: A clear and concise description of your question. + placeholder: What is your question? + - type: textarea + id: context + attributes: + label: Additional Context + description: Provide any additional context or details that might help us understand your question better. + placeholder: Add any relevant information here diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 000000000..9d866e392 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,11 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for all configuration options: +# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file + +version: 2 +updates: + - package-ecosystem: "pip" # See documentation for possible values + directory: "/" # Location of package manifests + schedule: + interval: "weekly" diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 000000000..258bd3324 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,32 @@ + + +## Description + +[Briefly describe the changes made in this pull request.] + +## Related Issues + +[Reference any related issues or tasks addressed by this pull request.] + +## Changes Made + +[List the specific changes made in this pull request.] + +## Checklist + +- [ ] Changes tested locally +- [ ] Code reviewed +- [ ] Documentation updated (if necessary) +- [ ] Unit tests added (if applicable) + +## Additional Notes + +[Add any additional notes or context for the reviewer(s).] diff --git a/.github/workflows/linting.yaml b/.github/workflows/linting.yaml new file mode 100644 index 000000000..aa0543699 --- /dev/null +++ b/.github/workflows/linting.yaml @@ -0,0 +1,30 @@ +name: Linting and Formatting + +on: + push: + branches: + - main + pull_request: + branches: + - main + +jobs: + lint-and-format: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v2 + + - name: Set up Python + uses: actions/setup-python@v2 + with: + python-version: '3.x' + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install pre-commit + + - name: Run pre-commit + run: pre-commit run --all-files --show-diff-on-failure From ac2c9452d8c6bf1fb260eac9c0121c76dbfba7af Mon Sep 17 00:00:00 2001 From: zrguo <49157727+LarFii@users.noreply.github.com> Date: Wed, 14 May 2025 13:56:15 +0800 Subject: [PATCH 3/4] Create .pre-commit-config.yaml --- .pre-commit-config.yaml | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 .pre-commit-config.yaml diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 000000000..0629b7432 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,28 @@ +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v5.0.0 + hooks: + - id: trailing-whitespace + exclude: ^lightrag/api/webui/ + - id: end-of-file-fixer + exclude: ^lightrag/api/webui/ + - id: requirements-txt-fixer + exclude: ^lightrag/api/webui/ + + + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.6.4 + hooks: + - id: ruff-format + exclude: ^lightrag/api/webui/ + - id: ruff + args: [--fix, --ignore=E402] + exclude: ^lightrag/api/webui/ + + + - repo: https://github.com/mgedmin/check-manifest + rev: "0.49" + hooks: + - id: check-manifest + stages: [manual] + exclude: ^lightrag/api/webui/ From f5ce99ed8953158bbdc7462bf00702654e5f59be Mon Sep 17 00:00:00 2001 From: zrguo <49157727+LarFii@users.noreply.github.com> Date: Wed, 14 May 2025 14:01:22 +0800 Subject: [PATCH 4/4] move --- .github/{ => workflows}/dependabot.yml | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename .github/{ => workflows}/dependabot.yml (100%) diff --git a/.github/dependabot.yml b/.github/workflows/dependabot.yml similarity index 100% rename from .github/dependabot.yml rename to .github/workflows/dependabot.yml