Repository navigation
Module 5: Foundational Concepts
Sculley et al. (2015) identified a problem often learned the hard way: machine learning systems accumulate hidden technical debt that only becomes visible under production conditions. They categorized five types of debt, and while their framework predates LLM agents, each category still applies to agent systems:
Entanglement. Changing one component unexpectedly affects behavior elsewhere.
- In agent systems: You tweak one agent's system prompt, and a downstream agent that parses its output starts failing because the output format shifted subtly.
- How to prevent it: Define explicit output schemas between agents so changes are caught by validation before they cascade.
Unstable data dependencies. Upstream data changes silently corrupt behavior.
- In agent systems: Your RAG pipeline's retrieval quality degrades because the vector store was re-indexed with different chunking parameters.
- How to prevent it: Run automated retrieval quality checks after any data source update.
Feedback loops. A deployed system's outputs influence its future inputs.
- In agent systems: One agent writes a result to shared state, and a later agent reads it as ground truth without verifying it. If that first result was wrong, the error propagates forward and compounds.
- How to prevent it: Tag agent-generated content so it can be distinguished from original sources, and validate before reuse.
Configuration debt. Undocumented parameters make systems brittle.
- In agent systems: Prompts, temperature settings, tool configurations, and model version selections are scattered across multiple files with no versioning, no tests, and no single source of truth.
- How to prevent it: Store all configuration in a single versioned location and require changes to go through the same review process as code.
Undeclared consumers. Downstream systems depend on outputs without being tracked.
- In agent systems: You change your agent's output format and discover that other processes were parsing that output. If the dependency isn't documented, there's no way to know the change will break anything until it does.
- How to prevent it: Version your agent's output schema and document what depends on it.
Serving real users introduces problems that don't exist in a notebook: handling concurrent requests, recovering from crashes, managing credentials securely, and scaling up or down based on demand. The following layers address these:
| Layer | What it does | Why it matters for agents |
|---|---|---|
| Containerization (Docker) | Packages your agent and its dependencies into a portable image that runs identically everywhere | Ensures consistent behavior across development, staging, and production environments |
| Orchestration (Kubernetes) | Runs and manages multiple container instances: schedules them, monitors their health, restarts crashed ones, and routes traffic among them | Agent services crash and stall in unpredictable ways. Orchestration recovers them without manual restarts. |
| API Gateway | Sits in front of your agent service, handling auth, rate limiting, routing, and SSL | Centralizes security and traffic management outside of agent application code |
| Secrets Management (Vault, AWS Secrets Manager) | Stores API keys, model credentials, and database passwords securely | Agent systems typically require multiple API keys; centralized secrets management prevents credential exposure |
| Autoscaling | Adds or removes running instances automatically based on demand (typically configured within the orchestrator) | Agent workloads are spiky. Autoscaling absorbs peaks and reduces cost during quiet periods. |
Orchestration keeps instances healthy; autoscaling decides how many to run. You usually need both: autoscaling without health management can launch instances that no one restarts when they fail.
Understanding what these layers do helps you (1) design your agent in ways that are container-friendly (stateless, configurable via environment variables), (2) choose the right managed services for your deployment, and (3) identify when a production failure is an infrastructure problem vs. an agent logic problem.
Assigned Reading
- The Agent Development Lifecycle (Article). LangChain.
- Sculley et al. (2015) — Hidden Technical Debt in ML Systems
- Docker Getting Started Guide
- Optional: The Agent Development Lifecycle (Harrison Chase): LangChain's founder walks through what production agent deployment involves (~45 min).
An agent that passes your test cases may still fail in production. It might be slow, expensive, unreliable on unexpected inputs, or biased in ways that accuracy alone cannot capture.
Liang et al. (2022) demonstrated this with HELM (Holistic Evaluation of Language Models), where they evaluated models across multiple metrics (accuracy, robustness, fairness, efficiency, and others) rather than accuracy alone. Their results showed that no single model leads on every metric, and that some metrics trade off against each other, such as capability against efficiency. The same pattern applies to agent systems: optimizing one dimension can degrade another.
These are the key dimensions agent systems can be evaluated on:
| Dimension | What it measures | Example failure |
|---|---|---|
| Task accuracy | Does the agent produce correct outputs? | Agent answers questions wrong 8% of the time |
| Safety & alignment | Does the agent refuse harmful requests and stay within bounds? | Agent follows injected instructions from user input |
| Resource efficiency | Token cost, latency, API calls per task | Agent uses $0.40/query when $0.05 is achievable |
| Robustness | Performance under unexpected or adversarial inputs | Agent crashes on multilingual input it wasn't tested on |
| Fairness & bias | Consistent performance across demographic groups | Agent approves loans at different rates by zipcode |
| Observability | Can you diagnose failures when they happen? | Agent fails silently with no trace, no error, just wrong output |
Some agent outputs can be checked against a known answer: whether a factual answer matches a reference, for example. Others have no single correct answer: reasoning quality, whether an answer is actually grounded in the sources the agent retrieved, response coherence. LLM-as-judge methodology uses a capable language model to evaluate those outputs against explicit criteria.
It requires careful judge prompt design, clear rubrics for each dimension, and validation by comparing judge scores against a sample of human-labeled outputs. It scales evaluation of subjective dimensions, but is limited by the judge model's own biases and blind spots. Human review is still necessary for dimensions like tone and reasoning quality that even judge models struggle to assess reliably.
Every prompt change, tool update, or model version swap should trigger your evaluation suite automatically. If the new version falls below the threshold on any dimension you can test automatically, the deployment is blocked. Some dimensions, such as tone or fairness in context, cannot be fully judged by an automated test. For those, the pipeline should route the change to human review before release.
This is the same CI/CD discipline that software engineering applies to code changes, extended to agent-specific dimensions. On every commit, the pipeline runs the evaluation suite, checks results against defined thresholds, and either deploys or blocks the release. Prompt changes are code changes and should be treated that way.
- Optional: Liang et al. (2022) — Holistic Evaluation of Language Models (HELM): The benchmark framework for multi-dimensional evaluation. Read Sections 1–3 for evaluation philosophy and metrics taxonomy.
- Chang et al. (2024) — A Survey on Evaluation of Large Language Models: Comprehensive survey contextualizing HELM within the broader evaluation literature. Section 4 covers benchmark limitations.
Observability is what lets you see what your agent actually did, step by step, so you can diagnose failures and verify behavior before approving actions.
Traditional software observability rests on three pillars:
- Logs record discrete timestamped events
- Metrics track numeric measurements over time (latency, error rate, throughput)
- Traces follow a single request's journey through all system components
Agent systems need all three, plus signals that traditional software does not produce:
- Prompt content and length sent to the LLM
- The model's reasoning trace and tool calls
- Inter-agent messages in multi-agent systems
- Token consumption per invocation
- Retrieval context and relevance scores (for RAG agents)
Without these agent-specific signals, a trace can tell you a request was slow but cannot tell you why. Was the prompt 12,000 tokens? Did the retrieval step return irrelevant documents? Did the model make six tool calls when one would have been sufficient?
LangSmith and LangFuse are observability platforms built specifically for LLM applications. Both capture the full agent execution trace (prompt content, model response, tool calls, sub-agent invocations, retrieved context, final output) and expose it through dashboards for debugging and trend analysis.
LangSmith integrates natively with LangChain/LangGraph. If you are using those frameworks (as in Modules 2–4), tracing works with minimal configuration. It is a hosted service.
LangFuse is open-source and framework-agnostic. It supports self-hosting, which matters when data sovereignty requirements prohibit sending prompt content to third-party services.
OpenTelemetry is a vendor-neutral instrumentation standard. Instead of writing instrumentation code specific to LangSmith or LangFuse, you instrument once with the OTel SDK and route trace data to any compatible backend (for example LangSmith, LangFuse, Datadog, or Grafana). Metrics backends such as Prometheus receive the metric signals, not trace spans.
The Guided Lab uses LangSmith's native tracing for speed. OpenTelemetry is the option to consider when you expect to change backends later.
These are the signals that indicate something is going wrong in a production agent system. For any system serving real users, set up automated alerts on these rather than relying on manual dashboard checks.
- Error rate spike. Sudden increase in failed requests or tool call errors.
- Token cost anomaly. Unexpected spend increase, often indicating runaway loops or prompts that have grown too large (e.g., unbounded conversation history or too many retrieved chunks).
- Retrieval quality degradation. For RAG agents, if relevance scores on retrieved documents start dropping, it usually means the underlying data changed (re-indexed, deleted, or corrupted) and the retrieval pipeline is now returning less useful context.
- Safety or guardrail violations. The agent produces outputs that violate its defined constraints, such as following injected instructions, leaking system prompt content, or acting outside its allowed scope. This is covered more in Chapter 4.
- Tool call failure rate. A specific tool starts failing (API down, credentials expired, rate limited) but the agent still returns output by working around it. The response looks normal but is missing data the agent was supposed to retrieve.
- Latency above target. Agent response time consistently exceeds what users or downstream systems expect. Often a symptom of the other issues above (runaway loops, excessive tool calls) rather than a root cause itself.
Assigned Reading
- LangSmith Observability Quickstart: Short guide on setting up tracing in LangSmith.
- LangSmith Documentation: Setup guides for tracing LangGraph and LangChain agents.
- LangFuse GitHub: Open-source LLM observability. Includes self-hosting guide.
- OpenTelemetry Getting Started: Vendor-neutral instrumentation for any language and any backend.
LLM-powered systems accept user input, call external tools, retrieve documents from vector stores, and pass outputs to downstream systems. Each of these capabilities is also an attack surface. OWASP publishes two lists: one for LLM applications in general, and one for agentic applications.
For each risk below, the tables give a plain-language description, an example in an agent you may have built in this course, and layered mitigations. "Layered" means no single control is enough. Combine controls at the input, the model's permissions, the tools, and the output. The lab's research agent (web search and webpage reading) and Module 4's three-role pipeline are used as running examples.
This chapter covers these risks with concrete mitigations you can apply to agent architectures.
| # | Risk | Agent example | Layered mitigations |
|---|---|---|---|
| LLM01 | Prompt Injection | A webpage the research agent reads contains hidden text telling it to ignore its task and reveal its instructions. | Treat all retrieved and tool content as untrusted data, not instructions. Keep system instructions separate from data. Limit what tools the agent may call. Validate outputs. Require human approval for high-impact actions. |
| LLM02 | Sensitive Information Disclosure | A support agent includes another customer's account details in a reply. | Give the agent least-privilege data access. Authorize each retrieval per user. Redact sensitive fields before they reach the model. Filter outputs. Log accesses. |
| LLM03 | Excessive Agency | An agent with a "run any SQL" tool deletes records after a manipulated instruction. | Grant only the tools and permissions the task needs. Prefer read-only access. Scope credentials narrowly. Add approval gates for irreversible actions. |
| LLM04 | Supply Chain | A pre-trained model or package pulled into the pipeline has been tampered with. | Pin and verify versions. Use trusted sources. Track the provenance of models and dependencies. Scan dependencies. |
| LLM05 | Data and Model Poisoning | Malicious examples are added to data used to fine-tune or index for the agent. | Vet and track data sources. Check for anomalies before ingestion. Test against a held-out evaluation set after data changes. |
| LLM06 | Unbounded Consumption | A crafted request makes the agent loop through tool calls and burn budget. | Rate limits and per-user quotas. Caps on tokens, steps, and loop iterations. Cost alerts. |
| LLM07 | Misinformation | A research agent states a fabricated citation as fact. | Ground answers in retrieved sources and show them. Add an LLM-as-judge or verification step. Use human review for high-stakes outputs. |
| LLM08 | Hidden Context Exposure | A user asks "What are your instructions?" and the bot prints its configuration. | Assume prompts can leak. Never put secrets in prompts. Enforce access control outside the model, not in the instructions. |
| LLM09 | Vector and Embedding Weaknesses | Poisoned documents are crafted to rank first for common queries. | Control who can write to the vector store. Validate documents at ingestion. Apply per-document access control at retrieval. Monitor retrieval relevance. |
| LLM10 | Improper Output Handling | Model-generated text is inserted directly into a web page or query. | Treat model output as untrusted input to the next component. Validate against a schema. Escape or encode. Use parameterized queries. |
The LLM Top 10 covers risks for any LLM-powered application. The Agentic Top 10 extends this to autonomous agents — systems that plan, use tools, maintain memory, and coordinate with other agents. Where the LLM list focuses on model-level vulnerabilities, the Agentic list focuses on how autonomy, delegation, and multi-step execution amplify those risks.
| # | Risk | Agent example | Layered mitigations |
|---|---|---|---|
| ASI01 | Agent Goal Hijack | Retrieved content redirects the agent's task. | Treat content as data. Re-check output against the original goal. Gate high-impact actions. |
| ASI02 | Tool Misuse & Exploitation | An injected instruction makes the agent send data to an external URL. | Allowlist tool destinations and parameters. Validate arguments. Limit tool scope. Log every call. |
| ASI03 | Identity & Privilege Abuse | A sub-agent inherits the supervisor's full credentials. | Issue each agent its own scoped credentials. Apply least privilege and short-lived tokens. |
| ASI04 | Agentic Supply Chain Vulnerabilities | A malicious MCP server is loaded at runtime. | Allowlist and pin tool servers. Verify before loading. Review third-party tool descriptions. |
| ASI05 | Unexpected Code Execution (RCE) | A code-writing agent runs generated code on the host. | Run code in a sandbox with no network and limited filesystem. Review before execution where possible. |
| ASI06 | Memory & Context Poisoning | False data is written to shared memory and reused later. | Tag the source of memory entries. Validate before reuse. Limit who and what can write to memory. |
| ASI07 | Insecure Inter-Agent Communication | A forged message from "Agent A" is acted on by Agent B. | Authenticate agents. Validate message schemas. Sign or verify messages. |
| ASI08 | Cascading Failures | A bad number from an upstream tool flows through three agents unchecked. | Validate between stages. Add circuit breakers and stage-level checks. Limit blast radius. |
| ASI09 | Human-Agent Trust Exploitation | A user approves a fraudulent request because the agent's recommendation seemed authoritative. | Show evidence and sources, not just conclusions. Display uncertainty. Require independent verification for high-stakes actions. |
| ASI10 | Rogue Agents | An agent pursues an objective that drifts from its purpose. | Monitor behavior against expected patterns. Restrict capabilities. Keep a kill switch and audit logs. |
Assigned Video
- OWASP's Top 10 Ways to Attack LLMs: AI Vulnerabilities Exposed (IBM Technologies). The ordering differs slightly between the 2025 and 2026 lists, but the threats are the same.
- OWASP Top 10 for LLM Applications (2026): The full reference for model-level risks.
- OWASP Top 10 for Agentic Applications (2026): Risks specific to autonomous agents.
- OWASP Agentic AI Threats and Mitigations (2025): The detailed 17-threat taxonomy that underpins the Agentic Top 10.
"The AI did it" is never a complete answer. When an agent denies a loan, screens out a qualified applicant, or misclassifies a medical image, accountability lands on people and organizations. This chapter covers the frameworks that structure that accountability.
The National Institute of Standards and Technology (NIST) is the U.S. federal agency that develops measurement standards, guidelines, and best practices across science and technology. Their AI Risk Management Framework (AI RMF 1.0, 2023) provides a structured methodology for managing AI risks, organized as four functions in a continuous cycle.
To make this concrete, consider a claims-processing agent that reviews insurance documents and drafts approval or denial letters:
Govern: Establish policies, roles, and accountability. For the claims agent: designate who owns the agent's risk decisions, require human sign-off on all denials, and define what "out of scope" means for this agent.
Map: Identify the system's intended uses, deployment context, affected populations, and specific risks. For the claims agent: it affects policyholders financially, could produce biased outcomes by zip code, and has access to sensitive health records.
Measure: Develop metrics and testing protocols that produce evidence about the system's actual risk profile. For the claims agent: track denial rates by demographic group, measure hallucination rate on document extraction, run adversarial prompt injection tests.
Manage: Implement mitigations based on evidence from Measure. Review effectiveness on an ongoing basis. For the claims agent: add a confidence threshold below which cases route to a human, retrain quarterly on corrected decisions, maintain an incident log.
The NIST RMF is guidance, not law. It gives you a methodology for thinking about risk. The EU AI Act, covered next, makes some of that thinking legally required.
The EU AI Act (2024) is the world's first comprehensive AI regulation. It applies to any AI system deployed in or affecting individuals in the EU, regardless of where the developer is based. Understanding the EU AI Act prepares you for the regulatory direction globally, not just in Europe.
It classifies AI systems into four tiers:
| Tier | Description | Agent example |
|---|---|---|
| Unacceptable | Prohibited outright | Social scoring agent that rates citizens based on behavior |
| High risk | Strict compliance: conformity assessments, documentation, human oversight, public registration | Agent that screens job applicants or assesses creditworthiness |
| Limited risk | Transparency obligations | Customer service chatbot (must disclose it's AI) |
| Minimal risk | No specific obligations | Internal code review agent, content summarizer |
Article 14 explicitly requires human oversight mechanisms for high-risk systems. Non-compliance carries fines up to 3% of global annual revenue.
The classification depends on deployment context, not technical architecture. The same LangGraph agent with RAG could be minimal risk or high risk depending on what decisions it informs. Ask four questions:
- What decisions or recommendations does the agent produce?
- Do those decisions affect individuals in protected domains (employment, credit, education, health, law enforcement)?
- What degree of human oversight exists between the agent's output and the impact on individuals?
- What's the potential harm if the agent produces a materially wrong output?
If the answers to #2 and #4 are "yes" and "significant," you're likely in high-risk territory with mandatory compliance obligations.
Both the EU AI Act (Article 14) and the NIST RMF (Govern function) require defining where human authority is needed. For high-risk systems, this translates into a concrete technical requirement: the agent must pause at irreversible decision points so a human can approve or reject before the action takes effect.
Human-in-the-loop (HITL) means the agent stops mid-execution, presents the pending action and its reasoning to a reviewer, and resumes only after approval. The key design questions are:
- Which actions require a gate? Any action that is hard to undo (sending a denial letter, filing a legal document, approving a financial transaction).
- What does the reviewer need to see? Not just the final output, but the reasoning trace, the source documents, and the confidence level.
- What happens on rejection? Does the agent retry with different parameters, escalate to a specialist, or terminate the workflow?
For a regulated use case, evaluate HITL support before choosing a framework. Some frameworks (LangGraph, OpenAI Agents SDK, CrewAI Flows) treat approval gates as a first-class primitive. Others (Strands, Google ADK) give you hooks and callbacks but leave the gate for you to build.
Four documentation artifacts translate risk assessment into auditable, accountable records:
- Model cards (Mitchell et al., 2019): Document the model's intended uses, limitations, evaluation results, demographic performance disparities, and out-of-scope uses.
- System cards: Extend model cards to the full system: deployment context, human oversight mechanism, incident response procedure, data provenance chain.
- Risk registers: Catalog identified risks, their likelihood, impact, and mitigations. A living document updated as the system evolves.
- Incident response plans: What happens when things go wrong. Who gets notified, what gets shut down, how affected users are informed.
These are the artifacts that demonstrate accountability when regulators, auditors, or affected individuals ask "who was responsible and what did you do about it?"
Assigned Video
- AI Governance and the EU AI Act: What Developers Need to Know (~15 minutes). Practitioner-oriented overview of the EU AI Act's four-tier risk classification and practical compliance obligations for developers building AI agent systems.
- EU AI Act Full Text (Regulation 2024/1689)
- NIST AI RMF 1.0: The full framework document. Read the Core Framework sections on Govern, Map, Measure, and Manage.
- Mitchell et al. (2019) — Model Cards for Model Reporting: The standard for AI model documentation and transparency.
Created: 05/15/2026. (C. Lizárraga)
Updated: 08/19/2026. (M. Yung)
2026.
Arizona Institute for Artificial Intelligence (AI2S).
Office of Responsible Artificial Intelligence. The University of Arizona.
AI Automation and Agents (v2)
Table of Contents
📂 Preparing your Portfolio in Github
MODULE 1
- 1.1 Module Overview
-
1.2 Foundational Concepts /
1.2 Addendum - 1.3. Module Activities
- 1.4. Additional Resources
Summary and Key Takeaways:
MODULE 2
- 2.1 Module Overview
-
2.2 Foundational Concepts /
2.2 Addendum - 2.3 Activities
- 2.4 Additional Resources
MODULE 3
- 3.1 Module Overview
-
3.2 Foundational Concepts /
3.2 Addendum - 3.3 Activities
- 3.4 Additional Resources
MODULE 4
MODULE 5