File size: 3,841 Bytes
644f326
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import re
import sys
from langchain_core.messages import AIMessage
from langchain_core.runnables import RunnableConfig
from langsmith import traceable

from src.agents.models.state import AgentState
from src.agents.models.structure import GuardrailStructure
from src.agents.prompts import GUARDRAIL_PROMPT
from src.core.logger import logger
from src.service.llm_provider.groq import get_llm

observe = traceable

INJECTION_PATTERNS = [
    r"print\s+(the\s+)?exact\s+system\s+prompt",
    r"system\s+prompt\s+and\s+internal\s+instructions",
    r"complete\s+configuration\s+and\s+initial\s+setup\s+instructions",
    r"ignore\s+(all\s+)?previous\s+instructions",
    r"switch\s+to\s+raw\s+retrieval\s+mode",
    r"print\s+every\s+context\s+chunk",
    r"you\s+are\s+now\s+metabot",
    r"bypass\s+(all\s+)?instructions",
]


@observe(name="guardrail_node", run_type="chain")
async def guardrail_node(state: AgentState, config: RunnableConfig | None = None) -> dict:
    """Validate user input against prompt injection, safety violations, and domain scope."""
    user_message = (state.get("user_message") or "").strip()
    lowered = user_message.lower()

    with logger.span("Guardrail node execution", user_message=user_message):
        logger.info("Executing input guardrails check", user_message=user_message)

        # 1. Fast regex heuristics for explicit injection attacks
        for pattern in INJECTION_PATTERNS:
            if re.search(pattern, lowered):
                reason = "I cannot fulfill requests that attempt to reveal system prompts, internal guidelines, or raw context data."
                logger.warning("Guardrail blocked prompt injection attempt via heuristics", pattern=pattern)
                return {
                    "is_blocked": True,
                    "block_reason": reason,
                }

        # 2. LLM classifier check for semantic scope, indirect injection, and toxicity
        try:
            model = (config or {}).get("configurable", {}).get("model")
            llm = get_llm(model=model)
            chain = GUARDRAIL_PROMPT | llm.with_structured_output(GuardrailStructure)

            res: GuardrailStructure = await chain.ainvoke({"user_message": user_message})

            if not res.is_allowed:
                reason = res.refusal_reason or (
                    "I am specialized in DevOps and cloud engineering. "
                    "I cannot assist with queries outside this domain or violating safety policies."
                )
                logger.warning(
                    "Guardrail blocked query",
                    violation_type=res.violation_type,
                    refusal_reason=reason,
                )
                return {
                    "is_blocked": True,
                    "block_reason": reason,
                }

            logger.info("Guardrail check passed: query is safe and in-scope")
            return {
                "is_blocked": False,
                "block_reason": None,
            }

        except Exception as e:
            logger.error("Guardrail LLM check error, allowing request through as fallback", error=str(e))
            return {
                "is_blocked": False,
                "block_reason": None,
            }


@observe(name="blocked_responder_node", run_type="chain")
async def blocked_responder_node(state: AgentState, config: RunnableConfig | None = None) -> dict:
    """Respond when an input is blocked by the guardrail."""
    reason = state.get("block_reason") or (
        "I cannot fulfill this request as it is outside the supported DevOps domain "
        "or violates safety policies."
    )
    logger.info("Blocked responder executing with refusal reason", reason=reason)
    return {
        "messages": [AIMessage(content=reason)],
        "ai_response": reason,
    }