{"id":50148654,"url":"https://github.com/nevin100/langgraph-revision","last_synced_at":"2026-05-24T07:02:34.281Z","repository":{"id":359736926,"uuid":"1242151486","full_name":"Nevin100/LangGraph-Revision","owner":"Nevin100","description":"This repository serves as an educational resource for understanding LangGraph, a framework for building stateful multi-actor applications with language models. ","archived":false,"fork":false,"pushed_at":"2026-05-23T06:57:02.000Z","size":195,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-05-23T08:29:56.726Z","etag":null,"topics":["agent","groq-api","langchain","langgraph","python","rag","sqlite","uv"],"latest_commit_sha":null,"homepage":"","language":"Jupyter Notebook","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Nevin100.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-05-18T07:09:40.000Z","updated_at":"2026-05-23T06:57:05.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/Nevin100/LangGraph-Revision","commit_stats":null,"previous_names":["nevin100/langgraph-revision"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/Nevin100/LangGraph-Revision","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Nevin100%2FLangGraph-Revision","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Nevin100%2FLangGraph-Revision/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Nevin100%2FLangGraph-Revision/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Nevin100%2FLangGraph-Revision/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Nevin100","download_url":"https://codeload.github.com/Nevin100/LangGraph-Revision/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Nevin100%2FLangGraph-Revision/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":33424573,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-23T22:14:44.296Z","status":"online","status_checked_at":"2026-05-24T02:00:06.296Z","response_time":57,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["agent","groq-api","langchain","langgraph","python","rag","sqlite","uv"],"created_at":"2026-05-24T07:02:28.474Z","updated_at":"2026-05-24T07:02:34.271Z","avatar_url":"https://github.com/Nevin100.png","language":"Jupyter Notebook","funding_links":[],"categories":[],"sub_categories":[],"readme":"# LangGraph Workflow Patterns \u0026 Advanced Topics\n\nA comprehensive learning repository demonstrating LangGraph's core workflow patterns and advanced features for building AI-powered applications with LLM agents.\n\n---\n\n## Table of Contents\n\n1. [Project Overview](#project-overview)\n2. [Getting Started](#getting-started)\n3. [Project Structure](#project-structure)\n4. [Core Workflow Patterns](#core-workflow-patterns)\n5. [Key Concepts \u0026 Implementations](#key-concepts--implementations)\n6. [Advanced Topics](#advanced-topics)\n7. [Common Issues \u0026 Solutions](#common-issues--solutions)\n8. [Dependencies](#dependencies)\n9. [Contributing \u0026 Future Work](#contributing--future-work)\n\n---\n\n## Project Overview\n\nThis repository is a **comprehensive LangGraph learning and reference repository** demonstrating production-ready implementations of:\n- **Core workflow patterns** (Sequential, Parallel, Conditional)\n- **Advanced features** (Persistence, Streaming, Memory Systems, Tools, RAG, HITL)\n- **11 complete implementations** with working code, not just concepts\n\nAll code uses **LLaMA-3.3-70b-versatile** model via Groq API, Python 3.12+, and production-grade LangGraph patterns.\n\n### ✅ What's Implemented (11 Complete Modules)\n\n**Fundamental Patterns:**\n1. Sequential Workflows - Linear task execution\n2. Parallel Workflows - Concurrent independent tasks\n3. Conditional Workflows - Dynamic routing based on logic\n\n**Production Features:**\n\u003cbr/\u003e\n4. Persistence - SQLite checkpointing \u0026 state resumption\n\u003cbr/\u003e\n5. Streaming - Real-time token streaming with async execution\n\u003cbr/\u003e\n6. Chat Memory (SQLite) - Persistent conversation history\n\u003cbr/\u003e\n7. Short-Term Memory - Thread-specific isolated sessions\n\u003cbr/\u003e\n8. Long-Term Memory - Global cross-session user profiles\n\u003cbr/\u003e\n9. Human-in-the-Loop - Workflow interrupts for human decisions\n\u003cbr/\u003e\n10. Tool Binding - LLM-driven autonomous tool selection\n\u003cbr/\u003e\n11. RAG - Retrieval-Augmented Generation with semantic search\n\n**Target Audience:** LangGraph learners, AI engineers, teams building production chatbots, multi-step AI workflows, and agent systems.\n\n---\n\n## Getting Started\n\n### Prerequisites\n\n- Python 3.12 or higher\n- Groq API key (for LLM features)\n- Git\n\n### Installation\n\n1. **Clone the repository:**\n   ```bash\n   git clone \u003crepository-url\u003e\n   cd langgraph-revision\n   ```\n\n2. **Create virtual environment (if not already done):**\n   ```bash\n   python -m venv .venv\n   source .venv/bin/activate  # On Windows: .venv\\Scripts\\activate\n   ```\n\n3. **Install dependencies:**\n   ```bash\n   pip install -r requirements.txt\n   ```\n\n4. **Set up environment variables:**\n   ```bash\n   cp .env.example .env  # Create .env file if needed\n   # Add your GROQ_API_KEY to .env\n   export GROQ_API_KEY=\"your-api-key-here\"\n   ```\n\n5. **Run notebooks:**\n   ```bash\n   jupyter notebook\n   ```\n\n---\n\n## Project Structure\n\n```\nlanggraph-revision/\n├── 1)Sequential_Workflow/                 ✅ COMPLETE\n│   ├── workflow.ipynb                     # BMI calculator (simple pattern)\n│   └── llmworkflow.ipynb                  # Q\u0026A system with LLM\n│\n├── 2)Parallel_Workflow/                   ✅ COMPLETE\n│   ├── simple_workflow.ipynb              # String processing in parallel\n│   └── llm_workflow.ipynb                 # 3 parallel LLM tasks + aggregation\n│\n├── 3)Conditional_Workflows/               ✅ COMPLETE\n│   ├── simple_workflow.ipynb              # Quadratic solver (discriminant-based)\n│   └── llm_workflow.ipynb                 # LLM-powered question classifier\n│\n├── 4)Persistence/                         ✅ COMPLETE\n│   └── workflow.ipynb                     # Joke workflow with checkpointing\n│\n├── 5)Streaming/                           ✅ COMPLETE\n│   ├── graph.py                           # Graph with async streaming support\n│   └── run.py                             # Async main with token streaming\n│\n├── 6)Sqllite_Integration/                 ✅ COMPLETE\n│   ├── code.py                            # Chat with SQLite persistence\n│   └── chat_memory.db                     # Database (auto-created)\n│\n├── 7)Short_Term_Memory/                   ✅ COMPLETE\n│   └── code.py                            # Thread-scoped conversation memory\n│\n├── 8)Long_Term_Memory/                    ✅ COMPLETE\n│   └── code.py                            # Global user profiles (InMemoryStore)\n│\n├── 9)HITL_Concept/                        ✅ COMPLETE\n│   └── code.py                            # Human-in-the-Loop with interrupts\n│\n├── 10)Tools/                              ✅ COMPLETE\n│   └── code.py                            # LLM with tool binding + execution\n│\n├── 11)RAG/                                ✅ COMPLETE\n│   └── code.py                            # RAG system with vector search\n│\n├── main.py                                # Entry point\n├── requirements.txt                       # Dependencies\n├── pyproject.toml                         # Project metadata\n└── README.md                              # This file\n```\n\n---\n\n## Core Workflow Patterns\n\n### 1. Sequential Workflows\n\n**Concept:** Tasks execute one after another in a strict order. Output of one task becomes input to the next.\n\n**Characteristics:**\n- Linear execution path\n- Each node waits for previous node to complete\n- State flows sequentially through nodes\n\n**Real-world Use Cases:**\n- Document processing pipelines\n- Data transformation chains\n- Step-by-step problem solving\n\n**Key Files:**\n- `1)Sequential_Workflow/workflow.ipynb` - Simple example with static data\n- `1)Sequential_Workflow/llmworkflow.ipynb` - LLM integration for multi-step reasoning\n\n**Example Flow:**\n```\nInput → Node1 → Node2 → Node3 → Output\n```\n\n---\n\n### 2. Parallel Workflows\n\n**Concept:** Multiple independent tasks execute simultaneously. Results are aggregated when all tasks complete.\n\n**Characteristics:**\n- Concurrent execution of multiple nodes\n- Requires `Annotated` types for state fields receiving parallel updates\n- Better performance for independent tasks\n- Reduces total execution time\n\n**Real-world Use Cases:**\n- Multi-perspective analysis (summarize, extract key points, suggest actions simultaneously)\n- Parallel data enrichment\n- Independent calculations that need aggregation\n\n**Key Files:**\n- `2)Parallel_Workflow/simple_workflow.ipynb` - Basic parallel execution\n- `2)Parallel_Workflow/llm_workflow.ipynb` - LLM tasks running in parallel\n\n**Important:** Using `Annotated[type, \"\"]` prevents `InvalidUpdateError` when parallel nodes update the same state field.\n\n**Example Flow:**\n```\n       ┌─→ Node1 ─┐\nInput →┼─→ Node2 ─┼→ Aggregator → Output\n       └─→ Node3 ─┘\n```\n\n---\n\n### 3. Conditional Workflows\n\n**Concept:** Workflow path is determined dynamically based on routing logic. Different branches execute based on conditions.\n\n**Characteristics:**\n- Decision-based routing\n- Router node returns destination node name (as string)\n- Enables dynamic behavior based on input analysis\n- Efficient filtering of tasks\n\n**Real-world Use Cases:**\n- Intent-based routing (customer support, question classification)\n- Specialized processing pipelines (math vs. general questions)\n- Dynamic task selection based on input type\n\n**Key Files:**\n- `3)Conditional_Workflows/simple_workflow.ipynb` - Quadratic equation solver with conditional branches\n- `3)Conditional_Workflows/llm_workflow.ipynb` - LLM-based question classifier and responder\n\n**Example Flow:**\n```\nInput → Router → Decision: \"math\" or \"general\"?\n           ↓                    ↓\n         Math Node          General Node\n           ↓                    ↓\n        Output             Output\n```\n\n---\n\n## Key Concepts \u0026 Implementations\n\n### State Management\n\n**TypedDict Definition:**\n```python\nclass WorkflowState(TypedDict):\n    question: str\n    category: str\n    answer: str\n```\n\nStates define all data flowing through the workflow. LangGraph maintains state consistency across nodes.\n\n### Node Functions\n\nNodes are functions that process state and return updated state:\n\n```python\ndef math_node(state: WorkflowState) -\u003e WorkflowState:\n    \"\"\"Process math questions\"\"\"\n    response = llm.invoke(prompt)\n    state['answer'] = response.content  # Extract content, not entire object\n    return state\n```\n\n**Important:** Always extract `.content` from LLM responses, not the entire message object.\n\n### Graph Construction\n\nLangGraph uses a builder pattern to construct workflows:\n\n```python\nbuilder = StateGraph(WorkflowState)\nbuilder.add_node(\"input_node\", input_node)\nbuilder.add_edge(START, \"input_node\")\nbuilder.add_conditional_edges(\"input_node\", router_function)\nworkflow = builder.compile()\n```\n\n### Router Functions\n\nRouter functions determine which node to execute next:\n\n```python\ndef llm_router(state: WorkflowState) -\u003e Literal['math_node', 'general_node']:\n    \"\"\"Classify and route to appropriate node\"\"\"\n    response = llm.invoke(prompt)\n    category = response.content.strip().lower()\n    state[\"category\"] = category\n    return category + \"_node\"  # Return node name as STRING\n```\n\n**Critical:** Router must return node name as string, not execute the node.\n\n### Handling Parallel Updates with Annotated\n\nWhen parallel nodes update the same state field:\n\n```python\nfrom typing import Annotated\n\nclass WorkflowState(TypedDict):\n    summary: Annotated[str, \"\"]        # Metadata tells LangGraph how to merge\n    key_points: Annotated[str, \"\"]\n    action_items: Annotated[str, \"\"]\n```\n\nThe `Annotated` metadata allows safe concurrent updates. Without this, `InvalidUpdateError` occurs.\n\n---\n\n## Advanced Topics\n\n### 1. Persistence \u0026 State Management\n\n**Definition:** Saving workflow state to allow resumption after interruptions, enabling audit trails and multi-session continuity.\n\n**Use Cases:**\n- Long-running workflows that might fail mid-execution\n- Audit trails and compliance requirements\n- Workflow history and debugging\n- Multi-turn conversations with context preservation\n\n**Implementation in Project:**\n- **Location:** `4)Persistence/workflow.ipynb`\n- **Technology:** SQLite Checkpointer\n- **Key Concept:** State is saved at each step, allowing workflow to resume from exactly where it paused\n\n**Implementation Approach:**\n```python\nfrom langgraph.checkpoint.sqlite import SqliteSaver\n\nconn = sqlite3.connect(\"workflow.db\", check_same_thread=False)\ncheckpointer = SqliteSaver(conn)\ngraph = builder.compile(checkpointer=checkpointer)\n\n# Resume workflow with thread_id\nresult = graph.invoke(\n    initial_state,\n    config={\"configurable\": {\"thread_id\": \"user-123\"}}\n)\n```\n\n**Persistence Strategies:**\n- **In-Memory:** Fast but lost on restart\n- **SQLite:** Good for development and testing (used in this project)\n- **PostgreSQL:** Scalable for production\n- **Custom Storage:** Cloud databases, etc.\n\n---\n\n### 2. Streaming in LangGraph\n\n**Definition:** Real-time output streaming as workflow executes, instead of waiting for completion.\n\n**Use Cases:**\n- Large LLM outputs (show tokens as they generate)\n- User experience improvement (no waiting for full response)\n- Progressive results display\n- Real-time monitoring and debugging\n\n**Implementation in Project:**\n- **Location:** `5)Streaming/` (graph.py, run.py)\n- **Key Feature:** Async streaming with `astream()` method\n- **Pattern:** Token-by-token output as LLM generates responses\n\n**Implementation Approach:**\n```python\nasync def main():\n    input_state = {\"messages\": [{\"role\": \"user\", \"content\": \"Your question\"}]}\n    \n    print(\"Streaming tokens:\\n\")\n    async for chunk in graph.astream(input_state, stream_mode=\"messages\"):\n        token = chunk[0].content\n        if token:\n            print(token, end=\"\", flush=True)\n\nasyncio.run(main())\n```\n\n**Stream Modes:**\n- `stream_mode=\"messages\"` - Stream individual tokens/messages\n- `stream_mode=\"updates\"` - Stream node updates\n- `stream_mode=\"values\"` - Stream complete state snapshots\n\n**Benefits:**\n- Better user experience\n- Earlier error detection\n- Real-time debugging and monitoring\n\n---\n\n### 3. Memory Systems in LangGraph\n\n#### Short-Term Memory\n\n**Definition:** Conversation context within current session only. Memory is thread-specific using `thread_id`.\n\n**Implementation in Project:**\n- **Location:** `7)Short_Term_Memory/code.py`\n- **Pattern:** Messages stored per thread, accessible only within that thread session\n- **Persistence:** SQLite database (`short_term.db`)\n\n**Key Concept:**\n```python\n# Different thread_id = different conversation = no shared memory\nconfig = {\"configurable\": {\"thread_id\": \"thread-123\"}}\n# Only messages within this thread are remembered\nfor chunk, metadata in graph.stream({\"messages\": messages}, config=config):\n    # Process streaming output\n```\n\n**Use Cases:**\n- Multi-turn conversations\n- Context-aware responses within single session\n- Temporary working memory\n- User-specific conversation history\n\n#### Long-Term Memory\n\n**Definition:** Persistent storage of knowledge/information across sessions and conversations.\n\n**Implementation in Project:**\n- **Location:** `8)Long_Term_Memory/code.py`\n- **Approaches:**\n  1. **Vector Database (RAG):** Store embeddings of important facts for semantic search\n  2. **Knowledge Base:** Structured information storage\n  3. **User Profiles:** Preferences and history across sessions\n  4. **Learned Patterns:** Insights from past interactions\n\n**Use Cases:**\n- User preferences across multiple sessions\n- Learned patterns from past interactions\n- Domain-specific knowledge base\n- Multi-session conversation continuity with context\n\n---\n\n### 4. SQLite Integration\n\n**Definition:** Persistent storage layer using SQLite for checkpointing and state management.\n\n**Implementation in Project:**\n- **Location:** `6)Sqllite_Integration/code.py`\n- **File:** `chat_memory.db` (SQLite database)\n- **Pattern:** Multi-threaded safe SQLite connection with `check_same_thread=False`\n\n**Implementation Pattern:**\n```python\nfrom langgraph.checkpoint.sqlite import SqliteSaver\n\n# Multi-thread safe connection\nconn = sqlite3.connect(\"chat_memory.db\", check_same_thread=False)\ncheckpointer = SqliteSaver(conn)\ngraph = builder.compile(checkpointer=checkpointer)\n\n# Use thread_id to manage conversation sessions\nconfig = {\"configurable\": {\"thread_id\": thread_id}}\n```\n\n**Real-World Use:**\n- Persistent chat history\n- Session management\n- Conversation recovery after interruptions\n- Multi-user conversation tracking\n\n---\n\n### 5. Human-in-the-Loop (HITL)\n\n**Definition:** Workflows that pause mid-execution to wait for human input/approval before proceeding.\n\n**Implementation in Project:**\n- **Location:** `9)HITL_Concept/code.py`\n- **Key Mechanism:** `interrupt()` and `Command(resume=value)` pattern\n- **Requirement:** Checkpointer is mandatory (state must be saved during pause)\n\n**How It Works:**\n1. Workflow executes normally until it hits `interrupt()`\n2. Entire state is saved to checkpointer\n3. Workflow pauses and waits for human decision\n4. Human reviews output and provides feedback\n5. `Command(resume=value)` resumes workflow from exact pause point\n6. Workflow continues execution with human's decision incorporated\n\n**Implementation Approach:**\n```python\ndef human_review(state: MessagesState):\n    draft = state[\"messages\"][-1].content\n    print(f\"[Node] Draft is ready:\\n{draft}\\n\")\n    \n    # Pause and wait for human decision\n    decision = interrupt({\n        \"question\": \"should we forward the mail?\",\n        \"draft\": draft\n    })\n    \n    if decision == \"approve\":\n        return {\"messages\": [AIMessage(content=\"Email approved and sent!\")]}\n    else:\n        return {\"messages\": [AIMessage(content=f\"Email cancelled. Feedback: {decision}\")]}\n\n# Add node to graph\nbuilder.add_node(\"human_review\", human_review)\n```\n\n**Use Cases:**\n- Approval workflows (high-stakes decisions need human review)\n- Interactive debugging and refinement\n- User confirmation for critical actions\n- Feedback collection and incorporation\n\n**Critical Considerations:**\n- **Checkpointer is Mandatory:** Without persistence, state cannot be saved during pause\n- **State Preservation:** Entire workflow state is maintained during interruption\n- **Resume Mechanism:** `Command(resume=value)` tells workflow where to continue and what to do next\n\n---\n\n### 6. Tool Binding \u0026 Autonomous Tool Use\n\n**Definition:** Enable LLMs to autonomously decide when to use external tools and execute them automatically.\n\n**Implementation in Project:**\n- **Location:** `10)Tools/code.py`\n- **Pattern:** LLM with `bind_tools()` + ToolNode for automatic execution\n- **Pre-built Tools:** Weather, Calculator, Joke (demo tools)\n\n**Implementation Approach:**\n```python\n@tool\ndef get_weather(city: str) -\u003e str:\n    \"\"\"Get the current weather of a city.\"\"\"\n    # Tool docstring is critical - LLM reads this to decide when to use\n\n@tool\ndef calculator(expression: str) -\u003e str:\n    \"\"\"Evaluate mathematical expressions.\"\"\"\n    return str(eval(expression))\n\nllm_with_tools = llm.bind_tools([get_weather, calculator, get_joke])\n\n# Graph routing\nfrom langgraph.prebuilt import ToolNode\nfrom langgraph.prebuilt.chat_agent_executor import tools_condition\n\nbuilder.add_node(\"tools\", ToolNode(tools))\nbuilder.add_conditional_edges(\"chatbot\", tools_condition)\nbuilder.add_edge(\"tools\", \"chatbot\")  # Loop back for final response\n```\n\n**Key Features:**\n- Tool docstrings are LLM's interface\n- Automatic tool selection based on context\n- Tool execution happens automatically\n- Loop pattern allows multiple tool calls before final response\n- Zero manual tool invocation needed\n\n**Use Cases:**\n- Chatbots that need external data (weather, stocks, APIs)\n- Calculation-intensive workflows\n- Information retrieval tasks\n- External system integration\n\n---\n\n### 7. Retrieval Augmented Generation (RAG)\n\n**Definition:** Ground LLM responses in custom knowledge base instead of LLM training data - prevents hallucinations.\n\n**Implementation in Project:**\n- **Location:** `11)RAG/code.py`\n- **Architecture:** Vector search → Retrieve → Generate pattern\n- **Vector DB:** Chroma (in-memory)\n- **Embeddings:** HuggingFace (all-MiniLM-L6-v2)\n- **Knowledge Base:** 6 LangGraph documentation samples\n\n**Implementation Approach:**\n```python\nfrom langchain_community.vectorstores import Chroma\nfrom langchain_huggingface import HuggingFaceEmbeddings\n\n# Create embeddings and vector store\nembeddings = HuggingFaceEmbeddings(model_name=\"all-MiniLM-L6-v2\")\ndocs = [Document(page_content=text) for text in knowledge_base]\nvector_store = Chroma.from_documents(docs, embeddings)\n\n# Retrieve node - semantic search\ndef retrieve(state):\n    docs = vector_store.similarity_search(state[\"question\"], k=2)\n    return {\"context\": docs}\n\n# Generate node - answer based on retrieved context\ndef generate(state):\n    context_text = \"\\n\".join([doc.page_content for doc in state[\"context\"]])\n    prompt = f\"Using this context:\\n{context_text}\\n\\nAnswer: {state['question']}\"\n    response = llm.invoke(prompt)\n    return {\"answer\": response.content}\n```\n\n**Graph Flow:**\n```\nUser Query → Retrieve Node (Vector Search) → Retrieved Docs\n              ↓\n              → Generate Node (LLM with Context)\n              ↓\n              → Final Answer (Grounded in knowledge base)\n```\n\n**Key Features:**\n- Vector semantic search for relevance\n- Context-grounded answers (no hallucinations)\n- Easy to add/update knowledge without retraining\n- Transparent source citations possible\n- Temperature=0 for consistency\n\n**Use Cases:**\n- Customer support bots (company knowledge base)\n- Document Q\u0026A systems\n- Internal knowledge bases\n- FAQ systems\n- Domain-specific chatbots\n\n---\n\n## Common Issues \u0026 Solutions\n\n### Issue 1: InvalidUpdateError - \"unhashable type: 'dict'\"\n\n**Symptom:**\n```\nTypeError: unhashable type: 'dict'\nAt key 'summary': Can receive only one value per step\n```\n\n**Cause:** Multiple parallel nodes updating same state field without `Annotated` type.\n\n**Solution:**\n```python\n# ❌ Wrong:\nclass WorkflowState(TypedDict):\n    summary: str\n\n# ✅ Correct:\nclass WorkflowState(TypedDict):\n    summary: Annotated[str, \"\"]\n```\n\n---\n\n### Issue 2: Router Returning Node Object Instead of String\n\n**Symptom:**\n```\nTypeError: unhashable type: 'dict'\n```\n\n**Cause:** Router function executes node and returns dict instead of returning node name.\n\n**Solution:**\n```python\n# ❌ Wrong:\ndef router(state):\n    if condition:\n        return node_function(state)  # Returns dict\n\n# ✅ Correct:\ndef router(state):\n    if condition:\n        return \"node_name\"  # Return string node name\n```\n\n---\n\n### Issue 3: LLM Response Appears as Object\n\n**Symptom:**\n```\nOutput: \u003clangchain_core.messages.ai_message.AIMessage object at 0x...\u003e\n```\n\n**Cause:** Not extracting `.content` from LLM response.\n\n**Solution:**\n```python\n# ❌ Wrong:\nstate['answer'] = response\n\n# ✅ Correct:\nstate['answer'] = response.content\n```\n\n---\n\n### Issue 4: Missing Environment Variables\n\n**Symptom:**\n```\nAuthenticationError: Groq API key not found\n```\n\n**Solution:**\n```bash\n# Add to .env file or environment:\nexport GROQ_API_KEY=\"your-actual-api-key\"\n\n# Or in Python:\nfrom dotenv import load_dotenv\nload_dotenv()\n```\n\n---\n\n## Dependencies\n\n### Core Dependencies\n\n| Package | Version | Purpose |\n|---------|---------|---------|\n| **langgraph** | \u003e=1.2.0 | Workflow orchestration framework |\n| **langchain** | \u003e=1.3.1 | LLM integration and tools |\n| **langchain-groq** | \u003e=1.1.2 | Groq LLM API integration |\n| **langchain-community** | Latest | Vector stores (Chroma), retriever integration |\n| **langchain-huggingface** | Latest | HuggingFace embeddings (all-MiniLM-L6-v2) |\n| **python-dotenv** | \u003e=1.2.2 | Environment variable management |\n| **ipython** | \u003e=9.13.0 | Interactive notebook environment |\n| **chroma** | Latest | Vector database for RAG |\n\n### Installation via Requirements\n\n```bash\npip install -r requirements.txt\n```\n\n### Installation via Pyproject.toml\n\n```bash\npip install -e .\n```\n\n---\n\n## Code Examples \u0026 Patterns\n\n### Example 1: Running a Simple Sequential Workflow\n\n```python\nfrom typing import TypedDict\nfrom langgraph.graph import START, END, StateGraph\n\nclass SimpleState(TypedDict):\n    text: str\n    processed: str\n\ndef step1(state: SimpleState) -\u003e SimpleState:\n    state['processed'] = state['text'].upper()\n    return state\n\ndef step2(state: SimpleState) -\u003e SimpleState:\n    state['processed'] += \"!\"\n    return state\n\nbuilder = StateGraph(SimpleState)\nbuilder.add_node(\"step1\", step1)\nbuilder.add_node(\"step2\", step2)\nbuilder.add_edge(START, \"step1\")\nbuilder.add_edge(\"step1\", \"step2\")\nbuilder.add_edge(\"step2\", END)\n\nworkflow = builder.compile()\nresult = workflow.invoke({\"text\": \"hello\", \"processed\": \"\"})\n```\n\n---\n\n### Example 2: Parallel Workflows with Aggregation\n\n```python\nfrom typing import Annotated\nfrom operator import add\n\nclass ParallelState(TypedDict):\n    query: str\n    results: Annotated[list, add]  # Accumulates results\n\ndef search1(state: ParallelState) -\u003e ParallelState:\n    return {\"results\": [\"Result from source 1\"]}\n\ndef search2(state: ParallelState) -\u003e ParallelState:\n    return {\"results\": [\"Result from source 2\"]}\n\nbuilder = StateGraph(ParallelState)\nbuilder.add_node(\"search1\", search1)\nbuilder.add_node(\"search2\", search2)\nbuilder.add_edge(START, [\"search1\", \"search2\"])  # Parallel\nbuilder.add_edge([\"search1\", \"search2\"], END)\n\nworkflow = builder.compile()\nresult = workflow.invoke({\"query\": \"test\", \"results\": []})\n```\n\n---\n\n### Example 3: LLM-Powered Conditional Router\n\n```python\nfrom langchain_groq import ChatGroq\nfrom typing import Literal\n\nllm = ChatGroq(model=\"llama-3.3-70b-versatile\", temperature=0.2)\n\ndef classify_query(state) -\u003e Literal['math_path', 'general_path']:\n    prompt = f\"Is this a math question? Reply only: 'math' or 'general'. Query: {state['query']}\"\n    response = llm.invoke(prompt)\n    category = response.content.strip().lower()\n    return \"math_path\" if category == \"math\" else \"general_path\"\n\n# Add to graph\nbuilder.add_conditional_edges(\"classifier\", classify_query)\n```\n\n---\n\n## Learning Path\n\n### Beginner (Weeks 1-2)\n1. Understand graph concepts (nodes, edges, states)\n2. Run simple sequential workflow examples (`1)Sequential_Workflow/workflow.ipynb`)\n3. Explore parallel workflows (`2)Parallel_Workflow/simple_workflow.ipynb`)\n4. Modify examples to understand state flow\n\n### Intermediate (Weeks 3-4)\n1. Implement conditional routing logic (`3)Conditional_Workflows/simple_workflow.ipynb`)\n2. Debug `Annotated` type issues for parallel nodes\n3. Integrate with LLM APIs (`1)Sequential_Workflow/llmworkflow.ipynb`)\n4. Understand state management and `MessagesState`\n5. Run LLM-based conditional routers (`3)Conditional_Workflows/llm_workflow.ipynb`)\n\n### Advanced (Weeks 5-8)\n1. **State Persistence:** Explore `4)Persistence/workflow.ipynb` - SQLite checkpointing \u0026 time travel\n2. **Real-time Streaming:** Study `5)Streaming/` - Async token streaming from LLMs\n3. **Chat Memory:** Build with `6)Sqllite_Integration/code.py` - Persistent conversations\n4. **Short-Term Memory:** Implement `7)Short_Term_Memory/code.py` - Thread-specific memory\n5. **Long-Term Memory:** Design `8)Long_Term_Memory/code.py` - Global user profiles\n\n### Expert (Weeks 9+)\n1. **Human-in-the-Loop:** `9)HITL_Concept/code.py` - Workflow interrupts for human decisions\n2. **Tool Binding:** `10)Tools/code.py` - LLM-driven autonomous tool use\n3. **RAG Systems:** `11)RAG/code.py` - Vector search + grounded generation\n4. Production deployment patterns with persistence\n5. Multi-agent workflows and communication\n6. Custom memory backends (PostgreSQL, Vector DBs)\n7. Advanced streaming strategies\n8. Performance optimization and scaling\n\n---\n\n## Next Steps \u0026 Future Development\n\n### Implemented Features ✅ (11 Complete Modules)\n\n**All features listed below are FULLY IMPLEMENTED with working code:**\n\n1. ✅ **Sequential Workflows** - Linear task execution with state flow\n2. ✅ **Parallel Workflows** - Concurrent independent tasks with aggregation\n3. ✅ **Conditional Workflows** - Dynamic routing based on logic\n4. ✅ **Persistence \u0026 State Management** - SQLite checkpointing with resumption\n5. ✅ **Real-time Streaming** - Async token streaming from LLMs\n6. ✅ **Chat with SQLite Memory** - Persistent conversation history\n7. ✅ **Short-Term Memory** - Thread-scoped isolated sessions\n8. ✅ **Long-Term Memory** - Global cross-session user profiles\n9. ✅ **Human-in-the-Loop** - Workflow interrupts with state preservation\n10. ✅ **Tool Binding** - LLM-driven autonomous tool selection \u0026 execution\n11. ✅ **Retrieval Augmented Generation** - Vector search + grounded answers\n\n### Potential Future Enhancements\n\n1. **Multi-Agent Workflows**\n   - Agent-to-agent communication patterns\n   - Shared workspace and tool usage\n   - Consensus mechanisms between agents\n\n2. **Advanced Memory Systems**\n   - Vector database integration (Pinecone, Weaviate, Milvus)\n   - Semantic similarity-based memory retrieval\n   - Hybrid memory (short + long term combined)\n\n3. **Production Deployment**\n   - Docker containerization examples\n   - Kubernetes orchestration\n   - Load balancing strategies\n   - API deployment patterns\n\n4. **Monitoring \u0026 Observability**\n   - LangSmith integration with custom metrics\n   - Performance optimization guide\n   - Error tracking and alerting\n   - Cost analysis per workflow\n\n5. **Advanced LLM Patterns**\n   - Function calling with complex schemas\n   - Structured output parsing\n   - Multi-model workflows\n   - Fallback strategies\n\n### Contributing\n\nTo contribute examples or improvements:\n\n1. Fork the repository\n2. Create feature branch: `git checkout -b feature/your-feature`\n3. Add well-documented examples\n4. Test thoroughly\n5. Submit pull request with documentation\n\n---\n\n## References \u0026 Resources\n\n### Official Documentation\n- [LangGraph Documentation](https://python.langchain.com/docs/langgraph)\n- [LangChain Documentation](https://python.langchain.com/docs)\n- [Groq API Documentation](https://groq.com/docs)\n\n### Key Concepts\n- [State Graphs in LangGraph](https://python.langchain.com/docs/langgraph/concepts/low_level_conceptual_guide)\n- [Routing and Conditional Edges](https://python.langchain.com/docs/langgraph/how-tos/define-nodes-edges)\n- [Persistence and Checkpointing](https://python.langchain.com/docs/langgraph/concepts/persistence)\n\n### Related Tools\n- [LangSmith - Debugging \u0026 Monitoring](https://smith.langchain.com/)\n- [LangChain Templates](https://templates.langchain.com/)\n- [LangGraph Hub](https://langchain-ai.github.io/langgraph/reference/library/)\n\n---\n\n## Troubleshooting Guide\n\n### Quick Fixes\n\n| Problem | Quick Fix |\n|---------|-----------|\n| `ModuleNotFoundError: No module named 'langgraph'` | Run `pip install -r requirements.txt` |\n| `AuthenticationError` with LLM | Check `GROQ_API_KEY` environment variable |\n| Workflow runs but produces no output | Check node return statements are updating state |\n| Parallel execution fails with state error | Use `Annotated` for concurrent state updates |\n| Router function not working | Ensure router returns string (node name), not object |\n\n---\n\n## FAQ\n\n**Q: What's the difference between parallel and sequential workflows?**  \nA: Sequential executes nodes one-by-one; parallel executes independent nodes simultaneously, reducing total time.\n\n**Q: When should I use conditional edges?**  \nA: When different paths should execute based on runtime conditions or input classification.\n\n**Q: How do I persist workflow state?**  \nA: Use LangGraph's checkpointer (SQLite, PostgreSQL, etc.) to save state at each step.\n\n**Q: Can I use LangGraph without LLMs?**  \nA: Yes, LangGraph works with any Python functions, though LLM integration is powerful.\n\n**Q: What's the purpose of `Annotated` in state definitions?**  \nA: It tells LangGraph how to merge values when multiple nodes update the same field concurrently.\n\n---\n\n## License\n\nThis project is provided as an educational resource.\n\n---\n\n## Contact \u0026 Support\n\nFor questions or issues:\n- Check the troubleshooting section\n- Review example notebooks\n- Consult official LangGraph documentation\n\n---\n\n**Last Updated:** May 2026  \n**Repository Version:** 0.1.0\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnevin100%2Flanggraph-revision","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnevin100%2Flanggraph-revision","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnevin100%2Flanggraph-revision/lists"}