SWE Agent LangGraph

repository·main·Indexed 20 days ago

https://github.com/langtalks/swe-agent

An AI-powered software engineering agent built with LangGraph that automates code implementation. It utilizes a two-stage workflow consisting of an Architect Agent for research and planning (generating an ImplementationPlan) and a Developer Agent for step-by-step execution and code modification. The system integrates LangChain, Anthropic's Claude Sonnet 4, Tree-sitter for code parsing, and Pydantic for state management.

Tokens
4.5K
Snippets
15
Records
19
Agent score
71%

What's inside swe-agent-langgraph

  1. How the SWE Agent architecture works

    main

    The system uses a two-stage LangGraph workflow to automate software engineering tasks:

    1. Architect Agent (Research & Planning): Analyzes requirements, researches the codebase structure, creates hypotheses, and generates a detailed ImplementationPlan consisting of atomic tasks.
    2. Developer Agent (Implementation): Receives the plan and executes it step-by-step. It performs atomic code modifications, creates/modifies files, and validates changes against requirements.

    Workflow Flow: User Request $\rightarrow$ Architect $\rightarrow$ Developer $\rightarrow$ Results.

  2. The Developer Agent Prompt Structure

    main

    The Developer Agent uses a chat-based prompt template to implement code changes. It relies on two primary input variables to provide context for the implementation task:

    • codebase_structure: A representation of the project's file hierarchy and structure to help the agent navigate the codebase.
    • scratchpad: A workspace or buffer where the agent can process intermediate thoughts, plan edits, or store temporary data during the implementation process.

    The prompt follows a specific sequence:

    1. System Message: Defines the agent's persona as a 'Senior Software Developer' and outlines its core responsibilities (understanding the plan and analyzing current code).
    2. Human Message (Context): Provides the {codebase_structure}.
    3. Placeholder: Injects the {scratchpad} content.
    4. Human Message (Instruction): Provides the final directive to copy relevant code snippets into an original_code context and execute edits based on the implementation plan.
    _type: "chat"
    input_variables:
        - scratchpad
        - codebase_structure
  3. Structure of the AI Software Architecture prompt

    main

    The think_step_prompt.md defines the system prompt for an AI Software Architecture agent. This agent acts as an advisor to a Human Software Engineer. Instead of invoking tools directly, the agent must reason about the next atomic step and provide structured guidance.

    An agent using this prompt must follow this specific output format:

    1. ## Your reasoning: A section where the agent explains its reasoning regarding the next task, focusing on one atomic step at a time.
    2. ## Instructions to the engineer: A section providing actionable guidance, including:
      • Tool to use: The specific tool the engineer should invoke.
      • File path: The full path (from the root folder) to the file the engineer needs to work on.

    If the task is complete, the agent should explicitly state that the task is done without suggesting a tool.

    Input Variables:

    • tool_descriptions: A list of available tools and their descriptions.
    • scratchpad: The current state or history of the interaction.

    Available Tools are injected into the prompt using the {tool_descriptions} placeholder.

    ## Your reasoning
    
    [Reasoning about the next atomic step]
    
    ## Instructions to the engineer
    Tool to use: [Tool Name]
    What is the full path ( from the root folder) to the file he need to work on: [File Path]
  4. Use the check_research_already_explored prompt for research evaluation

    main

    The check_research_already_explored prompt is a specialized system prompt designed for a critic research evaluator. Its purpose is to analyze proposed research steps to ensure they are not redundant and are aligned with the original task goal.

    Evaluation Logic

    The evaluator follows a specific procedure:

    1. Historical Analysis: Reviews previous research steps.
    2. Proposal Analysis: Analyzes the most recent AI message proposing a new step.
    3. Redundancy Check: Determines if the proposed step has already been explored.
    4. Goal Alignment: Verifies if the step connects to the initial human-provided task goal.

    Input Variables

    This prompt requires the following variable to be provided in the context:

    • implementation_research_scratchpad: Contains the historical research data and context used for the evaluation.
    # Input Variables
    - implementation_research_scratchpad
  5. The structure of the act_step_prompt

    main

    The act_step_prompt.md is a chat-type prompt template used by the Software Engineering Agent. It defines the agent's persona and operational constraints. The prompt is designed to ensure the agent acts as an executor of a Senior AI Software Architecture Consultant's reasoning rather than introducing its own independent logic.

    Key operational rules for the agent defined in this prompt:

    • Strict Adherence: The agent must strictly follow the thought process and analysis provided by the consultant.
    • Tool Execution: The agent must focus on the most recent <thought> block and execute the necessary tools to fulfill the requirements of that thought.
    • No Independent Reasoning: The agent is explicitly forbidden from introducing its own reasoning outside of the consultant's approach.
  6. Implementation Plan Extraction Prompt Structure

    main

    The extract_implementation_plan prompt is used by the Architect Agent to convert research findings into a structured, actionable implementation plan for a Developer Agent. It follows a chat-based format requiring specific input variables to function correctly.

    Input Variables

    • research_findings: The raw data and discoveries gathered during the research phase.
    • codebase_structure: The layout and organization of the project files.
    • output_format: A JSON schema defining the required structure of the resulting plan.

    Prompt Logic and Rules

    The prompt instructs the LLM to act as a Senior Software Architect following these constraints:

    1. Task Decomposition: Break findings into logical tasks (goals) and then into atomic tasks (concrete file edits or creations).
    2. Verbosity: Since the Architect cannot communicate with the Developer after handing over the plan, it must be highly verbose and include all necessary context from the research.
    3. Pathing: All file paths must be absolute relative to the project root, using the prefix ./workspace_repo/ (e.g., ./workspace_repo/src/main.py).
    4. Scope: Implementation plans should exclude README updates.
    5. Efficiency: Minimize file changes and complexity while ensuring the task is completed.
    {
      "input_variables": [
        "research_findings",
        "codebase_structure",
        "output_format"
      ]
    }
  7. Set up the development environment

    main

    To contribute to swe-agent-langgraph, you need to set up a local development environment using uv. This involves cloning the repository, syncing dependencies (including development tools), and optionally installing pre-commit hooks. You can verify the setup by running the test suite.

    # Clone your fork
    git clone https://github.com/langtalks/swe-agent-langgraph.git
    cd swe-agent-langgraph
    
    # Set up development environment
    uv sync --dev
    
    # Install pre-commit hooks (optional but recommended)
    pre-commit install
    
    # Run tests to ensure everything works
    uv run pytest
  8. Install and Quick Start SWE Agent

    main

    Follow these steps to set up and run the SWE Agent locally. This project requires Python 3.12+, uv for package management, and an Anthropic API key (Claude Sonnet 4).

    1. Clone the repository:

      git clone https://github.com/langtalks/swe-agent-langgraph.git
      cd swe-agent-langgraph
    2. Set up the environment:

      # Install dependencies with uv
      uv sync
      
      # Create environment file
      cp .env.example .env.local
      # Add your Anthropic API key and langsmith to .env.local
    3. Prepare a workspace (the codebase you want the agent to modify):

      git clone https://github.com/browser-use/browser-use ./workspace_repo
    4. Run the agent:

      # Activate environment
      source .venv/bin/activate
      
      # Start LangGraph server
      langgraph dev
    git clone https://github.com/langtalks/swe-agent-langgraph.git
    cd swe-agent-langgraph
    uv sync
    cp .env.example .env.local
    git clone https://github.com/browser-use/browser-use ./workspace_repo
    source .venv/bin/activate
    langgraph dev
  9. Configure the agent environment

    main

    The project uses several key files for configuration:

    • langgraph.json: Defines the agent graphs and their dependencies.
    • .env: Stores API keys and other environment variables.
    • pyproject.toml: Manages Python dependencies and project metadata.
  10. Use the implement_diff prompt for code editing

    main

    The implement_diff prompt is designed for a Developer Agent to perform precise code edits. It takes the context of an existing file, a specific code snippet that requires modification, and a description of the task.

    To use this prompt, you must provide the following input variables:

    • file_content: The full content of the file containing the snippet.
    • snippet: The specific block of code that needs to be edited.
    • task: A clear instruction describing the required change.

    The prompt instructs the model to output only the new code, maintaining the original indentation and spacing style, wrapped in a language-specific markdown code block.

    # The expected output format from the model
    put the new code here
  11. Format code changes using the code_change_request block

    main

    When implementing code changes, the Developer Agent must output changes using a specific <code_change_request> XML-style block. This format is used to map original code (including line numbers) to the new edited version.

    Each block must contain:

    1. original_code_snippet: The exact code being replaced, copied from the file content. Crucially, this must include the original line numbers in the format lineNumber| code.
    2. edit_code_snippet: The new version of the code. This should not include line numbers and should contain only the code without additional explanation.

    The agent should output only the necessary <code_change_request> blocks without further explanation.

    <code_change_request>
    original_code_snippet:
    127| For more examples see the [examples](examples) folder or join the [Discord](https://link.browser-use.com/discord) and show off your project.
    128| 
    129| Vision
    edit_code_snippet:
    For more examples see the [examples](examples) folder or join the [Discord](https://link.browser-use.com/discord) and show off your project.
    
    Project Structure - Main Folder Files
    
    The main directory contains several important files that configure and document the browser-use project:
    </code_change_request>
  12. Use the get_clear_implementation_plan prompt template

    main

    The get_clear_implementation_plan prompt is a chat-based template used by the Developer Agent to transition from codebase research to a concrete implementation plan. It requires several input variables to provide the agent with the necessary context to analyze a task and determine if further research is required before editing a file.

    To use this template, you must provide the following variables:

    • development_task: The specific task or feature to be implemented.
    • target_file: The exact path of the file that is to be modified.
    • file_content: The current content of the target file (if it is not a new file).
    • codebase_structure: A representation of the project's directory and file hierarchy.
    • additional_context: Any extra information relevant to the task.
    • atomic_implementation_research: A placeholder for research findings gathered during the exploration phase.
    {
      "input_variables": [
        "development_task",
        "target_file",
        "file_content",
        "codebase_structure",
        "additional_context",
        "atomic_implementation_research"
      ]
    }