langchainjs-for-beginners
AGENTS.md223 starsChanged 3 months agoMITView on GitHub
This is LangChain.js for Beginners - a comprehensive educational course teaching AI application development with LangChain.js and TypeScript. The repository contains 9 chapters (00-08) covering everything from basic chat models to autonomous agents, RAG systems, and Model Context Protocol (MCP) integration. Architecture: Educational course structure with 80+ runnable TypeScript examples organized by topic Key Technologies: LangChain.js, TypeScript, tsx, Node.js >=22.0.0 (LTS), MCP, Microsoft Foundry Purpose: Teaching developers how to build AI-powered applications using an agent-first philosophy Teaching Approach: Agent-first (Tools…
- Reads credentials
- Deletes or force-pushes
- Installs packages
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about code style.
Of the AGENTS.md files we read, the 31,542 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
The file
Show its rules and text
We split this AGENTS.md into the rules it gives an agent
45 rules. About 1 is common, 24 are distinctive, and 20 are very specific to this project.
≈1
Common · estimate
Many files like this have a rule of this kind.
≈24
Distinctive · estimate
This author's own choices. Worth a look.
20
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- could be automatic: a setting could enforce it
- Distinctive: line 95
When working on course content or examples:
- Distinctive: line 98
All examples use environment variables for configuration (never hardcode keys)
- Very specific: line 130
All examples use a 120-second timeout (TIMEOUT_MS in scripts/validation-common.ts)
- Distinctive: line 178
Use ES modules (import/export)
- Very specific: line 182
Always use process.env.AI_API_KEY (never hardcode)
- Very specific: line 185
Always use process.env.AI_EMBEDDING_MODEL (for embeddings)
- Distinctive: line 189
Keep examples focused and educational
- Distinctive: line 191
Use async/await for asynchronous operations
- Very specific: line 196
Use kebab-case for directories: 01-introduction
- Very specific: line 197
Use numbered prefixes for sequential content: 01-hello-world.ts
- Very specific: line 198
Use descriptive names: model-comparison.ts, not mc.ts
- Distinctive: line 215
Use meaningful variable names
- Distinctive: line 216
Avoid overly nested code
- Distinctive: line 217
Keep examples concise (typically <100 lines)
- Distinctive: line 230
Output: No build artifacts generated - this is a validation-only check
- Distinctive: line 256
Triggers: Only runs when commit message or PR title contains "validate-examples", or manually triggered
- Very specific: line 276
Create .ts file in appropriate chapter's code/ directory
- Very specific: line 277
Use numbered prefix: 05-new-example.ts
- Distinctive: line 278
Follow existing patterns for imports and structure
- Very specific: line 280
Run build check: npm run build
- Very specific: line 281
No changes to scripts/validation-common.ts needed
- Distinctive: line 285
Create the example file as above
- Distinctive: line 286
All examples already have a 120-second timeout — no extra list is required
- Very specific: line 287
If an example cannot run against Microsoft Foundry (API limitation), add it to SKIP_FILES in scripts/validation-common.ts
- Distinctive: line 291
Create the example file
- Very specific: line 292
Add to INTERACTIVE_FILES in scripts/validation-common.ts:
- Distinctive: line 317
Use clear, descriptive commit messages
- Very specific: line 326
All TypeScript files must compile (npm run build passes)
- Very specific: line 328
Update scripts/validation-common.ts if adding interactive, server, or skipped files
- Distinctive: line 329
Update chapter README.md if adding new concepts
- Common: line 337
Always use environment variables for API keys
- Very specific: line 338
Use .env.example as template (no real credentials)
- Distinctive: line 354
All examples timeout after 120 seconds
- Very specific: line 355
Consider rate limits when adding multiple API calls or using npm run test:parallel
- Distinctive: line 371
All examples already have a 120-second timeout
- Distinctive: line 372
Check for infinite loops, hanging API calls, or too many sequential model requests
- Very specific: line 373
If the example cannot run on Microsoft Foundry, add it to SKIP_FILES in scripts/validation-common.ts
- Distinctive: line 401
All examples are tested automatically to ensure they work
- Very specific: line 450
Start with 00-course-setup for environment configuration
- Distinctive: line 452
Follow the agent-first progression (Chapters 4 → 5 → 6 → 7 → 8)
- Distinctive: line 462
Use Microsoft Foundry for this course
- Very specific: line 468
Run npm run build frequently (fast feedback)
- Distinctive: line 469
Test individual examples during development
- Very specific: line 470
Run npm test before major commits
- Distinctive: line 472
Use manual trigger in GitHub Actions UI when needed
≈ “Common” is an estimate: at least 1 in 5 of the 40,246 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
AGENTS.md
Project Overview
This is LangChain.js for Beginners - a comprehensive educational course teaching AI application development with LangChain.js and TypeScript. The repository contains 9 chapters (00-08) covering everything from basic chat models to autonomous agents, RAG systems, and Model Context Protocol (MCP) integration.
Architecture: Educational course structure with 80+ runnable TypeScript examples organized by topic Key Technologies: LangChain.js, TypeScript, tsx, Node.js >=22.0.0 (LTS), MCP, Microsoft Foundry Purpose: Teaching developers how to build AI-powered applications using an agent-first philosophy Teaching Approach: Agent-first (Tools → Agents → Documents → Agentic RAG)
Repository Structure
LangChainJS-for-Beginners/
├── 00-course-setup/ # Initial setup and configuration
├── 01-introduction/ # LangChain.js basics
├── 02-chat-models/ # Chat models and interactions
├── 03-prompts-messages-outputs/ # Dynamic prompts, messages, and structured outputs
├── 04-function-calling-tools/ # Function calling and tool integration (Agent-first: Step 1)
├── 05-agents/ # Autonomous agents (Agent-first: Step 2)
├── 06-mcp/ # Model Context Protocol - connecting AI to external services
├── 07-documents-embeddings-semantic-search/ # Document processing, embeddings, semantic search (Agent-first: Step 3)
├── 08-agentic-rag-systems/ # Agentic RAG where agents decide when to search (Agent-first: Step 4)
│ └── samples/
│ └── mcp-rag-server/ # RAG as an MCP service (capstone example)
├── data/ # Sample data files
├── scripts/ # Build and validation scripts
│ ├── build-check.ts # TypeScript compilation validator
│ ├── test-setup.ts # Environment setup tester
│ ├── validation-common.ts # Shared validation config (timeouts, interactive/server/skip lists)
│ ├── validate-examples.ts # Sequential example test runner
│ └── validate-examples-parallel.ts # Parallel example test runner (CI)
├── .env.example # Environment configuration template
└── GLOSSARY.md # Comprehensive course glossaryEach chapter contains:
README.md- Conceptual explanations and learning contentassignment.md- Hands-on exercisescode/- Working code examplessolution/- Assignment solutionsimages/- Supporting diagrams (some chapters)
Setup Commands
Initial Setup
# Install dependencies
npm install
# Copy environment template
cp .env.example .env
# Edit .env with your AI provider credentials
# Required: AI_API_KEY, AI_ENDPOINT, AI_MODEL, AI_EMBEDDING_MODELAI Provider Configuration
This course uses Microsoft Foundry. Configure .env with your project credentials:
Microsoft Foundry:
AI_API_KEY=your_microsoft_foundry_api_key
AI_ENDPOINT=https://your-resource.openai.azure.com/openai/v1
AI_MODEL=gpt-5-mini
AI_EMBEDDING_MODEL=text-embedding-3-smallEnvironment Requirements
- Node.js >=22.0.0 (LTS - specified in
package.json) - npm (package manager)
- Valid AI provider credentials in
.envfile
Development Workflow
Running Individual Examples
# Run any TypeScript file directly with tsx
npx tsx 01-introduction/code/01-hello-world.ts
# Or use npm start
npm start 02-chat-models/code/01-multi-turn.ts
# Watch mode for development
npm run dev <file-path>Working on Course Content
When working on course content or examples:
- Each chapter is self-contained with its own code examples
- Code files use ES modules (
"type": "module"in package.json) - All examples use environment variables for configuration (never hardcode keys)
- Interactive, server, and skipped examples should be marked in
scripts/validation-common.ts
Testing Instructions
Quick Build Check (Fast - 10-30 seconds)
# Type-check all TypeScript files without running them
npm run buildThis type-checks all course TypeScript files (currently 80+) for:
- ✅ Type errors
- ✅ Syntax errors
- ✅ Import issues
- ✅ No API calls - just compilation
Full Validation (Comprehensive - 20-40 minutes sequential, ~5 minutes parallel)
# Run all code examples sequentially (avoids rate limiting)
npm test
# Run all code examples in parallel (faster; used in CI)
npm run test:parallelImportant Notes:
- Requires valid
AI_API_KEY,AI_ENDPOINT,AI_MODEL, andAI_EMBEDDING_MODELin.env - Sequential
npm testis safer against rate limits; CI usesnpm run test:parallel - Interactive files are tested with automated input
- All examples use a 120-second timeout (
TIMEOUT_MSinscripts/validation-common.ts) - Examples in
future/folder are not included in validation
Testing Specific Examples
# Run a single example
npx tsx 03-prompts-messages-outputs/code/03-basic-template.ts
# Test a specific chapter
npx tsx 08-agentic-rag-systems/code/*.tsTest File Categories
Configured in scripts/validation-common.ts:
Interactive Files (tested with automated input):
chatbot.tsstreaming-chat.tsqa-program.ts03-human-in-loop.tsconversational-rag.ts
Server Files (started, checked for a ready message, then stopped):
basic-mcp-server.tsmcp-rag-server.tsstdio-calculator-server.ts
Skipped Files (SKIP_FILES):
temperature-lab.ts- Usestemperature=0, which some Microsoft Foundry models reject
Code Style
TypeScript Configuration
{
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true
}Coding Conventions
Module System:
- Use ES modules (import/export)
- File extension required for local imports:
import { foo } from "./utils.js"
Environment Variables:
- Always use
process.env.AI_API_KEY(never hardcode) - Always use
process.env.AI_ENDPOINT - Always use
process.env.AI_MODEL - Always use
process.env.AI_EMBEDDING_MODEL(for embeddings) - Load from
.envusing dotenv
Code Examples:
- Keep examples focused and educational
- Include comments explaining key concepts
- Use async/await for asynchronous operations
- Handle errors gracefully
- Log outputs clearly for learning purposes
File Naming:
- Use kebab-case for directories:
01-introduction - Use numbered prefixes for sequential content:
01-hello-world.ts - Use descriptive names:
model-comparison.ts, notmc.ts
Import Patterns:
// LangChain imports
import { ChatOpenAI } from "@langchain/openai";
import { HumanMessage, SystemMessage } from "@langchain/core/messages";
// Standard library
import { config } from "dotenv";
import { readFile } from "fs/promises";Educational Code Quality
- Prioritize readability over cleverness
- Include inline comments for complex concepts
- Use meaningful variable names
- Avoid overly nested code
- Keep examples concise (typically <100 lines)
Build and Deployment
Build Process
The repository uses TypeScript compilation checking via scripts/build-check.ts:
# Build check (validates TypeScript compilation)
npm run buildOutput: No build artifacts generated - this is a validation-only check Purpose: Ensures all TypeScript files compile correctly before commits
Validation Process
The repository uses scripts/validate-examples.ts (sequential) and scripts/validate-examples-parallel.ts (CI):
# Full validation (runs all examples sequentially)
npm test
# Parallel validation (faster; used in GitHub Actions)
npm run test:parallelProcess:
- Finds all
.tsfiles incode/,solution/, andsamples/directories - Runs each file with
tsx(120-second timeout) - Provides automated input for interactive examples
- Starts server examples, checks for a ready message, then stops them
- Reports success/failure with detailed error messages
- Exits with error code 1 if any examples fail
CI/CD Pipeline
GitHub Actions workflow (.github/workflows/validate-examples.yml):
- Triggers: Only runs when commit message or PR title contains "validate-examples", or manually triggered
- Tests on Node.js 22 (LTS)
- Runs
npm run test:parallel - Uses secrets:
AI_API_KEY,AI_ENDPOINT,AI_MODEL,AI_EMBEDDING_MODEL - Timeout: 30 minutes
To trigger validation in your commit:
git commit -m "Update RAG examples validate-examples"To trigger validation manually:
- Go to GitHub Actions tab
- Select "Validate Code Examples" workflow
- Click "Run workflow"
Adding New Examples
Standard Example (Single API call, <30 seconds)
- Create
.tsfile in appropriate chapter'scode/directory - Use numbered prefix:
05-new-example.ts - Follow existing patterns for imports and structure
- Test locally:
npx tsx path/to/05-new-example.ts - Run build check:
npm run build - No changes to
scripts/validation-common.tsneeded
Slow Example (Multiple API calls)
- Create the example file as above
- All examples already have a 120-second timeout — no extra list is required
- If an example cannot run against Microsoft Foundry (API limitation), add it to
SKIP_FILESinscripts/validation-common.ts
Interactive Example (Requires user input)
- Create the example file
- Add to
INTERACTIVE_FILESinscripts/validation-common.ts:
export const INTERACTIVE_FILES = [
{ file: "chatbot.ts", input: "Hello\n" },
{ file: "your-new-interactive.ts", input: "test input\n" },
];Pull Request Guidelines
Before Submitting
# 1. Run build check
npm run build
# 2. Test affected examples locally
npx tsx path/to/changed-file.ts
# 3. Run full validation (optional but recommended)
npm testCommit Messages
- Use clear, descriptive commit messages
- Reference issue numbers if applicable
- Include "validate-examples" to trigger CI/CD validation when needed
- Examples:
- "Add vector store example to chapter 5" (no validation)
- "Add vector store example to chapter 5 validate-examples" (triggers validation)
PR Requirements
- All TypeScript files must compile (
npm run buildpasses) - Changed examples must run successfully
- Update
scripts/validation-common.tsif adding interactive, server, or skipped files - Update chapter README.md if adding new concepts
- Include comments in code for educational clarity
Security Considerations
Secrets Management
- NEVER commit
.envfile (included in.gitignore) - Always use environment variables for API keys
- Use
.env.exampleas template (no real credentials) - GitHub Actions uses repository secrets
API Keys
// ❌ WRONG - Hardcoded
const apiKey = "sk-abc123";
// ✅ CORRECT - Environment variable
const apiKey = process.env.AI_API_KEY;Rate Limiting
- Sequential validation (
npm test) runs examples one at a time to avoid rate limits - All examples timeout after 120 seconds
- Consider rate limits when adding multiple API calls or using
npm run test:parallel
Troubleshooting
"Missing AI_API_KEY" Error
# Ensure .env file exists and contains:
AI_API_KEY=your_key
AI_ENDPOINT=your_endpoint
AI_MODEL=gpt-5-mini
AI_EMBEDDING_MODEL=text-embedding-3-small"Command timed out"
- All examples already have a 120-second timeout
- Check for infinite loops, hanging API calls, or too many sequential model requests
- If the example cannot run on Microsoft Foundry, add it to
SKIP_FILESinscripts/validation-common.ts
"Module not found"
# Reinstall dependencies
rm -rf node_modules package-lock.json
npm installTypeScript Compilation Errors
# Check specific file
npx tsc --noEmit path/to/file.ts
# Check all files
npm run buildAdditional Notes
Course Philosophy
This is an educational repository optimized for learning:
- Examples are sequential and build on each other
- Code prioritizes clarity over performance
- Each chapter is self-contained for easy navigation
- All examples are tested automatically to ensure they work
- Pedagogical approach: Hands-on examples before heavy theory
- Terms and concepts defined before extensive use
- Additional/future content clearly marked as optional
- Deep dive sections available for those wanting more depth
Agent-First Teaching Philosophy
Unlike traditional LangChain tutorials that teach document search first, this course follows a modern, agent-first approach:
- Function Calling & Tools - Learn to give AI the ability to use tools
- Agents & MCP - Build autonomous agents that reason and make decisions
- Documents & Embeddings - Learn document processing and semantic search
- Agentic RAG - Combine agents with retrieval for intelligent systems
Why Agent-First?
- Mirrors how production AI systems work (agents with multiple capabilities)
- Teaches autonomous decision-making before retrieval patterns
- Enables students to build Agentic RAG where agents decide when to search
- More efficient than traditional "always-search" RAG patterns
Key Differentiator: Students learn to build RAG systems where agents intelligently decide when retrieval is necessary vs answering directly from general knowledge.
MCP RAG Server (Extended Example)
The course includes a capstone example that combines all learned concepts:
Location: 08-agentic-rag-systems/samples/mcp-rag-server/
What it demonstrates:
- Building an HTTP streamable MCP server that exposes RAG as a service
- Multiple agents sharing a centralized knowledge base
- Agentic decision-making (when to search vs answer directly)
- Enterprise architecture pattern for scalable AI systems
Files:
mcp-rag-server.ts- MCP server exposing searchDocuments and addDocument toolsmcp-rag-agent.ts- Agent client that connects to and uses the MCP RAG serverREADME.md- Complete architecture explanation and setup guide
Security Note: Example is for educational purposes and does not implement authentication/authorization. See MCP Security Documentation for production guidelines.
Run the example:
npx tsx 08-agentic-rag-systems/samples/mcp-rag-server/mcp-rag-agent.tsWorking with Chapters
- Start with
00-course-setupfor environment configuration - Each chapter has learning objectives in its README.md
- Follow the agent-first progression (Chapters 4 → 5 → 6 → 7 → 8)
- Try the assignments before looking at solutions
- Examples in
code/directory demonstrate concepts - Solutions in
solution/directory show complete implementations - Consult
GLOSSARY.mdfor definitions of all course terms - Extended samples in chapter
samples/folders show real-world patterns
Provider Configuration
Examples read credentials from .env (never hardcode keys):
- Use Microsoft Foundry for this course
- Change
AI_API_KEY,AI_ENDPOINT,AI_MODEL, andAI_EMBEDDING_MODELas needed - Documented in
00-course-setup/README.md
Testing Best Practices
- Run
npm run buildfrequently (fast feedback) - Test individual examples during development
- Run
npm testbefore major commits - Include "validate-examples" in commit message to trigger CI/CD validation
- Use manual trigger in GitHub Actions UI when needed
Quick Reference
# Setup
npm install
cp .env.example .env
# Development
npm start <file> # Run specific file
npm run dev <file> # Watch mode
# Testing
npm run build # Type-check (fast)
npm test # Full validation (sequential)
npm run test:parallel # Full validation (parallel / CI)
npx tsx <file> # Run individual file
# Trigger CI/CD validation
git commit -m "Your message validate-examples" # Triggers GitHub ActionsResources
- LangChain.js Documentation
- Model Context Protocol (MCP) Documentation
- MCP Security Best Practices
- Course README
- Course Glossary
- Microsoft Foundry
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

