Skip to content

Pritish053/langchain-101

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸš€ LangChain 101: Production-Ready AI Applications

Python 3.10+ LangChain License: MIT

Transform AI ideas into production-ready applications with LangChain. This repository contains six comprehensive demos that showcase real-world use cases, from code review assistants to legal document analyzers.

🎯 Perfect for: Developers who want to see practical AI applications, not toy examples.

🌟 What You'll Build

Demo Description Key Features
πŸ” Code Review Assistant Analyzes code for bugs and best practices AST parsing, security analysis, performance tips
πŸ“± Social Media Generator Creates platform-specific content Multi-platform templates, tone control, hashtag optimization
πŸ“§ Email Campaign Builder Multi-step marketing automation LCEL pipelines, strategy β†’ content generation
🎧 Customer Service Bot Context-aware support chatbot Session management, conversation history, escalation
πŸ”¬ Research Assistant Multi-tool research workflows Web search, calculations, data analysis
βš–οΈ Legal Document Analyzer Contract analysis with RAG Vector embeddings, source attribution, legal Q&A

πŸš€ Quick Start

1. Clone and Install

git clone https://github.com/your-username/langchain-101
cd langchain-101
pip install -r requirements.txt

2. Set Up Your API Key

cp .env.example .env
# Edit .env and add your OpenAI API key

3. Run Any Demo

python3 src/model_demo.py     # Start with code review assistant
python3 src/prompt_demo.py    # Try social media generator
python3 src/chain_demo.py     # Build email campaigns
python3 src/memory_demo.py    # Chat with customer service
python3 src/agent_demo.py     # Research with AI agents
python3 src/qa_bot_demo.py    # Analyze legal documents

πŸ“‹ Project Structure

langchain-101/
β”œβ”€β”€ src/                      # Demo applications
β”‚   β”œβ”€β”€ model_demo.py         # Code Review Assistant
β”‚   β”œβ”€β”€ prompt_demo.py        # Social Media Generator
β”‚   β”œβ”€β”€ chain_demo.py         # Email Campaign Builder
β”‚   β”œβ”€β”€ memory_demo.py        # Customer Service Bot
β”‚   β”œβ”€β”€ agent_demo.py         # Research Assistant
β”‚   └── qa_bot_demo.py        # Legal Document Analyzer
β”œβ”€β”€ sample_data/             # Example documents and data
β”œβ”€β”€ requirements.txt         # Python dependencies
└── .env.example            # Environment template

🎬 Live Demo Outputs

πŸ” Code Review Assistant (model_demo.py)

What it does: Analyzes code snippets and provides detailed feedback on quality, security, and best practices.

πŸ“Ί Sample Output:

πŸ” Code Review Assistant Demo
==================================================
Code being reviewed:

def calculate_user_score(users):
    total = 0
    for i in range(len(users)):
        if users[i]['score'] > 0:
            total = total + users[i]['score']
        else:
            print("Invalid score for user: " + users[i]['name'])
    return total / len(users)

==================================================
AI Review:

### 1. Overall Code Quality Assessment
The code is straightforward but has several areas for improvement regarding 
error handling, performance, and adherence to best practices.

### 2. Potential Bugs or Issues
- **Division by Zero**: If the input list is empty, this will raise a ZeroDivisionError
- **KeyError Risk**: Code assumes 'score' and 'name' keys exist in user dictionaries
- **Logic Error**: Includes invalid users in average calculation

### 3. Best Practice Recommendations
- Use enumerate() instead of range(len())
- Add input validation and error handling
- Use list comprehensions for cleaner code
- Add type annotations and docstrings

### 4. Security Concerns
- Input validation missing - could lead to runtime errors
- Consider logging instead of printing for production use

### 5. Revised Code Example
[Includes a complete, improved version with proper error handling]

πŸ“± Social Media Generator (prompt_demo.py)

What it does: Creates platform-specific content optimized for Twitter, LinkedIn, and Instagram with different tones and hashtag strategies.

πŸ“Ί Sample Output:

πŸ“± Social Media Content Generator Demo
==================================================

🎯 TWITTER Content:
------------------------------
πŸš€ Embracing #AI in remote work is transforming productivity! From automating 
repetitive tasks to enhancing collaboration, the future of work is here. How has 
AI improved your workflow? Share your experiences! πŸ’Όβœ¨ 
#RemoteWork #Productivity #FutureOfWork

🎯 LINKEDIN Content:
------------------------------
🌍 As the landscape of work continues to evolve, the integration of artificial 
intelligence (AI) is reshaping the way we approach remote productivity. From 
intelligent task automation to advanced communication tools, AI is streamlining 
workflows and enhancing collaboration among distributed teams.

A recent study highlighted that organizations leveraging AI saw a 30% increase 
in overall productivity, showcasing its potential to not only facilitate 
efficiency but also to empower employees by minimizing repetitive tasks.

As we navigate this new era of remote work, how do you see AI shaping your 
team's productivity and collaboration in the coming years? Let's discuss! πŸ’¬

🎯 INSTAGRAM Content:
------------------------------
🌟 Embracing the AI Revolution in Remote Work! 🌟

In a world where the traditional office is becoming a thing of the past, 
artificial intelligence is stepping up to redefine productivity from our home 
offices. 🏑✨ From smart scheduling and project management tools to AI-driven 
analytics that optimize our workflows, the possibilities are endless!

πŸ’‘ Imagine this: You start your day with an AI assistant that prioritizes your 
tasks, suggests the best times for meetings, and even automates routine emails...

#AI #RemoteWork #Productivity #WorkFromHome #Tech

πŸ“§ Email Campaign Builder (chain_demo.py)

What it does: Uses LCEL to create multi-step marketing campaigns that generate strategy, subject lines, and email content in sequence.

πŸ“Ί Click to see sample output
πŸ“§ Email Marketing Campaign Generator Demo
============================================================
Generating campaign for: AI-powered project management software
Target audience: small business owners and startup founders
Goal: increase trial sign-ups by 25%

πŸ“‹ MARKETING STRATEGY:
------------------------------
### Marketing Strategy for AI-Powered Project Management Software

**Key Messaging Themes:**
- Empowerment Through AI: Software uses AI to make project management easier
- Smart Decision-Making: Intelligent insights and data-driven capabilities
- Collaboration Made Simple: Enhanced team collaboration and communication
- Scalability for Growth: Software grows with the business

**Pain Points to Address:**
- Overwhelmed with tasks and lack of organization
- Limited resources and tight budgets
- Poor communication within teams
- Difficulty tracking multiple projects

**Value Propositions:**
- AI-Powered Automation saves time on repetitive tasks
- Real-Time Insights for quick decision making
- User-Friendly Interface requires minimal training
- Integration with existing tools (Slack, Google Workspace)

πŸ“¬ SUBJECT LINE OPTIONS:
------------------------------
1. "Unlock Your Free Trialβ€”Boost Productivity Now!"
2. "Struggling with Projects? Try AI Solutions Today!"
3. "Transform Your Workflowβ€”Start Your Free Trial!"
4. "Don't Miss Out! Experience AI Project Management!"
5. "Ready to Simplify Your Tasks? Sign Up Free!"

βœ‰οΈ FINAL EMAIL:
------------------------------
Subject: Transform Your Projects with AI – Start Your Free Trial Today!

Dear [Recipient's Name],

Are you overwhelmed by endless tasks and struggling to keep your projects on 
track? It's time to empower your business with our AI-powered project 
management software designed specifically for small business owners and 
startup founders like you.

Imagine having the ability to automate repetitive tasks, gain real-time 
insights, and enhance team collaborationβ€”all from a user-friendly platform...

πŸ‘‰ **Start Your Free Trial Today!**

Best regards,
[Your Name]

🎧 Customer Service Bot (memory_demo.py)

What it does: Maintains conversation context across multiple turns, remembering customer details and providing personalized support.

πŸ“Ί Click to see sample output
🎯 Customer Service Chatbot Demo
============================================================
🎧 Customer Service Session: customer_001

πŸ‘€ Customer: Hi, I'm having trouble logging into my account. My name is Sarah Chen 
and my username is [email protected]

πŸ€– Support Agent: Hello Sarah! I'm sorry to hear that you're having trouble 
logging in. Let's start by checking your username and password. Can you please 
confirm the password you're using? If it's not working, we can try resetting it.

------------------------------

πŸ‘€ Customer: I tried resetting my password but I'm not receiving the reset email. 
This is really frustrating!

πŸ€– Support Agent: I understand how frustrating that can be, Sarah. Let's try a 
few more troubleshooting steps. Could you please check your spam or junk folder 
to see if the reset email ended up there?

------------------------------

πŸ‘€ Customer: I checked my spam folder already. I have an important presentation 
tomorrow and need access to my files urgently.

πŸ€– Support Agent: I'm sorry to hear about the urgency of your situation, Sarah. 
To expedite this process, I recommend clearing your browser cache and cookies...

[Conversation continues with context retention throughout]

πŸ’‘ Notice how the bot:
   β€’ Remembers the customer's name and details
   β€’ Maintains context throughout the conversation  
   β€’ Provides specific, helpful solutions
   β€’ Escalates appropriately when needed

πŸ”¬ Research Assistant (agent_demo.py)

What it does: Combines multiple tools (web search, calculations, data analysis) to conduct comprehensive research workflows.

πŸ“Ί Click to see sample output
πŸ”¬ Research Assistant Agent Demo
======================================================================

πŸ“Š Research Scenario 1: Market Analysis
============================================================
Query: I need to research the AI market. Can you search for AI market size data 
and calculate the potential market value in 5 years assuming 35% annual growth 
from current $328 billion?

πŸ€– Research Assistant Response:
Based on the search results, the current global AI market size is $328 billion 
in 2023 with an expected growth rate of 35.2% CAGR from 2023 to 2030.

Calculating the potential market value in 5 years with a 35% annual growth from 
the current $328 billion, the estimated market value would be approximately 
$1,470.76 billion.

πŸ“Š Research Scenario 2: Environmental Research
============================================================
Query: Research climate change statistics and analyze the trend data. What do 
the numbers tell us about the urgency of action?

πŸ€– Research Assistant Response:
The climate change statistics reveal:
- Global temperature has risen by 1.1Β°C since pre-industrial times
- CO2 levels reached 421 ppm in 2023
- Arctic sea ice declining at 13% per decade
- 83% of climate scientists agree human activities are primary cause

The data indicates significant environmental impact with accelerating trends, 
emphasizing the urgency of action needed to address this global issue.

πŸ’‘ The Research Assistant can:
   β€’ Search for information (simulated)
   β€’ Perform complex calculations
   β€’ Analyze data trends
   β€’ Combine multiple tools to answer complex questions

βš–οΈ Legal Document Analyzer (qa_bot_demo.py)

What it does: Uses RAG (Retrieval-Augmented Generation) to analyze legal documents, extract key terms, and answer specific legal questions with source attribution.

πŸ“Ί Click to see sample output
βš–οΈ Legal Document Analysis System Demo
================================================================================
βœ… Successfully loaded and indexed: Professional Services Agreement

πŸ“‹ Comprehensive Analysis of: Professional Services Agreement

πŸ” Analysis 1: What are the key terms and conditions outlined in this document?
--------------------------------------------------
πŸ“ Answer: Key Terms and Conditions:
- Compliance with laws including GDPR and CCPA (Section 8)
- Force Majeure clause for circumstances beyond control (Section 9)
- Governing Law in the State of California (Section 10)
- IP ownership by Client upon full payment (Section 4)
- Confidentiality obligations survive termination (Section 5)
- Limited liability to total amount paid (Section 6)
- Binding arbitration for dispute resolution (Section 7)

πŸ“„ Source excerpts:
1. "Both parties agree to comply with all applicable federal, state, and local 
   laws and regulations, including data protection and privacy laws such as GDPR..."
2. "All work products, deliverables, and intellectual property created under this 
   Agreement shall be owned by Client upon full payment..."

πŸ” Analysis 2: What are the payment terms, fees, or financial obligations?
--------------------------------------------------
πŸ“ Answer: The payment terms include a total fee of $150,000 payable in monthly 
installments of $12,500. Payments are due within 30 days of invoice receipt. 
Late payments may incur a 1.5% monthly service charge.

πŸ’‘ Sample Questions Answered:
❓ What happens if payments are late?
πŸ’¬ Late payments incur a 1.5% monthly service charge.

❓ How can this contract be terminated?
πŸ’¬ Either party may terminate with thirty (30) days written notice.

❓ Who owns the intellectual property created?
πŸ’¬ The Client owns all IP upon full payment.

🎯 This system can analyze:
   β€’ Contracts and agreements
   β€’ Legal policies and procedures  
   β€’ Compliance documents
   β€’ Terms of service and privacy policies
   β€’ Employment handbooks

πŸ› οΈ Technical Features

πŸ”§ Modern LangChain Patterns

  • LCEL Pipelines: Complex multi-step workflows using | operator
  • ChatOpenAI Integration: Latest OpenAI models with proper response handling
  • Memory Management: Session-based conversation history with isolation
  • Vector Stores: FAISS for efficient document retrieval and semantic search
  • Agent Tools: LangGraph ReAct agents with custom tool integration

πŸ”’ Security & Best Practices

  • Safe Code Execution: AST-based evaluation for mathematical expressions
  • Environment Variables: Secure API key management with .env files
  • Input Validation: Comprehensive error handling and user input sanitization
  • Rate Limiting: Built-in considerations for deployment

πŸ“Š Code Quality

  • Error Handling: Comprehensive try/catch blocks with user-friendly messages
  • Logging: Structured output for monitoring and debugging
  • Documentation: Extensive inline documentation and setup guides

πŸ“š Learning Path

🎯 For Beginners

  1. Start with model_demo.py to understand basic LLM integration
  2. Try prompt_demo.py to learn prompt engineering
  3. Explore memory_demo.py for conversation management

πŸš€ For Intermediate Users

  1. Build with chain_demo.py to master LCEL pipelines
  2. Create agents with agent_demo.py for tool integration
  3. Implement RAG with qa_bot_demo.py for document analysis

πŸ’Ό For Advanced Users

  • Study error handling patterns in each demo
  • Implement monitoring and logging for your use case
  • Consider security and rate limiting for deployment

🀝 Contributing

We welcome contributions! Here's how you can help:

  1. Add New Demos: Create additional real-world use cases
  2. Improve Documentation: Enhance setup guides and explanations
  3. Testing: Add more test cases and validation scenarios
  4. Performance: Optimize existing implementations

πŸ“– Related Resources

πŸŽ‰ What's Next?

After running these demos, you'll have hands-on experience with:

  • βœ… Modern LangChain patterns
  • βœ… Real-world AI application architectures
  • βœ… Security and error handling best practices
  • βœ… Scalable application considerations

Ready to build your own AI applications? Start with any demo that matches your use case, then adapt it to your specific needs!


⭐ Found this helpful? Give us a star and share with your network!

πŸ“¬ Questions? Open an issue or check out the troubleshooting guide.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages