Most production agent incidents happen before the model even hallucinates. They happen when an engineering team asks a large language model to enforce authorization, compute exact refund math, track state across retries, and grade its own work inside one sprawling system prompt.

A reliable AI agent is not a bigger prompt. It is conventional software architecture wrapped tightly around a reasoning model such as Gemini Neon 4—keeping uncertainty inside the model while pushing determinism, state, permissions, and cost controls into ordinary code.

The Core Boundary: Deterministic Code vs. Model Reasoning

Every call to a reasoning model carries latency, non-determinism, and token cost. The fastest way to stabilize an agentic system is to draw a hard architectural line between what code guarantees and what the model interprets.

Responsibility Owner Implementation Pattern
Exact math, dates, limits, schema validation Deterministic code Pure functions, JSON Schema, server-side validators
Auth, permissions, side-effect allowlists Deterministic code Server-side policy checks and idempotency keys
Ambiguous intent, synthesis, open-ended routing Reasoning model Structured JSON output validated against an allowlist
Mandatory execution sequence & human pauses Workflow / Graph Typed state machine with persisted resume checkpoints
Iterative refinement against objective criteria Bounded loop External iteration/cost caps + independent evaluator

Four Layers Around the Model

In production agent harnesses aligned with Google Agent Development Kit (ADK) patterns, the model sits at the center of four defensive layers:

  • Learn (Progressive Context): Instead of stuffing an entire engineering handbook into the system prompt, load context in three stages—skill discovery metadata first, SKILL.md instructions on activation, and supporting scripts or domain references only during execution. Pair this with a concise repository map so the agent locates nearby tests before editing.
  • Guard (Deterministic Controls): Wrap every tool call with strict input schemas, separate read operations from side effects, enforce timeouts and idempotency keys, and execute linting, typechecking, secret scanning, and server-side authorization outside the model context.
  • Review (Fresh-Context Critique): Never let a primary agent grade its own loop output inside the same polluted conversation. Run an independent reviewer in a clean context against explicit acceptance criteria and raw tool traces, keeping human approval mandatory for irreversible mutations.
  • Score (Outcome & Trajectory Evals): A plausible final sentence does not prove an external mutation succeeded. Evaluate both the final outcome and the exact tool trajectory—tool selection, argument accuracy, call ordering, p95 latency, and mean cost per run.

Orchestration Topology: When to Skip Graphs and Bound Loops

Adding multi-agent graphs by default is one of the fastest ways to inflate latency and debugging overhead. Start with a single agent equipped with 2 to 5 narrow read/write tools. Only introduce a graph when you require mandatory sequencing, parallel fan-out/fan-in joins, typed state persistence across human approvals, or strict auditability of the execution path.

Topology Best Fit Main Strength Primary Risk
Single Agent Small scope, 2–5 narrow tools Minimal latency and low maintenance Control degrades as tool count grows
Sequential Workflow (SequentialAgent) Fixed assembly-line stages Predictable execution order Inflexible on open-ended inputs
Parallel Workflow (ParallelAgent) Independent research or read branches Lower wall-clock latency via fan-out/fan-in Merge complexity and parallel token spikes
Bounded Loop (LoopAgent) Iterative refinement with objective pass checks Converges on verifiable quality targets Runaway token spend if bounds are omitted
Graph Workflow Policy gates, branches, human pause states Deterministic control and full auditability Higher engineering and state overhead

A critical implementation detail in google/adk-python makes explicit bounds mandatory: LoopAgent defaults to max_iterations=None, which runs indefinitely unless you pass a hard cap or emit an explicit escalation signal (tool_context.actions.escalate = True). Production loops should enforce iteration, wall-clock duration, USD spend, and repeated-failure stop rules externally:

from google.adk.agents import LoopAgent

# Always set max_iterations; Python ADK defaults to None (unbounded)
refinement_loop = LoopAgent(
    name="VerifiedRefinementLoop",
    sub_agents=[worker_agent, fresh_context_critic],
    max_iterations=4,
)

# Exit early inside a deterministic validator tool when criteria pass:
# tool_context.actions.escalate = True

Similarly, human-in-the-loop approvals must pause workflow execution at the application layer (persisting a WAITING_FOR_APPROVAL state until an external resume(event) fires)—never by asking the model in a prompt to "wait for the user."

4-Store Memory Architecture and Automated Eval Gates

Dumping session logs, transactional records, user preferences, and raw files into a single vector database destroys retrieval precision. Partition memory by access contract—matching how Google ADK and Vertex AI Agent Engine separate short-term SessionService state from long-term Memory Bank consolidation:

Memory Layer Stored Data Storage Engine Retrieval & Write Rule
Session State Active turn events, current plan, tool outputs Runtime / SessionService Exact read/write scoped to active session
Structured Facts Orders, dates, quotas, permissions Transactional SQL DB Synchronous write, key-based exact query
Semantic Understanding Durable preferences and cross-session patterns Vector Store / VertexAiMemoryBankService Async extraction off hot path (PreloadMemoryTool / LoadMemoryTool) with provenance and TTL
Raw Artifacts Audio, video, PDFs, build outputs Object Storage Explicit reference ID; never auto-indexed as memory

Before releasing prompt, model, or tool changes, ADK AgentEvaluator pipelines validate both process and response quality in CI using trajectory and output thresholds:

{
  "criteria": {
    "tool_trajectory_avg_score": 1.0,
    "response_match_score": 0.8
  }
}
  • Release Gate Baseline: 100% pass rate on critical safety/mutation cases, >= 95% overall eval pass rate, 0 unvalidated side-effect errors, and enforced ceilings on p95 latency and mean cost per task.

Where This Breaks (Trade-offs & Failure Modes)

  • Premature Graph Complexity: Wrapping a simple 3-tool lookup flow in a multi-node graph with typed reducers adds serialization boilerplate and slows iteration without improving reliability.
  • Brittle Exact Trajectory Assertions: Setting tool_trajectory_avg_score with strict EXACT matching breaks valid runs whenever a reasoning model reorders two independent read calls. Switch independent read steps to IN_ORDER or ANY_ORDER matching, or evaluate state invariants directly.
  • Hot-Path Semantic Extraction Latency: Running LLM memory extraction synchronously before returning a user response spikes p95 latency and doubles token burn per turn. Queue semantic consolidation asynchronously after the turn completes (for example, via post-agent callbacks).
  • Test & Gate Gaming: If a coding or operational agent has write permissions over evals/, CI configs, or test thresholds, bounded loops can learn to weaken assertions or add skip flags to pass gates. Keep gate configs strictly read-only to the agent.

Production Decision Matrix & Rollout Checklist

  1. Phase 1 — Baseline: Ship 1 agent, 2–5 read-only tools, strict schemas, full event tracing, cost caps, and 20–30 labeled eval cases.
  2. Phase 2 — Safe Mutations: Split read and write tools, require idempotency keys and server-side policy checks, and mock external mutations in evals.
  3. Phase 3 — Controlled Workflows: Introduce typed workflow state, deterministic routing, parallel independent reads, and persisted human approval states.
  4. Phase 4 — Partitioned Memory & CI Hardening: Separate SQL facts from async semantic memory with provenance/deletion controls, enforce fresh-context reviews, and turn every production incident into a permanent regression case.

References & Primary Sources

This technical breakdown combines official Google ADK and Vertex AI documentation with the eight Google Cloud Tech engineering talks synthesized in the embedded playbook:

Embedded Reference Playbook

Expand Full Embedded Reference Playbook (GEMINI.md)

Original 20-section Markdown reference synthesized from the 8 source engineering talks, preserved verbatim for copy-paste and repository onboarding:

# Building Reliable AI Agents with Gemini Neon 4

A practical playbook for agent architecture, loops, graphs, memory, tools, guardrails, reviews, and evaluations.

> This document uses `Gemini Neon 4` as the name of the selected reasoning model. Replace it with the actual model identifier from your SDK. The architecture below is model- and framework-agnostic.

---

## 1. Core idea

A reliable agent is not a large prompt. It is a software system built around a model.

Use the model for interpretation, reasoning, and decisions under uncertainty. Use ordinary code for exact calculations, mandatory checks, permissions, critical sequencing, and irreversible actions.

```text
Agent system = Model + Tools + State + Control flow + Guardrails + Evals
```

Practical rule:

```text
Deterministic work       → function or service
Ambiguous reasoning      → Gemini Neon 4
Mandatory sequence       → workflow or graph
Iterative improvement    → bounded loop
Irreversible action      → validation + confirmation + audit
```

Do not ask a model to “be accurate” where accuracy can be guaranteed by code.

---

## 2. Choosing an architecture

Start with the smallest design that can solve the problem. Add complexity only when there is a measurable reason.

| Architecture | Best fit | Main strength | Main risk |
|---|---|---|---|
| Single agent | Small task, few tools, adaptive action order | Simple and flexible | Loses control as complexity grows |
| Sequential workflow | Steps always run in a fixed order | Predictable | Inflexible |
| Parallel workflow | Independent subtasks | Lower latency | Higher cost and merge complexity |
| Agent team | Stable specialist responsibilities | Isolated instructions and context | Delegation and handoff failures |
| Graph workflow | Required steps, branches, approvals, pauses | Control and auditability | More engineering overhead |
| Dynamic graph | Workflow shape depends on input | Adaptive | Harder to test and constrain |

### Decision tree

1. Can one model with two to five tools solve the task reliably?
   - Yes: start with one agent.
   - No: continue.
2. Are there stable, independent areas of responsibility?
   - Yes: introduce specialist agents.
3. Are there mandatory steps, financial actions, approvals, or policy requirements?
   - Yes: enforce them with a graph and deterministic nodes.
4. Are some reads or research tasks independent?
   - Yes: run them in parallel and add a join/synthesis step.
5. Must work repeat until it meets an objective standard?
   - Yes: use a bounded loop with an external evaluator.

### When not to use a graph

Do not build a graph merely because a system is described as “agentic.” A few functions and one agent are often faster, cheaper, and easier to maintain.

Use a graph when you need explicit control over:

- required steps;
- parallel execution;
- data dependencies;
- stopping points;
- human decisions;
- the path that produced a result.

---

## 3. Recommended production architecture

```text
User / Event
    │
    ▼
Input validation ──► Authentication / Authorization
    │
    ▼
Deterministic router
    │
    ├──► Simple response
    ├──► Single-agent loop
    ├──► Sequential workflow
    └──► Graph workflow
              │
              ├──► Data retrieval nodes
              ├──► Gemini Neon 4 reasoning nodes
              ├──► Deterministic policy nodes
              ├──► Tool/action nodes
              ├──► Independent reviewer
              └──► Human approval
    │
    ▼
Output validation ──► Audit log ──► Response
```

### Four layers around the model

#### Layer 1: Learn

Give the agent only relevant, current context:

- a concise repository or domain map;
- the current plan and task state;
- relevant documents;
- skills loaded on demand;
- exact user facts and relevant semantic memories.

Do not place an entire handbook in the system prompt.

#### Layer 2: Guard

Wrap the model in deterministic controls:

- schema validation;
- type checking and compilation;
- unit and integration tests;
- linters;
- secret scanning;
- SAST and dependency scanning;
- time, iteration, token, and cost budgets;
- tool and path allowlists;
- server-side authorization for every action.

#### Layer 3: Review

Separate generation from critique:

- run the reviewer in a fresh, independent context;
- compare results against requirements and a rubric;
- inspect screenshots or videos for UI work;
- review diffs, architecture, and scope for code changes;
- keep final approval with a human for critical operations.

#### Layer 4: Score

Evaluate the whole harness, not only the final answer:

- tool selection;
- tool arguments;
- action order;
- handoff quality;
- real-world outcome;
- cost and latency;
- consistency across repeated runs;
- regressions after changing the model, prompt, or tools.

---

## 4. Tool design

A tool is a contract between the model and the real world. Its public interface should be narrower than the underlying service.

### A good tool should have

- one clear responsibility;
- a strict input schema;
- a structured result;
- explicit error types;
- least-privilege access;
- a timeout;
- idempotency where possible;
- a trace ID;
- a clear distinction between reads and side effects.

Example:

```json
{
  "name": "create_refund",
  "description": "Creates a refund only after eligibility has been verified",
  "input_schema": {
    "type": "object",
    "required": ["order_id", "amount", "eligibility_token"],
    "properties": {
      "order_id": {"type": "string"},
      "amount": {"type": "number", "minimum": 0},
      "eligibility_token": {"type": "string"},
      "idempotency_key": {"type": "string"}
    },
    "additionalProperties": false
  },
  "side_effect": true,
  "requires_confirmation": true
}
```

Avoid broad tools:

```text
manage_order(order_id, action, options)
```

Prefer narrow operations:

```text
get_order(order_id)
check_refund_eligibility(order_id)
preview_refund(order_id, amount)
create_refund(order_id, amount, eligibility_token, idempotency_key)
```

The model should not calculate exact refund amounts, verify its own permissions, or claim that an operation succeeded. Code must do that.

---

## 5. Graph engineering

A graph describes relationships between units of work.

- **Node:** function, model call, agent, waiting state, or human action.
- **Edge:** transition condition and data contract.
- **State:** typed workflow state.

### Minimal graph

```text
START
  │
  ▼
load_facts()          # code, no model
  │
  ▼
reason_with_gemini()  # model reasoning
  │
  ▼
validate_output()     # code
  │
  ▼
END
```

### Fan-out and fan-in

```text
                 ┌──► get_order ─────┐
START ── fanout ─┼──► get_payment ───┼──► join ──► policy_check
                 └──► get_history ───┘
```

Independent reads run concurrently. The join waits for all required branches and combines their results into a typed object.

### Routing

Use deterministic routing when the option set is closed and the signal is already present in structured data:

```python
def route(case):
    if case.missing_fields:
        return "request_information"
    if case.requires_exception:
        return "human_review"
    if case.eligible:
        return "execute_action"
    return "reject"
```

Use Gemini Neon 4 as a router when the input is open-ended natural language and ordinary rules cannot classify it reliably. Validate the selected route against an allowlist afterward.

### Human in the loop

The workflow must persist its state and resume after a human decision.

```text
proposed_action
    │
    ▼
risk_check ── high risk ──► WAITING_FOR_APPROVAL
    │                              │
    low risk                       ▼
    │                         resume(event)
    └──────────────► execute_action
```

Do not simulate waiting with a prompt instruction. Stop the workflow at the application layer.

---

## 6. Loop engineering

Loops work well for bounded, repetitive, verifiable tasks.

```text
Plan → Act → Observe → Check → Improve
                 ▲               │
                 └───────────────┘
```

Every loop needs:

- `max_iterations`;
- `max_duration`;
- `max_tokens` or `max_cost`;
- a measurable success condition;
- an action allowlist;
- a repeated-failure stop rule;
- human escalation after the budget is exhausted.

```python
def run_loop(task, budget, evaluator):
    state = create_state(task)

    for attempt in range(budget.max_iterations):
        proposal = gemini_neon_4.act(state)
        action = validate_action(proposal.action)
        observation = execute(action)
        score = evaluator.evaluate(task, observation)
        state.record(proposal, observation, score)

        if score.passed:
            return success(state)
        if state.cost >= budget.max_cost:
            break
        if state.repeated_failure_count >= 2:
            break

    return escalate_to_human(state)
```

### Four common loop failures

1. **Runaway loops:** no stop rule, so tokens and money keep burning.
2. **Unverified autonomy:** the agent grades its own work in a polluted context.
3. **Uncheckable goals:** “make it better” has no measurable completion condition.
4. **Excessive complexity:** one loop tries to produce a large, multi-part artifact.

Fix them by enforcing budgets, using an independent evaluator, defining objective criteria, and moving complex work into a graph with smaller loops inside individual nodes.

---

## 7. Agent teams and handoffs

A specialist is justified when it has its own:

- instructions;
- tools;
- context;
- completion criteria;
- responsibility boundary.

```text
Coordinator
  ├── Shipping specialist
  ├── Billing specialist
  └── Policy specialist
```

All specialists may use the same underlying model. Their roles come from their instructions, tools, and context.

Do not use free-form summaries for handoffs when structured data is possible:

```json
{
  "task_id": "case-123",
  "from": "shipping_agent",
  "to": "billing_agent",
  "status": "completed",
  "facts": {
    "carrier_status": "lost",
    "tracking_id": "TRK-42"
  },
  "evidence": ["carrier-api:response-991"],
  "uncertainties": [],
  "requested_next_action": "check_refund_eligibility"
}
```

Evaluate two things:

1. Was the task delegated to the correct specialist?
2. Were the correct facts transferred without losing user updates?

---

## 8. Context and skills

Large system prompts become stale and displace useful context. Use progressive disclosure.

### Three stages of skill loading

1. **Discovery:** read only the skill name and short description.
2. **Activation:** load the main `SKILL.md` when the task matches.
3. **Execution:** load supporting scripts and references only when needed.

```text
skills/
  refund-processing/
    SKILL.md
    references/
      policy.md
      error-codes.md
    scripts/
      validate_refund.py
```

Skill metadata must explain precisely when the skill applies. Its instructions should define the process, constraints, validation steps, and stopping conditions.

Use a concise repository map instead of a full manual:

```markdown
# Repository map

- API: `src/api/`
- Domain rules: `src/domain/`
- Tool adapters: `src/tools/`
- Agent workflows: `src/agents/`
- Evals: `evals/`
- Commands: `docs/development.md`

Before editing, locate the nearest tests and read the relevant domain rule.
```

---

## 9. Agent memory

Do not put all memory into one vector store.

| Memory type | Example | Storage | Retrieval |
|---|---|---|---|
| Session state | current goal and tool results | runtime/session store | exact read |
| Structured facts | order, date, subscription | SQL/transactional DB | key-based query |
| Semantic understanding | stable preferences and patterns | vector store/memory bank | similarity search |
| Raw artifacts | audio, video, files | object storage | explicit reference |

### Writing rules

- Write confirmed facts immediately.
- Create semantic memories only from sufficiently strong signals.
- Run semantic extraction outside the latency-critical path.
- Do not treat raw media as memory automatically.
- Store source, time, owner, confidence, and deletion policy.
- Let users inspect, correct, and delete their memories.

### Session lifecycle

```text
Session start
  ├── Load exact facts from SQL
  ├── Retrieve relevant semantic memories
  └── Build bounded context

During session
  ├── Write confirmed facts synchronously
  └── Queue semantic extraction asynchronously

Session end
  ├── Extract durable understanding
  ├── Deduplicate / merge / expire
  └── Save provenance and confidence
```

Example semantic memory:

```json
{
  "memory_id": "mem-123",
  "user_id": "user-42",
  "statement": "Prefers concise technical answers",
  "confidence": 0.86,
  "source_session_ids": ["session-7", "session-12"],
  "created_at": "...",
  "last_confirmed_at": "...",
  "expires_at": null,
  "sensitivity": "low"
}
```

---

## 10. Evaluation strategy

Evaluate agents on two levels:

1. **Outcome:** is the final result correct?
2. **Trajectory:** did the agent take the correct steps?

A convincing text response does not prove that the external action happened.

| Evaluation target | Method | Best use |
|---|---|---|
| Reference answer | exact or semantic comparator | stable tasks with known answers |
| Requirements | checker | tasks with multiple valid answers |
| Exact facts and rules | code | dates, limits, schemas, permissions |
| Meaning and quality | LLM judge | clarity, completeness, rubric compliance |

Prefer deterministic checks. Use a model judge only when the criterion genuinely requires interpretation.

### Eval suite coverage

Include:

- normal successful cases;
- boundary values;
- missing or conflicting data;
- unavailable tools;
- repeated side-effect requests;
- requirement changes in multi-turn conversations;
- prompt injection attempts;
- incorrect handoffs;
- latency and budget overruns;
- user cancellation or refusal.

### Tool evaluation

Verify:

- correct tool selection;
- exact arguments;
- required call order;
- absence of unnecessary calls;
- no duplicated side effects;
- agreement between the real tool result and the final response.

Use mocks or a sandbox for financial operations and external mutations.

### Test the evaluator

Before trusting an evaluator, run it on labeled examples:

- known-good results pass;
- known-bad results fail;
- multiple valid solutions pass;
- incomplete answers are not silently completed by the evaluator;
- the rubric is applied consistently across different wording.

### Stability

One successful run does not establish reliability. Repeat critical cases and measure pass rate.

```text
release gate:
  critical_cases_pass_rate = 100%
  overall_pass_rate >= 95%
  side_effect_errors = 0
  p95_latency <= target
  mean_cost <= budget
```

---

## 11. CI/CD and deterministic gates

Run cheap objective checks before semantic review:

```text
format
→ lint
→ typecheck
→ unit tests
→ integration tests
→ secret scan
→ dependency scan
→ policy checks
→ agent evals
→ independent semantic review
→ human approval
→ deploy
```

### Prevent gaming the tests

- A new test must fail against the old implementation first.
- Existing tests require separate approval to change.
- Block unexpected `skip` tags, weakened assertions, and disabled linters.
- Block reductions in coverage or test count.
- Require lock files and scan new dependencies.
- Keep gate configuration outside the agent's write scope.
- Re-run tests to detect flakiness.

When a gate fails, return the raw diagnostic signal to the agent: rule ID, file, line, and assertion. Stop after a limited number of retries and escalate to a human.

---

## 12. Observability

Every run should produce a trace suitable for debugging and evaluation.

Minimum events:

```text
run_started
context_loaded
model_called
tool_requested
tool_validated
tool_completed
route_selected
approval_requested
approval_received
memory_written
evaluation_completed
run_completed / run_failed / run_escalated
```

Record:

- `run_id`, `trace_id`, and `user_id`;
- timestamp and latency;
- model, prompt, and tool versions;
- tool name and safely filtered arguments;
- token usage and cost;
- validation result;
- graph transition;
- stopping reason.

Never place secrets or unredacted sensitive data in logs.

---

## 13. Suggested project structure

```text
agent-system/
  app/
    api/
    models/
    agents/
      coordinator.py
      specialists/
    workflows/
      main_graph.py
      state.py
      routes.py
    tools/
      read/
      write/
      schemas/
    memory/
      session.py
      structured.py
      semantic.py
    policies/
    reviewers/
    observability/
  skills/
  prompts/
    system.md
    reviewer.md
  evals/
    cases/
    rubrics/
    metrics/
    regression/
  tests/
  docs/
    architecture.md
    repository-map.md
    operations.md
```

---

## 14. System prompt template for Gemini Neon 4

Use the prompt to define behavior, not to replace application-level controls.

```markdown
# Role

You are the reasoning component of an agent system. You may act only through the provided tools and within the current workflow.

# Objective

Achieve the user's goal using confirmed facts and the minimum necessary number of actions.

# Rules

1. Never invent tool results, external facts, or completed actions.
2. Validate required arguments before requesting a tool.
3. Do not claim success until a tool returns confirmation.
4. If data conflicts, expose the conflict and request a decision.
5. Do not perform an irreversible action without required confirmation.
6. Stop once the success criteria are satisfied.
7. Do not repeat an action indefinitely; return a structured blocker.
8. Separate facts, inferences, and assumptions.

# Output contract

Return JSON:

{
  "status": "continue | done | needs_input | blocked",
  "reasoning_summary": "brief explanation",
  "facts_used": [],
  "next_action": {
    "type": "tool | response | handoff",
    "name": "...",
    "arguments": {}
  },
  "uncertainties": [],
  "success_evidence": []
}
```

Validate the JSON at the application layer and reject unknown actions.

---

## 15. Independent reviewer prompt

```markdown
# Role

You are an independent reviewer. You did not create the result and must not defend the primary agent's decisions.

# Inputs

- original task;
- acceptance criteria;
- facts and evidence;
- tool trace;
- produced result.

# Review procedure

1. Evaluate every acceptance criterion separately.
2. Verify that claims are supported by evidence.
3. Identify missing requirements and unintended side effects.
4. Separate blocking defects from recommendations.
5. Do not silently repair the result.

# Output

{
  "verdict": "pass | fail | uncertain",
  "score": 0.0,
  "blocking_issues": [],
  "non_blocking_issues": [],
  "evidence_checked": [],
  "recommended_next_step": "accept | revise | human_review"
}
```

---

## 16. Implementation roadmap

### Phase 1: Baseline

- one agent;
- two to five read-only tools;
- strict schemas;
- full tracing;
- step and cost limits;
- 20–30 evaluation cases.

### Phase 2: Safe actions

- separate read and write tools;
- idempotency keys;
- policy checks;
- confirmation for side effects;
- audit log;
- mock tools for evaluations.

### Phase 3: Workflow

- typed state;
- deterministic policy nodes;
- routing;
- persistence and resume;
- human approval;
- parallel independent reads.

### Phase 4: Specialization

- agents split only along stable responsibility boundaries;
- structured handoffs;
- separate evaluations for specialists and coordinator;
- multi-agent cost controls.

### Phase 5: Memory

- session state;
- structured facts;
- semantic memory with provenance;
- asynchronous extraction;
- user controls for inspection and deletion.

### Phase 6: Production hardening

- deterministic gates;
- independent reviewer;
- CI evaluations;
- canary rollout and rollback;
- quality, cost, and latency monitoring;
- regression cases from every incident.

---

## 17. Anti-patterns

- One giant prompt instead of an architecture.
- A model with permission to perform any action.
- Unvalidated tool inputs or outputs.
- An agent grading its own work in the same context.
- Loops without iteration, time, and cost budgets.
- Goals expressed as “make it better.”
- All memory stored in one vector database.
- Side effects without idempotency keys.
- Human approval implemented only as a prompt instruction.
- Treating one successful demo as proof of reliability.
- Letting the agent edit tests and gate configuration.
- Adding more agents as a default solution.
- Parallelizing dependent steps.
- Passing an entire chat instead of a structured handoff.
- Claiming success without evidence of the external effect.

---

## 18. Production checklist

### Architecture

- [ ] Every model call has a clear reason to exist.
- [ ] Exact rules are implemented in code.
- [ ] Required sequencing is enforced by a workflow.
- [ ] Parallel operations are genuinely independent.
- [ ] Every agent has a clear responsibility boundary.

### Tools and safety

- [ ] Tool inputs and outputs have schemas.
- [ ] Read and write operations are separated.
- [ ] Side effects require confirmation and are idempotent.
- [ ] Authorization is enforced server-side.
- [ ] Secrets are unavailable to the model and absent from logs.
- [ ] The agent cannot modify its own gates.

### Loops

- [ ] Iteration, time, token, and cost budgets exist.
- [ ] Success is objectively checkable.
- [ ] Repeated failures stop the loop.
- [ ] Human escalation is available.

### Memory

- [ ] Session state, facts, semantic memory, and artifacts are separated.
- [ ] Memories include provenance and confidence.
- [ ] Semantic extraction does not block the live path.
- [ ] TTL, correction, and deletion are supported.

### Evaluations

- [ ] Both outcome and trajectory are tested.
- [ ] Tool choice, arguments, and ordering are covered.
- [ ] Multi-turn and handoff cases exist.
- [ ] Evaluators are tested on labeled examples.
- [ ] Critical cases are repeated.
- [ ] Regressions block release.

### Observability

- [ ] Every run has a trace.
- [ ] Model, prompt, and tool versions are recorded.
- [ ] Pass rate, p95 latency, and cost are monitored.
- [ ] Incidents become regression cases.

---

## 19. Compact operating formula

```text
Start with one agent.
Give it narrow tools.
Move exact rules into code.
Put mandatory steps in a graph.
Run independent steps in parallel.
Bound every loop with a budget and a measurable goal.
Separate generation from critique.
Store facts exactly and understanding semantically.
Evaluate both the outcome and the path.
Do not release without deterministic gates and regression evals.
```

---

## 20. Sources used for the synthesis

This playbook was synthesized from cleaned captions and local transcripts of eight videos. The material was reorganized and paraphrased by topic rather than reproduced as a verbatim transcript.

1. [Graph Engineering with ADK](https://youtu.be/Mzr7byMFy_4)
2. [Why everyone is talking about graphs in AI (and when to skip them)](https://youtu.be/2sS9XS-Fw90)
3. [4 ways loop engineering fails (and how to fix them)](https://youtu.be/ruNekO9De8E)
4. [Building a custom evaluation for your agent](https://youtu.be/GatM9XV0gOw)
5. [3 ways to design your agentic system](https://youtu.be/czosBPhFnDI)
6. [AI Agent Memory Architecture](https://youtu.be/8C4bh59FtsI)
7. [How Google engineers build AI agents in production](https://youtu.be/BKVDdL1InsA)
8. [AI agent design patterns](https://youtu.be/GDm_uH6VxPY)