DocumentationAgent Action Firewall

LangChain Integration

Add security policies to LangChain agents with Agent Action Firewall.

Overview

Wrap LangChain tools with firewall protection to ensure all agent actions are validated against your security policies.

Tool Wrapper

TypeScript
import { Tool, DynamicTool } from 'langchain/tools';
import { AgentFirewallClient } from '@agent-action-firewall/sdk';

const firewall = new AgentFirewallClient({
  baseUrl: process.env.AGENT_FIREWALL_BASE_URL!,
  apiKey: process.env.AGENT_FIREWALL_API_KEY!,
  agentId: 'langchain-agent',
});

// Wrap any LangChain tool with firewall protection
function wrapToolWithFirewall(tool: Tool): Tool {
  const originalCall = tool._call.bind(tool);

  tool._call = async (input: string) => {
    // Submit to firewall
    const response = await firewall.submitAction({
      tool: tool.name,
      operation: 'execute',
      params: { input },
    });

    if (response.status === 'denied') {
      return `Action denied: ${response.decision?.reason}`;
    }

    if (response.status === 'pending_approval') {
      const approved = await firewall.waitForApproval(response.id);
      if (approved.status !== 'allowed') {
        return 'Action not approved';
      }
    }

    // Execute original tool
    return originalCall(input);
  };

  return tool;
}

Custom Firewall Tool

TypeScript
import { DynamicTool } from 'langchain/tools';

// Create a firewall-aware tool
const secureDatabaseTool = new DynamicTool({
  name: 'secure_database_query',
  description: 'Query the database with security validation',
  func: async (query: string) => {
    const response = await firewall.submitAction({
      tool: 'database',
      operation: 'query',
      params: { query },
    });

    switch (response.status) {
      case 'allowed':
        return executeQuery(query);
      case 'pending_approval':
        const result = await firewall.waitForApproval(response.id);
        return result.status === 'allowed'
          ? executeQuery(query)
          : 'Query not approved';
      case 'denied':
        return `Query denied: ${response.decision?.reason}`;
    }
  },
});

Agent Executor Integration

TypeScript
import { ChatOpenAI } from 'langchain/chat_models/openai';
import { initializeAgentExecutorWithOptions } from 'langchain/agents';

// Wrap all tools with firewall
const protectedTools = tools.map(wrapToolWithFirewall);

// Create agent with protected tools
const agent = await initializeAgentExecutorWithOptions(
  protectedTools,
  new ChatOpenAI({ modelName: 'gpt-4' }),
  {
    agentType: 'openai-functions',
    verbose: true,
  }
);

// Run agent - all tool calls validated by firewall
const result = await agent.run('Update customer record for user 123');

ReAct Agent Pattern

TypeScript
import { ReActAgent } from 'langchain/agents';

class FirewallReActAgent extends ReActAgent {
  async executeAction(action: string, actionInput: string) {
    // Intercept action execution
    const response = await firewall.submitAction({
      tool: action,
      operation: 'execute',
      params: { input: actionInput },
    });

    if (response.status !== 'allowed') {
      if (response.status === 'pending_approval') {
        const approved = await firewall.waitForApproval(response.id);
        if (approved.status !== 'allowed') {
          return 'Action requires approval that was not granted';
        }
      } else {
        return `Action blocked: ${response.decision?.reason}`;
      }
    }

    return super.executeAction(action, actionInput);
  }
}

Callback Integration

Use LangChain callbacks to log all actions to the firewall:

TypeScript
import { BaseCallbackHandler } from 'langchain/callbacks';

class FirewallCallback extends BaseCallbackHandler {
  name = 'FirewallCallback';

  async handleToolStart(
    tool: { name: string },
    input: string
  ) {
    console.log(`Tool ${tool.name} starting with input: ${input}`);
    // Pre-validate with firewall if needed
  }

  async handleToolEnd(output: string) {
    console.log(`Tool completed with output: ${output}`);
    // Log completion to audit trail
  }
}

// Use in agent
const agent = await initializeAgentExecutorWithOptions(
  tools,
  llm,
  { callbacks: [new FirewallCallback()] }
);

Next Steps