@loopman/langchain-sdk 1.8.0 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +7 -1
  2. package/dist/agents/loopman-agent.d.ts.map +1 -1
  3. package/dist/agents/loopman-agent.js.map +1 -1
  4. package/dist/helpers/template-generator-static.d.ts +27 -0
  5. package/dist/helpers/template-generator-static.d.ts.map +1 -0
  6. package/dist/helpers/template-generator-static.js +52 -0
  7. package/dist/helpers/template-generator-static.js.map +1 -0
  8. package/dist/helpers/template-generator.d.ts +50 -0
  9. package/dist/helpers/template-generator.d.ts.map +1 -0
  10. package/dist/helpers/template-generator.js +85 -0
  11. package/dist/helpers/template-generator.js.map +1 -0
  12. package/dist/index.d.ts +3 -0
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +4 -0
  15. package/dist/index.js.map +1 -1
  16. package/dist/langgraph/loopman-context-node.d.ts +2 -2
  17. package/dist/langgraph/loopman-context-node.d.ts.map +1 -1
  18. package/dist/langgraph/loopman-context-node.js +32 -20
  19. package/dist/langgraph/loopman-context-node.js.map +1 -1
  20. package/dist/langgraph/loopman-validation-node.d.ts +45 -15
  21. package/dist/langgraph/loopman-validation-node.d.ts.map +1 -1
  22. package/dist/langgraph/loopman-validation-node.js +144 -21
  23. package/dist/langgraph/loopman-validation-node.js.map +1 -1
  24. package/dist/mcp/loopman-mcp-client.d.ts.map +1 -1
  25. package/dist/mcp/loopman-mcp-client.js +5 -0
  26. package/dist/mcp/loopman-mcp-client.js.map +1 -1
  27. package/dist/services/loopman.service.d.ts +11 -2
  28. package/dist/services/loopman.service.d.ts.map +1 -1
  29. package/dist/services/loopman.service.js +26 -9
  30. package/dist/services/loopman.service.js.map +1 -1
  31. package/dist/templates.json +20 -0
  32. package/examples/README.md +346 -0
  33. package/examples/templates/README.md +285 -0
  34. package/examples/templates/langchain-full-review/.env.example +3 -0
  35. package/examples/templates/langchain-full-review/README.md +165 -0
  36. package/examples/templates/langchain-full-review/index.ts +54 -0
  37. package/examples/templates/langchain-full-review/package.json +29 -0
  38. package/examples/templates/langchain-full-review/tsconfig.json +22 -0
  39. package/examples/templates/langchain-tool-validation/.env.example +3 -0
  40. package/examples/templates/langchain-tool-validation/README.md +137 -0
  41. package/examples/templates/langchain-tool-validation/index.ts +65 -0
  42. package/examples/templates/langchain-tool-validation/package.json +29 -0
  43. package/examples/templates/langchain-tool-validation/tsconfig.json +22 -0
  44. package/examples/templates/langgraph-hello-world/.env.example +3 -0
  45. package/examples/templates/langgraph-hello-world/README.md +71 -0
  46. package/examples/templates/langgraph-hello-world/index.ts +147 -0
  47. package/examples/templates/langgraph-hello-world/package.json +27 -0
  48. package/examples/templates/langgraph-hello-world/tsconfig.json +22 -0
  49. package/package.json +7 -4
@@ -0,0 +1,20 @@
1
+ {
2
+ "langgraph-hello-world": {
3
+ "index.ts": "import { HumanMessage, ToolMessage } from \"@langchain/core/messages\";\nimport { END, MemorySaver, START, StateGraph } from \"@langchain/langgraph\";\nimport { ChatOpenAI } from \"@langchain/openai\";\nimport { config } from \"dotenv\";\nimport { tool } from \"langchain\";\nimport * as z from \"zod\";\n\nimport {\n LoopmanGraphState,\n createLoopmanConditionalEdge,\n createLoopmanContextNode,\n createLoopmanValidationNode,\n enrichSystemPrompt,\n} from \"@loopman/langchain-sdk\";\n\nconfig();\n\n// Define your tools\nconst sayHello = tool(\n ({ name }) => {\n console.log(`Hello, ${name}!`);\n return `Hello, ${name}! Welcome to Loopman.`;\n },\n {\n name: \"say_hello\",\n description: \"Say hello to someone\",\n schema: z.object({\n name: z.string().describe(\"The name of the person to greet\"),\n }),\n }\n);\n\n// Agent node with context enrichment\nasync function agentNode(state: any) {\n const { messages, guidelines, decisionContext } = state;\n\n // Enrich system prompt with guidelines and decision history\n const systemPrompt = enrichSystemPrompt(\n \"You are a helpful assistant that greets people ....\",\n { guidelines, decisionContext },\n { maxDecisions: 3 }\n );\n\n const model = new ChatOpenAI({ model: \"gpt-4o-mini\" });\n const modelWithTools = model.bindTools([sayHello]);\n\n const messagesWithContext =\n (guidelines && guidelines.length > 0) ||\n (decisionContext && decisionContext.length > 0)\n ? [{ role: \"system\", content: systemPrompt }, ...messages]\n : messages;\n\n const response = await modelWithTools.invoke(messagesWithContext);\n\n return {\n messages: [response],\n requiresValidation: response.tool_calls && response.tool_calls.length > 0,\n };\n}\n\n// Tool execution node\nasync function toolNode(state: any) {\n const { messages } = state;\n const lastMessage = messages[messages.length - 1];\n\n if (!lastMessage.tool_calls || lastMessage.tool_calls.length === 0) {\n return {};\n }\n\n const toolCall = lastMessage.tool_calls[0];\n const result = await sayHello.invoke(toolCall.args);\n\n return {\n messages: [\n new ToolMessage({\n content: result,\n tool_call_id: toolCall.id,\n }),\n ],\n };\n}\n\n// Build the graph with context loading\nconst workflow = new StateGraph(LoopmanGraphState)\n .addNode(\n \"load_context\",\n createLoopmanContextNode({\n apiKey: process.env.LOOPMAN_API_KEY!,\n workflowId: process.env.LOOPMAN_WORKFLOW_ID!,\n category: \"hello-world\",\n debug: true,\n })\n )\n .addNode(\"agent\", agentNode)\n .addNode(\n \"loopman_validation\",\n createLoopmanValidationNode({\n apiKey: process.env.LOOPMAN_API_KEY!,\n workflowId: process.env.LOOPMAN_WORKFLOW_ID!,\n debug: true,\n })\n )\n .addNode(\"tools\", toolNode)\n .addEdge(START, \"load_context\")\n .addEdge(\"load_context\", \"agent\")\n .addEdge(\"agent\", \"loopman_validation\")\n .addConditionalEdges(\n \"loopman_validation\",\n createLoopmanConditionalEdge({ debug: true }),\n {\n execute: \"tools\",\n rejected: END,\n retry: \"agent\",\n timeout: END,\n error: END,\n }\n )\n .addEdge(\"tools\", END);\n\n// Compile and run\nconst checkpointer = new MemorySaver();\nconst app = workflow.compile({ checkpointer });\n\nasync function main() {\n const config = { configurable: { thread_id: \"hello-world-thread\" } };\n const inputs = {\n messages: [new HumanMessage(\"Say hello to Alice\")],\n };\n\n console.log(\"Starting LangGraph workflow with context enrichment...\");\n\n for await (const output of await app.stream(inputs, config)) {\n const nodeName = Object.keys(output)[0];\n console.log(`Step: ${nodeName}`);\n }\n\n const finalState = await app.getState(config);\n console.log(\"Final status:\", finalState.values.loopmanTaskStatus);\n console.log(\"Guidelines loaded:\", finalState.values.guidelines?.length || 0);\n console.log(\n \"Decision context loaded:\",\n finalState.values.decisionContext?.length || 0\n );\n console.log(\"Workflow completed!\");\n}\n\nmain().catch(console.error);\n",
4
+ "package.json": "{\n \"name\": \"loopman-langgraph-hello-world\",\n \"version\": \"1.0.0\",\n \"description\": \"Loopman LangGraph Hello World Example\",\n \"main\": \"index.ts\",\n \"type\": \"module\",\n \"scripts\": {\n \"start\": \"tsx index.ts\",\n \"dev\": \"tsx index.ts\",\n \"build\": \"tsc\",\n \"run\": \"node dist/index.js\"\n },\n \"dependencies\": {\n \"@langchain/core\": \"^1.0.2\",\n \"@langchain/langgraph\": \"^1.0.1\",\n \"@langchain/openai\": \"^1.0.0\",\n \"@loopman/langchain-sdk\": \"^1.12.0\",\n \"dotenv\": \"^17.2.3\",\n \"langchain\": \"^1.0.2\",\n \"tsx\": \"^4.20.6\",\n \"typescript\": \"^5.9.3\",\n \"zod\": \"^3.25.76\"\n },\n \"devDependencies\": {\n \"@types/node\": \"^24.9.2\"\n }\n}\n",
5
+ "tsconfig.json": "{\n \"compilerOptions\": {\n \"target\": \"ES2022\",\n \"module\": \"ES2022\",\n \"lib\": [\"ES2022\"],\n \"moduleResolution\": \"bundler\",\n \"resolveJsonModule\": true,\n \"allowJs\": true,\n \"outDir\": \"./dist\",\n \"rootDir\": \"./\",\n \"strict\": true,\n \"esModuleInterop\": true,\n \"skipLibCheck\": true,\n \"forceConsistentCasingInFileNames\": true,\n \"declaration\": true,\n \"declarationMap\": true,\n \"sourceMap\": true\n },\n \"include\": [\"**/*.ts\"],\n \"exclude\": [\"node_modules\", \"dist\"]\n}\n\n",
6
+ "README.md": "# Loopman LangGraph Hello World\n\nThis project demonstrates how to integrate Loopman with LangGraph using Context Enrichment / Feedback Loop mode.\n\n## About LangGraph\n\nLangGraph is LangChain's official framework for building stateful, multi-actor applications with LLMs. It provides:\n\n- **Stateful workflows**: Explicit state management across nodes\n- **Conditional routing**: Dynamic edges based on state\n- **Streaming support**: Real-time updates during execution\n- **Visual debugging**: Graph visualization and inspection\n\n## Setup\n\n1. Install dependencies:\n```bash\nnpm install\n```\n\n2. Copy .env.example to .env and configure your keys:\n```bash\ncp .env.example .env\n```\n\nEdit the .env file and replace the placeholders with your actual values:\n- `OPENAI_API_KEY`: Your OpenAI API key\n- `LOOPMAN_API_KEY`: Your Loopman API key\n- `LOOPMAN_WORKFLOW_ID`: Your workflow ID from Loopman\n\n3. Run the example:\n```bash\nnpm start\n```\n\n## Graph Architecture\n\nThe workflow follows this pattern:\n\n```\nSTART\n ↓\nload_context (load guidelines and decision history)\n ↓\nagent (LLM decides action)\n ↓\nloopman_validation (create task + poll)\n ↓\n[conditional edge based on status]\n ↓\n├─→ tools (APPROVED: execute)\n├─→ agent (NEEDS_CHANGES: retry)\n└─→ END (REJECTED/TIMEOUT/ERROR: end)\n ↓\nEND\n```\n\n## Key Features\n\n- **Context Enrichment**: Loads validation guidelines and historical decisions\n- **Prompt Enhancement**: Automatically enriches system prompts with context\n- **Learning from History**: Agent learns from past human decisions\n- **Category Filtering**: Guidelines filtered by category for relevance\n- **Feedback Loop**: Human feedback is stored and used to improve future decisions\n\n## Learn More\n\n- [LangGraph Documentation](https://js.langchain.com/docs/langgraph/)\n- [Loopman LangGraph Integration Guide](https://github.com/loopman/loopman-langchain-sdk/blob/main/docs/LANGGRAPH_INTEGRATION.md)\n- [Loopman Documentation](https://loopman.dev/docs)\n\n"
7
+ },
8
+ "langchain-tool-validation": {
9
+ "index.ts": "import { MemorySaver } from \"@langchain/langgraph\";\nimport { config } from \"dotenv\";\nimport { createAgent, tool } from \"langchain\";\nimport * as z from \"zod\";\nimport { loopmanMiddleware } from \"@loopman/langchain-sdk\";\n\n// Load environment variables\nconfig();\n\n// Simple hello world tool\nconst sayHello = tool(\n ({ name }) => {\n console.log(`Hello, ${name}!`);\n return `Hello, ${name}! Welcome to Loopman.`;\n },\n {\n name: \"say_hello\",\n description: \"Say hello to someone\",\n schema: z.object({\n name: z.string().describe(\"The name of the person to greet\"),\n }),\n }\n);\n\n// Create agent with Loopman middleware\nconst checkpointer = new MemorySaver();\n\nconst agent = createAgent({\n model: \"openai:gpt-4o-mini\",\n systemPrompt: \"You are a helpful assistant that greets people.\",\n tools: [sayHello],\n middleware: [\n loopmanMiddleware({\n apiKey: process.env.LOOPMAN_API_KEY!,\n workflowId: process.env.LOOPMAN_WORKFLOW_ID!,\n interruptOn: {\n say_hello: true, // Requires human validation\n },\n debug: true,\n }),\n ],\n checkpointer,\n});\n\n// Run the agent\nasync function main() {\n const config = { configurable: { thread_id: \"hello-world-thread\" } };\n\n const result = await agent.invoke(\n {\n messages: [\n {\n role: \"user\",\n content: \"Say hello to Alice\",\n },\n ],\n },\n config\n );\n\n console.log(\"Agent response:\", result.messages[result.messages.length - 1].content);\n}\n\nmain().catch(console.error);\n\n",
10
+ "package.json": "{\n \"name\": \"loopman-langchain-tool-validation\",\n \"version\": \"1.0.0\",\n \"description\": \"Loopman LangChain Tool Validation Example\",\n \"main\": \"index.ts\",\n \"type\": \"module\",\n \"scripts\": {\n \"start\": \"tsx index.ts\",\n \"dev\": \"tsx index.ts\",\n \"build\": \"tsc\",\n \"run\": \"node dist/index.js\"\n },\n \"dependencies\": {\n \"@langchain/core\": \"^1.0.2\",\n \"@langchain/mcp-adapters\": \"^1.0.0\",\n \"@langchain/langgraph\": \"^1.0.1\",\n \"@langchain/openai\": \"^1.0.0\",\n \"@loopman/langchain-sdk\": \"^1.12.0\",\n \"dotenv\": \"^17.2.3\",\n \"langchain\": \"^1.0.2\",\n \"tsx\": \"^4.20.6\",\n \"typescript\": \"^5.9.3\",\n \"zod\": \"^3.25.76\"\n },\n \"devDependencies\": {\n \"@types/node\": \"^24.9.2\"\n }\n}\n\n",
11
+ "tsconfig.json": "{\n \"compilerOptions\": {\n \"target\": \"ES2022\",\n \"module\": \"ES2022\",\n \"lib\": [\"ES2022\"],\n \"moduleResolution\": \"bundler\",\n \"resolveJsonModule\": true,\n \"allowJs\": true,\n \"outDir\": \"./dist\",\n \"rootDir\": \"./\",\n \"strict\": true,\n \"esModuleInterop\": true,\n \"skipLibCheck\": true,\n \"forceConsistentCasingInFileNames\": true,\n \"declaration\": true,\n \"declarationMap\": true,\n \"sourceMap\": true\n },\n \"include\": [\"**/*.ts\"],\n \"exclude\": [\"node_modules\", \"dist\"]\n}\n\n",
12
+ "README.md": "# Loopman LangChain - Tool Validation Mode\n\nThis project demonstrates how to integrate Loopman with LangChain using **Tool Validation** mode.\n\n## About Tool Validation Mode\n\nIn this mode, Loopman middleware intercepts specific tool calls and requires human validation before execution. This is useful when:\n- Certain actions need human approval (e.g., sending emails, making payments)\n- You want to validate AI decisions before they affect real systems\n- Compliance requires human oversight for specific operations\n\n## Setup\n\n1. Install dependencies:\n```bash\nnpm install\n```\n\n2. Copy .env.example to .env and configure your keys:\n```bash\ncp .env.example .env\n```\n\nEdit the .env file and replace the placeholders with your actual values:\n- `OPENAI_API_KEY`: Your OpenAI API key\n- `LOOPMAN_API_KEY`: Your Loopman API key\n- `LOOPMAN_WORKFLOW_ID`: Your workflow ID from Loopman\n\n3. Run the example:\n```bash\nnpm start\n```\n\n## How It Works\n\n### 1. Define Tools\n\n```typescript\nconst sayHello = tool(\n ({ name }) => {\n console.log(`Hello, ${name}!`);\n return `Hello, ${name}! Welcome to Loopman.`;\n },\n {\n name: \"say_hello\",\n description: \"Say hello to someone\",\n schema: z.object({\n name: z.string().describe(\"The name of the person to greet\"),\n }),\n }\n);\n```\n\n### 2. Add Loopman Middleware\n\n```typescript\nconst agent = createAgent({\n model: \"openai:gpt-4o-mini\",\n tools: [sayHello],\n middleware: [\n loopmanMiddleware({\n apiKey: process.env.LOOPMAN_API_KEY!,\n workflowId: process.env.LOOPMAN_WORKFLOW_ID!,\n interruptOn: {\n say_hello: true, // Requires human validation\n },\n debug: true,\n }),\n ],\n checkpointer,\n});\n```\n\n### 3. Run the Agent\n\n```typescript\nconst result = await agent.invoke(\n {\n messages: [{ role: \"user\", content: \"Say hello to Alice\" }],\n },\n config\n);\n```\n\n## Key Features\n\n- **Selective Validation**: Only specified tools require approval\n- **Automatic Interception**: Middleware handles validation workflow\n- **Stateful**: Uses checkpointer to maintain conversation state\n- **Debug Mode**: Verbose logging for development\n\n## Workflow\n\n```\n1. User sends message\n ↓\n2. Agent generates tool call (say_hello)\n ↓\n3. Loopman middleware intercepts\n ↓\n4. Creates validation task\n ↓\n5. Waits for human decision\n ↓\n6. If approved → Execute tool\n If rejected → Return to agent with feedback\n```\n\n## Configuration Options\n\n### interruptOn\n\nSpecify which tools require validation:\n\n```typescript\ninterruptOn: {\n say_hello: true, // Always validate\n send_email: true, // Always validate\n get_weather: false, // Never validate (auto-execute)\n}\n```\n\n### debug\n\nEnable/disable verbose logging:\n\n```typescript\ndebug: true // Show detailed logs\ndebug: false // Production mode\n```\n\n## Learn More\n\n- [Loopman Middleware Documentation](https://github.com/loopman/loopman-langchain-sdk/blob/main/docs/TOOL_VALIDATION_MODE.md)\n- [LangChain Agent Documentation](https://js.langchain.com/docs/how_to/agent_executor)\n- [Loopman Documentation](https://loopman.dev/docs)\n\n"
13
+ },
14
+ "langchain-full-review": {
15
+ "index.ts": "import { config } from \"dotenv\";\nimport { tool } from \"langchain\";\nimport * as z from \"zod\";\nimport { createLoopmanAgent } from \"@loopman/langchain-sdk\";\n\n// Load environment variables\nconfig();\n\n// Simple hello world tool\nconst sayHello = tool(\n ({ name }) => {\n console.log(`Hello, ${name}!`);\n return `Hello, ${name}! Welcome to Loopman.`;\n },\n {\n name: \"say_hello\",\n description: \"Say hello to someone\",\n schema: z.object({\n name: z.string().describe(\"The name of the person to greet\"),\n }),\n }\n);\n\n// Create Loopman agent with full human review process\nconst agent = createLoopmanAgent({\n apiKey: process.env.LOOPMAN_API_KEY!,\n workflowId: process.env.LOOPMAN_WORKFLOW_ID!,\n model: \"openai:gpt-4o-mini\",\n systemPrompt: \"You are a helpful assistant that greets people.\",\n category: \"hello-world\",\n additionalTools: [sayHello],\n requireApprovalForTools: [\"say_hello\"], // Requires validation\n debug: true,\n});\n\n// Run the agent\nasync function main() {\n const result = await agent.processWithHumanValidation({\n input: \"Say hello to Alice\",\n });\n\n console.log(\"Agent response:\", result.response);\n if (result.decision) {\n console.log(\"Decision status:\", result.decision.status);\n if (result.decision.feedback) {\n console.log(\"Human feedback:\", result.decision.feedback);\n }\n }\n\n await agent.disconnect();\n}\n\nmain().catch(console.error);\n\n",
16
+ "package.json": "{\n \"name\": \"loopman-langchain-full-review\",\n \"version\": \"1.0.0\",\n \"description\": \"Loopman LangChain Full Human Review Example\",\n \"main\": \"index.ts\",\n \"type\": \"module\",\n \"scripts\": {\n \"start\": \"tsx index.ts\",\n \"dev\": \"tsx index.ts\",\n \"build\": \"tsc\",\n \"run\": \"node dist/index.js\"\n },\n \"dependencies\": {\n \"@langchain/core\": \"^1.0.2\",\n \"@langchain/mcp-adapters\": \"^1.0.0\",\n \"@langchain/langgraph\": \"^1.0.1\",\n \"@langchain/openai\": \"^1.0.0\",\n \"@loopman/langchain-sdk\": \"^1.12.0\",\n \"dotenv\": \"^17.2.3\",\n \"langchain\": \"^1.0.2\",\n \"tsx\": \"^4.20.6\",\n \"typescript\": \"^5.9.3\",\n \"zod\": \"^3.25.76\"\n },\n \"devDependencies\": {\n \"@types/node\": \"^24.9.2\"\n }\n}\n\n",
17
+ "tsconfig.json": "{\n \"compilerOptions\": {\n \"target\": \"ES2022\",\n \"module\": \"ES2022\",\n \"lib\": [\"ES2022\"],\n \"moduleResolution\": \"bundler\",\n \"resolveJsonModule\": true,\n \"allowJs\": true,\n \"outDir\": \"./dist\",\n \"rootDir\": \"./\",\n \"strict\": true,\n \"esModuleInterop\": true,\n \"skipLibCheck\": true,\n \"forceConsistentCasingInFileNames\": true,\n \"declaration\": true,\n \"declarationMap\": true,\n \"sourceMap\": true\n },\n \"include\": [\"**/*.ts\"],\n \"exclude\": [\"node_modules\", \"dist\"]\n}\n\n",
18
+ "README.md": "# Loopman LangChain - Full Human Review Mode\n\nThis project demonstrates how to integrate Loopman with LangChain using **Full Human Review Process** mode.\n\n## About Full Human Review Mode\n\nIn this mode, the Loopman Agent handles the entire workflow including:\n- Creating validation tasks\n- Waiting for human approval\n- Handling feedback and retries\n- Managing the complete lifecycle\n\nThis is useful when:\n- You want a complete HITL (Human-In-The-Loop) solution\n- The agent should wait for human decisions before proceeding\n- You need full control over the validation workflow\n\n## Setup\n\n1. Install dependencies:\n```bash\nnpm install\n```\n\n2. Copy .env.example to .env and configure your keys:\n```bash\ncp .env.example .env\n```\n\nEdit the .env file and replace the placeholders with your actual values:\n- `OPENAI_API_KEY`: Your OpenAI API key\n- `LOOPMAN_API_KEY`: Your Loopman API key\n- `LOOPMAN_WORKFLOW_ID`: Your workflow ID from Loopman\n\n3. Run the example:\n```bash\nnpm start\n```\n\n## How It Works\n\n### 1. Define Tools\n\n```typescript\nconst sayHello = tool(\n ({ name }) => {\n console.log(`Hello, ${name}!`);\n return `Hello, ${name}! Welcome to Loopman.`;\n },\n {\n name: \"say_hello\",\n description: \"Say hello to someone\",\n schema: z.object({\n name: z.string().describe(\"The name of the person to greet\"),\n }),\n }\n);\n```\n\n### 2. Create Loopman Agent\n\n```typescript\nconst agent = createLoopmanAgent({\n apiKey: process.env.LOOPMAN_API_KEY!,\n workflowId: process.env.LOOPMAN_WORKFLOW_ID!,\n model: \"openai:gpt-4o-mini\",\n systemPrompt: \"You are a helpful assistant that greets people.\",\n category: \"hello-world\",\n additionalTools: [sayHello],\n requireApprovalForTools: [\"say_hello\"],\n debug: true,\n});\n```\n\n### 3. Process with Human Validation\n\n```typescript\nconst result = await agent.processWithHumanValidation({\n input: \"Say hello to Alice\",\n});\n\nconsole.log(\"Agent response:\", result.response);\nif (result.decision) {\n console.log(\"Decision status:\", result.decision.status);\n console.log(\"Human feedback:\", result.decision.feedback);\n}\n```\n\n## Key Features\n\n- **Complete HITL Workflow**: Agent manages the entire validation lifecycle\n- **Automatic Polling**: Waits for human decisions\n- **Feedback Handling**: Processes human feedback and retries if needed\n- **Category Support**: Organize validations by category\n- **Debug Mode**: Verbose logging for development\n\n## Workflow\n\n```\n1. User sends message\n ↓\n2. Agent processes with LLM\n ↓\n3. Agent generates tool call\n ↓\n4. Creates Loopman validation task\n ↓\n5. Polls for human decision\n ↓\n6. If approved → Execute and return result\n If rejected → Process feedback and retry\n If timeout → Handle timeout\n```\n\n## Configuration Options\n\n### requireApprovalForTools\n\nSpecify which tools require validation:\n\n```typescript\nrequireApprovalForTools: [\"say_hello\", \"send_email\"]\n// Only these tools will require human approval\n```\n\n### category\n\nOrganize validations by category:\n\n```typescript\ncategory: \"hello-world\"\n// Helps filter and organize validation tasks\n```\n\n### debug\n\nEnable/disable verbose logging:\n\n```typescript\ndebug: true // Show detailed logs\ndebug: false // Production mode\n```\n\n## Response Structure\n\nThe `processWithHumanValidation` method returns:\n\n```typescript\n{\n response: string, // Final agent response\n decision?: {\n status: \"APPROVED\" | \"REJECTED\" | \"NEEDS_CHANGES\",\n feedback?: string, // Human feedback if provided\n createdAt: Date,\n updatedAt: Date,\n }\n}\n```\n\n## Learn More\n\n- [Loopman Agent Documentation](https://github.com/loopman/loopman-langchain-sdk/blob/main/docs/LOOPMAN_AGENT.md)\n- [LangChain Documentation](https://js.langchain.com/docs)\n- [Loopman Documentation](https://loopman.dev/docs)\n\n"
19
+ }
20
+ }
@@ -0,0 +1,346 @@
1
+ # Examples - Loopman LangChain SDK
2
+
3
+ A comprehensive collection of examples demonstrating LangChain v1.0 agent patterns and Loopman's Human-in-the-Loop (HITL) integration, from basics to production-ready patterns.
4
+
5
+ ## 📚 Structure
6
+
7
+ ```
8
+ examples/
9
+ ├── 1-basics/ # LangChain fundamentals (no Loopman)
10
+ ├── 2-loopman-integration/ # Loopman HITL core features
11
+ ├── 3-real-world-examples/ # Production use cases
12
+ └── 4-advanced-patterns/ # Sophisticated HITL patterns
13
+ ```
14
+
15
+ ---
16
+
17
+ ## 🎓 Learning Path
18
+
19
+ ### For Beginners
20
+ Start with the basics and progress through each level:
21
+
22
+ 1. **[1-basics/](1-basics/README.md)** - Learn LangChain agent fundamentals
23
+ - Simple agents with tools
24
+ - Conversational memory
25
+ - Native HITL middleware
26
+
27
+ 2. **[2-loopman-integration/](2-loopman-integration/README.md)** - Add Loopman HITL
28
+ - Transparent validation
29
+ - Middleware modes
30
+ - MCP integration
31
+
32
+ 3. **[3-real-world-examples/](3-real-world-examples/README.md)** - Apply to real scenarios
33
+ - Task management
34
+ - Data processing
35
+ - Content workflows
36
+
37
+ 4. **[4-advanced-patterns/](4-advanced-patterns/README.md)** - Master advanced techniques
38
+ - Conditional HITL
39
+ - Context-aware validation
40
+ - Risk-based approval
41
+
42
+ ### For Experienced Developers
43
+ Jump directly to relevant sections:
44
+
45
+ - **Need HITL fast?** → [2-loopman-integration/01-middleware-basic.ts](2-loopman-integration/01-middleware-basic.ts)
46
+ - **Building a workflow?** → [3-real-world-examples/](3-real-world-examples/README.md)
47
+ - **Need conditional approval?** → [4-advanced-patterns/conditional-hitl.ts](4-advanced-patterns/conditional-hitl.ts)
48
+ - **Want the complete agent API?** → [2-loopman-integration/03-loopman-agent.ts](2-loopman-integration/03-loopman-agent.ts)
49
+ - **Review LangChain basics** → [1-basics/](1-basics/README.md)
50
+
51
+ ---
52
+
53
+ ## 🚀 Quick Start
54
+
55
+ ### Prerequisites
56
+
57
+ ```bash
58
+ # Install dependencies
59
+ npm install
60
+
61
+ # Configure environment
62
+ cp ../env.example .env
63
+ # Edit .env and add your API keys
64
+ ```
65
+
66
+ ### Run Your First Example
67
+
68
+ ```bash
69
+ # 1. Basic agent (no HITL)
70
+ npx tsx 1-basics/01-simple-agent.ts
71
+
72
+ # 2. Loopman transparent HITL
73
+ npx tsx 2-loopman-integration/01-middleware-basic.ts
74
+
75
+ # 3. Real-world use case
76
+ npx tsx 3-real-world-examples/task-management/task-approval.ts
77
+
78
+ # 4. Advanced pattern
79
+ npx tsx 4-advanced-patterns/conditional-hitl.ts
80
+ ```
81
+
82
+ ---
83
+
84
+ ## 📂 Detailed Breakdown
85
+
86
+ ### 1️⃣ Basics - LangChain Fundamentals
87
+ **Path:** `1-basics/`
88
+
89
+ Learn core LangChain concepts without Loopman complexity:
90
+
91
+ | Example | Concept | Key Learning |
92
+ |---------|---------|--------------|
93
+ | `01-simple-agent.ts` | Basic agent | Tools, memory, invoke |
94
+ | `02-memory-and-context.ts` | Conversational memory | Checkpointers, thread IDs, context |
95
+ | `03-langchain-native-hitl.ts` | Native HITL | Interruptions, Command.resume() |
96
+
97
+ **Who should start here:**
98
+ - New to LangChain v1.0
99
+ - Want to understand agent fundamentals
100
+ - Need reference for vanilla LangChain patterns
101
+
102
+ [👉 Full documentation](1-basics/README.md)
103
+
104
+ ---
105
+
106
+ ### 2️⃣ Loopman Integration - Core HITL Features
107
+ **Path:** `2-loopman-integration/`
108
+
109
+ Loopman's transparent HITL middleware and agent patterns:
110
+
111
+ | Example | Concept | Key Feature |
112
+ |---------|---------|-------------|
113
+ | `01-middleware-basic.ts` | Transparent HITL | No interrupt handling needed! |
114
+ | `02-middleware-modes.ts` | Three operation modes | tool-validation, prompt-enhancement, full |
115
+ | `03-loopman-agent.ts` | High-level Loopman API | All-in-one solution (recommended) |
116
+
117
+ **Key differences from native HITL:**
118
+
119
+ ```typescript
120
+ // ❌ Native LangChain - manual interrupt handling
121
+ if (result.__interrupt__) {
122
+ const decision = await waitForHuman();
123
+ await agent.invoke(new Command({ resume: decision }));
124
+ }
125
+
126
+ // ✅ Loopman - completely transparent!
127
+ const result = await agent.invoke(...);
128
+ // Human validation already handled ✨
129
+ ```
130
+
131
+ [👉 Full documentation](2-loopman-integration/README.md)
132
+
133
+ ---
134
+
135
+ ### 3️⃣ Real-World Examples - Production Use Cases
136
+ **Path:** `3-real-world-examples/`
137
+
138
+ Complete, domain-specific implementations:
139
+
140
+ | Domain | Example | Scenario |
141
+ |--------|---------|----------|
142
+ | **Task Management** | `task-management/task-approval.ts` | CRUD ops with selective approval |
143
+ | **Data Processing** | `data-processing/data-validation.ts` | ETL with quality checks and fixes |
144
+ | **Content Workflow** | `content-workflow/content-review.ts` | Draft/publish with editorial review |
145
+
146
+ **Pattern:** Safe operations auto-approved, destructive operations require approval
147
+
148
+ ```typescript
149
+ interruptOn: {
150
+ read_data: false, // ✅ Auto-approved
151
+ create_draft: false, // ✅ Auto-approved
152
+ publish: true, // ⚠️ Requires approval
153
+ delete: true // ⚠️ Requires approval
154
+ }
155
+ ```
156
+
157
+ [👉 Full documentation](3-real-world-examples/README.md)
158
+
159
+ ---
160
+
161
+ ### 4️⃣ Advanced Patterns - Sophisticated HITL
162
+ **Path:** `4-advanced-patterns/`
163
+
164
+ Context-aware, intelligent validation:
165
+
166
+ | Pattern | Example | Use Case |
167
+ |---------|---------|----------|
168
+ | **Conditional HITL** | `conditional-hitl.ts` | Amount-based, risk-based, time-based rules |
169
+
170
+ **Example:** Auto-approve small payments, require approval for large ones
171
+
172
+ ```typescript
173
+ const needsApproval =
174
+ amount > userApprovalLimit ||
175
+ isHighRiskCountry(country) ||
176
+ !isBusinessHours();
177
+ ```
178
+
179
+ [👉 Full documentation](4-advanced-patterns/README.md)
180
+
181
+ ---
182
+
183
+ ## 🔧 Environment Configuration
184
+
185
+ Create a `.env` file in the examples directory:
186
+
187
+ ```env
188
+ # Required
189
+ OPENAI_API_KEY=sk-your-openai-api-key
190
+
191
+ # Optional (for Loopman examples)
192
+ LOOPMAN_API_KEY=your-loopman-api-key
193
+ LOOPMAN_CHANNEL_ID=your-channel-id
194
+ ```
195
+
196
+ ---
197
+
198
+ ## 💡 Common Patterns
199
+
200
+ ### Pattern 1: Safe vs. Sensitive Operations
201
+
202
+ Categorize operations by risk level:
203
+
204
+ ```typescript
205
+ // ✅ Always safe - read operations
206
+ list_items: false
207
+ get_item: false
208
+ analyze_data: false
209
+
210
+ // ✅ Usually safe - create/update
211
+ create_draft: false
212
+ update_task: false
213
+
214
+ // ⚠️ Requires approval - destructive/public
215
+ delete_item: true
216
+ publish_content: true
217
+ send_email: true
218
+ bulk_operations: true
219
+ ```
220
+
221
+ ### Pattern 2: Transparent HITL with Loopman
222
+
223
+ Add middleware and forget about interruptions:
224
+
225
+ ```typescript
226
+ const agent = createAgent({
227
+ model: "openai:gpt-4o-mini",
228
+ tools: [myTool],
229
+ middleware: [
230
+ loopmanMiddleware({
231
+ apiKey: process.env.LOOPMAN_API_KEY!,
232
+ workflowId: "my-workflow",
233
+ interruptOn: { my_tool: true },
234
+ }),
235
+ ],
236
+ });
237
+
238
+ // Just invoke - HITL happens automatically!
239
+ const result = await agent.invoke({ messages: [...] }, config);
240
+ ```
241
+
242
+ ### Pattern 3: Auto-Retry on Feedback
243
+
244
+ Use `invokeWithRetry()` for automatic retry on human corrections:
245
+
246
+ ```typescript
247
+ import { invokeWithRetry } from "../src/loopman-agent-wrapper";
248
+
249
+ const result = await invokeWithRetry(
250
+ agent,
251
+ { messages: [...] },
252
+ config,
253
+ { maxRetries: 5, debug: true }
254
+ );
255
+ // Handles NEEDS_CHANGES and auto-retries ✨
256
+ ```
257
+
258
+ ### Pattern 4: Conditional Approval
259
+
260
+ Tools decide if approval needed based on context:
261
+
262
+ ```typescript
263
+ const myTool = tool(({ amount, user }) => {
264
+ if (amount > user.approvalLimit) {
265
+ // Create pending task for approval
266
+ return createPendingTask(amount);
267
+ }
268
+ // Auto-approve
269
+ return executeImmediately(amount);
270
+ });
271
+ ```
272
+
273
+ ---
274
+
275
+ ## 🎯 Choose Your Path
276
+
277
+ ### I want to learn LangChain basics
278
+ 👉 Start with [1-basics/01-simple-agent.ts](1-basics/01-simple-agent.ts)
279
+
280
+ ### I need to add HITL to my agent
281
+ 👉 Jump to [2-loopman-integration/01-middleware-basic.ts](2-loopman-integration/01-middleware-basic.ts)
282
+
283
+ ### I'm building a specific feature
284
+ 👉 Browse [3-real-world-examples/](3-real-world-examples/README.md) for your domain
285
+
286
+ ### I need advanced validation logic
287
+ 👉 Study [4-advanced-patterns/conditional-hitl.ts](4-advanced-patterns/conditional-hitl.ts)
288
+
289
+ ---
290
+
291
+ ## 📖 Additional Resources
292
+
293
+ ### Documentation
294
+ - [Main README](../README.md) - SDK overview and API reference
295
+ - [Double Validation Layer](../docs/DOUBLE_VALIDATION_LAYER.md)
296
+ - [Auto-Correction with Feedback](../docs/AUTO_CORRECTION_WITH_FEEDBACK.md)
297
+ - [Middleware Modes](../docs/TOOL_VALIDATION_MODE.md)
298
+ - [Loopman Agent Guide](../docs/LOOPMAN_AGENT.md)
299
+
300
+ ### LangChain Resources
301
+ - [LangChain v1.0 Quickstart](https://docs.langchain.com/oss/javascript/langchain/quickstart)
302
+ - [Human-in-the-Loop Guide](https://docs.langchain.com/oss/javascript/langchain/human-in-the-loop)
303
+ - [Tools Documentation](https://docs.langchain.com/oss/javascript/langchain/tools)
304
+
305
+ ---
306
+
307
+ ## 🛠️ Development Tips
308
+
309
+ ### Debugging
310
+ - Enable `debug: true` in middleware config
311
+ - Use VSCode debug configurations (`.vscode/launch.json`)
312
+ - Check console output for detailed logs
313
+
314
+ ### Testing
315
+ - Use short timeouts during development (30s instead of 5min)
316
+ - Mock API responses to avoid rate limits
317
+ - Test with different `thread_id` values for isolated conversations
318
+
319
+ ### Production
320
+ - Replace `MemorySaver` with `PostgresSaver` or `RedisSaver`
321
+ - Set appropriate timeouts based on expected human response times
322
+ - Monitor approval rates and tune thresholds
323
+
324
+ ---
325
+
326
+ ## 🤝 Contributing
327
+
328
+ Found a bug or have an improvement?
329
+
330
+ 1. Check existing examples for similar patterns
331
+ 2. Follow the established structure (1-basics, 2-loopman, etc.)
332
+ 3. Add comprehensive comments and documentation
333
+ 4. Update this README with your example
334
+ 5. Test thoroughly before submitting
335
+
336
+ ---
337
+
338
+ ## 📄 License
339
+
340
+ MPL-2.0 - See [LICENSE](../LICENSE) for details
341
+
342
+ ---
343
+
344
+ **Happy coding! 🚀**
345
+
346
+ For questions or support, check the [main documentation](../README.md) or open an issue on GitHub.
@@ -0,0 +1,285 @@
1
+ # LangChain SDK Templates
2
+
3
+ This directory contains working example projects that serve as templates for users integrating Loopman with their LangChain applications.
4
+
5
+ ## Overview
6
+
7
+ These are **not** template files - they are **real, functional examples** that:
8
+ - Can be run independently (`npm install && npm start`)
9
+ - Are tested to ensure they work correctly
10
+ - Are exported during build for use by the web application
11
+ - Serve as a single source of truth for starter projects
12
+
13
+ ## Available Templates
14
+
15
+ ### `langgraph-hello-world/`
16
+
17
+ A complete **LangGraph** integration example demonstrating:
18
+ - Context Enrichment mode (loading guidelines and decision history)
19
+ - Validation with human-in-the-loop
20
+ - Tool execution after approval
21
+ - Retry mechanism for rejected actions
22
+
23
+ **Best for:** Complex stateful workflows with conditional routing
24
+
25
+ **How to run:**
26
+ ```bash
27
+ cd langgraph-hello-world
28
+ cp .env.example .env
29
+ # Edit .env with your API keys
30
+ npm install
31
+ npm start
32
+ ```
33
+
34
+ ### `langchain-tool-validation/`
35
+
36
+ A **LangChain middleware** integration demonstrating:
37
+ - Selective tool validation (only specific tools require approval)
38
+ - Automatic interception of tool calls
39
+ - Lightweight integration with existing agents
40
+ - Stateful conversation with checkpointer
41
+
42
+ **Best for:** Adding validation to existing LangChain agents
43
+
44
+ **How to run:**
45
+ ```bash
46
+ cd langchain-tool-validation
47
+ cp .env.example .env
48
+ # Edit .env with your API keys
49
+ npm install
50
+ npm start
51
+ ```
52
+
53
+ ### `langchain-full-review/`
54
+
55
+ A **Loopman Agent** integration demonstrating:
56
+ - Complete HITL (Human-In-The-Loop) workflow
57
+ - Automatic polling for human decisions
58
+ - Feedback handling and retry mechanism
59
+ - Full lifecycle management
60
+
61
+ **Best for:** Complete turnkey HITL solution
62
+
63
+ **How to run:**
64
+ ```bash
65
+ cd langchain-full-review
66
+ cp .env.example .env
67
+ # Edit .env with your API keys
68
+ npm install
69
+ npm start
70
+ ```
71
+
72
+ ## How Templates Work
73
+
74
+ ### 1. Development & Testing
75
+
76
+ Templates are maintained as working examples in this directory. When you update a template:
77
+
78
+ ```bash
79
+ cd langgraph-hello-world
80
+ # Make changes to index.ts, README.md, etc.
81
+ npm start # Test your changes
82
+ ```
83
+
84
+ ### 2. Export to JSON
85
+
86
+ During SDK build, templates are exported to `dist/templates.json`:
87
+
88
+ ```bash
89
+ npm run build
90
+ # Runs: tsc && node scripts/export-templates.js
91
+ ```
92
+
93
+ This creates a JSON file with all template contents:
94
+
95
+ ```json
96
+ {
97
+ "langgraph-hello-world": {
98
+ "index.ts": "... full file contents ...",
99
+ "package.json": "... full file contents ...",
100
+ ...
101
+ }
102
+ }
103
+ ```
104
+
105
+ ### 3. Web Application Usage
106
+
107
+ The web application imports this JSON and generates customized starter projects:
108
+
109
+ ```typescript
110
+ import sdkTemplates from './sdk-templates.json';
111
+
112
+ // Customize template with user's workflow ID and API key
113
+ const files = processTemplate(sdkTemplates['langgraph-hello-world'], {
114
+ workflowId: 'user-workflow-123',
115
+ apiKey: 'user-api-key-xyz',
116
+ });
117
+
118
+ // Generate downloadable zip
119
+ createZipFromFiles(files);
120
+ ```
121
+
122
+ ## Adding a New Template
123
+
124
+ 1. **Create the template directory:**
125
+ ```bash
126
+ mkdir -p examples/templates/my-new-template
127
+ cd examples/templates/my-new-template
128
+ ```
129
+
130
+ 2. **Add required files:**
131
+ - `index.ts` - Main code example
132
+ - `package.json` - Dependencies and scripts
133
+ - `tsconfig.json` - TypeScript configuration
134
+ - `README.md` - Usage instructions
135
+ - `.env.example` - Environment variable template
136
+
137
+ 3. **Test it works:**
138
+ ```bash
139
+ npm install
140
+ npm start
141
+ ```
142
+
143
+ 4. **Update export script:**
144
+ Edit `scripts/export-templates.js` to include your new template.
145
+
146
+ 5. **Build and commit:**
147
+ ```bash
148
+ cd ../../../
149
+ npm run build
150
+ git add examples/templates/my-new-template
151
+ git add dist/templates.json
152
+ git commit -m "feat(templates): add my-new-template example"
153
+ ```
154
+
155
+ ## Design Principles
156
+
157
+ ### ✅ DO
158
+
159
+ - **Use environment variables** for dynamic values
160
+ ```typescript
161
+ workflowId: process.env.LOOPMAN_WORKFLOW_ID!
162
+ ```
163
+
164
+ - **Keep examples simple** and focused on one concept
165
+
166
+ - **Include detailed comments** explaining key concepts
167
+
168
+ - **Test before committing** - ensure it runs successfully
169
+
170
+ - **Document prerequisites** in the template's README
171
+
172
+ ### ❌ DON'T
173
+
174
+ - **Use template placeholders** in the code
175
+ ```typescript
176
+ // ❌ Bad
177
+ workflowId: "{{WORKFLOW_ID}}"
178
+
179
+ // ✅ Good
180
+ workflowId: process.env.LOOPMAN_WORKFLOW_ID!
181
+ ```
182
+
183
+ - **Add non-working code** - everything should be executable
184
+
185
+ - **Hardcode credentials** - always use .env files
186
+
187
+ - **Include node_modules** or build artifacts
188
+
189
+ ## Template Structure
190
+
191
+ Each template should follow this structure:
192
+
193
+ ```
194
+ template-name/
195
+ ├── index.ts # Main entry point
196
+ ├── package.json # NPM dependencies and scripts
197
+ ├── tsconfig.json # TypeScript configuration
198
+ ├── README.md # Template-specific documentation
199
+ └── .env.example # Environment variables (no secrets!)
200
+ ```
201
+
202
+ ### Required Scripts in package.json
203
+
204
+ ```json
205
+ {
206
+ "scripts": {
207
+ "start": "tsx index.ts",
208
+ "dev": "tsx index.ts",
209
+ "build": "tsc",
210
+ "run": "node dist/index.js"
211
+ }
212
+ }
213
+ ```
214
+
215
+ ### Required Environment Variables
216
+
217
+ At minimum, include:
218
+
219
+ ```bash
220
+ OPENAI_API_KEY=your-openai-api-key-here
221
+ LOOPMAN_API_KEY=your-loopman-api-key-here
222
+ LOOPMAN_WORKFLOW_ID=your-workflow-id-here
223
+ ```
224
+
225
+ ## Updating Templates
226
+
227
+ When you update a template:
228
+
229
+ 1. **Make changes** in the template directory
230
+ 2. **Test locally** to ensure it still works
231
+ 3. **Build SDK** to regenerate `templates.json`
232
+ 4. **Commit both** the template files and `dist/templates.json`
233
+ 5. **Release SDK** to make updates available to web app
234
+
235
+ ## Testing
236
+
237
+ ### Manual Testing
238
+
239
+ ```bash
240
+ cd examples/templates/langgraph-hello-world
241
+ npm install
242
+ npm start
243
+ ```
244
+
245
+ ### Automated Testing (Future)
246
+
247
+ We plan to add:
248
+ - E2E tests for each template
249
+ - Validation of template structure
250
+ - Dependency version checks
251
+ - README completeness checks
252
+
253
+ ## Publishing
254
+
255
+ Templates are included in the npm package:
256
+
257
+ ```json
258
+ {
259
+ "files": [
260
+ "dist",
261
+ "examples/templates",
262
+ "README.md",
263
+ "LICENSE"
264
+ ]
265
+ }
266
+ ```
267
+
268
+ This ensures users can:
269
+ - Reference the source code
270
+ - Copy templates directly if needed
271
+ - See the latest working examples
272
+
273
+ ## Related Documentation
274
+
275
+ - [Templates System Guide](../../docs/TEMPLATES.md) - Detailed architecture
276
+ - [LangGraph Integration](../../docs/LANGGRAPH_INTEGRATION.md) - Integration patterns
277
+ - [SDK README](../../README.md) - Main documentation
278
+
279
+ ## Questions?
280
+
281
+ If you have questions about templates:
282
+ - Check [Templates System Guide](../../docs/TEMPLATES.md)
283
+ - Open an issue on GitHub
284
+ - Contact the Loopman team
285
+
@@ -0,0 +1,3 @@
1
+ OPENAI_API_KEY=your-openai-api-key-here
2
+ LOOPMAN_API_KEY=your-loopman-api-key-here
3
+ LOOPMAN_WORKFLOW_ID=your-workflow-id-here