Skip to main content

Saizul Amin

AI

Building an Autonomous Coding Agent with LangGraph and Claude 3.5 Sonnet in Python (2026 Guide)

📅 28 Aug 2026 ⏱ 3 min read
AI
In this article

    The Next Frontier: Autonomous AI Coding Agents

    While basic LLM chatbots can generate short snippets of code, true software engineering requires autonomous iteration: reading repository structures, executing bash commands, interpreting compiler errors, running unit tests, and self-correcting logic until all tests pass. Using LangGraph—a stateful cyclical orchestration framework—combined with Claude 3.5 Sonnet, developers can construct robust, sandboxed coding agents capable of resolving complex GitHub issues autonomously.

    Authored by Saizul Amin based on hands-on AI agentic workflow engineering and system design.

    LangGraph State Machine Design for Code Generation

    Unlike linear LangChain chains, autonomous software agents require cyclical graph topologies. The agent must loop through a cycle of execution and self-reflection until defined criteria are met.

    Graph Node Responsibilities Output Artifact
    Planner Node Analyzes problem statement, inspects codebase, drafts execution plan Structured step-by-step task checklist
    Coder Node Writes or edits specific files based on planning context Unified diff or file rewrite instructions
    Test Runner Node Executes pytest or test suites inside a secure container Exit codes, stdout, stderr, stack traces
    Debugger Node Evaluates failed test output, updates hypothesis, invokes Coder Refined code patch or termination decision

    Full Implementation: Stateful Agent Graph in Python

    Below is an end-to-end Python implementation using LangGraph and Anthropic’\”s Claude 3.5 Sonnet:

    
    import operator
    from typing import Annotated, Sequence, TypedDict
    import subprocess
    from langchain_anthropic import ChatAnthropic
    from langchain_core.messages import BaseMessage, HumanMessage, SystemMessage
    from langgraph.graph import StateGraph, END
    
    # Define Agent State
    class AgentState(TypedDict):
        task_description: str
        target_file: str
        code_content: str
        test_output: str
        iteration: int
        is_success: bool
        messages: Annotated[Sequence[BaseMessage], operator.add]
    
    # Initialize LLM
    llm = ChatAnthropic(model="claude-3-5-sonnet-20241022", temperature=0.1)
    
    # Node 1: Code Generator
    def code_generator_node(state: AgentState) -> dict:
        prompt = f'\'''\'''\''You are an expert Python engineer.
    Task: {state['\''task_description'\'']}
    Target File: {state['\''target_file'\'']}
    Previous Test Output / Errors: {state['\''test_output'\'']}
    Current Code:
    {state['\''code_content'\'']}
    
    Return ONLY valid, updated Python code for the target file. No markdown fences.'\'''\'''\''
    
        response = llm.invoke([HumanMessage(content=prompt)])
        return {
            "code_content": response.content.strip(),
            "iteration": state["iteration"] + 1,
            "messages": [response]
        }
    
    # Node 2: Test Runner & Verification
    def test_runner_node(state: AgentState) -> dict:
        # Write updated code to disk
        with open(state["target_file"], "w") as f:
            f.write(state["code_content"])
    
        # Run pytest in isolated process
        cmd = ["pytest", "test_" + state["target_file"]]
        res = subprocess.run(cmd, capture_output=True, text=True)
    
        success = (res.returncode == 0)
        output = res.stdout if success else res.stderr + "
    " + res.stdout
    
        return {
            "test_output": output,
            "is_success": success
        }
    
    # Conditional Routing Logic
    def should_continue(state: AgentState) -> str:
        if state["is_success"]:
            return END
        if state["iteration"] >= 5:
            print("[WARNING] Maximum iterations reached. Exiting.")
            return END
        return "coder"
    
    # Construct State Graph
    workflow = StateGraph(AgentState)
    workflow.add_node("coder", code_generator_node)
    workflow.add_node("tester", test_runner_node)
    
    workflow.set_entry_point("coder")
    workflow.add_edge("coder", "tester")
    workflow.add_conditional_edges("tester", should_continue, {
        "coder": "coder",
        END: END
    })
    
    app = workflow.compile()
    

    Security Sandbox Considerations: Docker Containerization

    Autonomous agents must never execute code directly on the host machine. To prevent security vulnerabilities or catastrophic data loss:

    • Docker Sandbox Containers: Always execute agent subprocesses inside ephemeral, read-only root Docker containers with disabled network access (--network none).
    • Execution Timeouts: Enforce strict per-command execution timeouts (e.g., 30 seconds) to prevent infinite while loops or recursion crashes.

    Stateful multi-agent graphs represent the modern foundation of next-generation developer tooling, automating testing, debugging, and continuous feature integration.

    Share this article
    Md Saizul Amin
    Written by

    Digital Systems Strategist · AI Agent Developer · 9+ years in digital & IT

    Md Saizul Amin is a digital systems strategist and AI automation engineer from Dhaka, Bangladesh. With 9+ years across IT, web development and digital marketing, he writes practical guides on technology, business, education and online growth — and builds the same kinds of systems (AI agents, websites, SEO and ad campaigns) for clients in Bangladesh, the UK and the USA.

    9+Years in digital & IT
    50+Websites developed
    7Live AI agent systems
    $150K+Ad spend managed

    Specialist in

    AI agents & n8n automationLLM integration (Gemini, GPT-4o, Claude)Custom software & web appsWordPress developmentSEO · AEO · GEOMeta & Google AdsEmail deliverabilityCRM & funnelsIT infrastructure & cybersecurity

    Credentials & experience

    • 🎓
      B.Sc. in Computer Science & EngineeringBangladesh University of Business & Technology (BUBT), 2017–2021
    • 🤖
      AI Automation Engineer · Web Developer · SEO SpecialistUnique Mark Limited, Birmingham UK — 2024 to present
    • 🌱
      IT SpecialistGreen Fund Initiative Inc., USA — 2024 to present
    • 🏥
      Junior IT Consultant — Ministry of Health (DGHS)Built the first national Shareable Health Record website; supported 6,000+ facilities
    • 🧭
      Head of ITWEDO Bangladesh — led IT for 50+ staff, 2021–2023

    ✔ Researched and written by the author, informed by hands-on work on real projects. Articles are updated when facts, tools or guidelines change.

    Want results like this for your business?

    AI agents, custom software, websites and growth systems — let’s talk about yours.