AI Agents: Mastering 3 Essential Patterns (Reflexive). Part 3 of 3

Published: (January 4, 2026 at 05:21 PM EST)
5 min read
Source: Dev.to

Source: Dev.to

The code for these patterns is available on GitHub.
Repo

The Reflexive Pattern – When There’s No Time to Think

In Article 2 (ReAct) we turned our agent into a meticulous “Investigator.”
The agent would sit down, analyze, plan, Google‑search, and then answer.
That works great for complex tasks, but it has a huge bug in the real world: it’s slow.

Think of it this way: if you touch a hot stove, your brain doesn’t start a debate:

“Hmm, I detect a temperature of 200 °C, this will cause protein denaturation, I suggest moving the biceps…”

Haha, no. Your spinal cord takes command and pulls your hand away before you even feel the pain.

The Reflexive Pattern (sometimes called Semantic Router) is exactly that: the “reflex action” of artificial intelligence.

Reflexive Pattern illustration

The Use Case: The Security Sentinel

Imagine a system that reads your server logs in real‑time. Among thousands of normal visits, a malicious request appears:

GET /search?q=' OR 1=1;--

If you use a ReAct agent here, you’re dead. The agent would think:

“Wow, an unusual pattern. I’ll use the search tool to understand what ‘SQL Injection’ is. Ah, I see it’s dangerous. Proceeding to block.”

By the time it finishes “thinking” (10‑15 seconds), your database is already leaked on the Dark Web.

Here is where the Reflexive Agent shines

StimulusReflexTime
Sees the malicious stringExecutes block_ip()sub‑second

Example Reflex Actions (Python)

def block_ip(ip: str, reason: str) -> str:
    """Blocks a malicious IP address immediately."""
    msg = f"⛔ BLOCKING IP [{ip}]: {reason}"
    logger.warning(msg)
    return msg

def escalate_to_admin(log_id: str, severity: str) -> str:
    """Escalates a critical issue to a human administrator."""
    msg = f"⚠️ ADMIN ALERT: Log [{log_id}] - Severity [{severity}]"
    logger.critical(msg)
    return msg

def log_normal_traffic(source: str) -> str:
    """Registers legitimate and safe traffic."""
    msg = f"✅ Normal traffic from [{source}]"
    logger.info(msg)
    return msg
# ----------------------------------------------------------------------
# 4. Agno Agent Configuration (Reflexive Pattern)
# ----------------------------------------------------------------------
model_id = os.getenv("BASE_MODEL", "gpt-4o-mini")

agent = Agent(
    model=OpenAIChat(id=model_id),
    tools=[block_ip, escalate_to_admin, log_normal_traffic],
    instructions=[
        "You are an automated security system (Reflexive Pattern).",
        "Your job is to classify incoming logs and execute the corresponding tool IMMEDIATELY.",
        "Action rules:",
        "- If you detect SQL Injection, XSS, or known attacks → use `block_ip`.",
        "- If you detect server errors (500), service downs, or timeouts → use `escalate_to_admin`.",
        "- If traffic seems legitimate, successful login, or normal navigation → use `log_normal_traffic`.",
        "DO NOT explain your decision. DO NOT greet. Just execute the tool directly in response to the stimulus.",
        "Process the log and terminate execution."
    ]
)
# ----------------------------------------------------------------------
# 5. Flow Simulation (The Stream)
# ----------------------------------------------------------------------
def main():
    logger.info("Starting Security Sentinel Agent (Reflexive)...")
    print("--- Security Sentinel - Reflexive Pattern ---")

    # Simulated logs
    logs = [
        "User 'admin' logged in successfully from 192.168.1.10",
        "GET /search?q=' OR 1=1;-- (SQL Injection attempt from 203.0.113.5)",
        "Service 'PaymentGateway' timed out after 3000ms (Error 500)",
        "User 'jdoe' updated profile picture",
        "alert('hacked') sent via form from 88.22.11.44",
        "DB_ERROR: Connection pool exhausted (LogID: 4452)",
        "Bot crawler identified: Googlebot/2.1 from 66.249.66.1",
        "Multiple failed login attempts for user 'sys'..."
        # ... additional logs could be added here
    ]

    for entry in logs:
        # The agent receives each log entry as a stimulus and reacts instantly.
        response = agent.run(entry)
        print(response)

if __name__ == "__main__":
    main()

The code above demonstrates a purely reflexive workflow: the agent receives a log line, matches it against the hard‑coded rules, and immediately triggers the appropriate tool—no deliberation, no loops, sub‑second response.

def main():
    logs = [
        "admin' from 45.33.22.11",
        "HealthCheck: All systems operational - latency 12ms",
        "Unauthorized access attempt to /etc/passwd from 172.16.0.50"
    ]

    print(f"\nProcessing {len(logs)} logs in the 'stream'...\n")

    for i, log_entry in enumerate(logs, 1):
        try:
            print(f"[{i}] Stimulus: {log_entry}")
            logger.info(f"Processing log {i}: {log_entry}")

            # In reflexive mode, we expect the agent to execute the tool immediately.
            # We use show_tool_calls=True to demonstrate the action.
            agent.print_response(log_entry, show_tool_calls=True)
            print("-" * 50)

        except Exception as e:
            logger.error(f"Error processing log {i}: {str(e)}")
            print(f"An error occurred in event {i}: {e}")

if __name__ == "__main__":
    main()

Restrictive Instructions (Negative Constraints)

In the system prompt (instructions), we explicitly forbid the agent to think or chat:

  • DO NOT explain
  • Just execute

The agent is programmed solely to fire tools.

Direct Mapping

There are no feedback loops. The flow is linear:

Incoming Log → Classification → Tool Execution

Model Selection

  • gpt-4o-mini is configured.
  • Using a smaller, faster model prioritizes latency and processing volume.

Why This Pattern Is Cool (Pros)

  • Absurd Speed (Minimal Latency): By not generating “thought” text, the response is almost instantaneous.
  • High Throughput: Perfect for processing thousands of emails, live chats, or monitoring alerts per minute.
  • Predictable (Determinism): Removing “creativity” makes the agent behave like a classic script—given X, it always does Y.
  • Cost‑Effective: Fewer output tokens and smaller models = lower API bills.

Where It Fails (Cons)

  • Goldfish Memory (Contextual Blindness): The agent reacts only to the current input. If an attack is split into three steps over 10 minutes, it won’t connect the dots.
  • Stubborn (Rigidity): Ambiguous inputs not covered by its rules may cause failures or incorrect classifications.
  • Black Box: Unlike ReAct, there are no “Thought” logs to explain why an action was taken.

Comparison for Developers

FeatureReAct (Level 2)Reflexive (Level 3)
AnalogySherlock HolmesA Nightclub Bouncer
PriorityQuality and ReasoningSpeed and Volume
LoopYes (Think‑Act‑Observe)No (Fire and Forget)
Ideal ModelTop Models (GPT‑4o, Claude)Light Models (Mini, Haiku)

Tips from the Trenches

1. Beware the “Ban Hammer”

Since this agent shoots first and asks questions later, false positives are common.
Advice: Make the action flag_for_review() instead of delete_account() unless you are 100 % sure.

2. Be Strict with the Prompt (Negative Constraints)

  • Bad prompt: “Classify this text.”
  • Good prompt: “Classify this text. DO NOT explain your reason. DO NOT generate introductory text. Only return the JSON.”

3. The Hybrid Architecture

The Reflexive pattern is the “Infantry.” Deploy it on the front line to filter out ~80 % of easy noise.
If it encounters something it doesn’t understand or is ambiguous, escalate the ticket to a ReAct agent (smarter and more expensive) for deeper investigation. This yields the best of both worlds.

Happy Coding! 🤖

Back to Blog

Related posts

Read more »

The RGB LED Sidequest 💡

markdown !Jennifer Davishttps://media2.dev.to/dynamic/image/width=50,height=50,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%...

Mendex: Why I Build

Introduction Hello everyone. Today I want to share who I am, what I'm building, and why. Early Career and Burnout I started my career as a developer 17 years a...