Skip to main content
가드레일은 에이전트 실행의 주요 지점에서 콘텐츠를 검증하고 필터링하여 안전하고 규정을 준수하는 AI 애플리케이션을 구축할 수 있도록 지원합니다. 민감한 정보를 감지하고, 콘텐츠 정책을 시행하며, 출력을 검증하고, 문제가 발생하기 전에 안전하지 않은 동작을 방지할 수 있습니다. 일반적인 사용 사례는 다음과 같습니다:
  • PII(개인 식별 정보) 유출 방지
  • 프롬프트 인젝션 공격 탐지 및 차단
  • 부적절하거나 유해한 콘텐츠 차단
  • 비즈니스 규칙 및 규정 준수 요구사항 시행
  • 출력 품질 및 정확성 검증
미들웨어를 사용하여 전략적 지점에서 실행을 가로채는 방식으로 가드레일을 구현할 수 있습니다. 에이전트가 시작되기 전, 완료된 후, 또는 모델 및 도구 호출 주변에 적용할 수 있습니다.
미들웨어 흐름 다이어그램
가드레일은 두 가지 상호 보완적인 방식으로 구현할 수 있습니다:

결정론적 가드레일

정규식 패턴, 키워드 매칭 또는 명시적 검사와 같은 규칙 기반 로직을 사용합니다. 빠르고 예측 가능하며 비용 효율적이지만, 미묘한 위반 사항을 놓칠 수 있습니다.

모델 기반 가드레일

LLM 또는 분류기를 사용하여 의미론적 이해를 바탕으로 콘텐츠를 평가합니다. 규칙이 놓치는 미묘한 문제를 포착할 수 있지만, 더 느리고 비용이 많이 듭니다.
LangChain은 내장 가드레일(예: PII 감지, human-in-the-loop)과 두 가지 접근 방식 중 하나를 사용하여 커스텀 가드레일을 구축할 수 있는 유연한 미들웨어 시스템을 모두 제공합니다.

내장 가드레일

PII 감지

LangChain은 대화에서 PII(개인 식별 정보)를 감지하고 처리하기 위한 내장 미들웨어를 제공합니다. 이 미들웨어는 이메일, 신용카드, IP 주소 등과 같은 일반적인 PII 유형을 감지할 수 있습니다. PII 감지 미들웨어는 규정 준수 요구사항이 있는 의료 및 금융 애플리케이션, 로그를 삭제해야 하는 고객 서비스 에이전트, 그리고 일반적으로 민감한 사용자 데이터를 처리하는 모든 애플리케이션에 유용합니다. PII 미들웨어는 감지된 PII를 처리하기 위한 여러 전략을 지원합니다:
전략설명예시
redact[REDACTED_TYPE]으로 교체[REDACTED_EMAIL]
mask부분적으로 가림(예: 마지막 4자리)****-****-****-1234
hash결정론적 해시로 교체a8f5f167...
block감지 시 예외 발생오류 발생
import { createAgent, piiRedactionMiddleware } from "langchain";

const agent = createAgent({
  model: "openai:gpt-4o",
  tools: [customerServiceTool, emailTool],
  middleware: [
    // Redact emails in user input before sending to model
    piiRedactionMiddleware({
      piiType: "email",
      strategy: "redact",
      applyToInput: true,
    }),
    // Mask credit cards in user input
    piiRedactionMiddleware({
      piiType: "credit_card",
      strategy: "mask",
      applyToInput: true,
    }),
    // Block API keys - raise error if detected
    piiRedactionMiddleware({
      piiType: "api_key",
      detector: /sk-[a-zA-Z0-9]{32}/,
      strategy: "block",
      applyToInput: true,
    }),
  ],
});

// 사용자가 PII를 제공하면 전략에 따라 처리됩니다
const result = await agent.invoke({
  messages: [{
    role: "user",
    content: "My email is [email protected] and card is 4532-1234-5678-9010"
  }]
});
내장 PII 유형:
  • email - 이메일 주소
  • credit_card - 신용카드 번호(Luhn 검증됨)
  • ip - IP 주소
  • mac_address - MAC 주소
  • url - URL
구성 옵션:
매개변수설명기본값
piiType감지할 PII 유형(내장 또는 커스텀)필수
strategy감지된 PII를 처리하는 방법("block", "redact", "mask", "hash")"redact"
detector커스텀 감지기 정규식 패턴undefined(내장 사용)
applyToInput모델 호출 전 사용자 메시지 검사true
applyToOutput모델 호출 후 AI 메시지 검사false
applyToToolResults실행 후 도구 결과 메시지 검사false
PII 감지 기능에 대한 전체 세부 정보는 미들웨어 문서를 참조하세요.

Human-in-the-loop

LangChain은 민감한 작업을 실행하기 전에 사람의 승인을 요구하는 내장 미들웨어를 제공합니다. 이는 높은 위험도의 결정에 가장 효과적인 가드레일 중 하나입니다. Human-in-the-loop 미들웨어는 금융 거래 및 이체, 프로덕션 데이터 삭제 또는 수정, 외부 당사자에게 통신 전송, 그리고 상당한 비즈니스 영향을 미치는 모든 작업과 같은 경우에 유용합니다.
import { createAgent, humanInTheLoopMiddleware } from "langchain";
import { MemorySaver, Command } from "@langchain/langgraph";

const agent = createAgent({
  model: "openai:gpt-4o",
  tools: [searchTool, sendEmailTool, deleteDatabaseTool],
  middleware: [
    humanInTheLoopMiddleware({
      interruptOn: {
        // 민감한 작업에 대한 승인 요구
        send_email: { allowAccept: true, allowEdit: true, allowRespond: true },
        delete_database: { allowAccept: true, allowEdit: true, allowRespond: true },
        // 안전한 작업은 자동 승인
        search: false,
      }
    }),
  ],
  checkpointer: new MemorySaver(),
});

// Human-in-the-loop은 지속성을 위해 스레드 ID가 필요합니다
const config = { configurable: { thread_id: "some_id" } };

// 에이전트는 민감한 도구를 실행하기 전에 일시 중지하고 승인을 기다립니다
let result = await agent.invoke(
  { messages: [{ role: "user", content: "Send an email to the team" }] },
  config
);

result = await agent.invoke(
  new Command({ resume: { decisions: [{ type: "approve" }] } }),
  config  // 일시 중지된 대화를 재개하기 위해 동일한 스레드 ID 사용
);
승인 워크플로우 구현에 대한 전체 세부 정보는 human-in-the-loop 문서를 참조하세요.

커스텀 가드레일

더 정교한 가드레일을 위해 에이전트가 실행되기 전이나 후에 실행되는 커스텀 미들웨어를 생성할 수 있습니다. 이를 통해 검증 로직, 콘텐츠 필터링 및 안전 검사를 완전히 제어할 수 있습니다.

Before agent 가드레일

“before agent” 훅을 사용하여 각 호출이 시작될 때 한 번 요청을 검증합니다. 이는 인증, 속도 제한 또는 처리가 시작되기 전에 부적절한 요청을 차단하는 것과 같은 세션 수준 검사에 유용합니다.
import { createMiddleware, AIMessage } from "langchain";

const contentFilterMiddleware = (bannedKeywords: string[]) => {
  const keywords = bannedKeywords.map(kw => kw.toLowerCase());

  return createMiddleware({
    name: "ContentFilterMiddleware",
    beforeAgent: (state) => {
      // 첫 번째 사용자 메시지 가져오기
      if (!state.messages || state.messages.length === 0) {
        return;
      }

      const firstMessage = state.messages[0];
      if (firstMessage._getType() !== "human") {
        return;
      }

      const content = firstMessage.content.toString().toLowerCase();

      // 금지된 키워드 검사
      for (const keyword of keywords) {
        if (content.includes(keyword)) {
          // 처리 전에 실행 차단
          return {
            messages: [
              new AIMessage(
                "부적절한 콘텐츠가 포함된 요청은 처리할 수 없습니다. 요청을 다시 표현해 주세요."
              )
            ],
            jumpTo: "end",
          };
        }
      }

      return;
    },
  });
};

// 커스텀 가드레일 사용
import { createAgent } from "langchain";

const agent = createAgent({
  model: "openai:gpt-4o",
  tools: [searchTool, calculatorTool],
  middleware: [
    contentFilterMiddleware(["hack", "exploit", "malware"]),
  ],
});

// 이 요청은 처리되기 전에 차단됩니다
const result = await agent.invoke({
  messages: [{ role: "user", content: "How do I hack into a database?" }]
});

After agent 가드레일

“after agent” 훅을 사용하여 사용자에게 반환하기 전에 최종 출력을 한 번 검증합니다. 이는 모델 기반 안전 검사, 품질 검증 또는 완전한 에이전트 응답에 대한 최종 규정 준수 스캔에 유용합니다.
import { createMiddleware, AIMessage, initChatModel } from "langchain";

const safetyGuardrailMiddleware = () => {
  const safetyModel = initChatModel("openai:gpt-4o-mini");

  return createMiddleware({
    name: "SafetyGuardrailMiddleware",
    afterAgent: async (state) => {
      // 최종 AI 응답 가져오기
      if (!state.messages || state.messages.length === 0) {
        return;
      }

      const lastMessage = state.messages[state.messages.length - 1];
      if (lastMessage._getType() !== "ai") {
        return;
      }

      // 모델을 사용하여 안전성 평가
      const safetyPrompt = `이 응답이 안전하고 적절한지 평가하세요.
      'SAFE' 또는 'UNSAFE'로만 응답하세요.

      응답: ${lastMessage.content.toString()}`;

      const result = await safetyModel.invoke([
        { role: "user", content: safetyPrompt }
      ]);

      if (result.content.toString().includes("UNSAFE")) {
        return {
          messages: [
            new AIMessage(
              "해당 응답을 제공할 수 없습니다. 요청을 다시 표현해 주세요."
            )
          ],
          jumpTo: "end",
        };
      }

      return;
    },
  });
};

// 안전 가드레일 사용
import { createAgent } from "langchain";

const agent = createAgent({
  model: "openai:gpt-4o",
  tools: [searchTool, calculatorTool],
  middleware: [safetyGuardrailMiddleware()],
});

const result = await agent.invoke({
  messages: [{ role: "user", content: "How do I make explosives?" }]
});

여러 가드레일 결합

미들웨어 배열에 추가하여 여러 가드레일을 쌓을 수 있습니다. 가드레일은 순서대로 실행되어 계층화된 보호를 구축할 수 있습니다:
import { createAgent, piiRedactionMiddleware, humanInTheLoopMiddleware } from "langchain";

const agent = createAgent({
  model: "openai:gpt-4o",
  tools: [searchTool, sendEmailTool],
  middleware: [
    // 레이어 1: 결정론적 입력 필터(before agent)
    contentFilterMiddleware(["hack", "exploit"]),

    // 레이어 2: PII 보호(모델 전후)
    piiRedactionMiddleware({
      piiType: "email",
      strategy: "redact",
      applyToInput: true,
    }),
    piiRedactionMiddleware({
      piiType: "email",
      strategy: "redact",
      applyToOutput: true,
    }),

    // 레이어 3: 민감한 도구에 대한 사람의 승인
    humanInTheLoopMiddleware({
      interruptOn: {
        send_email: { allowAccept: true, allowEdit: true, allowRespond: true },
      }
    }),

    // 레이어 4: 모델 기반 안전 검사(after agent)
    safetyGuardrailMiddleware(),
  ],
});

추가 리소스


Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.
I