A comprehensive collection of LangChain and LangGraph examples demonstrating AI agents, tool calling, real-time web search, and RAG (Retrieval Augmented Generation) with vector databases.
- Text Summarization with OpenAI and local Ollama
- Tool Calling with static functions
- Real-time Web Search with Tavily API
- Structured Responses with Pydantic models
- LangGraph ReAct Agents with multi-step reasoning
- RAG with Vector Databases using ChromaDB
- MongoDB Atlas Vector Search for cloud-based RAG
- Short-Term Memory with conversation chains
- Job Search Agent example
- Python 3.9+
- uv package manager
- Ollama (for local LLM)
- API Keys:
- OpenAI API key (optional, for GPT models)
- Tavily API key (for real-time search)
- Clone the repository
git clone <your-repo-url>
cd LangChainProject- Install dependencies
uv sync- Set up environment variables
Create a .env file in the project root:
OPENAI_API_KEY=sk-proj-your-key-here
TAVILY_API_KEY=tvly-dev-your-key-here- Install and run Ollama (for local models)
# Install Ollama from https://ollama.ai/
# Pull the llama3.1 model
ollama pull llama3.1:8bLangChainProject/
βββ main_1summerization.py # Text summarization with OpenAI
βββ main_2summerization_with_local_ollama.py # Summarization with Ollama
βββ main_3tool_call.py # Static tool calling example
βββ main_4tool_call_tavily.py # Multiple tools + Tavily search
βββ main_5simple_tavily.py # Simple Tavily search with structured output
βββ main_6job_search_example.py # Job search agent example
βββ main_7langgraph_react_agent.py # LangGraph ReAct agent (NEW! β)
βββ main_8chromadb_rag.py # Knowledge base RAG (in-memory)
βββ main_9real_chromadb.py # Real ChromaDB vector database (NEW! β)
βββ main_10_mongo_vector_search.py # MongoDB Atlas Vector Search (NEW! β)
βββ main_11_memory_example.py # Short-term memory example (NEW! β)
βββ flow_7.png # LangGraph visualization
βββ .env # Environment variables (create this)
βββ pyproject.toml # Project dependencies
βββ chroma_db/ # ChromaDB storage (created on first run)
β βββ chroma.sqlite3 # SQLite metadata
β βββ [UUID]/ # Vector embeddings
βββ README.md # This file
Summarizes text about Ruby Learner platform using GPT-3.5-turbo.
uv run python main_1summerization.pyOutput: A concise 2-bullet summary of the input text.
Same as above but uses local Ollama model (no API key needed).
uv run python main_2summerization_with_local_ollama.pyAdvantages:
- π Free - no API costs
- π Private - runs locally
- β‘ Fast - no network latency
Demonstrates how AI agents can call custom functions to retrieve information.
uv run python main_3tool_call.pyFeatures:
- Static course database
get_course_info()functionget_student_count()function- LLM decides which tool to use
Example Query: "Tell me about the Flutter course and how many students it has."
Combines static tools with real-time web search using Tavily.
uv run python main_4tool_call_tavily.pyFeatures:
- Tests 3 different queries:
- Latest AI news (uses Tavily)
- Course information (uses static function)
- Bitcoin price (uses Tavily)
- LLM automatically chooses the right tool
Requires: TAVILY_API_KEY in .env file
Clean, simple example of real-time web search with structured responses.
uv run python main_5simple_tavily.pyFeatures:
- Real-time web search
- Structured output with Pydantic models
- Includes sources (URLs and titles)
- Easy to customize for your queries
Example Output:
Answer:
The latest news about AI in December 2025 includes Google's new Gemini 3 Deep Think mode...
Sources:
1. AI News Today, December 5, 2025...
https://ts2.tech/en/ai-news-today-december-5-2025...
2. Anthropic News Today...
https://ts2.tech/en/anthropic-news-today...
Searches for job postings on LinkedIn and returns structured results.
uv run python main_6job_search_example.pyFeatures:
- Searches for AI Engineer jobs
- Returns company, title, location, description
- Includes source URLs
- Similar to the reference example pattern
Example Query: "Search for 3 job postings for an AI engineer using langchain in the bay area on linkedin"
Multi-step reasoning agent that can use multiple tools and decide when to stop.
uv run python main_7langgraph_react_agent.pyFeatures:
- π ReAct Pattern: Reasoning β Action β Observation loop
- π οΈ Multiple Tools: Calculator + Tavily web search
- π€ Agent Decides: When to use tools, which tools, and when to stop
- π Visualization: Generates
flow_7.pngshowing the agent workflow
Key Difference from LangChain:
- LangChain: Single pass, one-shot tool calling
- LangGraph: Multi-step reasoning, can call tools multiple times
Example Queries:
# Query 1: Math calculation
"What is 1234 multiplied by 5678?"
# Query 2: Web search + reasoning
"What is the temperature in Tokyo? List it and then triple it"Why LangGraph?
- More control over agent flow
- Can create complex multi-agent systems
- Better for tasks requiring multiple steps
- Similar to how ChatGPT/Claude work internally
Simple RAG example using in-memory knowledge base (no database setup needed).
uv run python main_8chromadb_rag.pyFeatures:
- π Stores course information (Flutter, Kotlin, LangChain, AI/ML)
- π Agent searches knowledge base before answering
- π₯ Includes metadata (student counts, topics)
- π‘ Perfect for learning RAG concepts
Example Queries:
# Query 1
"Tell me about Flutter and how many students are enrolled?"
# Query 2
"What courses are available about mobile development and AI?"Production-ready RAG with persistent vector database using ChromaDB.
uv run python main_9real_chromadb.pyFeatures:
- πΎ Persistent Storage: Data saved to disk (
./chroma_db/) - π’ Vector Embeddings: Uses Ollama to generate 4096-dimensional vectors
- π― Semantic Search: Finds similar content, not just keyword matching
- β‘ Fast: HNSW algorithm for O(log n) similarity search
- ποΈ SQLite Backend: Metadata stored in SQLite, vectors in binary files
What Gets Created:
chroma_db/
βββ chroma.sqlite3 # Metadata (258 KB)
βββ [UUID]/
βββ data_level0.bin # Vector embeddings (1.6 MB)
How It Works:
- First run: Creates ChromaDB, generates embeddings (takes ~30 seconds)
- Later runs: Loads from disk instantly
- Agent searches by semantic similarity
- Returns relevant documents with metadata
Example Output:
π§ Creating new ChromaDB...
β³ Generating embeddings with Ollama...
β
ChromaDB created at: /path/to/chroma_db
π Stored 5 documents with vector embeddings
Query: Tell me about mobile app development frameworks
π Searching ChromaDB for: 'mobile app development frameworks'
β
Found: Flutter, Kotlin, LangChain courses
Why Use ChromaDB?
- β Store your company's knowledge
- β Semantic search (understands meaning, not just keywords)
- β Scales to millions of documents
- β Perfect for chatbots, documentation search, Q&A systems
See chromadb_structure.md for detailed architecture explanation.
Cloud-based vector search using MongoDB Atlas with LangChain integration.
uv run python main_10_mongo_vector_search.pyFeatures:
- βοΈ Cloud Database: MongoDB Atlas (no local setup needed)
- π’ Vector Embeddings: Uses Ollama
nomic-embed-textmodel - π Atlas Vector Search: Native MongoDB vector search capabilities
- π Fallback Search: Manual cosine similarity if Atlas search index not configured
- π Metadata Support: Stores and queries course info, topics, student counts
Prerequisites:
- MongoDB Atlas account (free tier available)
- Connection string with password in
.env:MONGODB_URI=mongodb+srv://user:password@cluster0.mongodb.net/... MONGO_DB_NAME=rab_test MONGO_COLLECTION=rab_test
What Gets Created:
MongoDB Atlas:
βββ rab_test (database)
βββ rab_test (collection)
βββ Document 1 (page_content, embedding, course, topic, students)
βββ Document 2 (...)
βββ Document 3 (...)
How It Works:
- Connects to MongoDB Atlas cloud database
- Generates embeddings using Ollama locally
- Stores documents with vector embeddings in MongoDB
- Performs semantic similarity search
- Returns relevant documents with scores
Example Output:
π Query: Tell me about mobile app development frameworks
Result 1 (similarity: 0.8120):
Course: Flutter
Topic: Mobile Development
Students: 150
Content: Flutter is a cross-platform mobile development framework...
Result 2 (similarity: 0.7243):
Course: Kotlin
Topic: Android Development
Students: 120
Content: Kotlin is a modern programming language...
ChromaDB vs MongoDB Atlas:
| Feature | ChromaDB (main_9) | MongoDB Atlas (main_10) |
|---|---|---|
| Storage | Local files | Cloud database |
| Setup | Zero config | Requires MongoDB account |
| Scalability | Limited to disk | Unlimited cloud storage |
| Multi-user | Single machine | Multiple users/apps |
| Cost | Free | Free tier available |
| Best For | Development, prototypes | Production, team collaboration |
When to Use MongoDB Atlas:
- β Production applications
- β Team collaboration (shared database)
- β Already using MongoDB for other data
- β Need backup/replication
- β Want managed infrastructure
Interactive conversation with memory using ConversationBufferWindowMemory.
uv run python main_11_memory_example.pyFeatures:
- Interactive Chat: Type messages and get AI responses
- Short-Term Memory: Remembers last K interactions (configurable)
- Automatic Updates: Memory updates with each conversation turn
How It Works:
- Uses
ConversationBufferWindowMemoryto store recent messages ConversationChainautomatically manages memory context- Each response considers previous conversation history
- Memory window prevents unlimited growth (keeps only recent interactions)
Example Interaction:
You: Hi, my name is John
AI: Hello John! Nice to meet you.
You: What's my name?
AI: Your name is John.
Memory Types in LangChain:
ConversationBufferMemory: Unlimited memory (grows forever)ConversationBufferWindowMemory: Limited to last K interactions βConversationSummaryMemory: Summarizes old messages to save spaceConversationTokenBufferMemory: Limited by token count
Why Short-Term Memory?
- Prevents memory from growing too large
- Focuses on recent context
- Better for long conversations
- Configurable window size
- Visit https://tavily.com/
- Sign up for free account
- Get your API key
- Add to
.envfile:TAVILY_API_KEY=tvly-dev-your-key-here
- Visit https://platform.openai.com/
- Create account and add payment method
- Generate API key
- Add to
.envfile:OPENAI_API_KEY=sk-proj-your-key-here
Note: You can use Ollama (free, local) instead of OpenAI for most examples.
| Feature | LangChain (main_1-6) | LangGraph (main_7) | RAG (main_8-9) | MongoDB Atlas (main_10) | Memory (main_11) |
|---|---|---|---|---|---|
| Purpose | Single-pass tasks | Multi-step reasoning | Knowledge retrieval | Cloud vector search | Conversation context |
| Tool Calls | One-shot | Multiple, iterative | Search database | Search cloud DB | N/A |
| State | Stateless | Stateful graph | Persistent data | Cloud persistent | Conversation history |
| Storage | N/A | N/A | Local files | MongoDB Atlas | In-memory buffer |
| Use Case | Simple queries | Complex workflows | Company knowledge | Production RAG | Chatbots, assistants |
| Example | "What's 2+2?" | "Search, then calculate" | "Find in our docs" | "Team knowledge base" | "Remember my name" |
- LangChain (main_1-6): Quick tasks, single tool calls, real-time data
- LangGraph (main_7): Multi-step reasoning, agent workflows, complex decisions
- RAG ChromaDB (main_8-9): Local development, prototypes, single-user apps
- RAG MongoDB (main_10): Production apps, team collaboration, cloud deployment
- Memory (main_11): Interactive applications, chatbots, virtual assistants
Beginner:
main_1β Learn basic LangChainmain_2β Try local Ollamamain_3β Understand tool calling
Intermediate:
4. main_5 β Real-time search with Tavily
5. main_7 β Multi-step agents with LangGraph
6. main_8 β Understand RAG concepts
Advanced:
7. main_9 β Production RAG with ChromaDB (local)
8. main_10 β Cloud RAG with MongoDB Atlas (production)
9. main_11 β Interactive applications with memory
httpcore.ConnectError: [Errno 61] Connection refused
Solution: Start Ollama first
ollama serveValueError: TAVILY_API_KEY not found
Solution: Add key to .env file
TAVILY_API_KEY=tvly-dev-your-key-hereModuleNotFoundError: No module named 'chromadb'
Solution: Reinstall dependencies
uv syncβ Error: MONGODB_URI not properly set in .env file
Solution: Add your MongoDB Atlas connection string to .env with actual password
MONGODB_URI=mongodb+srv://username:YOUR_PASSWORD@cluster0.mongodb.net/...
MONGO_DB_NAME=rab_test
MONGO_COLLECTION=rab_test- LangChain Docs: https://python.langchain.com/
- LangGraph Docs: https://langchain-ai.github.io/langgraph/
- ChromaDB Docs: https://docs.trychroma.com/
- MongoDB Atlas: https://www.mongodb.com/atlas
- LangChain-MongoDB: https://github.com/langchain-ai/langchain-mongodb
- Ollama Models: https://ollama.ai/library
- Tavily Search: https://tavily.com/
Feel free to add more examples or improve existing ones!
MIT
# Run any script
uv run python <script-name>.py
# Install new dependency
uv add <package-name>
# Sync dependencies
uv sync- Set Python interpreter to
.venv/bin/python - Use "uv run" for running scripts
- Or configure run configuration to use the virtual environment
LangChain is a framework for building applications with Large Language Models (LLMs). It provides:
- Tool calling capabilities
- Prompt templates
- Memory management
- Agent workflows
Tools are functions that AI agents can call to:
- Search the web (Tavily)
- Query databases
- Perform calculations
- Access external APIs
Using Pydantic models to get consistent, typed responses from LLMs:
class AgentResponse(BaseModel):
answer: str
sources: List[Source]| Feature | Ollama (Local) | OpenAI (Cloud) |
|---|---|---|
| Cost | Free | Pay per token |
| Privacy | Runs locally | Sends to API |
| Speed | Fast (no network) | Depends on network |
| Quality | Good | Better for complex tasks |
uv add langchain-communityMake sure .env file exists in project root with:
TAVILY_API_KEY=tvly-dev-your-actual-key-here- Make sure Ollama is running:
ollama serve
- Check if model is installed:
ollama list ollama pull llama3.1:8b
Configure PyCharm to use .venv/bin/python or run with uv run command.
- Start here:
main_2summerization_with_local_ollama.py- Understand basic LangChain usage - Learn tools:
main_3tool_call.py- See how agents call functions - Add search:
main_5simple_tavily.py- Real-time web search - Advanced:
main_6job_search_example.py- Build practical agents
Feel free to:
- Add more examples
- Improve documentation
- Report issues
- Suggest features
MIT License
Ruby Learner Myanmar
Happy Coding! π
Last updated: December 29, 2025