Agent Logic Designer Worksheet Agent Logic Designer
Lesson 1: Agentic Theory and Tool Use
Researcher Name
Simulation Date
Architectural Objective
In this lab, you will map the logical flow of a ReAct (Reason + Act) agent. The agent must solve a complex coding task that requires multiple steps: reading a file, analyzing content, writing a fix, and verifying. Your goal is to design the internal "thought" process that keeps the agent on track without human intervention.
Tool definitions
read_file(path): Returns string
write_file(path, content): Returns bool
list_dir(dir): Returns array
bash_exec(cmd): Returns {stdout, stderr}
1. System Prompt Synthesis
Define the core identity and constraints of your agent to prevent "hallucination loops."
2. Logic Flow Visualization
Trace the agent's path for the prompt: "Find the memory leak in metrics.py and fix it."
Observation 0
Task: "Find the memory leak in metrics.py and fix it."
Thought 1
Action 1 (Tool Call)
Observation 1 (Tool Output)
Failure Case: "The Hallucination Loop"
What logic would you implement to detect if an agent is repeating the same failing action 3 times in a row?
Agentic Foundations Slides MODULE 01: AGENTIC FOUNDATIONS
Agentic Theory &
Tool Use
Architecting the bridge between Large Language Models and the external operating system.
The Shift
CHATBOTS
"Write me a Python script that calculates Fibonacci numbers."
AGENTS
"Calculate Fibonacci numbers, save them to a file, and deploy the API."
Core Capabilities
Autonomous Execution Decision making without human-in-the-loop.
External State Mutation The ability to change files, databases, or cloud infra.
Feedback Sensitivity Reading error logs to pivot strategies.
The ReAct Pattern
Thought
Agent reasons about the current state and goal.
Action
Agent selects a tool and provides arguments.
Input
The specific parameters (e.g., shell command).
Observe
The external tool output (stdout, stderr).
// Loop termination condition
"Repeat until Thought determines the goal is reached OR the Observation indicates a terminal failure."
How Tool Calling Actually Works
LLMs don't "click" buttons. They output structured text (usually JSON) that your orchestrator interprets.
// Model Output
{
"thought": "I need to check the folder contents.",
"action": "list_directory",
"action_input": {
"path": "./src"
}
}
Step 1: Declaration
Provide the model with tool signatures (name, desc, JSON schema).
Step 2: Parsing
Capture the model response and validate against the schema.
Step 3: Execution
Run the local function and return output to the LLM context.
Agent Architecture Facilitator Guide Agent Architecture Facilitator
Lesson 1: Agentic Theory and Tool Use • Discussion Guide
Version 1.0.4
Learning Objectives
• Analyze the transition from static generation to agentic loops.
• Map the ReAct pattern (Reasoning + Acting) to concrete tool implementations.
• Identify common failure modes in autonomous loops (recursion depth, hallucination).
Pacing Guide
Intro/Hook10m
Theory Slides20m
Logic Mapping30m
Socratic Debrief15m
Instructional Scripts & Prompts
The Opening Hook
"Imagine you have a junior developer who is incredibly fast, but every 5 minutes they forget where they are, what they were doing, and they can't actually see their terminal. They can only hear what you tell them. How do you build a system that lets them work independently?"
Prompt A: Tool Agency
"If an LLM returns a tool-call to `delete_file`, but the path is `../../etc/passwd`, whose responsibility is it to stop it? The model, the prompt, or the orchestrator?"
Goal: Pivot discussion toward Lesson 2 (Sandboxing) and the idea of 'Orchestrator Responsibility'.
Prompt B: The "Infinite Loop"
"An agent tries to install a package, fails, and tries again. It fails again. How do we program 'frustration' or 'pivoting' into a purely mathematical model?"
Goal: Discuss state management and 'Short Term Memory' (context window).
Common Graduate-Level Misconceptions
01
"Agents are just better models." Actually, agency is a software architecture, not a model property. A weak model with a great loop often outperforms a strong model with a poor loop.
02
"Context window is the only memory." Students often forget that 'Action History' should be distilled. Dumping 50 tool outputs into the context window will eventually degrade the model's reasoning performance.
Worksheet Answer Key / Guidance
Ideal Thought 1: "The goal is to find a memory leak. I should first list the files to confirm `metrics.py` exists and then read it to identify potential leak patterns (e.g., global list growth)."
Ideal Action 1: `read_file(path="metrics.py")`
The Hallucination Loop Fix: Implementation of a "Sentinel" variable or a "Retry Counter" that triggers a system-level override if the same action/observation pair repeats N times.
Sandboxing Safety Slides Security & Containment
Sandboxing &
Safety Layers
Building the "prison" that keeps your autonomous agents from compromising the host system.
The Threat Model
RM -RF /
The agent interprets a prompt too literally and deletes the entire project structure or OS components.
Credential Theft
The agent accesses .env files or ~/.ssh and exfiltrates them to a public endpoint.
Resource Exhaustion
A logic loop triggers a fork bomb or a recursive file write that fills the disk in seconds.
"An autonomous agent is, by definition, an Unprivileged User with Privileged Access to your compute."
Docker: The Perfect Jail
01
Namespace Isolation
The agent thinks it's the root user, but it's isolated from the host PID and Network stacks.
02
Resource Quotas
Limit CPU to 0.5 cores and RAM to 512MB. If the agent goes wild, the container dies, not the server.
03
Ephemeral State
Reset the container after every task. Persistent malware cannot survive the 'reboot'.
Safe Agent Workflow
1. Spin up ephemeral container
2. Inject ONLY required files
3. Agent runs tools via Docker API
4. Wipe container & extract results
The "No-Phone-Home" Policy
Default Deny Egress
Why should a code-fixing agent need access to the open internet?
No CURL to random IPs
No DNS tunneling
Proxy only to internal Registry
Network Isolation Required
Security Audit Facilitator Guide Security Audit Protocol
Lesson 2: Sandboxing and Safety Layers • Faculty Guide
Core Mission
In this session, students move from "How do I make it work?" to "How do I make it safe?". Your role is to play the 'Red Team'—constantly probing their architecture for edge cases where an agent could escape containment.
Infrastructure Audit Points
1. User Context (The 'Root' Trap)
Most students will default to USER root in their Dockerfiles for convenience. Facilitator Tip: Ask: "If the agent finds a kernel exploit, and it's already root in the container, how much easier is the 'escape' to the host?" Answer: Significant. Demand they implement a low-privilege agent_user.
2. Bind Mounts vs. Named Volumes
Students often bind mount the whole project directory. The Danger: The agent can delete the Dockerfile itself, or modify the host's .bashrc if they aren't careful. Guidance: Push for readonly mounts or specific subdirectories.
3. The Network Wall
Verify they use --network none or a custom bridge with egress filtering. Check: Can the agent curl a webhook to dump the environment variables?
Simulation Scenarios
Scenario Student Architecture Red Team Counter The Infinite Loop Agent writes to a file in a while true loop. Disk Quota? (ulimit) The Secret Stealer Agent tries to read /root/.aws/credentials. Mount Isolation? The Heavy Lifter Agent starts a crypto miner or stress test. CPU/RAM Limits?
The Golden Rule of Agentic Security:
"Assume the LLM is compromised and actively trying to destroy your infrastructure. If your system is still safe under that assumption, you have a good sandbox."
Sandbox Blueprint Lab Worksheet Agent Sandbox Blueprint
Lesson 2: Containerization & Isolation Lab
Classification: Restricted
Objective: Harden the Environment
Your autonomous agent is ready to write and execute code. However, giving it a raw terminal on your laptop is suicide. Your task is to design the Dockerfile and the Execution Command that creates a "secure-by-default" coding environment.
1
Blueprint: The Dockerfile
Write out the core layers of your agent's sandbox. Remember to avoid running as root.
# Hardened Agent Dockerfile
FROM python:3.11-slim
Required: Create non-privileged user
Required: Set safe working directory
Logic Check: Why Slim?
Why should we use slim or alpine instead of a full ubuntu image for an agent?
Logic Check: PATH Isolation
How do you prevent the agent from accessing system-level binaries like ssh?
2
Runtime Constraints: The `docker run` Command
Fill in the missing security flags for this execution command.
docker run
--rm # Remove on exit
--name agent-sandbox
____________________________ # Limit RAM to 512MB
____________________________ # Limit CPU to 0.5 shares
____________________________ # Disable ALL networking
-v ./agent_work:/home/agent/app:_______ # Mount as Read-Only or Read-Write? Why?
agent-hardened-image
Risk Assessment
You have implemented the above sandbox. An LLM agent is asked to "Optimize the system." It tries to execute a fork bomb : :(){ :|:& };:. Explain which of your constraints above stops this from crashing the host machine.
REPL Loop Implementation Slides Core Loop Implementation
Implementing the
REPL Loop
Read, Eval, Print, Loop: The metabolic process of an autonomous coding agent.
The "Metabolic" Cycle
READ
Ingest Goal + Tool Observations.
EVAL
LLM decides the next Action.
EXEC
Run the tool in the sandbox.
LOOP
Append result to context & repeat.
Teaching "Self-Correction"
The secret of Vibe Coding isn't writing perfect code—it's having an agent that hates errors.
stderr: "ModuleNotFoundError: No module named 'requests'"
Traditional software crashes.
An Agent sees this as New Data.
The Error Handling Loop
Identify: Parse Traceback for specific line numbers.
Context: Auto-read the offending file around the error line.
Patch: LLM generates a targeted diff to fix the specific error.
State & Context Drift
GOOD
Short-Term Memory
Tool execution history for the current task. Purged on completion.
BAD
Context Bloat
Keeping 10,000 lines of previous error logs. Causes the LLM to lose focus on the goal.
Implementation Checklist
Output Truncation
Max Loop Iterations
State Serialization
Human Interrupt Sig
REPL Loop Implementation Teacher Guide Loop Logic Facilitator
Lesson 3: Implementing the REPL Loop • Technical Guide
100%
Loop Stability
Implementation Strategy
Students have the sandbox and the tool-use theory. Now they need to write the "Brain" of the orchestrator. This lesson is highly technical, focusing on process management (Python subprocess) and state synchronization.
Key Scripting Pattern to Teach:
while agent.is_active:
thought, tool, args = agent.think(history)
result = sandbox.execute(tool, args)
history.append({"action": tool, "observation": result})
if "SUCCESS" in result: break
Crucial Warning
Ensure students implement a Max Iteration Cap (e.g., 10 loops). Without this, an agent can rack up massive API costs in minutes by looping indefinitely on a syntax error.
Troubleshooting the Agent's Brain
Challenge: Context Window Overflow
When the agent runs pip install, the output might be 2,000 lines of "Requirement already satisfied."
Solution: Implement 'Observation Truncation'. If length > 1000, keep only the first 500 and last 500 lines.
Challenge: Hallucinated Tools
The model tries to call search_google() but you only provided read_file().
Solution: The orchestrator must catch the error and return a message: "Error: Tool 'search_google' does not exist. Available tools: [...]"
Socratic Lab Prompts
"If the agent writes a script that requires an infinite input loop (e.g., `input('Enter name:')`), what happens to your REPL? How do you implement a timeout for individual tool calls?"
"How does the model 'know' it's finished? Is it a special tool call like `submit_answer()`, or just a specific string in the thought process?"
Final Success Metric
A student is successful if their agent can:
1. Attempt to run a script that doesn't exist.
2. Receive a FileNotFoundError.
3. Reason that it needs to create the file.
4. Create it and successfully execute it on the next turn.
REPL Logic Flowchart Activity Worksheet REPL Logic Flowchart
Lesson 3: Mapping the Autonomous Loop
Orchestrator Architecture
Before you code the orchestrator, you must map the state transitions . An autonomous agent lives in a continuous loop of status checks. If your loop logic is flawed, the agent might stop too early or loop forever on a trivial error.
Complete the Orchestrator Flow
Start Task
Process: LLM Interaction
Generate Thought + Tool Call
"I should check the logs to see why the API is down."
Decision
Is tool valid?
No (Error)
Feedback to Agent
Yes (Execute)
Run in Sandbox
Master Loop Control Logic
How does the system decide between Terminating (Success/Failure) vs. Looping? Write the pseudo-code for the termination condition below.
The "Context Compression" Problem
Every iteration adds the tool output to the history. If the agent runs 10 loops, the history might be too long for the LLM. Describe a summarization strategy to keep the history compact without losing the crucial technical details of previous attempts.
# Plan for Context Compression:
Self-Healing Systems Slides Level 5: Resilience & Autonomy
Self-Healing
Systems
Engineering software that monitors its own failures and generates its own patches in real-time.
The "Phoenix" Pattern
Standard servers wait for a Human SRE to wake up at 3 AM.
A Self-Healing server wakes itself up.
Observability
The system listens to its own Exception stream.
Agency
An on-call agent is triggered by the stack trace.
Resurrection
The agent patches the code and restarts the service.
Real-Time Patching Loop
[14:02:01] ERROR: Database Connection Timeout
[14:02:02] TRIGGER: RepairAgent invoked
[14:02:05] ANALYSIS: LLM identifies missing retry logic
[14:02:08] PATCH: Applying line-diff to db_connector.py
[14:02:10] RESTART: Service back online
The "Lethal" Side of Self-Healing
Regression Hazard
An agent "fixes" a bug by deleting the security check that was causing it. The service stays online but is now vulnerable.
Recursive Mutation
The agent patches the code, the patch causes a new error, which the agent tries to fix, creating a 'Software Frankenstein'.
Mitigation: "The Immutable Shadow"
Always test the patch against a Golden Test Suite before deploying to live runtime.
Final Mastery Challenge
The "Chaos Monkey" Test
You will deploy a simple Python API. We will inject a manual error into your source code.
Your system is successful IF it can detect, fix, and restart without a single human keystroke.
Uptime: 99.9%
Tests: Passing
Autonomous Mode: ACTIVE
System Resilience Facilitator Guide System Resilience Facilitator
Lesson 5: Self-Healing Systems • Capstone Guide
The Capstone: "The Eternal Server"
This is the mastery-based final challenge. Students must integrate everything they've learned: Tool-use (to read logs), Sandboxing (to test patches safely), REPL Loops (to iterate on fixes), and Orchestration (to manage the repair process).
Technical Requirement:
"The agent must NOT have write-access to the live production files. It must write a patch to a TEMPORARY file, run it against a test suite in a SANDBOX, and only if tests pass, swap the production file."
Final Rubric
Detection
Safety Check
Successful Patch
The "Chaos Monkey" Protocol
As the instructor, you will introduce one of the following "injuries" to their server while it's running. Observe if their agent detects and repairs it.
Injury A: The Syntax Poison
Delete a trailing parenthesis in the main API route file.
Expected Agent Action: Run 'python -m py_compile', catch SyntaxError, identify missing ')', apply patch.
Injury B: The Logic Poison
Change a return True to return False in a critical authentication function.
Expected Agent Action: Run unit tests, see 'AuthTest' fail, read 'auth.py', find the logic flip, revert it.
Closing the Sequence
"By the end of this lab, you have moved from writing code to Engineering Evolution. Your software no longer rots; it learns."
Debrief Question 1
"When do we NOT want a system to self-heal? (e.g., Financial transactions, Medical software?)"
Debrief Question 2
"If an agent fixes its own code, who owns the Copyright? The original student or the agent orchestrator?"
Self-Healing Architecture Proposal Worksheet Resilience Architecture Proposal
Capstone: Self-Healing System Design
System Integrity: 100%
The Challenge: "The Eternal Server"
"Build a Python API that, when corrupted by a manual source-code edit, detects the failure via its own heartbeat monitor, triggers an AI Agent to identify the error, tests a fix in a sandbox, and deploys the patch to stay online."
1. The Heartbeat Layer
How does your system 'know' it's broken? Describe the monitoring script that triggers the agent.
2. The Verification Layer
Before the agent patches the live code, how do you ensure the fix doesn't break everything else? (Test Suite Architecture)
Autonomous Repair Protocol (Visual Flow)
Failure Detected
Invoke Agent
Identify & Patch
Deploy & Reboot
Risk & Ethics Disclosure
Autonomous systems that modify their own source code represent a unique security risk. If a hacker manages to trigger your "Self-Healing" agent with a malicious prompt, they could trick the agent into installing a backdoor. How do you implement a "Human-in-the-Loop Override" for high-risk changes?
Project ID: PHOENIX-09
Autonomous Mode: Standby