langchain-workflow-builder
Builds LLM applications with LangChain including chains, agents, memory, tools, and RAG pipelines. Use when users request "LangChain setup", "LLM chain", "AI workflow", "conversational AI", or "RAG pipeline".
What this skill does
# LangChain Workflow Builder
Build powerful LLM applications with chains, agents, and retrieval-augmented generation.
## Core Workflow
1. **Setup LangChain**: Install and configure
2. **Create chains**: Build processing pipelines
3. **Add memory**: Enable conversation context
4. **Define tools**: Extend agent capabilities
5. **Implement RAG**: Add knowledge retrieval
6. **Deploy**: Production-ready setup
## Installation
```bash
npm install langchain @langchain/openai @langchain/community
```
## Basic Chains
### Simple LLM Chain
```typescript
// chains/simple.ts
import { ChatOpenAI } from '@langchain/openai';
import { ChatPromptTemplate } from '@langchain/core/prompts';
import { StringOutputParser } from '@langchain/core/output_parsers';
const model = new ChatOpenAI({
modelName: 'gpt-4-turbo-preview',
temperature: 0.7,
});
const prompt = ChatPromptTemplate.fromMessages([
['system', 'You are a helpful assistant that {task}.'],
['human', '{input}'],
]);
const chain = prompt.pipe(model).pipe(new StringOutputParser());
// Usage
const result = await chain.invoke({
task: 'summarizes text concisely',
input: 'Summarize this article: ...',
});
```
### Sequential Chain
```typescript
// chains/sequential.ts
import { RunnableSequence } from '@langchain/core/runnables';
// Chain 1: Extract key points
const extractChain = ChatPromptTemplate.fromMessages([
['system', 'Extract the key points from the following text.'],
['human', '{text}'],
]).pipe(model).pipe(new StringOutputParser());
// Chain 2: Summarize key points
const summarizeChain = ChatPromptTemplate.fromMessages([
['system', 'Create a brief summary from these key points.'],
['human', '{keyPoints}'],
]).pipe(model).pipe(new StringOutputParser());
// Combined chain
const fullChain = RunnableSequence.from([
{
keyPoints: extractChain,
originalText: (input) => input.text,
},
{
summary: summarizeChain,
keyPoints: (input) => input.keyPoints,
},
]);
const result = await fullChain.invoke({ text: 'Long article...' });
// { summary: '...', keyPoints: '...' }
```
### Branching Chain
```typescript
// chains/branching.ts
import { RunnableBranch } from '@langchain/core/runnables';
const classifyChain = ChatPromptTemplate.fromMessages([
['system', 'Classify the query as: question, complaint, or feedback'],
['human', '{query}'],
]).pipe(model).pipe(new StringOutputParser());
const questionChain = ChatPromptTemplate.fromMessages([
['system', 'Answer this question helpfully.'],
['human', '{query}'],
]).pipe(model).pipe(new StringOutputParser());
const complaintChain = ChatPromptTemplate.fromMessages([
['system', 'Respond empathetically to this complaint.'],
['human', '{query}'],
]).pipe(model).pipe(new StringOutputParser());
const feedbackChain = ChatPromptTemplate.fromMessages([
['system', 'Thank the user for their feedback.'],
['human', '{query}'],
]).pipe(model).pipe(new StringOutputParser());
const routingChain = RunnableSequence.from([
{
classification: classifyChain,
query: (input) => input.query,
},
RunnableBranch.from([
[(input) => input.classification.includes('question'), questionChain],
[(input) => input.classification.includes('complaint'), complaintChain],
feedbackChain, // Default
]),
]);
```
## Memory & Conversation
### Buffer Memory
```typescript
// memory/conversation.ts
import { BufferMemory } from 'langchain/memory';
import { ConversationChain } from 'langchain/chains';
const memory = new BufferMemory({
returnMessages: true,
memoryKey: 'history',
});
const chain = new ConversationChain({
llm: model,
memory,
prompt: ChatPromptTemplate.fromMessages([
['system', 'You are a helpful assistant.'],
new MessagesPlaceholder('history'),
['human', '{input}'],
]),
});
// Conversation maintains context
await chain.invoke({ input: 'My name is Alice' });
await chain.invoke({ input: 'What is my name?' }); // Remembers Alice
```
### Window Memory
```typescript
// memory/window.ts
import { BufferWindowMemory } from 'langchain/memory';
const memory = new BufferWindowMemory({
k: 5, // Keep last 5 exchanges
returnMessages: true,
memoryKey: 'history',
});
```
### Summary Memory
```typescript
// memory/summary.ts
import { ConversationSummaryMemory } from 'langchain/memory';
const memory = new ConversationSummaryMemory({
llm: model,
memoryKey: 'history',
});
// Summarizes conversation to save tokens
```
### Persistent Memory with Redis
```typescript
// memory/redis.ts
import { BufferMemory } from 'langchain/memory';
import { RedisChatMessageHistory } from '@langchain/community/stores/message/redis';
const memory = new BufferMemory({
chatHistory: new RedisChatMessageHistory({
sessionId: `user:${userId}:session:${sessionId}`,
client: redisClient,
ttl: 3600, // 1 hour
}),
returnMessages: true,
memoryKey: 'history',
});
```
## Tools & Agents
### Define Custom Tools
```typescript
// tools/custom.ts
import { DynamicTool, DynamicStructuredTool } from '@langchain/core/tools';
import { z } from 'zod';
// Simple tool
const searchTool = new DynamicTool({
name: 'search',
description: 'Search the web for information',
func: async (query: string) => {
const results = await searchAPI.search(query);
return JSON.stringify(results);
},
});
// Structured tool with schema
const calculatorTool = new DynamicStructuredTool({
name: 'calculator',
description: 'Perform mathematical calculations',
schema: z.object({
expression: z.string().describe('Mathematical expression to evaluate'),
}),
func: async ({ expression }) => {
try {
const result = eval(expression); // Use safer math parser in production
return String(result);
} catch {
return 'Error: Invalid expression';
}
},
});
// Database query tool
const dbQueryTool = new DynamicStructuredTool({
name: 'query_database',
description: 'Query the database for user or order information',
schema: z.object({
table: z.enum(['users', 'orders', 'products']),
filter: z.record(z.string()).optional(),
limit: z.number().default(10),
}),
func: async ({ table, filter, limit }) => {
const results = await db[table].findMany({
where: filter,
take: limit,
});
return JSON.stringify(results);
},
});
```
### Create Agent
```typescript
// agents/react.ts
import { createReactAgent, AgentExecutor } from 'langchain/agents';
import { pull } from 'langchain/hub';
// Get standard ReAct prompt
const prompt = await pull('hwchase17/react');
// Create agent
const agent = await createReactAgent({
llm: model,
tools: [searchTool, calculatorTool, dbQueryTool],
prompt,
});
// Create executor
const executor = new AgentExecutor({
agent,
tools: [searchTool, calculatorTool, dbQueryTool],
verbose: true,
maxIterations: 5,
});
// Run agent
const result = await executor.invoke({
input: 'What is the square root of the number of users in our database?',
});
```
### OpenAI Functions Agent
```typescript
// agents/openai-functions.ts
import { createOpenAIFunctionsAgent, AgentExecutor } from 'langchain/agents';
const prompt = ChatPromptTemplate.fromMessages([
['system', 'You are a helpful assistant with access to tools.'],
new MessagesPlaceholder('chat_history'),
['human', '{input}'],
new MessagesPlaceholder('agent_scratchpad'),
]);
const agent = await createOpenAIFunctionsAgent({
llm: new ChatOpenAI({ modelName: 'gpt-4-turbo-preview' }),
tools: [searchTool, calculatorTool],
prompt,
});
const executor = new AgentExecutor({
agent,
tools: [searchTool, calculatorTool],
memory: new BufferMemory({
returnMessages: true,
memoryKey: 'chat_history',
}),
});
```
## RAG Pipeline
### Document Loading
```typescript
// rag/loader.ts
import { DirectoryLoader } from 'langchain/document_loaders/fs/directory';
import { PDFLoader } from 'langchain/document_loaders/fs/pdf';
import { TextLoader } from 'langchain/document_loaRelated in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.