๐Ÿง  Agents

๐Ÿง  Agentic AI Fundamentals

๐Ÿ’ก An LLM answers. An agent acts. The difference is not a longer prompt โ€” it is a control loop with tools, memory, a permission envelope, and a stop condition. Mix those wrong and you get a token furnace that can also DROP TABLE. Mix them right and you get boring, reversible work.

๐Ÿ—บ๏ธ The map

Read this as a curriculum, not a glossary. Five layers, each one only justified when the layer below is not enough:

  1. ๐ŸŽฏ Definition โ€” LLM vs workflow vs agent. Answers: who chooses the next step?
  2. ๐Ÿงฉ Anatomy โ€” model, planner, tools, memory, guardrails, orchestrator. Answers: what is the system besides the LLM?
  3. ๐Ÿ” Patterns โ€” ReAct, plan-and-execute, reflection, Anthropicโ€™s five workflows. Answers: how does control flow?
  4. ๐Ÿ”ง Integration โ€” function calling, MCP, multi-agent, skills. Answers: how does it touch the world?
  5. ๐Ÿญ Production โ€” memory, LLMOps, HITL (or HIL), prompt injection, evals. Answers: how do you ship it without a pager?

๐ŸŽฏ What is Agentic AI?

Classic AI already had the word. Russell & Norvig treat an agent as something that perceives and acts toward a performance measure [7]. PEAS โ€” Performance, Environment, Actuators, Sensors โ€” is still the right checklist. LLM-era โ€œagentic AIโ€ is that idea with a language model as the policy: the model interprets a goal, selects actions (usually tool calls), observes results, and continues until a stop condition.

The useful distinction is not โ€œchatbot vs agent.โ€ It is who owns control flow [1]:

  • ๐Ÿ’ฌ Traditional LLM generation โ€” prompt โ†’ response. One shot, maybe a few turns of chat. No tools, no state machine, no side effects.
  • ๐Ÿงฑ Workflow โ€” LLMs and tools orchestrated through predefined code paths. You wrote the graph. The model fills in nodes. Predictable, cheap to debug.
  • ๐Ÿค– Agent โ€” the LLM dynamically directs its own process and tool use. Runtime observations change what happens next. Flexible, expensive, compounding-error-prone.

A system becomes meaningfully agentic when all of these are true:

  • ๐ŸŽฏ A persistent goal, not only a response request
  • ๐Ÿ“ฆ State across multiple steps
  • ๐Ÿ› ๏ธ Dynamic selection of tools or actions
  • ๐Ÿ‘๏ธ Feedback from an environment (API, codebase, browser, user)
  • ๐Ÿ”„ Replanning after failures or new information
  • ๐Ÿ›‘ Explicit completion and stopping criteria
  • ๐Ÿ›ก๏ธ Bounded autonomy โ€” a permission envelope, not โ€œdo whateverโ€

A fixed chain of three predetermined LLM calls is a workflow, not an agent. The key test: do runtime observations change what the system decides to do next?

๐Ÿงฉ Anatomy of an agent

The LLM is not the agent. The agent is a system that uses an LLM as a policy. Strip the other parts and you have an eloquent intern with root access.

Component Job If you skip it
๐Ÿง  LLM / policy Interpret goal, reason, select the next action You do not have an agent โ€” you have a script
๐Ÿ—บ๏ธ Planner Goal โ†’ tasks, dependencies, completion criteria Thrashing, duplicated work, no progress metric
๐Ÿ› ๏ธ Tool layer Controlled access to APIs, DBs, search, code Hallucinated side effects, or no side effects
๐Ÿงพ Working memory Current task, recent observations, tool results Context overflow or amnesia mid-run
๐Ÿ“š Long-term memory Cross-session facts, preferences, experience Stateless intern every morning
๐Ÿ’พ State manager Checkpoints, retries, approvals, resume Crash = start over; HITL = hope
๐Ÿงช Evaluator Did the output actually satisfy the spec? Confident wrong answers
๐Ÿ›ก๏ธ Guardrails Auth, data, safety, cost, operational bounds The DROP TABLE demo
๐ŸŽ›๏ธ Orchestrator Run the loop; decide continue / retry / pause / stop Infinite loops and silent hangs

โŒ When an agent is the wrong tool

An agent is usually the wrong choice when the process is predictable, rules-based, or high-risk without room for runtime judgment. Prefer a conventional workflow (or just software) when:

  • ๐Ÿ“‹ Every step can be defined in advance
  • ๐ŸŽฏ Deterministic output is required
  • ๐Ÿ”Œ A simple API, SQL query, or rules engine solves it
  • โš–๏ธ Errors have severe legal, financial, or safety consequences
  • โฑ๏ธ Latency or cost budgets are extremely tight
  • ๐Ÿงช There is no reliable way to verify success
  • ๐Ÿ”“ The agent would have broad permissions but limited supervision

Rule: deterministic software for what can be specified; agentic decision-making only for the uncertain portion. Anthropicโ€™s production note is the same: many apps only need a well-prompted single call with retrieval [1].

๐Ÿ›ก๏ธ Autonomy as a permission envelope

Autonomy is not a vibe in the system prompt. It is a permission envelope enforced outside the model. For every tool and action, specify:

  • ๐Ÿ“‚ Which resources the agent can access
  • ๐Ÿ”’ Read-only vs mutating operations
  • ๐Ÿข Data and tenant boundaries
  • ๐Ÿ’ธ Transaction and spending limits
  • ๐Ÿ™‹ Actions that require human approval
  • ๐Ÿ›‘ Max steps, retries, runtime, and token budget
  • ๐Ÿšซ Prohibited actions
  • ๐Ÿšจ Escalation and shutdown conditions

Enforce this with authorization services, sandboxing, typed tool schemas, policy engines, database roles, and approval workflows. Prompt instructions are not a security boundary. If the model generates DROP TABLE, its database identity should lack permission to execute it.

๐Ÿ” Control-loop patterns

Three loops cover most โ€œrealโ€ agents. Workflows (next section) cover the cases where you should not let the model own the path at all.

๐Ÿ”„ ReAct โ€” reason, act, observe

ReAct (Yao et al., ICLR 2023) [2] interleaves verbal reasoning traces with actions so the model can reason to act and act to reason. The loop:

  1. ๐Ÿง  Interpret the current goal and evidence (Thought)
  2. ๐Ÿ› ๏ธ Select an action or tool (Action)
  3. โš™๏ธ Execute it
  4. ๐Ÿ‘๏ธ Observe the result (Observation)
  5. ๐Ÿ” Update the approach and repeat

WHERE. The correct next step depends on external information โ€” support tickets, docs search, codebase inspection, browser tasks. Example: inspect an order โ†’ observe it already shipped โ†’ consult refund policy โ†’ propose the right resolution.

TRADE-OFFS. High latency, token use, error accumulation, runaway loops. In production, keep reasoning internal; log actions, observations, and decisions as structured traces. Cap turns. Prefer structured tool arguments over free-form โ€œthoughtโ€ leaking into the UI.

๐Ÿ—บ๏ธ Plan-and-Execute

Separate strategy from tactics. A planner creates a list or graph of subtasks. Executors complete them. The planner may revise based on results.

  • โœ… Better organization for long tasks
  • โœ… Easier parallelization and progress tracking
  • โœ… Specialized models for plan vs execute
  • โœ… Per-step retry and approval
  • โš ๏ธ Original plan goes stale
  • โš ๏ธ Planning adds latency and tokens
  • โš ๏ธ A bad plan poisons many downstream tasks
  • โš ๏ธ Overkill for simple tasks

Strong implementations support incremental replanning โ€” patch the graph, do not regenerate it from scratch after every observation.

๐Ÿชž Reflection / self-correction

After a candidate answer or action, an evaluator scores it. The agent revises. Reflexion [4] stores those verbal critiques in an episodic buffer so later trials improve without weight updates โ€” linguistic RL.

Reflection works when grounded in objective signals: tests, schema validation, policy rules, compilers, citations. Asking the same model to โ€œcheck itselfโ€ with no external signal often reinforces the original mistake and burns tokens. Cap attempts. Prefer a cheaper/different evaluator than the generator when you can.

๐Ÿช“ Goal decomposition

Turn a wish into a task spec before you turn it into steps:

  • ๐Ÿ Desired final state
  • ๐Ÿšง Constraints and permissions
  • ๐Ÿ“ฅ Required inputs
  • ๐Ÿ› ๏ธ Available tools
  • ๐Ÿ”— Dependencies
  • โœ… Success criteria
  • ๐Ÿšจ Failure and escalation conditions

Subtasks should map to a tool or a verifiable operation โ€” โ€œretrieve account status,โ€ โ€œvalidate schemaโ€ โ€” not โ€œinvestigate the problem.โ€ Represent complex work as a dependency graph, not only a linear checklist. After each step, update state and drop steps that are no longer necessary.

๐ŸŒณ Chain vs tree vs graph

How the model (or orchestrator) explores the plan:

Shape What it is When
โ›“๏ธ Chain-of-thought [8] One main path of intermediate reasoning Mostly sequential, low branching
๐ŸŒณ Tree-of-thought [3] Generate candidate โ€œthoughts,โ€ score, search (BFS/DFS), backtrack Search problems, diagnosis, early choices that dead-end. Game of 24: CoT 4% vs ToT 74% on GPT-4
๐Ÿ•ธ๏ธ Graph planning Shared deps, cycles, parallel branches, reusable intermediates Software changes, research, multi-agent coordination, LangGraph-style state

Tree and graph search improve quality and explode cost. Use the simplest representation that meets the reliability bar. Store structured plans; do not stream raw private reasoning to users.

๐Ÿงฑ Workflow patterns โ€” stay on the ladder

Anthropicโ€™s production catalog [1] is five composable workflows built on an augmented LLM (retrieval + tools + memory). These are not agents. Code still owns the path. Use them until you genuinely cannot hardcode the next step.

โ›“๏ธ Prompt chaining

Decompose into a fixed sequence. Output of call n is input to n+1. Put a programmatic gate (schema, regex, cheap classifier) between steps so a bad intermediate cannot poison the rest.

WHERE. Outline โ†’ (check outline) โ†’ draft. Marketing copy โ†’ translate. Each call is an easier task; you trade latency for accuracy.

๐Ÿš Routing

Classify the input, dispatch to a specialized prompt / tool set / model. Optimizing one category no longer hurts the others.

WHERE. Support intents. Easy questions โ†’ small model; hard ones โ†’ large model. A router is a classifier; a manager (later) also plans and aggregates.

โšก Parallelization

Two flavors:

  • โœ‚๏ธ Sectioning โ€” independent subtasks at the same time (speed + focused attention)
  • ๐Ÿ—ณ๏ธ Voting โ€” same task, many attempts, aggregate (confidence)

WHERE. Guardrail model in parallel with the answer model. Vulnerability review with several prompts. Evals that score different dimensions separately.

๐Ÿ‘ท Orchestratorโ€“workers

A central LLM dynamically breaks the task, delegates, synthesizes. Topologically similar to parallelization; the difference is flexibility โ€” subtasks are not hardcoded [1].

WHERE. Multi-file code edits. Research across unknown sources. This is the closest workflow to a true agent โ€” still wrap it in budgets and structured returns.

๐Ÿชž Evaluatorโ€“optimizer

Generator writes; evaluator critiques; loop until the rubric passes or the budget dies. Same shape as Reflection, but the path is a workflow you designed, not an open-ended ReAct wander.

Two signs of fit [1]: (1) human feedback would demonstrably improve the output; (2) an LLM can provide that feedback. Literary translation, iterative search, code that has tests.

๐Ÿ”ง Tool use, MCP, and trust

Treat the modelโ€™s function call as an untrusted request, not an authorized command.

Also: allowlists, idempotency keys, timeouts, rate limits, output-size caps, and protection against SSRF, SQL injection, path traversal, and command injection. Expose high-level parameterized tools (โ€œrefund orderโ€) rather than arbitrary shells or SQL.

๐Ÿ”Œ Model Context Protocol

MCP [5] is an open JSON-RPC protocol for connecting LLM apps to external context. Three roles:

  • ๐Ÿ  Host โ€” the app the user sees (IDE, desktop, your agent)
  • ๐Ÿ“Ž Client โ€” connector inside the host, 1:1 with a server
  • ๐Ÿ–ฅ๏ธ Server โ€” exposes capabilities

Servers offer:

  • ๐Ÿ› ๏ธ Tools โ€” model-controlled functions with JSON Schema (side effects allowed)
  • ๐Ÿ“„ Resources โ€” application-controlled, mostly read-only context (files, schemas, docs)
  • ๐Ÿ“ Prompts โ€” user-controlled templates for a domain workflow

MCP standardizes discovery and message exchange. It does not make tools safe. Auth, consent, sandboxing, and trust policy still live in the host and server. A random MCP server is a supply-chain decision.

๐Ÿ•ธ๏ธ Frameworks and state

Frameworks (LangChain, LangGraph, CrewAI, AutoGen/AG2, OpenAI Agents SDK, Claude Agent SDK) are accelerators. They are also abstraction traps [1]. Start with the API. If you use a framework, you should be able to draw the underlying calls.

  • ๐Ÿ”— LangChain โ€” models, prompts, tools, retrievers, message history. Fine for pipelines. Do not hide business state, permissions, or checkpoints inside a memory abstraction you cannot inspect.
  • ๐Ÿ•ธ๏ธ LangGraph [9] โ€” stateful graph (Pregel-style), not a DAG. Nodes read and update a typed state. Edges can be conditional. Cycles are the point: ReAct, retries, HITL pauses. Checkpointers snapshot state each super-step โ†’ resume, time-travel, crash recovery. Requires recursion limits, reducers, and terminal states.
  • ๐Ÿ‘ฅ CrewAI / AutoGen โ€” role-playing multi-agent: sequential handoffs, manager delegation, group chat. Benefit is specialization. Risks: duplicated work, context loss, cost, undebuggable transcripts.
  • ๐Ÿ“ฆ OpenAI Agents SDK โ€” hosted loop with handoffs, guardrails, tracing. Convenient on-rails; still version the whole config, not just the model.

A DAG assumes an acyclic, predetermined sequence. An agent graph revisits nodes based on updated state. That flexibility is why you need explicit stop conditions โ€” an agent that can always return โ€œneeds more investigationโ€ will.

๐Ÿ‘ฅ Multi-agent systems

Add a second agent only when roles are clearly separable or work is independently parallelizable. Otherwise you bought a meeting.

๐Ÿ‘” Managerโ€“worker vs ๐Ÿš routerโ€“worker

  • ๐Ÿš Router โ€” classify, send to one specialist. Light.
  • ๐Ÿ‘” Manager โ€” plan, delegate, dependency management, retries, aggregation, conflict resolution. Heavy.

Workers should receive minimal, task-specific context and return structured payloads: result, evidence, uncertainty, errors, recommended next action. The manager validates workers; it does not automatically trust them.

๐Ÿ“จ Safe handoffs

Prefer structured messages over dumping the full transcript. A handoff should contain:

  • ๐Ÿ†” Task ID and parent goal
  • ๐ŸŽฏ Exact subtask
  • ๐Ÿ“Œ Necessary facts only
  • ๐Ÿ› ๏ธ Allowed tools and resources
  • ๐Ÿท๏ธ Data sensitivity labels
  • ๐Ÿ“ Expected output schema
  • โฑ๏ธ Deadline / resource budget
  • โœ… Completion criteria

Redact secrets; pass access-controlled IDs. Authorize each receiving agent independently. Version shared state with provenance โ€” which agent produced this fact, from which source.

โ™พ๏ธ Loops and circular handoffs

Enforce at the orchestrator, not in the prompt:

  • ๐Ÿ”ข Max turns and handoff depth
  • ๐Ÿ” Per-agent retry limits
  • โฑ๏ธ Global time and token budgets
  • ๐Ÿ‘ฃ Visited-state / handoff history
  • ๐Ÿงฌ Duplicate-task detection (hash normalized task + state)
  • ๐Ÿ“ˆ Progress metrics that must move
  • ๐Ÿ Explicit terminal states
  • ๐Ÿ™‹ Escalate after repeated failure

๐ŸŽ’ Skills

A skill is a packaged capability: instructions, tool defs, examples, validators, domain knowledge. Do not stuff every tool into the system prompt. Load on demand:

  1. ๐Ÿงญ Classify intent
  2. ๐Ÿ”Ž Search a skill registry (metadata / embeddings)
  3. ๐Ÿ” Filter by user and tenant permissions
  4. ๐Ÿ“ฅ Load instructions + tools
  5. ๐Ÿ“ฆ Execute in a restricted environment
  6. โœ… Validate output
  7. ๐Ÿ“œ Record skill version in the trace

Skills should be trusted/signed, versioned, tested, and permission-scoped. A skill file is prompt injection with a README if you load it from the open internet.

๐Ÿงช โ€œDeterministicโ€ multi-agent tests

The LLM is probabilistic. Make the contract around it deterministic:

  • ๐Ÿ“ Fixed state schemas and tool interfaces
  • ๐ŸŒก๏ธ Low temperature where routing matters
  • ๐Ÿ“Œ Pinned model, prompt, tool, and skill versions
  • ๐ŸŽญ Mocked tools and replayable fixtures
  • ๐ŸŒฑ Seeded execution where the API allows
  • ๐Ÿ›‘ Explicit routing and stopping policies
  • ๐Ÿฅ‡ Golden scenarios + property / invariant tests
  • ๐Ÿ“œ Trace comparison and repeated-run stability

Measure separately: task correctness, route consistency, tool selection, argument accuracy, steps, cost, latency, policy compliance. Goal is controlled variability, not pretending the whole system is a pure function.

๐Ÿง  Memory, state, and context

Two memories, one trap:

  • ๐Ÿงพ Working memory โ€” this run: goal, recent messages, plan, tool results, pending calls. Lives in the prompt and/or a workflow state store. Precise and temporary.
  • ๐Ÿ“š Long-term semantic memory โ€” cross-session facts, preferences, prior decisions. External store, retrieved when relevant. Selectively written, permission-aware, provenance-tracked, revisable.

๐Ÿงฎ Context budget

Assign tokens to buckets before the model sees anything:

  • ๐Ÿ“œ System and policy (pinned โ€” compaction cannot drop these)
  • ๐ŸŽฏ Current user request
  • ๐Ÿ’ฌ Recent interactions
  • ๐Ÿ—บ๏ธ Active plan and state
  • ๐Ÿ“š Retrieved evidence
  • ๐Ÿ› ๏ธ Tool results
  • ๐Ÿ“ค Reserved output space

When you approach the limit: drop redundant tool output, replace older turns with structured summaries, persist large artifacts externally and pass references. Limit retrieval count and chunk size before data hits the model.

๐Ÿ—œ๏ธ Compaction and chunking

Chunk by semantic unit (turns, topics, tasks, documents, time), not arbitrary character counts. Overlap a little so references survive boundaries.

Compaction replaces old raw content with a structured summary: confirmed facts, preferences, decisions + rationale, open questions, completed actions, identifiers, source refs. Hierarchical: recent turns stay detailed; older sessions become task summaries; ancient history becomes durable facts. Keep links to originals when auditability matters. Compaction is lossy on purpose โ€” be honest about it.

๐Ÿ˜ The agent that never forgets

Permanent memory is not a feature; it is a liability portfolio:

  • ๐Ÿ” Sensitive or stale data retention
  • ๐Ÿšช Cross-user / cross-tenant leakage
  • โš–๏ธ Privacy and deletion compliance (right to be forgotten)
  • โ˜ ๏ธ Memory poisoning via malicious inputs
  • ๐Ÿ“‰ Irrelevant retrieval, slower vector search
  • ๐Ÿ’ธ Larger prompts, higher cost
  • ๐ŸงŠ Personalization on outdated facts

Need: retention policies, user controls, tenant isolation, encryption, access logs, expiration, deletion, relevance thresholds. More memory โ‰  better agent.

โš”๏ธ Retrieval conflicts

Rank by recency, source authority, confidence, and scope. Current explicit user instructions normally override inferred historical preferences. Verified records may override an unsupported claim when the fact matters. Keep value and provenance โ€” do not silently overwrite. For high-impact clashes, ask:

โ€œYour current request says X; the saved config says Y. Which should I use?โ€

Memory is evidence, not truth.

๐Ÿ‘ค Safe personalization across stateless sessions

Keep the model call stateless. Store the profile externally, user-scoped. Inject only relevant authorized fields. Controls: strong identity, consent, field-level ACL, encryption, minimization, expiration, user review + deletion, provenance timestamps, separation of preferences vs sensitive records. The model must not decide which userโ€™s memory to load.

๐Ÿฆ  Memorization of undesirable behavior

If a bad action, unsafe workaround, or injected โ€œpolicyโ€ gets written to memory, retrieval will teach the next run to repeat it. Example: a user convinces the agent that approval is unnecessary; that sentence is stored as procedure; later sessions skip HITL.

Mitigations: never learn security rules from conversation; separate user facts from immutable system policy; validate memory writes; trust + provenance scores; expire low-confidence memories; review high-impact procedural memories.

๐Ÿ’พ State store and vectors

Durable transactional store as source of truth. Each run is a state machine: run ID, version, current node, completed / pending actions, tool results, approvals, retries, timestamps. Want: atomic transitions, optimistic concurrency, idempotency keys, checkpoint after material steps, replication, queues with DLQ, worker leases, recover from latest checkpoint, audit log. Side effects via outbox so state and the real world cannot diverge.

For vectors: stable ID + version + timestamp + source on every record. Write the primary row first; embed asynchronously. Readers filter by active version. Dedup with content hashes and novelty thresholds โ€” long-running agents otherwise embed the same observation forever, inflating index size, latency, and prompt tokens.

๐Ÿญ LLMOps for agents

Classic MLOps versions datasets, training jobs, and model artifacts [10]. LLMOps versions the behavior-producing system:

  • ๐Ÿง  Foundation model + provider version
  • ๐Ÿ“œ System prompt
  • ๐Ÿ› ๏ธ Tools and schemas
  • ๐Ÿ“š Retrieval / memory config
  • ๐Ÿ•ธ๏ธ Agent graph
  • ๐Ÿ›ก๏ธ Guardrails and evaluators
  • ๐Ÿ“– Knowledge sources

The weights can sit still while a tool description change wrecks production. Treat the whole bundle as one release manifest.

๐Ÿ™‹ Human-in-the-loop

Pause before irreversible, expensive, sensitive, or low-confidence actions: external messages, payments, deletes, infra changes, regulated decisions.

The screen shows: proposed action, exact target, arguments, evidence, expected impact, risk, alternatives. Bind the approval to the exact action; expire it if state changed so an old yes cannot authorize a mutated call.

โ˜ ๏ธ Prompt injection

OWASP still ranks prompt injection as LLM01 [6]. Retrieved pages, emails, PDFs, images, and tool outputs may contain hostile instructions. For agents this is not a parlor trick โ€” it is confused-deputy with tools.

  • ๐Ÿงฑ Separate trusted instructions from untrusted content; label origin and trust
  • ๐Ÿšซ Never treat retrieved text as system policy
  • ๐Ÿ› ๏ธ Least-privilege tools for the current task
  • ๐Ÿ›ก๏ธ External policy checks on every action
  • ๐Ÿ™‹ HITL for high-risk ops
  • ๐Ÿ” Do not put secrets in the prompt
  • ๐ŸŒ Restrict network and filesystem
  • ๐Ÿงน Sanitize tool output; test with adversarial content

Content can inform an answer. Content cannot grant itself permissions.

๐Ÿ’ฃ Destructive actions

Defense in depth, not a polite system prompt:

  • ๐Ÿ‘€ Read-only DB credentials by default
  • ๐Ÿงฉ Parameterized tools, not arbitrary SQL
  • โœ… Allowlisted statements and tables; AST-parse SQL; reject DDL
  • ๐Ÿ™‹ HITL for authorized destruction
  • ๐Ÿงช Transactions, dry-run previews, row and time limits
  • ๐Ÿ’พ Backups and audit logs

๐Ÿ’ธ Cost of the loop

Optimize at the workflow, measure cost per successful task (a cheap model that retries forever is expensive):

  • ๐Ÿงญ Route simple work to small models; large models for hard planning / validation
  • ๐Ÿ—œ๏ธ Compact context; retrieve fewer, better chunks
  • ๐Ÿ’พ Cache stable prompts, embeddings, tool results
  • โšก Parallelize independent steps
  • ๐Ÿ“ Structured tool outputs (less prose to re-ingest)
  • ๐Ÿ›‘ Stop when marginal gain is flat; cap reflection
  • ๐Ÿงฑ Replace LLM decisions with rules where you can

๐Ÿ“ก Tracing

One trace ID per user request. Every model call, retrieval, tool call, handoff, state transition, approval, and error is a child span (LangSmith, OpenTelemetry, your tracer). Record: model/prompt versions, sanitized I/O, tool name + validated args, latency, tokens, cost, retrieved IDs, routing decisions, retries, policy decisions, outcome, user feedback. Redact before log. Dashboards: success, latency, cost, loop rate, tool failures, escalations, policy violations.

๐Ÿ›ก๏ธ Layered guardrails

Prefer deterministic validators when the rule is code-shaped. Model-based judges are for semantic quality โ€” calibrate them, version them, and never let a judge be the only lock on a high-risk action.

๐Ÿ“บ Streaming UI

Separate user-visible events from internal tokens. Publish structured events: accepted, planning, searching, tool running, waiting for approval, partial answer, retrying, done/failed. Stream safe response text; show concise tool status. Do not stream private reasoning or unvalidated tool dumps. Support cancel, reconnectable streams, ordered event IDs, backpressure, resumable state.

๐Ÿ“ฆ Versioning, rollback, A/B

Ship a manifest, canary it, keep the previous bundle deployable. Pin in-flight runs to the version they started on. For A/B: assign users or stable sessions so a conversation does not switch mid-thread; change one major factor at a time; pre-register metrics (completion, accuracy, corrections, tool success, steps, latency, cost per success, escalations, safety, satisfaction). Stratify by task difficulty โ€” a win on easy tickets can hide a regression on hard ones. Sequence: replay โ†’ shadow โ†’ limited live โ†’ rollback thresholds. Same traffic-strategy instincts as model serving [10].

๐Ÿช™ My 2 cents

Stop asking โ€œshould we use agents?โ€ Ask the questions that force an architecture:

  • ๐Ÿ“‹ Can I write the steps as a DAG today?
  • ๐Ÿ’ฅ What is the blast radius of a wrong tool call?
  • ๐Ÿงช How do I know the task is done โ€” test, schema, human?
  • ๐Ÿ’ธ What is the token budget per successful outcome?
  • ๐Ÿ™‹ Who approves irreversible actions?

Answer those and the pattern almost picks itself:

  • ๐Ÿ’ฌ Single call + RAG when the path is a paragraph
  • ๐Ÿงฑ Workflow when the path is a recipe
  • ๐Ÿค– Agent when the path is unknown and the environment gives ground truth
  • ๐Ÿ‘ฅ Multi-agent only when roles are separable
  • ๐Ÿ›ก๏ธ Permission envelope outside the model โ€” always

Contracts that are non-optional:

  • ๐ŸŽ›๏ธ Orchestrator-enforced budgets, not prompt manners
  • ๐ŸŽ’ Skills over god-prompts
  • ๐Ÿ“œ Memory is evidence, never policy
  • ๐Ÿ“ฆ Version the whole agent config, not the weights alone
  • ๐Ÿ“ก Traces you can replay; evals you can fail a release on

๐ŸŒฑ Treat agentic AI as something you design โ€” a control loop with a kill switch โ€” not a prompt you hope stays on the rails.

๐Ÿ“š References

  1. Erik S. and Barry Zhang, โ€œBuilding effective agents,โ€ Anthropic Engineering, anthropic.com/engineering/building-effective-agents
  2. Shunyu Yao et al., โ€œReAct: Synergizing Reasoning and Acting in Language Models,โ€ ICLR 2023, arxiv.org/abs/2210.03629
  3. Shunyu Yao et al., โ€œTree of Thoughts: Deliberate Problem Solving with Large Language Models,โ€ NeurIPS 2023, arxiv.org/abs/2305.10601
  4. Noah Shinn et al., โ€œReflexion: Language Agents with Verbal Reinforcement Learning,โ€ NeurIPS 2023, arxiv.org/abs/2303.11366
  5. Model Context Protocol, specification, modelcontextprotocol.io
  6. OWASP GenAI Security Project, โ€œLLM01: Prompt Injection,โ€ genai.owasp.org/llmrisk/llm01-prompt-injection
  7. Stuart Russell and Peter Norvig, Artificial Intelligence: A Modern Approach, aima.cs.berkeley.edu
  8. Jason Wei et al., โ€œChain-of-Thought Prompting Elicits Reasoning in Large Language Models,โ€ NeurIPS 2022, arxiv.org/abs/2201.11903
  9. LangChain, โ€œLangGraph checkpointers,โ€ docs.langchain.com/โ€ฆ/langgraph/checkpointers
  10. Amirhessam Tahmassebi, โ€œMLOps Deployment Strategies,โ€ 2-Cents, two-cents/mlops-deployment-strategies.html
  11. LangChain, LangSmith tracing, docs.smith.langchain.com
  12. OpenAI, Agents SDK, openai.github.io/openai-agents-python
  13. CrewAI, documentation, docs.crewai.com
  14. AG2 (AutoGen), ag2.ai
  15. OWASP, โ€œTop 10 for Large Language Model Applications,โ€ owasp.org/www-project-top-10-for-large-language-model-applications