langchain-reference-architecture

0
0
Source

Implement LangChain reference architecture patterns for production. Use when designing LangChain systems, implementing scalable patterns, or architecting enterprise LLM applications. Trigger with phrases like "langchain architecture", "langchain design", "langchain scalable", "langchain enterprise", "langchain patterns".

Install

mkdir -p .claude/skills/langchain-reference-architecture && curl -L -o skill.zip "https://mcp.directory/api/skills/download/8580" && unzip -o skill.zip -d .claude/skills/langchain-reference-architecture && rm skill.zip

Installs to .claude/skills/langchain-reference-architecture

About this skill

LangChain Reference Architecture

Overview

Production architectural patterns for LangChain: layered project structure, provider abstraction for vendor flexibility, chain registry for dynamic management, RAG architecture, and multi-agent orchestration.

Layered Architecture

src/
├── api/                    # HTTP layer (Express/Fastify/FastAPI)
│   ├── routes/
│   │   ├── chat.ts         # POST /api/chat, /api/chat/stream
│   │   └── documents.ts    # POST /api/documents/ingest
│   └── middleware/
│       ├── auth.ts         # JWT/OAuth validation
│       └── rateLimit.ts    # Per-user rate limiting
├── core/                   # Business logic (pure, testable)
│   ├── chains/
│   │   ├── summarize.ts    # Summarize chain factory
│   │   ├── qa.ts           # Q&A chain factory
│   │   └── rag.ts          # RAG chain factory
│   ├── agents/
│   │   └── assistant.ts    # Agent with tools
│   └── tools/
│       ├── calculator.ts
│       └── search.ts
├── infra/                  # External integrations
│   ├── llm/
│   │   └── factory.ts      # LLM provider factory
│   ├── vectorStore/
│   │   └── pinecone.ts     # Vector store setup
│   └── cache/
│       └── redis.ts        # Response caching
├── config/
│   ├── index.ts            # Config loader + validation
│   └── models.ts           # Model configurations
└── index.ts                # App entry point

Provider Abstraction (LLM Factory)

// src/infra/llm/factory.ts
import { ChatOpenAI } from "@langchain/openai";
import { ChatAnthropic } from "@langchain/anthropic";
import { BaseChatModel } from "@langchain/core/language_models/chat_models";

type Provider = "openai" | "anthropic";

interface ModelConfig {
  provider: Provider;
  model: string;
  temperature?: number;
  maxRetries?: number;
  timeout?: number;
}

const DEFAULT_CONFIG: Partial<ModelConfig> = {
  temperature: 0,
  maxRetries: 3,
  timeout: 30000,
};

export function createModel(config: ModelConfig): BaseChatModel {
  const merged = { ...DEFAULT_CONFIG, ...config };

  switch (merged.provider) {
    case "openai":
      return new ChatOpenAI({
        model: merged.model,
        temperature: merged.temperature,
        maxRetries: merged.maxRetries,
        timeout: merged.timeout,
      });

    case "anthropic":
      return new ChatAnthropic({
        model: merged.model,
        temperature: merged.temperature,
        maxRetries: merged.maxRetries,
      });

    default:
      throw new Error(`Unknown provider: ${merged.provider}`);
  }
}

// Usage: swap providers without touching chain code
const model = createModel({
  provider: "openai",
  model: "gpt-4o-mini",
});

Chain Registry

// src/core/chains/registry.ts
import { Runnable } from "@langchain/core/runnables";

class ChainRegistry {
  private chains = new Map<string, Runnable>();

  register(name: string, chain: Runnable) {
    this.chains.set(name, chain);
  }

  get(name: string): Runnable {
    const chain = this.chains.get(name);
    if (!chain) throw new Error(`Chain not found: ${name}`);
    return chain;
  }

  list(): string[] {
    return Array.from(this.chains.keys());
  }
}

export const registry = new ChainRegistry();

// At startup:
registry.register("summarize", summarizeChain);
registry.register("qa", qaChain);
registry.register("rag", ragChain);

// In API routes:
app.post("/api/chain/:name/invoke", async (req, res) => {
  const chain = registry.get(req.params.name);
  const result = await chain.invoke(req.body.input);
  res.json({ result });
});

RAG Architecture

// src/core/chains/rag.ts
import { ChatOpenAI, OpenAIEmbeddings } from "@langchain/openai";
import { PineconeStore } from "@langchain/pinecone";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import { StringOutputParser } from "@langchain/core/output_parsers";
import { RunnableSequence, RunnablePassthrough } from "@langchain/core/runnables";

export function createRAGChain(vectorStore: PineconeStore) {
  const retriever = vectorStore.asRetriever({ k: 4 });
  const model = new ChatOpenAI({ model: "gpt-4o-mini", temperature: 0 });

  const prompt = ChatPromptTemplate.fromTemplate(`
Answer based only on the provided context.
If the answer is not in the context, say "I don't have that information."

Context:
{context}

Question: {question}`);

  return RunnableSequence.from([
    {
      context: retriever.pipe(
        (docs) => docs.map((d: any) => d.pageContent).join("\n\n")
      ),
      question: new RunnablePassthrough(),
    },
    prompt,
    model,
    new StringOutputParser(),
  ]);
}

Multi-Agent Orchestration

// src/core/agents/orchestrator.ts
import { ChatOpenAI } from "@langchain/openai";
import { createToolCallingAgent, AgentExecutor } from "langchain/agents";
import { ChatPromptTemplate, MessagesPlaceholder } from "@langchain/core/prompts";

interface SpecializedAgent {
  name: string;
  description: string;
  executor: AgentExecutor;
}

class AgentOrchestrator {
  private agents: SpecializedAgent[] = [];
  private router: any;

  register(agent: SpecializedAgent) {
    this.agents.push(agent);
  }

  async route(input: string): Promise<string> {
    // Use LLM to pick the right agent
    const model = new ChatOpenAI({ model: "gpt-4o-mini", temperature: 0 });
    const agentList = this.agents
      .map((a) => `- ${a.name}: ${a.description}`)
      .join("\n");

    const routerPrompt = ChatPromptTemplate.fromTemplate(`
Given these specialized agents:
${agentList}

Which agent should handle this request? Reply with just the agent name.
Request: {input}`);

    const routerChain = routerPrompt.pipe(model).pipe(new StringOutputParser());
    const agentName = (await routerChain.invoke({ input })).trim();

    const agent = this.agents.find((a) => a.name === agentName);
    if (!agent) {
      return `No agent found for: ${input}`;
    }

    const result = await agent.executor.invoke({ input, chat_history: [] });
    return result.output;
  }
}

// Usage
const orchestrator = new AgentOrchestrator();
orchestrator.register({
  name: "code-reviewer",
  description: "Reviews code for bugs and best practices",
  executor: codeReviewAgent,
});
orchestrator.register({
  name: "data-analyst",
  description: "Analyzes data and generates reports",
  executor: dataAnalystAgent,
});

Configuration-Driven Design

// src/config/index.ts
import { z } from "zod";
import "dotenv/config";

const ConfigSchema = z.object({
  llm: z.object({
    provider: z.enum(["openai", "anthropic"]),
    model: z.string(),
    temperature: z.number().min(0).max(2).default(0),
    maxRetries: z.number().default(3),
  }),
  vectorStore: z.object({
    provider: z.enum(["pinecone", "faiss", "memory"]),
    indexName: z.string().optional(),
  }),
  server: z.object({
    port: z.number().default(8000),
    cors: z.boolean().default(true),
  }),
  langsmith: z.object({
    enabled: z.boolean().default(false),
    project: z.string().default("default"),
  }),
});

export type Config = z.infer<typeof ConfigSchema>;

export function loadConfig(): Config {
  return ConfigSchema.parse({
    llm: {
      provider: process.env.LLM_PROVIDER ?? "openai",
      model: process.env.LLM_MODEL ?? "gpt-4o-mini",
      temperature: Number(process.env.LLM_TEMPERATURE ?? 0),
    },
    vectorStore: {
      provider: process.env.VECTOR_STORE_PROVIDER ?? "memory",
      indexName: process.env.PINECONE_INDEX,
    },
    server: {
      port: Number(process.env.PORT ?? 8000),
    },
    langsmith: {
      enabled: process.env.LANGSMITH_TRACING === "true",
      project: process.env.LANGSMITH_PROJECT ?? "default",
    },
  });
}

Error Handling

IssueCauseFix
Circular importsWrong layeringCore should never import from API layer
Provider not foundUnknown in factoryAdd to factory switch statement
Chain not registeredMissing startup initRegister all chains in app bootstrap
Config validation failMissing env varAdd to .env.example, validate on startup

Resources

Next Steps

Use langchain-multi-env-setup for environment management.

svg-icon-generator

jeremylongshore

Svg Icon Generator - Auto-activating skill for Visual Content. Triggers on: svg icon generator, svg icon generator Part of the Visual Content skill category.

8227

d2-diagram-creator

jeremylongshore

D2 Diagram Creator - Auto-activating skill for Visual Content. Triggers on: d2 diagram creator, d2 diagram creator Part of the Visual Content skill category.

4926

automating-mobile-app-testing

jeremylongshore

This skill enables automated testing of mobile applications on iOS and Android platforms using frameworks like Appium, Detox, XCUITest, and Espresso. It generates end-to-end tests, sets up page object models, and handles platform-specific elements. Use this skill when the user requests mobile app testing, test automation for iOS or Android, or needs assistance with setting up device farms and simulators. The skill is triggered by terms like "mobile testing", "appium", "detox", "xcuitest", "espresso", "android test", "ios test".

14217

performing-penetration-testing

jeremylongshore

This skill enables automated penetration testing of web applications. It uses the penetration-tester plugin to identify vulnerabilities, including OWASP Top 10 threats, and suggests exploitation techniques. Use this skill when the user requests a "penetration test", "pentest", "vulnerability assessment", or asks to "exploit" a web application. It provides comprehensive reporting on identified security flaws.

4615

designing-database-schemas

jeremylongshore

Design and visualize efficient database schemas, normalize data, map relationships, and generate ERD diagrams and SQL statements.

11514

analyzing-logs

jeremylongshore

Analyze application logs to detect performance issues, identify error patterns, and improve stability by extracting key insights.

11410

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

1,1421,171

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

969933

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

683829

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

691549

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

797540

pdf-to-markdown

aliceisjustplaying

Convert entire PDF documents to clean, structured Markdown for full context loading. Use this skill when the user wants to extract ALL text from a PDF into context (not grep/search), when discussing or analyzing PDF content in full, when the user mentions "load the whole PDF", "bring the PDF into context", "read the entire PDF", or when partial extraction/grepping would miss important context. This is the preferred method for PDF text extraction over page-by-page or grep approaches.

697374

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.