AI & Machine Learning

Building AI Agents from Scratch: Complete Guide with LangGraph, CrewAI, and LlamaIndex

Discover how to create powerful AI agents using open-source frameworks like LangGraph, CrewAI, and LlamaIndex. This step-by-step guide covers fundamentals, implementation, and comparisons to help you build autonomous systems efficiently.

A

Andrew Snyder

AI & Automation Editor

December 30, 2025 min read
Share:

Introduction to AI Agents

In the rapidly evolving field of artificial intelligence, AI agents represent a significant advancement beyond traditional chatbots. These intelligent systems can perceive their environment, make decisions, and take actions autonomously to achieve specific goals. Whether automating complex workflows or handling multi-step tasks, AI agents are becoming essential tools for developers and businesses alike.

This guide walks you through constructing AI agents from the ground up using three popular frameworks: LangGraph, CrewAI, and LlamaIndex. Each offers unique strengths, and we'll explore their setups, core concepts, and practical implementations. By the end, you'll have the knowledge to choose and deploy the right tool for your needs.

What Are AI Agents?

AI agents are software entities designed to operate independently in dynamic environments. Unlike simple models that respond to prompts, agents incorporate reasoning, memory, and tool usage to execute tasks over multiple steps.

Key Components of an AI Agent

  • Perception: Gathering data from the environment or user inputs.
  • Reasoning: Analyzing information and planning actions using LLMs (Large Language Models).
  • Action: Interacting with tools, APIs, or external services.
  • Memory: Retaining context across interactions for continuity.

Agents excel in scenarios like research automation, customer support, or data analysis, where single-pass responses fall short.

Types of AI Agents

Understanding agent architectures helps in selecting the appropriate framework:

  • Reactive Agents: Respond directly to stimuli without memory (e.g., basic rule-based bots).
  • Model-Based Agents: Maintain an internal world model for better decision-making.
  • Goal-Based Agents: Focus on achieving predefined objectives through planning.
  • Utility-Based Agents: Optimize for the best outcome by evaluating trade-offs.
  • Learning Agents: Improve performance over time via feedback loops.

Most modern frameworks support goal-based and learning agents, leveraging LLMs for flexibility.

Building AI Agents with LangGraph

LangGraph, developed by LangChain, models agents as graphs where nodes represent actions or decisions, and edges define flows. This structure is ideal for complex, stateful workflows.

For more details, check the official repository: LangGraph GitHub.

Step-by-Step Setup

  1. Install Dependencies:

    pip install -U langchain-community langgraph tavily-python
    
  2. Set Up API Keys: Obtain keys for OpenAI and Tavily (a search tool):

    import os
    os.environ["OPENAI_API_KEY"] = "your-openai-key"
    os.environ["TAVILY_API_KEY"] = "your-tavily-key"
    
  3. Define Tools: Agents need tools like search:

    from langchain_community.tools.tavily_search import TavilySearchResults
    tools = [TavilySearchResults(max_results=1)]
    
  4. Create the Graph: Build nodes for agent reasoning and tool execution:

    from langgraph.prebuilt import create_react_agent
    agent_executor = create_react_agent(model, tools)
    
  5. Invoke the Agent:

    from langgraph import InvokeArgs
    for chunk in agent_executor.stream(InvokeArgs(messages=[input]), stream_mode="values"):
        chunk["messages"][-1].pretty_print()
    

Explore example notebooks here: LangGraph Cookbook.

LangGraph shines in customizable, cyclical workflows, adding value through precise control over state management.

Building AI Agents with CrewAI

CrewAI enables collaborative multi-agent systems, where 'crews' of specialized agents work together like a team. This is perfect for task delegation in real-world applications.

Visit the repo: CrewAI GitHub.

Step-by-Step Implementation

  1. Installation:

    pip install crewai crewai-tools langchain-openai
    
  2. Configure Environment:

    import os
    os.environ["OPENAI_API_KEY"] = "your-key"
    
  3. Define Agents: Create role-specific agents:

    from crewai import Agent
    researcher = Agent(
        role='Senior Researcher',
        goal='Research latest AI advancements',
        backstory='Expert with 20+ years...',
        tools=[search_tool],
        llm="gpt-4o-mini"
    )
    
  4. Set Up Tasks:

    from crewai import Task
    research_task = Task(
        description='Research top 3 frameworks...',
        agent=researcher
    )
    
  5. Assemble and Kickoff Crew:

    from crewai import Crew
    crew = Crew(agents=[researcher, writer], tasks=[research_task, write_task])
    result = crew.kickoff()
    print(result)
    

CrewAI adds value by simulating human teamwork, making it intuitive for hierarchical processes like content creation pipelines.

Building AI Agents with LlamaIndex

LlamaIndex focuses on retrieval-augmented generation (RAG) agents, excelling in knowledge-intensive tasks with custom tool integration.

Repo link: LlamaIndex GitHub.

Detailed Steps

  1. Install Packages:

    pip install llama-index llama-index-llms-openai llama-index-tools-tavily
    
  2. Environment Setup: Similar to others, set OpenAI and Tavily keys.

  3. Initialize LLM and Tools:

    from llama_index.llms.openai import OpenAI
    from llama_index.tools.tavily import TavilyToolSpec
    llm = OpenAI(model="gpt-4o-mini")
    tool = TavilyToolSpec(max_results=5)
    
  4. Create ReAct Agent:

    from llama_index.core.agent import ReActAgent
    agent = ReActAgent.from_tools(tools=[tool], llm=llm, verbose=True)
    
  5. Run the Agent:

    response = agent.chat("What is new in AI agents?")
    print(response)
    

LlamaIndex provides robust RAG capabilities, enhancing agents with precise information retrieval for research-heavy use cases.

Framework Comparison

FeatureLangGraphCrewAILlamaIndex
Core StrengthStateful graphsMulti-agent collaborationRAG-focused tools
Ease of UseModerate (graph concepts)High (team metaphor)High (RAG simplicity)
CustomizationExcellentGoodVery Good
Best ForComplex cyclesTeam workflowsKnowledge queries
CommunityGrowingActiveMature

Choose based on your workflow: graphs for precision, crews for delegation, RAG for data-driven tasks.

Real-World Applications and Best Practices

  • Automation: Use agents for email triage or code generation.
  • Research: Combine search tools for up-to-date insights.
  • Tips: Always implement error handling, monitor costs, and iterate with human feedback.

Example: An agent crew for market analysis—researcher gathers data, analyst processes, reporter summarizes.

Conclusion

Building AI agents empowers you to tackle sophisticated problems autonomously. Start with these frameworks, experiment via their GitHub repos, and scale to production. With practice, you'll unlock innovative solutions tailored to your domain.

This guide provides actionable steps; adapt code to your LLMs and tools for optimal results.


<div style="text-align: center; margin-top: 2rem;"> <a href="https://www.analyticsvidhya.com/blog/2024/07/build-ai-agents-from-scratch/" target="_blank" rel="noopener noreferrer" class="view-full-resource-btn" style="display: inline-block; background-color: #f97316; color: white; padding: 12px 24px; border-radius: 8px; text-decoration: none; font-weight: 600; transition: background-color 0.2s;">View Full Resource</a> </div>
The #1 Newsletter in AI

Stay ahead of the AI curve

The most important updates, news, and content — delivered in one weekly newsletter.

No spam. Unsubscribe anytime. Privacy policy

AI Agents
LangGraph
CrewAI
LlamaIndex
Python AI
ai-agents
A

About Andrew Snyder

AI & Automation Editor

Andrew covers practical AI automation, workflow design, and the tools teams use to streamline everyday operations.

Comments (0)