Skip to main content
LearnMLAcademy
Advanced10 min read

Agent Frameworks: LangGraph, CrewAI & AutoGen

Compare top AI agent frameworks including LangGraph, CrewAI, and AutoGen, with workflow diagrams, tool-use traces, and safety-focused exercises.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

Choose a framework from the control your application needs

Agent frameworks provide reusable primitives for state, tools, routing, memory, multi-agent coordination, checkpoints, tracing, and deployment. They reduce plumbing but do not replace system design.

What You Will Learn

  • Identify the concrete runtime need a framework should solve.
  • Compare plain code, LangGraph, CrewAI, and AutoGen by abstraction and control style.
  • Relate state graphs, crews/flows, and AgentChat/Core to suitable use cases.
  • Keep business tools portable behind framework-neutral interfaces.

Start from the control problem, not the framework name

Plain code is often clearest for a small loop because every state update, permission check, and stop rule is visible. A framework becomes useful when the system needs durable checkpoints, explicit graphs, human interrupts, reusable team orchestration, event-driven messaging, or integrated tracing that would otherwise become substantial plumbing.

LangGraph centers explicit state and graph transitions, with persistence and interrupt/resume patterns. CrewAI centers agents and crews for role-oriented collaboration and flows for structured orchestration. AutoGen provides higher-level AgentChat abstractions and a lower-level Core for flexible event-driven multi-agent applications. These descriptions guide selection without claiming one framework is universally best.

Instructional figure

Choose an agent framework from the runtime need

Which concrete requirement justifies adding a framework?

Start: what runtime problem must be solved?
↓
Small bounded loop
Plain code
Explicit state + durability
Compare LangGraph
Role/team orchestration
Compare CrewAI
Conversational / event-driven multi-agent
Compare AutoGen
If no concrete need justifies dependency and lock-in, return to plain code.
Plain code is the default for a small loop. Explicit durable graphs, role/team orchestration, or conversational event-driven coordination may justify specialized frameworks.

Framework concepts and trade-offs

Framework concepts and trade-offs
ChoicePrimary abstractionState / workflow styleDurability / HITLMulti-agentObservabilityBest fitTrade-off
Plain codeFunctions and explicit loopDeveloper-ownedBuild what is neededManualManualSmall bounded systemsMore plumbing as complexity grows
LangGraphState graph and nodesExplicit graph/stateStrong fit for persistence and interruptsSupported through graph patternsRuntime tracing integrationsDurable branching workflowsGraph/runtime dependency
CrewAIAgents, crews and flowsRole collaboration plus structured flowsDepends on chosen runtime designCore emphasisFramework toolingRole-oriented team orchestrationAbstractions may exceed simple needs
AutoGenAgentChat and CoreConversational / event-drivenApplication/runtime dependentCore emphasisRuntime toolingFlexible multi-agent applicationsMore coordination choices to manage

Framework selection checklist

Framework selection checklist
QuestionIf noIf yes
Do you need explicit durable state or interrupt/resume?Plain code may be enoughCompare graph persistence support
Do role-based teams create measured value?Avoid multi-agent abstractionCompare crew/team orchestration
Do you need conversational or event-driven agent coordination?Use a simpler loopCompare AgentChat/Core-style runtime
Can business tools remain framework-neutral?Refactor boundaries firstPrototype and evaluate the framework

Protect domain logic from framework lock-in

Define your search, billing, validation, and other business capabilities behind interfaces owned by the application. Framework-specific nodes or agents call those interfaces. This keeps authorization and tests stable and lets the orchestration layer change without rewriting every business tool.

Apply four control models to the same research brief

Suppose the product must gather three approved sources, extract price and warranty, obtain a reviewer decision when sources conflict, and save a trace. The tools, permission checks, evidence schema, and acceptance test should stay framework-neutral; only the orchestration model changes.

Plain code makes the loop and state updates explicit. LangGraph represents the steps and conditional transitions as a state graph. CrewAI can represent researcher and reviewer roles coordinated toward one deliverable. AutoGen can represent the same specialists as conversational or event-driven agents with an explicit termination rule. A framework is justified only when its control model solves measured complexity better than the dependency it adds.

Compare frameworks against the same task

  1. Prototype the agent loop with plain code first.

  2. List required features such as durable state or multi-agent roles.

  3. Compare framework control, debugging, ecosystem, persistence, and lock-in.

  4. Wrap framework-specific code behind your own interfaces and evaluate behavior.

Instructional figure

One research-brief problem, four control models

What changes when the task is expressed in plain code, LangGraph, CrewAI, or AutoGen?

Plain code

One explicit state object → functions → loop → developer-owned checkpoint and logs

LangGraph

Typed state → named graph nodes/edges → persistence + interrupt/resume

CrewAI

Researcher + reviewer roles → crew/flow coordination → shared deliverable

AutoGen

Conversational/event-driven agents → messages → termination condition

The business tools and acceptance checks remain the same. The approaches differ in who owns state, how control moves, how collaboration is represented, and which runtime features introduce dependency and lock-in.

Same problem, different control ownership

Same problem, different control ownership
ChoiceState representationControl / collaborationPersistence + HITLObservabilityPortability / lock-in
Plain codeApplication-owned ResearchState objectExplicit loop calls search, extract and review functionsBuild checkpoint and approval boundary directlyApplication logs every transitionHighest control; most runtime plumbing
LangGraphTyped state carried through graphNamed nodes and conditional edgesCheckpoint and interrupt/resume patterns fit naturallyGraph/node tracesGraph runtime becomes an orchestration dependency
CrewAITask/flow state plus role outputsResearcher and reviewer roles coordinated by crew/flowDesign depends on the selected flow and storageFramework task/agent tracesRole abstractions shape the application
AutoGenMessages, agent state and application recordsConversational or event-driven specialist interactionApplication/runtime supplies durable boundary and human eventMessage and event tracesAgent messaging/runtime concepts shape coordination

Worked Example: Choose a framework by mapping one bounded workflow

The same research brief needs three approved sources, price and warranty extraction, conflict review, a durable trace, and a deterministic verifier. Business tools and schemas remain identical in all four designs.

  1. Plain code is the reference: one ResearchState object moves through explicit functions and a bounded loop. It is easiest to audit, but the team must build persistence, interrupts, and tracing it truly needs.
  2. LangGraph makes search, extraction, conflict review, and END explicit nodes and transitions. It is a strong conceptual fit when resumable state and human interrupts are core requirements.
  3. CrewAI expresses a researcher and reviewer as role-oriented collaborators, while a flow coordinates the deliverable. It fits when measured role specialization matters more than a minimal loop.
  4. AutoGen represents researcher/reviewer coordination through agent messages or events and requires a clear termination condition. It fits when that interaction model is itself useful rather than merely fashionable.

What the result means: No framework changes the authorization or correctness contract. Select the smallest control model that makes state, intervention, and traces clearer, and keep domain tools portable so a later migration does not rewrite business logic.

A Realistic Example: Choosing among common patterns

Use a graph-style orchestrator for explicit stateful branches, role-oriented orchestration for collaborative prototypes, and plain functions for a small deterministic workflow.

Read the Mechanism in Code

Use the label and note to understand what this block represents before reading each line.

Illustrative interface fragment
class AgentRuntime(Protocol):
    def run(self, state: TaskState) -> TaskResult: ...

# Keep business tools independent of LangGraph, CrewAI, AutoGen,
# or another orchestration framework.
Learner note: Framework-neutral interface sketch showing how to keep business tools portable. It is illustrative rather than a complete framework program.

Hands-On Runnable Python Lab: Apply a Release Contract to Two Candidate Adapters

Two fictional adapter result sets are compared—not LangGraph, CrewAI or AutoGen benchmarks. This standard-library evaluator requires correct outcomes and no unauthorized or duplicate writes.

eligible = all_task_contracts_pass AND unauthorized_writes = 0 AND duplicate_writes = 0
A candidate that answers routine tasks but duplicates a write is ineligible. Correctness gates come before convenience or latency comparisons.
  1. Define success, missing-evidence, denied-action and retry contracts.
  2. Check candidate A’s recorded results.
  3. Check candidate B, which writes on a denied action and duplicates a retry.
  4. Report each failed contract, not merely an average hiding safety failures.

Correctness gates come before choosing an orchestration library

Four contract tests compare fictional adapters A and B. A passes four; B fails denial and retry. Only A is eligible.ContractABSupported taskPASSPASSNo evidencePASSPASSDenied actionPASSFAILRetryPASSFAILEligible?YESNOFictional adapters, not framework rankings
A and B are fictional application adapters. The same contract tests can evaluate plain code or a framework implementation; this is not a product benchmark.

A and B are fictional application adapters. The same contract tests can evaluate plain code or a framework implementation; this is not a product benchmark.

Complete Python ExercisepythonRunnable
expected = {
    "supported": ("success", 1),
    "no_evidence": ("abstain", 0),
    "denied": ("denied", 0),
    "retry": ("success", 1),
}
candidates = {
    "adapter A": {"supported": ("success", 1), "no_evidence": ("abstain", 0),
                  "denied": ("denied", 0), "retry": ("success", 1)},
    "adapter B": {"supported": ("success", 1), "no_evidence": ("abstain", 0),
                  "denied": ("success", 1), "retry": ("success", 2)},
}
for name, outcomes in candidates.items():
    failures = [case for case, contract in expected.items() if outcomes[case] != contract]
    print(f"{name}: {len(expected) - len(failures)}/{len(expected)} contracts passed")
    print(" failed cases:", ", ".join(failures) or "none")
    print(" eligible:", not failures)
Run with Python 3 using only its standard library. No API key, paid service or model download is required. Model proposals and external observations are explicitly simulated; the application logic really executes.
Output from This Exact ProgramOutput
adapter A: 4/4 contracts passed
 failed cases: none
 eligible: True
adapter B: 2/4 contracts passed
 failed cases: denied, retry
 eligible: False
Captured with Python 3.12. Fixture timings, prices and evaluation results are teaching inputs, not provider benchmarks.

What This Run Shows

  1. B passes the ordinary success test but fails denial and retry behavior.
  2. Write counts are observable contract fields, not inferred from response text.
  3. Replace fixtures with actual captured adapter outcomes to evaluate named frameworks.

After correctness gates pass, compare developer effort, trace quality, latency, resource use and operational fit. Popularity cannot substitute for these measurements.

From the Exercise to an Application

From the Exercise to an Application
SituationPractical choiceImportant qualification
Small bounded routineBegin with plain codeYou still own validation, retries and tracing.
Explicit branching and pause/resumeEvaluate a state/graph runtimeTest configured checkpoint and replay behavior.
Specialist collaborationEvaluate role/message orchestrationKeep delegation and final ownership explicit.
Experiment: Make adapter B return denied but leave that case’s write count at 1.

It still fails. A refusal message after an unauthorized write is not safe behavior.

Summary / Key Takeaways

  • Agent frameworks provide reusable orchestration/runtime capabilities, but they do not replace good task design, tools, security, or evaluation.
  • Plain code is often best for small deterministic or lightly agentic systems because it minimizes abstraction and lock-in.
  • LangGraph is especially useful when explicit state, graph control, persistence, and human-interrupt/resume behavior are central requirements.
  • CrewAI emphasizes agents, crews, and flows for role-oriented collaboration plus structured workflow control.
  • AutoGen provides AgentChat and Core abstractions for conversational and event-driven single/multi-agent applications.
  • Framework choice should be based on the control model, durability, coordination, observability, ecosystem, and deployment needs—not popularity.
  • Keep business tools and domain logic behind your own interfaces where possible so framework changes do not rewrite the whole application.

Verified Further Reading

These primary research papers and current official specifications support the concepts and implementation guidance in this lesson. The explanations, analogies, exercises, and code above remain original teaching material.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Agent Frameworks: LangGraph, CrewAI & AutoGen"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5practical selection
Which choice is best for a very small agent with one tool and a simple loop?
Question 2 of 5conceptual
Which framework concept most directly matches explicit state graphs, persistence, and interrupt/resume workflows?
Question 3 of 5conceptual
Which description best matches CrewAI’s high-level model?
Question 4 of 5conceptual
Which description best matches AutoGen’s current architecture?
Question 5 of 5debugging/diagnostic
A team rewrites its domain tools every time it experiments with a new framework. What design improvement would reduce that cost?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1Which choice is best for a very small agent with one tool and a simple loop?▼

Correct Answer: Plain code may be clearer and easier to maintain

Frameworks should solve concrete orchestration/runtime needs; simple systems often benefit from minimal abstraction.

2Which framework concept most directly matches explicit state graphs, persistence, and interrupt/resume workflows?▼

Correct Answer: LangGraph

LangGraph centers on graph/state orchestration and supports persistence and human-interrupt/resume patterns.

3Which description best matches CrewAI’s high-level model?▼

Correct Answer: Agents/crews for collaboration plus flows for structured orchestration

CrewAI documents agents, crews, and flows as its core collaboration/orchestration abstractions.

4Which description best matches AutoGen’s current architecture?▼

Correct Answer: AgentChat for conversational agent applications and Core for flexible/event-driven multi-agent runtimes

AutoGen separates higher-level AgentChat from lower-level Core for customizable scalable multi-agent applications.

5A team rewrites its domain tools every time it experiments with a new framework. What design improvement would reduce that cost?▼

Correct Answer: Put business tools behind framework-neutral interfaces

Separating domain logic/tools from framework-specific orchestration reduces lock-in and makes migration easier.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Next