Package Exports
- @loopman/langchain-sdk
- @loopman/langchain-sdk/dist/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@loopman/langchain-sdk) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
Loopman SDK TypeScript
A TypeScript SDK demonstrating AI agent development with LangChain v1.0 and Human-in-the-Loop (HITL) validation patterns.
📋 Table of Contents
- Overview
- Features
- Prerequisites
- Installation
- Quick Start
- Examples
- Loopman Middleware
- Debugging
- Project Structure
- API Reference
- Development
- License
🎯 Overview
This SDK provides a comprehensive demonstration of building AI agents with LangChain v1.0, featuring:
- Simple Agent Pattern: Basic tool usage with conversational memory
- Human-in-the-Loop Validation: Using LangChain's native
humanInTheLoopMiddleware - Loopman Integration: Custom middleware for Loopman platform integration
Perfect for learning agent patterns, HITL workflows, and building production-ready AI assistants.
✨ Features
🤖 Agent Capabilities
- ✅ Tool Calling: Dynamic tool execution with Zod validation
- ✅ Conversational Memory: Stateful conversations with checkpointers
- ✅ Multi-turn Interactions: Context-aware dialogue management
- ✅ Streaming Support: Real-time response streaming
🛡️ Human-in-the-Loop
- ✅ Native HITL Middleware: LangChain's
humanInTheLoopMiddleware - ✅ Custom Loopman Middleware: Platform-specific integration
- ✅ LangGraph Integration: Reusable validation nodes with conditional routing
- ✅ Full State Sharing: Send complete agent state to human reviewers
- ✅ Business Context: Define context, proposed decisions, and reasoning
- ✅ Context Enrichment: Automatic guidelines and decision history integration
- ✅ Helper Functions:
enrichSystemPrompt()for simplified agent integration - ✅ Decision Types: Approve, Edit, Reject workflows
- ✅ Selective Interruption: Per-tool configuration
- ✅ Double Validation Layer: Global MCP validation + tool-specific validation
- ✅ Flexible Execution Modes: Auto-execution or manual control after approval
🔧 Developer Experience
- ✅ TypeScript: Full type safety with TSDoc comments
- ✅ Debugging: VSCode launch configurations
- ✅ Examples: Three complete working examples
- ✅ Documentation: Inline comments and guides
📦 Prerequisites
- Node.js: 18+
- OpenAI API Key: Required for model calls
- npm/yarn: Package manager
🚀 Installation
1. Install Dependencies
npm install2. Configure Environment
Create a .env file in the project root:
cp env.example .envEdit .env and add your API keys:
OPENAI_API_KEY=sk-your-openai-api-key-here
LOOPMAN_API_KEY=your-loopman-api-key-here # Optional⚡ Quick Start
Basic Agent
import { createAgent, tool } from "langchain";
import { MemorySaver } from "@langchain/langgraph";
import * as z from "zod";
// Define a tool
const greetTool = tool(({ name }) => `Hello, ${name}!`, {
name: "greet",
description: "Greet a user by name",
schema: z.object({
name: z.string(),
}),
});
// Create agent
const agent = createAgent({
model: "openai:gpt-4o-mini",
tools: [greetTool],
checkpointer: new MemorySaver(),
});
// Run agent
const result = await agent.invoke(
{
messages: [{ role: "user", content: "Greet Alice" }],
},
{ configurable: { thread_id: "demo" } }
);Human-in-the-Loop Agent
import { humanInTheLoopMiddleware } from "langchain";
const agent = createAgent({
model: "openai:gpt-4o-mini",
tools: [sendEmail],
middleware: [
humanInTheLoopMiddleware({
interruptOn: {
send_email: {
allowedDecisions: ["approve", "edit", "reject"],
description: "⚠️ Email requires approval",
},
},
}),
],
checkpointer: new MemorySaver(),
});Loopman Platform Integration
import { loopmanMiddleware } from "./src/loopman-middleware";
const agent = createAgent({
model: "openai:gpt-4o-mini",
tools: [sendEmail],
middleware: [
loopmanMiddleware({
apiKey: process.env.LOOPMAN_API_KEY!,
workflowId: "email-workflow",
interruptOn: {
send_email: true, // Requires validation
read_email: false, // Auto-approved
},
pollingInterval: 5000, // Poll every 5 seconds
timeout: 300000, // 5 minutes
}),
],
checkpointer: new MemorySaver(),
});
// Usage - No manual interruption handling needed!
const result = await agent.invoke(
{
messages: [{ role: "user", content: "Send email to alice" }],
},
{ configurable: { thread_id: "demo" } }
);
// ✅ Middleware handles HITL transparentlyLangGraph with Context Enrichment
import {
LoopmanGraphState,
createLoopmanContextNode,
enrichSystemPrompt,
} from "loopman-langchain-sdk";
import { StateGraph } from "@langchain/langgraph";
// 1. Create context node to load guidelines and decision history
const contextNode = createLoopmanContextNode({
apiKey: process.env.LOOPMAN_API_KEY!,
workflowId: "my-workflow",
category: "email",
});
// 2. Use context in agent with one-liner
async function agentNode(state: typeof LoopmanGraphState.State) {
const { messages, guidelines, decisionContext } = state;
// ✨ Automatically enrich system prompt with Loopman context
const systemPrompt = enrichSystemPrompt("You are a helpful assistant.", {
guidelines,
decisionContext,
});
const response = await model.invoke([
{ role: "system", content: systemPrompt },
...messages,
]);
return { messages: [response] };
}
// 3. Build workflow
const workflow = new StateGraph(LoopmanGraphState)
.addNode("load_context", contextNode)
.addNode("agent", agentNode)
.addEdge(START, "load_context")
.addEdge("load_context", "agent");📚 Examples
Comprehensive examples are organized in the examples/ directory by complexity level:
Quick Start Examples
1. Basics (examples/1-basics/)
01-simple-agent.ts- Basic agent with tools and memory02-memory-and-context.ts- Conversational memory deep dive03-langchain-native-hitl.ts- LangChain's native HITL middleware
2. Loopman Integration (examples/2-loopman-integration/)
01-middleware-basic.ts- Transparent HITL with Loopman middleware02-middleware-modes.ts- Three operation modes (tool-validation, prompt-enhancement, full)03-loopman-agent.ts- High-level Loopman agent API04-loopman-agent-and-tool-validation.ts- Double validation layer
3. Real-World Examples (examples/3-real-world-examples/)
task-management/task-approval.ts- CRUD operations with selective approvaldata-processing/data-validation.ts- ETL with quality checkscontent-workflow/content-review.ts- Draft/publish workflowcontent-workflow/reddit-news-writer.ts- Automated news curation
4. Advanced Patterns (examples/4-advanced-patterns/)
conditional-hitl.ts- Context-aware, intelligent validation
5. LangGraph Integration (examples/5-langgraph-integration/)
loopman-validation-graph.ts- LangGraph workflow with validation node and context enrichmentfull-state-example.ts- Complete state sharing with business context and custom formatting
Running Examples
# Basics
npx tsx examples/1-basics/01-simple-agent.ts
npx tsx examples/1-basics/03-langchain-native-hitl.ts
# Loopman Integration
npx tsx examples/2-loopman-integration/01-middleware-basic.ts
npx tsx examples/2-loopman-integration/03-loopman-agent.ts
# Real-World
npx tsx examples/3-real-world-examples/content-workflow/reddit-news-writer.ts
npx tsx examples/3-real-world-examples/task-management/task-approval.ts
# Advanced
npx tsx examples/4-advanced-patterns/conditional-hitl.ts
# LangGraph Integration
npx tsx examples/5-langgraph-integration/loopman-validation-graph.ts
npm run example:langgraph-full-stateSee Examples README for detailed documentation and learning paths.
New:
- Check out the LangGraph Integration Guide for building stateful workflows with Loopman validation nodes
- See Full State Integration Guide for sharing complete agent state with human reviewers
Key Features Demonstrated:
- Transparent validation: No manual interruption handling
- Automatic polling: Middleware polls for decisions
- Timeout handling: Built-in timeout and retry logic
- Fallback mechanism: Auto-approval on API errors
- Clean code: Simple invoke() calls, HITL happens behind the scenes
- Debug logging for development
🔌 Loopman Middleware
Custom middleware for integrating with the Loopman Human-in-the-Loop platform.
Key Feature: Transparent Validation
The middleware handles everything automatically! No need to manually check for interruptions or poll for decisions.
// Just invoke the agent - HITL happens transparently!
const result = await agent.invoke(
{
messages: [{ role: "user", content: "Send email to alice" }],
},
config
);
// ✅ Decision already validated by human (if required)Configuration
import { loopmanMiddleware } from "./src/loopman-middleware";
loopmanMiddleware({
// Required
apiKey: "your-loopman-api-key",
workflowId: "email-workflow",
// Optional
executionId: "custom-execution-id", // Auto-generated if not provided
apiBaseUrl: "https://api.loopman.io", // Default
timeout: 5 * 60 * 1000, // 5 minutes
pollingInterval: 5000, // Poll every 5 seconds
debug: true, // Enable logging
// Tool configuration
interruptOn: {
send_email: true, // Requires validation
read_email: false, // Auto-approved
},
});Decision Flow (Automatic)
graph TD
A[Agent calls tool] --> B{Requires validation?}
B -->|No| C[Execute immediately]
B -->|Yes| D[Middleware sends to Loopman API]
D --> E[Middleware polls for decision]
E --> F[Notify user via mobile/web]
F --> G{Human decision}
G -->|Approve| H[Middleware executes as-is]
G -->|Edit| I[Middleware executes with modifications]
G -->|Reject| J[Middleware returns error message]
H --> K[Return result to application]
I --> K
J --> K
style D fill:#90EE90
style E fill:#90EE90
style H fill:#90EE90
style I fill:#90EE90
style J fill:#90EE90Note: Green boxes = Handled by middleware (transparent to your code)
Response Types
// Approve
{ type: "approve" }
// Edit/Modify
{
type: "edit",
editedAction: {
name: "send_email",
args: { to: "alice@example.com", subject: "Modified" }
}
}
// Reject
{
type: "reject",
message: "Reason for rejection"
}🐛 Debugging
VSCode launch configurations are provided in .vscode/launch.json.
Available Configurations
- Debug Current Example: Debug the currently open TypeScript file
- Debug Simple Agent: Launch
examples/1-basics/01-simple-agent.ts - Debug HITL Agent: Launch
examples/1-basics/03-langchain-native-hitl.ts - Debug Loopman Middleware: Launch
examples/2-loopman-integration/01-middleware-basic.ts
Usage
- Open an example file
- Press
F5or click the debug icon - Select a configuration
- Set breakpoints as needed
📁 Project Structure
loopman-langchain-sdk-typescript/
├── src/
│ ├── agents/
│ │ └── loopman-agent.ts # High-level Loopman agent API
│ ├── client/
│ │ └── loopman-api.ts # Loopman API client
│ ├── helpers/
│ │ └── prompt-orchestrator.ts # Prompt building utilities
│ ├── mcp/
│ │ ├── loopman-mcp-client.ts # MCP client integration
│ │ └── tool-registry.ts # Tool registry for MCP
│ ├── services/
│ │ ├── loopman.service.ts # Main Loopman service
│ │ ├── polling.service.ts # Polling logic
│ │ └── logger.service.ts # Logging service
│ ├── loopman-middleware.ts # Core middleware implementation
│ ├── loopman-agent-wrapper.ts # Wrapper helpers (invokeWithRetry)
│ ├── index.ts # Main export entry point
│ └── types.ts # TypeScript type definitions
├── examples/
│ ├── 1-basics/ # LangChain fundamentals
│ ├── 2-loopman-integration/ # Loopman HITL integration
│ ├── 3-real-world-examples/ # Production use cases
│ └── 4-advanced-patterns/ # Advanced HITL patterns
├── docs/ # Detailed documentation
├── dist/ # Compiled JavaScript (generated)
├── .env # Environment variables (root)
├── env.example # Example environment file
├── package.json # Dependencies and scripts
├── tsconfig.json # TypeScript configuration
└── README.md # This file📖 API Reference
Loopman Middleware API
loopmanMiddleware(config)
Creates a LangChain middleware for Loopman integration.
Parameters:
config.apiKey(string, required): Loopman API keyconfig.workflowId(string, required): Workflow identifierconfig.executionId(string, optional): Execution IDconfig.mode(string, optional): Operation mode (tool-validation,prompt-enhancement,full)config.interruptOn(Record<string, boolean>, optional): Tool validation configconfig.timeout(number, optional): Decision timeout in msconfig.pollingInterval(number, optional): Polling interval in msconfig.debug(boolean, optional): Enable debug logging
Returns: AgentMiddleware
Example:
const middleware = loopmanMiddleware({
apiKey: process.env.LOOPMAN_API_KEY!,
workflowId: "my-workflow",
interruptOn: { send_email: true },
debug: true,
});Loopman Agent API
createLoopmanAgent(config)
Creates a complete Loopman agent with MCP integration and double validation layer.
Parameters:
config.apiKey(string, required): Loopman API keyconfig.workflowId(string, required): Workflow identifierconfig.model(string, required): Model identifier (e.g.,"openai:gpt-4o-mini")config.systemPrompt(string, required): System prompt for the agentconfig.additionalTools(array, optional): Custom tools to addconfig.category(string, optional): Category for guidelines organizationconfig.language(string, optional): Language for human review interfaceconfig.requireApprovalForTools(array, optional): Tools requiring approval (['*']for all)config.manualExecutionMode(boolean, optional): Manual execution modeconfig.pollingIntervalMs(number, optional): Polling intervalconfig.pollingTimeoutMs(number, optional): Polling timeoutconfig.debug(boolean, optional): Enable debug logging
Returns: LoopmanAgent
Example:
const agent = createLoopmanAgent({
apiKey: process.env.LOOPMAN_API_KEY!,
workflowId: "my-workflow",
model: "openai:gpt-4o-mini",
systemPrompt: "Your instructions...",
additionalTools: [myTool],
debug: true,
});
const result = await agent.processWithHumanValidation({
input: "Your task...",
});See Loopman Agent Guide for complete API documentation.
🛠️ Development
Scripts
# Development
npm run build # Compile TypeScript to JavaScript
npm run clean # Remove dist/ folder
# Examples (run directly with tsx)
npx tsx examples/1-basics/01-simple-agent.ts
npx tsx examples/2-loopman-integration/01-middleware-basic.ts
npx tsx examples/3-real-world-examples/content-workflow/reddit-news-writer.tsAdding New Tools
- Define the tool with Zod schema:
const myTool = tool(
({ param }) => {
// Tool logic here
return "result";
},
{
name: "my_tool",
description: "What the tool does",
schema: z.object({
param: z.string().describe("Parameter description"),
}),
}
);- Add to agent:
const agent = createAgent({
model: "openai:gpt-4o-mini",
tools: [myTool, ...otherTools],
// ... other config
});Extending Loopman Middleware
The Loopman middleware is fully implemented with:
- ✅ Real Loopman API integration via HTTP calls
- ✅ Polling for decision responses with configurable intervals
- ✅ Timeout and retry logic
- ✅ Comprehensive error handling and logging
- ✅ Support for multiple operation modes (tool-validation, prompt-enhancement, full)
See src/loopman-middleware.ts for the complete implementation.
🔗 Related Resources
SDK Documentation
- LangGraph Integration Guide - Build stateful workflows with validation nodes
- LangGraph Context Enrichment - Load guidelines and decision history
- LangGraph Helper Functions - Utility functions for context integration
- LangGraph Custom State - Use Loopman with your own state schema
- requiresValidation Mechanism - How validation triggering works
- Validation Node Context Enrichment - Auto context loading after validation ⭐ New
- Loopman Agent Guide - Full agent implementation with MCP
- Tool Validation Mode - Middleware tool validation
- Auto-Correction with Feedback - Agent retry patterns
- Evolution to LangGraph - Migration roadmap
LangChain Documentation
Loopman Platform
- Loopman LangChain SDK - Production HITL SDK
- Loopman Web App - Web interface
- Loopman Mobile App - Flutter mobile app
📄 License
MPL-2.0 (Mozilla Public License 2.0). See LICENSE.
🤝 Contributing
This is a demonstration project. For production use, see the Loopman LangChain SDK.
💡 Tips
Environment Variables
- Keep
.envfiles out of version control - Use
env.exampleas a template - Store sensitive keys in environment variables
Debugging
- Use VSCode debug configurations for step-through debugging
- Enable
debug: truein middleware for detailed logging - Check SDK debug logs (via
LoggerService) for tool execution details
Performance
- Use
MemorySaverfor development only - Use persistent checkpointers (PostgreSQL) in production
- Consider timeout values for HITL workflows
Best Practices
- Always validate tool schemas with Zod
- Handle errors gracefully in tools
- Use descriptive tool names and descriptions
- Test HITL workflows thoroughly
Built using LangChain v1.0 and TypeScript.