{"id":26686916,"url":"https://github.com/timeless-residents/handson-langchain","last_synced_at":"2026-05-11T06:04:36.624Z","repository":{"id":275217808,"uuid":"925441902","full_name":"timeless-residents/handson-langchain","owner":"timeless-residents","description":"Comprehensive LangChain tutorial: from basic concepts to over 10 advanced agent implementations","archived":false,"fork":false,"pushed_at":"2025-02-18T05:47:36.000Z","size":4,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-02-18T06:32:55.058Z","etag":null,"topics":["agent","ai-agents","ai-assistant","case-study","chatgpt","conversational-ai","langchain","language-models","llm","llm-integration","ml-tutorial","nlp","openai","prompt-engineering","python","python-ai","tutorial"],"latest_commit_sha":null,"homepage":"","language":"Python","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/timeless-residents.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}},"created_at":"2025-01-31T22:17:33.000Z","updated_at":"2025-02-18T05:47:39.000Z","dependencies_parsed_at":"2025-01-31T23:23:27.617Z","dependency_job_id":null,"html_url":"https://github.com/timeless-residents/handson-langchain","commit_stats":null,"previous_names":["timeless-residents/handson-langchain"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/timeless-residents%2Fhandson-langchain","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/timeless-residents%2Fhandson-langchain/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/timeless-residents%2Fhandson-langchain/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/timeless-residents%2Fhandson-langchain/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/timeless-residents","download_url":"https://codeload.github.com/timeless-residents/handson-langchain/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245650477,"owners_count":20650105,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","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","ai-agents","ai-assistant","case-study","chatgpt","conversational-ai","langchain","language-models","llm","llm-integration","ml-tutorial","nlp","openai","prompt-engineering","python","python-ai","tutorial"],"created_at":"2025-03-26T12:15:16.480Z","updated_at":"2026-05-11T06:04:31.590Z","avatar_url":"https://github.com/timeless-residents.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# LangChain and LangGraph Hands-on Tutorial and Case Studies\n\nA comprehensive learning path covering both LangChain and LangGraph, featuring 100+ practical implementations progressing from basic concepts to advanced agent architectures.\n\n## Overview\n\nThis repository provides a structured approach to learning modern LLM application development using both LangChain and LangGraph frameworks. The collection begins with fundamental concepts and gradually progresses to complex, specialized agent implementations and graph-based workflows. It serves as both an educational resource and a reference for implementing AI agents in real-world scenarios.\n\n## Getting Started\n\n### Prerequisites\n\n- Python 3.9+\n- OpenAI API key\n- Basic understanding of Python and API concepts\n\n### Installation\n\n1. Clone this repository:\n   ```bash\n   git clone https://github.com/timeless-residents/handson-langchain.git\n   cd langchain-tutorial\n   ```\n   This command creates a local copy of the repository. We use HTTPS cloning for broader compatibility and easier setup compared to SSH, especially for users behind corporate firewalls.\n\n2. Create a virtual environment:\n   ```bash\n   python -m venv venv\n   source venv/bin/activate  # On Windows: venv\\Scripts\\activate\n   ```\n   Virtual environments are crucial for project isolation. This prevents dependency conflicts between different projects and ensures reproducible environments. The `venv` module is chosen over alternatives like `virtualenv` because it's included in Python's standard library since Python 3.3.\n\n3. Install common dependencies:\n   ```bash\n   pip install langchain langchain-openai langchain-community langgraph python-dotenv\n   ```\n   We install these specific packages because:\n   - `langchain`: Core framework for building LLM applications\n   - `langchain-openai`: OpenAI-specific implementations\n   - `langchain-community`: Community-contributed components\n   - `langgraph`: Graph-based workflow management\n   - `python-dotenv`: Secure environment variable management\n\n4. Set up your OpenAI API key:\n   Create a `.env` file in the root directory with the following content:\n   ```\n   OPENAI_API_KEY=your_api_key_here\n   ```\n   We use environment variables instead of hardcoding API keys for security best practices. The `.env` file is included in `.gitignore` to prevent accidental exposure of sensitive credentials.\n\n## Repository Structure\n\nThe repository follows a progressive learning path, with each directory serving a specific educational purpose:\n\n```\nlangchain-tutorial/\n  ├── step1.py           # Basic LLM usage with LangChain\n  ├── step2.py           # Multi-tool agent implementation\n  ├── steps/             # Additional introductory steps (optional)\n  │   ├── step3.py\n  │   └── ...\n  ├── usecase-001/       # Basic Calculator Agent (LangChain)\n  │   ├── main.py\n  │   ├── README.md\n  │   └── requirements.txt\n  └── ...\n```\n\nThis structure is designed for incremental learning, with each subsequent directory building upon concepts introduced in previous sections.\n\n## Learning Path\n\n### Part 1: Getting Started with LangChain\n\n#### Step 1: Basic LLM Usage (`step1.py`)\n```python\nfrom langchain_openai import OpenAI\nfrom dotenv import load_dotenv\n\n# Load environment variables from .env file\nload_dotenv()\n\n# Create OpenAI LLM instance\nllm = OpenAI()\n\n# Query the LLM\nprompt = \"What's the weather like today?\"\nresponse = llm.invoke(prompt)\n\nprint(\"LLM Response:\")\nprint(response)\n```\n\nThis code demonstrates several key concepts:\n1. **Environment Setup**: `load_dotenv()` loads environment variables securely, a crucial practice for managing API keys and sensitive data.\n2. **LLM Initialization**: `OpenAI()` creates an LLM instance with default parameters. We use the default settings initially for simplicity, but these can be customized for temperature, max tokens, etc.\n3. **Synchronous Invocation**: `llm.invoke(prompt)` sends a synchronous request to the LLM. We use synchronous calls here for clarity, though asynchronous operations are available for production scenarios.\n\n#### Step 2: Multi-Tool Agent Implementation (`step2.py`)\n```python\nfrom langchain.agents import initialize_agent, Tool\nfrom langchain.tools import DuckDuckGoSearchRun\nfrom langchain_openai import OpenAI\nfrom datetime import datetime\n\n# Initialize tools\nsearch = DuckDuckGoSearchRun()\ncalculator = Tool(\n    name=\"Calculator\",\n    func=lambda x: eval(x),\n    description=\"Useful for mathematical calculations\"\n)\ntime_tool = Tool(\n    name=\"Time\",\n    func=lambda _: datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"),\n    description=\"Returns the current time\"\n)\n\n# Create and initialize the agent\nllm = OpenAI(temperature=0)\nagent = initialize_agent(\n    tools=[search, calculator, time_tool],\n    llm=llm,\n    agent=\"zero-shot-react-description\",\n    verbose=True\n)\n```\n\nThis implementation showcases several advanced concepts:\n1. **Tool Integration**: Each tool is encapsulated with a clear name and description, helping the agent understand when to use each tool.\n   - The calculator uses `eval()` for simple calculations (Note: In production, use safer evaluation methods)\n   - The time tool provides formatted current time\n   - DuckDuckGoSearchRun enables web searches without API keys\n\n2. **Agent Configuration**:\n   - `temperature=0`: Set to 0 for deterministic responses, crucial for tool-using agents\n   - `zero-shot-react-description`: This agent type is chosen because it:\n     - Requires no examples (zero-shot)\n     - Uses ReAct (Reasoning and Acting) framework\n     - Can choose tools based on their descriptions\n\n3. **Verbose Mode**: Enabled for learning purposes, allowing observation of the agent's decision-making process.\n\n### Part 2: Comprehensive Use Cases\n\nEach use case demonstrates specific patterns and techniques:\n\n#### LangChain Foundational Use Cases (001-010)\nEach implementation is carefully structured to demonstrate specific capabilities:\n\n- **001: Basic Calculator Agent**\n  ```python\n  from langchain.agents import create_react_agent\n  from langchain.tools import Tool\n  \n  def safe_eval(expression: str) -\u003e float:\n      \"\"\"\n      Safely evaluate mathematical expressions.\n      \n      Args:\n          expression (str): Mathematical expression to evaluate\n          \n      Returns:\n          float: Result of the evaluation\n          \n      Safety:\n          - Uses ast.literal_eval instead of eval()\n          - Validates input format\n          - Handles division by zero\n      \"\"\"\n      import ast\n      try:\n          # Convert string to abstract syntax tree\n          tree = ast.parse(expression, mode='eval')\n          \n          # Validate node types\n          for node in ast.walk(tree):\n              if not isinstance(node, (ast.Expression, ast.Num, ast.BinOp,\n                                     ast.UnaryOp, ast.Add, ast.Sub, ast.Mult,\n                                     ast.Div)):\n                  raise ValueError(\"Invalid expression\")\n          \n          # Evaluate if safe\n          return float(eval(compile(tree, '\u003cstring\u003e', 'eval')))\n      except ZeroDivisionError:\n          raise ValueError(\"Division by zero\")\n      except Exception as e:\n          raise ValueError(f\"Invalid expression: {str(e)}\")\n  ```\n  \n  This implementation demonstrates:\n  - **Security**: Uses AST parsing instead of direct eval()\n  - **Error Handling**: Comprehensive error cases\n  - **Type Safety**: Explicit return type\n  - **Documentation**: Detailed docstring with Args, Returns, and Safety sections\n\n[Additional use cases would follow with similar detailed explanations...]\n\n## Best Practices Demonstrated\n\n### 1. Type Hinting\n```python\nfrom typing import List, Dict, Optional\n\ndef process_data(input_data: List[Dict[str, any]],\n                config: Optional[Dict[str, str]] = None) -\u003e Dict[str, any]:\n    \"\"\"\n    Process input data according to optional configuration.\n    \n    Args:\n        input_data: List of dictionaries containing data to process\n        config: Optional configuration parameters\n        \n    Returns:\n        Processed data as a dictionary\n    \"\"\"\n    # Implementation\n```\n\nType hints are used throughout the codebase because they:\n- Enable better IDE support\n- Facilitate early error detection\n- Serve as inline documentation\n- Support static type checking\n\n### 2. Error Handling\n```python\nclass CustomError(Exception):\n    \"\"\"Base class for custom exceptions\"\"\"\n    pass\n\ndef handle_api_request(url: str) -\u003e Dict[str, any]:\n    \"\"\"\n    Handle external API requests with comprehensive error handling.\n    \n    Args:\n        url: API endpoint URL\n        \n    Returns:\n        API response data\n        \n    Raises:\n        CustomError: When API request fails\n    \"\"\"\n    try:\n        response = requests.get(url)\n        response.raise_for_status()\n        return response.json()\n    except requests.RequestException as e:\n        raise CustomError(f\"API request failed: {str(e)}\")\n    except json.JSONDecodeError as e:\n        raise CustomError(f\"Invalid JSON response: {str(e)}\")\n```\n\nThis pattern demonstrates:\n- Custom exception classes\n- Specific exception handling\n- Detailed error messages\n- Proper error propagation\n\n## Limitations and Trade-offs\n\n### 1. LLM Dependencies\n- **API Costs**: The implementations rely on OpenAI's API, which incurs usage costs. This may limit scalability for high-volume applications.\n- **Rate Limiting**: OpenAI's API has rate limits that may affect performance in production environments.\n- **Latency**: API calls introduce network latency, which can impact real-time applications.\n\n### 2. Technical Constraints\n- **Memory Management**:\n  - Conversation history can grow large, impacting performance\n  - Token limits restrict context window size\n  - Memory implementations may not persist across sessions by default\n\n- **Tool Integration**:\n  - Tools must be pre-defined and cannot be dynamically created during runtime\n  - Complex tools may require significant error handling\n  - Tool descriptions must be carefully crafted to ensure proper agent usage\n\n- **Error Handling Challenges**:\n  - LLM responses can be unpredictable\n  - Tool execution may fail in unexpected ways\n  - Error recovery strategies may need manual intervention\n\n### 3. Implementation Trade-offs\n- **Synchronous vs Asynchronous**:\n  - Examples use synchronous calls for clarity\n  - Production environments may need async implementations for better performance\n  - Async implementations add complexity to error handling\n\n- **Security Considerations**:\n  - Safe evaluation of expressions limits mathematical capabilities\n  - API key management requires careful handling\n  - Input validation adds processing overhead\n\n- **Development Complexity**:\n  - Debugging LLM-based systems can be challenging\n  - Testing requires mock implementations of LLM responses\n  - Maintaining consistent behavior across different LLM versions\n\n### 4. Framework Limitations\n- **LangChain**:\n  - Documentation may lag behind rapid development\n  - Some features may be experimental or unstable\n  - Community tools may have varying levels of maintenance\n\n- **LangGraph**:\n  - Graph-based workflows add complexity\n  - State management can become complicated\n  - Learning curve for graph-based thinking\n\n### 5. Production Considerations\n- **Scalability**:\n  - Cost increases linearly with usage\n  - Parallel processing may be limited by API constraints\n  - State management becomes complex at scale\n\n- **Monitoring**:\n  - LLM behavior can be difficult to monitor\n  - Tool usage patterns may need custom logging\n  - Performance metrics require careful definition\n\n- **Maintenance**:\n  - Regular updates needed for API changes\n  - Tool integrations may break with external changes\n  - Prompt engineering may need ongoing refinement\n\nThese limitations and trade-offs should be carefully considered when implementing these patterns in production environments. Mitigation strategies should be developed based on specific use case requirements.\n\n## License\n\nThis project is licensed under the MIT License - see the LICENSE file for details.\n\n## Acknowledgments\n\n- The LangChain and LangGraph teams for creating excellent frameworks\n- OpenAI for providing the underlying language models\n- All contributors who have helped improve this collection\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftimeless-residents%2Fhandson-langchain","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftimeless-residents%2Fhandson-langchain","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftimeless-residents%2Fhandson-langchain/lists"}