LangGraph vs CrewAI vs AutoGen: Best Local Coding Agents

Compare LangGraph, CrewAI, and AutoGen for local coding agents on Ollama, LM Studio, and vLLM—covering state control, tool calling, sandboxing, and VR

LangGraph, CrewAI, and AutoGen compared for local AI coding agent workflows

LOCAL AI ENGINEERING · AGENT FRAMEWORKS · SOFTWARE DEVELOPMENT

By Abdulrahman Maslmany • Software Engineering and AI Architecture • Updated December 1, 2026

A local AI coding agent is not just a language model with access to a terminal. It is a small software system that has to inspect a project, decide what to do, call tools, handle failures, and avoid damaging the files it was meant to help with.

That last part matters more than it might seem. A model can suggest a plausible change that is still wrong, run a command in the wrong directory, or misunderstand a test failure. The orchestration framework helps organize the process, but it does not make the model reliable by itself.

Three names often come up when developers compare agent frameworks for local LLMs: LangGraph, CrewAI, and Microsoft AutoGen. They are not interchangeable products. LangGraph emphasizes explicit workflow control and state, CrewAI makes it straightforward to organize role-based agents and tasks, and AutoGen is an established framework for conversational multi-agent applications. Microsoft has since released the Microsoft Agent Framework (1.0) as the newer direction for agent and workflow development.

This guide looks at what each approach is good at, where it adds complexity, and what changes when the model runs locally through tools such as Ollama, LM Studio, or vLLM. It also includes a small LangGraph example, with code execution deliberately left behind a safe integration point rather than pretending that running generated code on the host is harmless.

Quick Answer: Which Framework Should You Choose?

Choose LangGraph when you need explicit state, branching, retries, and checkpoints for coding loops. Choose CrewAI when a role-and-task structure makes the application easier to reason about. Evaluate Microsoft Agent Framework for new Microsoft-oriented agent projects, and treat AutoGen primarily as an option for understanding or maintaining existing applications. All three can integrate with local runners like Ollama, LM Studio, and vLLM through compatible endpoints.

Local Agent Framework Selector

Select your primary workload, local model runner, and preferred control pattern for architectural guidance. This tool reflects workflow trade-offs, not measured benchmark results.

SUGGESTED ARCHITECTURE

LangGraph

Explicit graph state, conditional transitions, and checkpoints make it easier to manage code edits, test failures, retries, and human approval.

1. Why Build a Local Coding Agent?

A coding agent combines a language model with tools that can inspect files, propose edits, run checks, and report what happened. A conventional assistant may answer a question about a function. An agent can take a sequence of actions: read the function, inspect its callers, draft a patch, run a test, and use the result to decide what to do next.

Running the model locally can be useful when source code should remain on a workstation, when internet access is limited, or when a team wants more control over inference costs. Local execution is not automatically private or secure, though. Logs, editor extensions, tool servers, and network-enabled containers can still expose project data if they are configured carelessly.

A Realistic Coding-Agent Loop

  1. Inspect the workspace. Read only the files relevant to the reported issue.
  2. Understand the failure. Check the error message, test expectations, and nearby code before changing anything.
  3. Propose a patch. Generate a focused change instead of rewriting unrelated files.
  4. Validate it. Run tests and static checks in a restricted environment.
  5. Review the result. Show the diff and test output, including failures.
  6. Ask before sensitive actions. Require approval for destructive commands, broad file changes, or operations that access credentials or external services.

The framework coordinates this loop. It cannot guarantee that the model has understood the repository or that the tests cover the bug. Good tool design, clear permissions, and meaningful tests are still the developer's responsibility.

2. How LangGraph, CrewAI, and AutoGen Differ

LangGraph: Explicit Workflow Control

LangGraph represents an application as nodes connected by edges. A node might inspect a repository, generate a patch, run a test, or ask for human approval. The edges determine what happens next.

This model is useful when the workflow needs predictable branches. For example, a failed test can send execution back to the patching step, while a passing test can move to a review step. Checkpointing can preserve state so a workflow can resume after an interruption, depending on how persistence is configured.

Inspect project

↓

Draft a focused patch

↓

Run isolated tests

↓

Review test result

↙ Pass or fail ↘

Prepare review

Revise within retry limit

There is a trade-off: a graph makes control flow visible, but the developer has to design and maintain that flow. Checkpoints do not automatically lower token usage, improve code quality, or make tools safe. Those outcomes depend on the state schema, prompts, tool permissions, and implementation.

Documentation: LangGraph persistence and checkpointing.

CrewAI: Organizing Work Around Roles and Tasks

CrewAI gives developers a role-and-task-oriented way to organize agent work. A coding crew might include a researcher that investigates an issue, a developer that proposes a change, and a reviewer that checks the result.

This structure can make responsibilities easier to describe, especially when a task genuinely benefits from separate perspectives. It can also add overhead. Each agent may need its own instructions and context, and passing work between agents can mean more model calls and repeated information. A three-agent crew is not automatically better than one well-designed workflow.

CrewAI can be connected to compatible local model providers and inference endpoints, including Ollama and LM Studio. Check the current provider documentation for the exact integration and model capabilities you plan to use.

Microsoft AutoGen: Conversational Multi-Agent Applications

AutoGen introduced patterns for applications in which agents exchange messages, collaborate, and coordinate tool use. That conversational model is useful to understand when maintaining an existing AutoGen application or studying earlier multi-agent designs.

For a new project, do not assume that AutoGen is the default current Microsoft choice. Microsoft has introduced the Microsoft Agent Framework, which brings together ideas from AutoGen and Semantic Kernel. Review the current project status, support policy, and migration guidance before committing a new production system to an older framework.

Architectural comparison of LangGraph, CrewAI, and AutoGen frameworks for local AI coding agents

3. State Management and Context Usage

One easy way to waste local inference capacity is to keep sending the model information it has already seen. A coding agent can accumulate source files, tool output, test logs, and previous messages. If the application includes all of that in every request, the prompt becomes larger even when the next decision needs only a small part of it.

Keep Application State Separate From Chat History

For a code-fixing workflow, the application may need to store fields such as:

  • The current file or proposed patch.
  • The latest test result and a shortened error summary.
  • The current workflow stage.
  • The number of repair attempts already made.
  • Whether a human approval step is still required.

These values do not all need to be repeated to the model. Store structured results in the workflow state, then send only the relevant details when the next model decision is made. Keep enough information to reproduce and audit the operation, but avoid treating the entire conversation as the only database.

Practical recommendation

Keep application state separate from the model's conversation history. Store structured results between operations and send only the information required for the next decision.

For a related look at memory limits, see How to Pool System RAM with VRAM for Local AI Coding Agents.

4. Tool Calling with Ollama, LM Studio, and vLLM

Tool calling lets a model request an operation through a defined interface rather than writing an informal instruction that the application has to interpret. A tool might accept a file path and return file contents, or accept a test target and return a structured result.

Structured output helps, but valid JSON is not proof that a request is safe. The application must still check the requested tool, validate every argument, enforce path restrictions, and decide whether the operation is permitted. A model should not be allowed to turn an arbitrary string into an unrestricted shell command.

Connecting Frameworks to Local Inference Servers

Local inference servers differ in their support for tool calling, parallel function calls, and constrained output. Test the exact model and server combination instead of assuming that every model exposed through an OpenAI-compatible endpoint behaves identically:

  • Ollama: Exposes both a native API and an OpenAI-compatible endpoint (typically at http://localhost:11434/v1). Works straightforwardly with LangGraph via ChatOpenAI or native LangChain Ollama integrations, and with CrewAI via its Ollama/LiteLLM configuration.
  • LM Studio: Provides a local desktop developer server with an OpenAI-compatible endpoint (typically at http://localhost:1234/v1). When pairing LM Studio with frameworks that route through LiteLLM (such as CrewAI), pay attention to the /v1 base URL and the provider prefix (for example, using an openai/ prefix with a placeholder API key so LiteLLM routes to your local server instead of expecting a cloud provider).
  • vLLM and llama.cpp: Useful when you need higher throughput, fine-grained KV-cache control, or grammar- and schema-constrained decoding for more consistent JSON tool outputs.

For a comparison of local inference options, see vLLM vs Ollama vs llama.cpp for Local LLM Inference.

Connecting Agents to Tools via MCP

The Model Context Protocol (MCP) provides a standardized way for compatible applications to connect models and agents to external tools and resources. Learn more in our MCP Guide for Local LLMs.

5. Token Consumption in Multi-Agent Systems

Multi-agent systems can use more tokens than a single-agent workflow, but the difference depends on the design. If three agents each receive the same long repository context, the application may repeat much of that input. If agents exchange lengthy summaries or run several review rounds, usage grows further.

More agents do not necessarily mean better results. For a small bug, a single model call followed by a deterministic test may be enough. Separate agents make more sense when the work can be divided into genuinely distinct tasks and the additional review is worth the cost.

To keep context manageable, send only relevant files, trim repetitive logs, summarize earlier decisions, set a maximum number of retries, and monitor prompt tokens separately from generated tokens. Longer contexts can also increase KV-cache memory use during inference. See Context Window VRAM Scaling from 32K to 128K.

6. AutoGen and Microsoft Agent Framework

AutoGen remains relevant when you are reading existing projects, maintaining an application built with it, or learning how conversational multi-agent systems were structured. That does not mean it should automatically be selected for a new application.

Microsoft Agent Framework is the newer Microsoft framework (reaching 1.0 GA in 2026) to evaluate for new agent and workflow development. It draws on concepts from AutoGen and Semantic Kernel—adding session-based state management, middleware, and typed graph-based workflows—but it should not be treated as a drop-in replacement without checking the migration guide.

If you already have an AutoGen project, start by identifying which APIs it uses, which model clients it depends on, and how tools and termination conditions are configured. Then compare the migration guide with the effort required to keep the existing application running. A migration is worthwhile when it solves a real maintenance or capability problem—not simply because a newer name exists.

Reference: Microsoft Agent Framework: migration from AutoGen.

7. Safe Execution of AI-Generated Code

Generated code should be treated as untrusted input. Even a helpful coding model can produce a script that deletes files, reads environment variables, opens network connections, or consumes more resources than expected. Do not run its output directly on your everyday host environment.

A container can reduce some risks when configured carefully. The following command is an illustrative starting point for running Python tests in a container with no network access and limited resources:

docker run --rm \
  --network none \
  --memory=4g \
  --cpus=2 \
  --pids-limit=100 \
  --cap-drop=ALL \
  --security-opt=no-new-privileges \
  --read-only \
  --tmpfs /tmp:rw,noexec,nosuid,size=512m \
  --mount type=bind,src="$PWD",dst=/workspace,rw \
  -w /workspace \
  python:3.11-slim \
  sh -c "pip install --no-cache-dir pytest && python -m pytest"

Note that with --network none, pip install can only succeed if the package is already cached or available locally; for repeatable and offline-safe runs, build and review a custom image with pytest and your pinned dependencies pre-installed rather than installing packages at runtime.

There are important limits. The example mounts the current project directory as writable, so code inside the container can change those files. Use a disposable copy or a dedicated Git worktree if you want to protect the original checkout. Also review image provenance, mounted paths, user permissions, secrets, and Docker daemon access. Containers are not a complete security boundary for every threat model; stronger isolation may require a dedicated VM or sandbox service.

8. Building a Basic LangGraph Workflow with a Local Model

The following example demonstrates a small graph that asks a local model to propose a corrected Python function. It deliberately does not execute the returned code. The test node is a placeholder until you connect a properly isolated runner.

The example uses Ollama's OpenAI-compatible endpoint (http://localhost:11434/v1). If you prefer LM Studio, start its local server and point base_url to its endpoint (typically http://localhost:1234/v1) with the loaded model identifier. Always check the current LangChain integration documentation if package APIs change.

pip install langgraph langchain-openai langchain-core
ollama pull qwen2.5-coder:14b
ollama serve

Save the Python code below as a file such as coding_agent.py:

from typing import TypedDict

from langchain_core.messages import HumanMessage, SystemMessage
from langchain_openai import ChatOpenAI
from langgraph.graph import END, StateGraph


class AgentState(TypedDict):
    code: str
    error: str
    iterations: int
    test_passed: bool
    patch: str


llm = ChatOpenAI(
    base_url="http://localhost:11434/v1",  # Or http://localhost:1234/v1 for LM Studio
    api_key="ollama",
    model="qwen2.5-coder:14b",
    temperature=0,
)


def patch_code(state: AgentState) -> dict:
    prompt = f"""
Review this Python code and the reported test failure.

Original code:
{state["code"]}

Test output:
{state["error"]}

Return a corrected implementation only.
Do not include Markdown fences or unrelated changes.
"""

    response = llm.invoke([
        SystemMessage(
            content=(
                "You are a careful Python developer. "
                "Make the smallest reasonable correction. "
                "Do not claim that code has been tested."
            )
        ),
        HumanMessage(content=prompt),
    ])

    raw = response.content
    if not isinstance(raw, str):
        raise ValueError("Unexpected model response format")

    clean_code = raw.strip()

    if clean_code.startswith("```"):
        lines = clean_code.splitlines()
        if lines and lines[0].startswith("```"):
            lines = lines[1:]
        if lines and lines[-1].strip() == "```":
            lines = lines[:-1]
        clean_code = "\n".join(lines).strip()

    if not clean_code:
        raise ValueError("The model returned empty code")

    return {
        "patch": clean_code,
        "iterations": state["iterations"] + 1,
    }


def execute_test(state: AgentState) -> dict:
    # Connect this node to a restricted test runner.
    # Do not execute model-generated code on the host.
    raise NotImplementedError(
        "Configure an isolated test runner before enabling execution."
    )


def should_continue(state: AgentState) -> str:
    if state["test_passed"]:
        return "success"

    if state["iterations"] >= 3:
        return "stop"

    return "retry"


workflow = StateGraph(AgentState)

workflow.add_node("patcher", patch_code)
workflow.add_node("tester", execute_test)

workflow.set_entry_point("patcher")
workflow.add_edge("patcher", "tester")

workflow.add_conditional_edges(
    "tester",
    should_continue,
    {
        "success": END,
        "stop": END,
        "retry": "patcher",
    },
)

agent = workflow.compile()

# This invocation is intentionally not enabled yet:
# The tester node must be implemented and connected to an
# isolated execution environment before running the graph.

There is a deliberate gap in this example: the test runner is not implemented, so the graph cannot complete an end-to-end repair cycle as written. That is preferable to quietly executing model-generated code on the host. Once a sandboxed runner is available, implement the tester node so it returns an updated test_passed value and a concise test result in error.

A production version should also validate patches before applying them, restrict file paths, capture logs, enforce timeouts, cap retries, preserve checkpoints where appropriate, and ask for approval before changing important files.

9. LangGraph vs CrewAI vs AutoGen: Practical Comparison

Area LangGraph CrewAI AutoGen
Core modelGraph-based workflowsRoles, agents, and tasksConversational agent patterns
Control flowExplicit nodes and transitionsTask and process orchestrationMessage and event-driven interaction
State and contextStructured state and checkpointsAgent and task contextMessages and agent state
Typical fitControlled, branching workflowsWork that maps to specialized rolesExisting conversational multi-agent apps
Local modelsThrough compatible model integrations (Ollama, LM Studio, vLLM)Through supported local providers and LiteLLMDepends on client and model integration
RecoveryCheckpointing is a core capabilityDepends on orchestration and persistence setupDepends on application and runtime design
New-project noteEvaluate current LangGraph APIsEvaluate current CrewAI APIsReview maintenance status and Microsoft's newer Agent Framework

This table describes architectural tendencies, not benchmark results. It does not claim that one framework is faster or more accurate. Those outcomes depend on the model, prompts, hardware, tools, context strategy, and workload.

10. Hardware Requirements for Local Coding Agents

The orchestration framework is usually not the main source of GPU memory use. The language model, quantization format, context length, KV cache, inference engine, and number of concurrent requests matter much more.

  • 12GB GPU: Can run smaller quantized models. Larger models may need CPU offloading, shorter context, or reduced concurrency.
  • 16GB GPU: A practical entry point for some small and medium quantized coding models, depending on their size and context requirements.
  • 24GB GPU: Gives more room for quantized models around the 14B class and useful context lengths, but the exact fit depends on quantization and runtime overhead.
  • Two 24GB GPUs: May allow larger model placement or tensor parallelism when the inference software supports the chosen setup. The memory is not automatically pooled into one seamless 48GB allocation.
  • Apple Silicon unified memory: Larger-memory configurations can run models that would not fit in a smaller discrete GPU, although memory bandwidth and inference software affect speed.

For multi-GPU setups, see PCIe 4.0 x8 vs x16 for Dual-GPU LLM Workloads. For Apple hardware, see Mac Studio Ultra vs RTX 4090 for Local LLMs.

You can estimate model memory with the Local LLM VRAM Calculator. Treat the result as an estimate rather than a guarantee; runtime overhead and context settings can change the actual requirement.

11. Frequently Asked Questions

Which framework should I choose for a local coding agent?

LangGraph is a strong fit when you need explicit state, branching, retries, and checkpoints. CrewAI is useful when the work naturally divides into specialized roles and tasks. For a new Microsoft-based agent project, evaluate Microsoft Agent Framework rather than assuming AutoGen is the current default.

Can CrewAI work with local language models like Ollama and LM Studio?

Yes. CrewAI can connect to compatible local model providers and OpenAI-compatible inference endpoints such as Ollama and LM Studio. Check the current provider instructions and test tool calling, structured output, and context limits with the exact model you intend to run.

Should I use AutoGen for a new project?

Do not choose it without checking its current maintenance and support status. It remains useful when working with existing AutoGen applications, while Microsoft Agent Framework is the newer Microsoft direction to evaluate for new development.

How much GPU memory does a local coding agent need?

There is no single requirement. The model weights, quantization, context length, KV cache, inference engine, and concurrency all affect memory use. A 24GB GPU can run a range of quantized coding models, but not every model or context configuration will fit.

How can I stop an agent from running destructive commands?

Do not expose an unrestricted shell. Use an allowlist of tools, validate arguments, restrict file access, run code in an isolated environment, apply resource limits, and require explicit approval for sensitive operations.

Does LangGraph automatically reduce token consumption?

No. LangGraph gives developers control over state and workflow structure. Token use still depends on how much conversation history, source code, and tool output the application sends to the model.

Can several agents share one GPU?

They can send requests to the same local model server, but concurrency is limited by available memory, model size, context length, and inference-server scheduling. More simultaneous agents can increase queue times and memory pressure.

Is a multi-agent system always better than one agent?

No. Multiple agents can help when tasks are genuinely separable, but they also add coordination overhead, repeated context, and more model calls. Start with the simplest workflow that solves the problem, then add agents only when the benefit is clear.


Abdulrahman Maslmany

Abdulrahman Maslmany

TECHNOLOGY AND SOFTWARE ENGINEERING WRITER

Abdulrahman writes about software engineering, local AI infrastructure, development tools, and practical applications of artificial intelligence. His articles focus on implementation details, trade-offs, and the limitations developers should understand before choosing a tool.

GitHub  |  Dev.to  |  Hugging Face  |  About Us and Editorial Standards

Editorial note: This article is an architectural comparison, not a benchmark report. Framework APIs, model compatibility, and hardware behavior can change between releases. The code is an educational starting point, not a ready-to-deploy autonomous coding system. Test all examples in a controlled environment and consult the current documentation before using them in production.