Comprehensive tutorial and code examples for building multi-agent systems with LangChain
This repository provides a complete, production-ready example of building multi-agent systems using LangChain. It demonstrates how to create specialized AI agents that can collaborate to solve complex tasks through orchestration patterns.
- Agent Architecture: Design patterns for AI agents
- Multi-Agent Orchestration: Coordinate multiple agents effectively
- Tool Integration: Equip agents with external tools and APIs
- Memory Management: Implement conversation and context memory
- Error Handling: Build robust multi-agent systems
- Performance Optimization: Optimize for cost and speed
- Complete Working Examples: Copy-paste ready code
- Step-by-Step Tutorials: From basic to advanced patterns
- Production Best Practices: Security, testing, deployment
- Real-World Use Cases: Practical applications
- TypeScript: Full type safety
- Jest Tests: Comprehensive test coverage
- Node.js 18+ installed
- Basic knowledge of TypeScript
- Understanding of async/await patterns
- API keys for OpenAI and/or Anthropic
git clone https://github.com/groovy-web/langchain-multi-agent-example.git
cd langchain-multi-agent-example
npm installcp .env.example .envEdit .env and add your API keys:
OPENAI_API_KEY=sk-your-openai-key
ANTHROPIC_API_KEY=sk-ant-your-anthropic-key
TAVILY_API_KEY=tvly-your-tavily-key # For search
SERPER_API_KEY=your-serper-key # For Google searchnpm run basic-example1. Single Agent Setup
// examples/01-single-agent.ts
import { ChatOpenAI } from "@langchain/openai";
import { AgentExecutor, createReactAgent } from "langchain/agents";
const llm = new ChatOpenAI({ temperature: 0 });
const agent = await createReactAgent({
llm,
tools: [],
prompt: "You are a helpful assistant.",
});
const agentExecutor = new AgentExecutor({
agent,
tools: [],
});
const result = await agentExecutor.invoke({
input: "What is the capital of France?",
});2. Adding Tools to Agents
// examples/02-agent-with-tools.ts
import { SerperAPI } from "@langchain/community/tools";
const searchTool = new SerperAPI();
const calculator = new CalculatorTool();
const agent = await createReactAgent({
llm,
tools: [searchTool, calculator],
prompt: "You are a research assistant.",
});3. Sequential Agent Chain
// examples/03-sequential-agents.ts
import { AgentChain } from "../lib/agent-chain";
const researcher = createAgent({
role: "Researcher",
goal: "Find information on {topic}",
tools: [searchTool],
});
const writer = createAgent({
role: "Writer",
goal: "Write a blog post about {topic}",
tools: [],
});
const chain = new AgentChain([researcher, writer]);
const result = await chain.run({ topic: "AI agents" });4. Parallel Agent Execution
// examples/04-parallel-agents.ts
import { ParallelExecutor } from "../lib/parallel-executor";
const agents = [
createTranslatorAgent({ language: "Spanish" }),
createTranslatorAgent({ language: "French" }),
createTranslatorAgent({ language: "German" }),
];
const executor = new ParallelExecutor();
const translations = await executor.executeAll(agents, {
text: "Hello, world!",
});5. Hierarchical Agent Teams
// examples/05-hierarchical-agents.ts
import { ManagerAgent } from "../lib/manager-agent";
const manager = new ManagerAgent({
name: "Project Manager",
subAgents: [
{ name: "Researcher", agent: researchAgent },
{ name: "Writer", agent: writerAgent },
{ name: "Editor", agent: editorAgent },
],
coordination: "sequential", // or "parallel"
});
const report = await manager.coordinate({
task: "Create a market research report",
topic: "Electric Vehicles",
});6. Agent with Memory
// examples/06-agent-with-memory.ts
import { BufferMemory } from "langchain/memory";
const memory = new BufferMemory({
memoryKey: "chat_history",
returnMessages: true,
});
const agent = await createReactAgent({
llm,
tools: [searchTool],
prompt: "You are a helpful assistant with memory.",
memory,
});
// First interaction
await agentExecutor.invoke({
input: "My name is Alice",
});
// Agent remembers!
await agentExecutor.invoke({
input: "What is my name?",
});7. Self-Correction Agent
// examples/07-self-correcting-agent.ts
import { ReviewAgent } from "../lib/review-agent";
const writer = createWriterAgent();
const reviewer = new ReviewAgent({
criteria: ["accuracy", "clarity", "style"],
maxIterations: 3,
});
const content = await reviewer.improveWithFeedback({
contentGenerator: writer,
topic: "Quantum Computing",
});8. Multi-Agent Debate
// examples/08-agent-debate.ts
import { AgentDebate } from "../lib/agent-debate";
const debate = new AgentDebate({
protagonist: createAgent({ stance: "pro-ai" }),
antagonist: createAgent({ stance: "skeptic" }),
moderator: createAgent({ stance: "neutral" }),
rounds: 3,
});
const summary = await debate.conduct({
topic: "Will AI replace human workers?",
});// real-world/content-pipeline.ts
const pipeline = new AgentPipeline([
{
agent: seoResearcher,
outputKey: "keywords",
},
{
agent: contentWriter,
inputKeys: ["keywords"],
outputKey: "draft",
},
{
agent: humanEditor,
inputKeys: ["draft"],
outputKey: "edited",
},
{
agent: publisher,
inputKeys: ["edited"],
outputKey: "published",
},
]);
const result = await pipeline.execute({
topic: "Best practices for API design",
});// real-world/customer-support.ts
const triageAgent = new TriageAgent({
categories: ["billing", "technical", "feature-request"],
});
const routingMap = {
billing: billingAgent,
technical: technicalSupportAgent,
"feature-request": productTeamAgent,
};
const supportSystem = new SupportSystem({
triageAgent,
routingMap,
escalation: humanAgent,
});
const response = await supportSystem.handleTicket({
customerQuery: "I was charged twice!",
customerHistory: customerData,
});// real-world/research-assistant.ts
const researchTeam = new ResearchTeam({
leader: leadResearcher,
members: [
dataCollector,
dataAnalyzer,
reportWriter,
],
});
const research = await researchTeam.conductResearch({
question: "What is the impact of remote work on productivity?",
sources: ["arxiv", "google-scholar", "news"],
depth: "comprehensive",
});# Run all tests
npm test
# Run specific test suite
npm test -- single-agent.test.ts
# Watch mode
npm run test:watch
# Coverage
npm run test:coverage- Start Here: Run
npm run basic-example - Read Tutorials: Follow
examples/01-through08- - Study Real-World: Check
real-world/examples - Build Your Own: Use patterns learned
- Optimize: Read best practices and optimize
All examples are modular. Mix and match patterns:
import { AgentChain, ParallelExecutor, ManagerAgent } from './lib';
const customSystem = new ManagerAgent({
subAgents: [
new AgentChain([agent1, agent2]),
new ParallelExecutor([agent3, agent4]),
],
});We welcome improvements! See CONTRIBUTING.md
MIT License - see LICENSE
If you find this helpful, please give us a star!
Made with β€οΈ by Groovy Web
Explore more open-source tools from Groovy Web:
- langchain-multi-agent-example -- Multi-agent systems tutorial with LangChain
- rag-system-pgvector -- Production RAG with PostgreSQL + pgvector
- rag-systems-production -- Enterprise-grade RAG systems
- ai-testing-mcp -- AI testing via Model Context Protocol
- edge-computing-starter -- Cloudflare Workers + Hono template
- claude-code-workflows -- Workflows for Claude Code
- groovy-web-ai-agents -- Production AI agent configs
- groovy-web-examples -- Groovy/Grails examples