https://github.com/juansebsol/langraph-learn
Examples demonstrating how to build, route, and manage stateful AI agent graphs from scratch using LangGraph.
https://github.com/juansebsol/langraph-learn
ai ai-agents langraph learning-by-doing llm
Last synced: about 4 hours ago
JSON representation
Examples demonstrating how to build, route, and manage stateful AI agent graphs from scratch using LangGraph.
- Host: GitHub
- URL: https://github.com/juansebsol/langraph-learn
- Owner: juansebsol
- Created: 2025-11-10T23:59:18.000Z (7 months ago)
- Default Branch: main
- Last Pushed: 2025-12-21T06:34:18.000Z (5 months ago)
- Last Synced: 2025-12-23T00:59:19.172Z (5 months ago)
- Topics: ai, ai-agents, langraph, learning-by-doing, llm
- Language: JavaScript
- Homepage:
- Size: 56.6 KB
- Stars: 0
- Watchers: 0
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# LangGraph Learning Project .js
A simple, educational project to learn LangGraph from scratch using JavaScript and Node.js. This project contains progressive examples that build upon each other to help you understand the core concepts of LangGraph.
## What is LangGraph?
LangGraph is a library for building stateful, multi-actor applications with LLMs. It allows you to:
- Create graphs where nodes are functions (tools, prompts, LLMs)
- Define edges that control the flow between nodes
- Manage state across multiple steps
- Create loops and conditional routing
- Build complex AI agents
## Project Structure
```
langraph-learn/
├── README.md # This file
├── package.json # Dependencies and scripts
├── .gitignore # Git ignore file
├── CONCEPTS.md # Core concepts explained
├── utils/
│ └── llm-setup.js # LLM setup utility
├── 01_basic_graph.js # Example 1: Simple linear graph
├── 02_conditional_routing.js # Example 2: Conditional edges
├── 03_stateful_agent.js # Example 3: State management
├── 04_practical_example.js # Example 4: Real-world use case
├── 05_simple_llm.js # Example 5: Simple LLM node
├── 06_chat_agent.js # Example 6: Chat agent with memory
├── 07_agent_with_tools.js # Example 7: Agent with tools
├── 08_react_agent.js # Example 8: ReAct pattern agent
├── 09_streaming.js # Example 9: Streaming responses
├── 10_error_handling.js # Example 10: Error handling & retry
├── 11_multi_agent.js # Example 11: Multi-agent collaboration
├── 12_human_in_loop.js # Example 12: Human-in-the-loop pattern
├── 13_checkpoints.js # Example 13: Checkpoints & persistence
├── 14_parallel_execution.js # Example 14: Parallel node execution
└── 15_graph_composition.js # Example 15: Graph composition
```
## Setup
1. **Install Node.js** (if you haven't already):
- Download from [nodejs.org](https://nodejs.org/)
- Verify installation: `node --version`
2. **Install dependencies:**
```bash
npm install
```
3. **Set up environment variables (for LLM examples):**
- Create a `.env` file in the root directory
- Add your API key(s):
```bash
# OpenRouter (recommended - supports multiple models)
OPENROUTER_API_KEY=your_openrouter_api_key_here
# Or use OpenAI directly
OPENAI_API_KEY=your_openai_api_key_here
# Or use Anthropic
ANTHROPIC_API_KEY=your_anthropic_api_key_here
```
- Get your OpenRouter key from: [openrouter.ai/keys](https://openrouter.ai/keys)
- Get your OpenAI key from: [platform.openai.com/api-keys](https://platform.openai.com/api-keys)
- Get your Anthropic key from: [console.anthropic.com](https://console.anthropic.com/)
4. **Run examples:**
```bash
# Basic examples (no API key required)
npm run example1
npm run example2
npm run example3
npm run example4
# LLM examples (API key required)
npm run example5
npm run example6
npm run example7
npm run example8
npm run example9
npm run example10
npm run example11
npm run example12
npm run example13
npm run example14
npm run example15
```
## Learning Path
### Foundation (Examples 1-4) - No API Key Required
**Example 1: Basic Graph**
- Learn the fundamentals: creating nodes, connecting them with edges, and running a simple graph.
**Example 2: Conditional Routing**
- Understand how to route flow based on conditions and create dynamic graphs.
**Example 3: Stateful Agent**
- Learn state management - how to pass and modify state between nodes, and create loops.
**Example 4: Practical Example**
- Apply everything you've learned to build a useful agent for task prioritization.
### LLM Integration (Examples 5-10) - API Key Required
**Example 5: Simple LLM Node**
- Integrate an LLM into a LangGraph node
- Learn how to call LLMs and handle responses
- Understand basic prompt engineering
**Example 6: Chat Agent with Memory**
- Create a chat agent that maintains conversation history
- Learn how to manage message arrays in state
- Implement multi-turn conversations
**Example 7: Agent with Tools (Function Calling)**
- Create an agent that can use tools
- Learn how to define and execute tools
- Understand tool calling and responses
**Example 8: ReAct Pattern Agent**
- Implement the ReAct (Reasoning + Acting) pattern
- Learn iterative reasoning-action-observation loops
- Build agents that reason before acting
**Example 9: Streaming Responses**
- Stream LLM responses in real-time
- Learn how to process stream events
- Provide better UX for long-running tasks
**Example 10: Error Handling and Retry Logic**
- Handle errors gracefully in LangGraph
- Implement retry logic with exponential backoff
- Learn fallback strategies and error recovery
### Advanced Patterns (Examples 11-15) - API Key Required
**Example 11: Multi-Agent Collaboration System**
- Create multiple specialized agents working together
- Learn agent coordination and handoff patterns
- Implement shared state between agents
- Build task delegation workflows
**Example 12: Human-in-the-Loop Pattern**
- Interrupt graph execution for human input
- Implement approval workflows
- Create interactive decision points
- Handle user feedback in the workflow
**Example 13: Checkpoints and Persistence**
- Save and load graph state
- Resume execution from checkpoints
- Implement state persistence strategies
- Build fault-tolerant workflows
**Example 14: Parallel Node Execution**
- Execute multiple nodes simultaneously
- Learn fan-out/fan-in patterns
- Merge parallel results
- Optimize performance with concurrency
**Example 15: Graph Composition / Modular Graphs**
- Create reusable sub-graphs
- Compose smaller graphs into larger workflows
- Build modular, maintainable architectures
- Organize complex systems with graph nesting
## Key Concepts
- **Graph**: The overall structure containing nodes and edges
- **Node**: A function that processes data and returns results
- **Edge**: Defines how data flows from one node to another
- **State**: Data that persists and is modified as the graph executes
- **Conditional Edge**: An edge that routes based on a condition
- **Reducer**: Functions that determine how state is merged/updated
- **Multi-Agent**: Multiple agents coordinating to solve tasks
- **Human-in-the-Loop**: Interrupting execution for human input
- **Checkpoints**: Saving state to resume execution later
- **Parallel Execution**: Running multiple nodes simultaneously
- **Graph Composition**: Combining smaller graphs into larger ones
## Prerequisites
- Node.js (v18 or higher recommended)
- Basic understanding of JavaScript/Node.js
- Familiarity with async/await
## Resources
- [LangGraph.js Documentation](https://langchain-ai.github.io/langgraphjs/)
- [LangGraph.js GitHub](https://github.com/langchain-ai/langgraphjs)
- [LangChain Documentation](https://js.langchain.com/)
## Troubleshooting
### API Compatibility
If you encounter errors related to the StateGraph API, the LangGraph.js API may have changed. Check the [official documentation](https://langchain-ai.github.io/langgraphjs/) for the latest API.
### Common Issues
1. **Module not found**: Make sure you've run `npm install`
2. **Syntax errors**: Ensure you're using Node.js v18 or higher
3. **Import errors**: Verify that `"type": "module"` is set in package.json
### Getting Help
- Check the [LangGraph.js documentation](https://langchain-ai.github.io/langgraphjs/)
- Review the [CONCEPTS.md](./CONCEPTS.md) file for detailed explanations
- Look at the example code comments for guidance
## LLM Setup
The project includes a utility module (`utils/llm-setup.js`) that supports multiple LLM providers:
- **OpenRouter** (recommended): Supports multiple models (OpenAI, Anthropic, etc.)
- **OpenAI**: Direct OpenAI API access
- **Anthropic**: Direct Anthropic API access
The utility automatically detects which API keys are available and uses the appropriate provider. Examples prefer OpenRouter if available, falling back to OpenAI or Anthropic.
### Supported Models
- **OpenRouter**: `openai/gpt-4`, `openai/gpt-3.5-turbo`, `anthropic/claude-3-sonnet`, etc.
- **OpenAI**: `gpt-4`, `gpt-3.5-turbo`, etc.
- **Anthropic**: `claude-3-opus-20240229`, `claude-3-sonnet-20240229`, etc.
### Configuration
You can configure the default provider and model in your `.env` file:
```bash
# Set default provider (openrouter, openai, or anthropic)
LLM_PROVIDER=openrouter
# Set default model
DEFAULT_MODEL=openai/gpt-4
# OpenRouter specific settings (optional)
OPENROUTER_BASE_URL=https://openrouter.ai/api/v1
OPENROUTER_REFERRER=https://github.com/your-username/langraph-learn
```
**Note:** OpenRouter configuration may need adjustment based on your LangChain.js version. If you encounter issues, try:
1. Check your LangChain.js version: `npm list @langchain/openai`
2. Consult the [LangChain.js documentation](https://js.langchain.com/) for the correct API
3. Use OpenAI or Anthropic directly if OpenRouter doesn't work
4. Check the `utils/llm-setup.js` file for configuration details
## Notes
- All examples use ES6 modules (import/export)
- The project uses `"type": "module"` in package.json
- Examples are designed to be educational and well-commented
- No external API keys required for basic examples (Examples 1-4 work without LLMs)
- LLM examples (5-10) require an API key from at least one provider
- The API used in these examples is based on LangGraph.js v0.2.0+
- OpenRouter configuration may need adjustment based on your LangChain.js version