19. AI Engineering — Interview Workshop#
A fast, conceptual revision guide for 03-ai-engineer-interview-notes. Synthesizes all four end-to-end interview project walkthroughs (24 follow-ups) and 50 practice Q&As — covering foundations, RAG, memory and checkpoints, multi-agent coordination, MCP/A2A protocols, AWS deployment trade-offs, and governance/observability — without code bloat.
Foundations: Models, Agents, Frameworks & Workflows#
Revision Notes#
Reference file: AI Engineering — Interview Workshop.html (Practice Q1–Q7, Q12–Q13, Q15, Q24)
Concept#
In interviews, the first filter is whether you clearly separate what the model does, what the orchestration framework does, and what the hosting runtime and application code enforce. An AI agent is not a smarter chatbot — it is an application that pairs an LLM with instructions, tools, and a bounded execution loop where application code (never the model directly) performs real-world actions.
Key Mental Models#
- Three distinct stack layers:
- Model & model access: The LLM (e.g., Claude) generates text or tool requests; Amazon Bedrock provides managed API access without running inference servers. Amazon SageMaker AI enters when a team needs custom model training or self-managed serving control — not merely to keep up with changing business documents.
- Orchestration framework: Strands (agent loop,
@toolregistration,GraphBuilder) or LangGraph (explicit graph state and durable checkpoints) coordinates prompts, tool calls, and control flow. - Hosting runtime & infrastructure: AWS Lambda, Amazon ECS on Fargate, or Amazon Bedrock AgentCore Runtime runs the application code and wires in databases, memory, networking, and IAM permissions.
- Fixed workflow vs. agent autonomy:
- Use fixed control flow (ordinary Python sequence or graph) whenever steps are known and mandatory (e.g., retrieve before answering, validate before booking).
- Use agent choice when the next useful tool or delegation depends on the user's request or an intermediate result.
- Combine both: code enforces stage order while the model handles language interpretation inside each stage.
- Tokens & prompt boundaries:
- Tokens are tokenizer units (not word counts). System instructions, tool schemas, chat history, and retrieved passages all consume the input budget, and room must be reserved for output.
- System instructions define stable role, scope, and evidence rules; user input states the current task; retrieved passages / tool outputs are untrusted evidence — never authority to override instructions or bypass permissions.
- Deterministic code for deterministic work:
- Put calculations, validations, and external lookups in narrow, typed Python
@toolfunctions (or class methods when multiple tools share a managed resource like a SQLite connection or reusable client). - Test tool functions directly in isolation before blaming LLM reasoning for provider or parsing bugs.
- Fluency is never a correctness test: constrain tasks with evidence, preserve explicit error statuses, and enforce iteration limits so a failing tool cannot spin forever.
- Put calculations, validations, and external lookups in narrow, typed Python
Interview-ready architectures start with deterministic code workflows and add bounded tool loops, stateful graphs, or multi-agent teams only when dynamic inputs or parallel I/O justify the cost.
Code Reference#
def reciprocal_rank_fusion(
dense_ids: list[str], bm25_ids: list[str], k: int = 60
) -> list[tuple[str, float]]:
"""Fuse vector + BM25 rankings without brittle score normalization."""
# RRF uses rank positions rather than raw cosine/BM25 scores (which live on
# incompatible scales). k=60 dampens the dominance of rank #1 outliers while
# rewarding documents retrieved highly by BOTH semantic and lexical search.
scores: dict[str, float] = {}
for rank, doc_id in enumerate(dense_ids, start=1):
scores[doc_id] = scores.get(doc_id, 0.0) + 1.0 / (k + rank)
# -> for dense=['doc_a','doc_b','doc_c']:
# -> {'doc_a': 1/61 (0.0164), 'doc_b': 1/62 (0.0161), 'doc_c': 1/63 (0.0159)}
for rank, doc_id in enumerate(bm25_ids, start=1):
scores[doc_id] = scores.get(doc_id, 0.0) + 1.0 / (k + rank)
# -> after bm25=['doc_c','doc_a','doc_d']:
# -> {'doc_a': 0.0325, 'doc_c': 0.0323, 'doc_b': 0.0161, 'doc_d': 0.0159}
return sorted(scores.items(), key=lambda x: x[1], reverse=True)
# -> [('doc_a', 0.0325...), ('doc_c', 0.0323...), ('doc_b', 0.0161...), ('doc_d', 0.0159...)]
from hybrid_rrf import reciprocal_rank_fusion
dense = ["doc_a", "doc_b", "doc_c"]
bm25 = ["doc_c", "doc_a", "doc_d"]
print(reciprocal_rank_fusion(dense, bm25))
# [('doc_a', 0.03252247488101534), ('doc_c', 0.032266458495966696), ('doc_b', 0.016129032258064516), ('doc_d', 0.015873015873015872)]
Project 1 — Company Policy Assistant (RAG & Document Pipelines)#
Revision Notes#
Reference file: AI Engineering — Interview Workshop.html (Case 1 Q1–Q6; Practice Q8–Q11, Q16–Q17)
Concept#
When company knowledge changes frequently (e.g., 200 policy documents updated weekly), Retrieval-Augmented Generation (RAG) supplies current evidence at query time instead of retraining a model. The core interview challenge is moving from a local handbook prototype to an accurate, access-scoped, refreshable, and hosted employee service.
How It Works#
Because vector similarity and reranking measure relevance rather than permission, employee ACL metadata derived from trusted caller identity must pre-filter the index before generation.
Key Mental Models#
- Separate storage, indexing, and generation:
- Uploading a file to S3 does not make it searchable. An ingestion pipeline must fetch bytes (
get_object), extract text, split into meaning-preserving chunks (keeping rules together with their exceptions and small overlap), generate vectors with one consistent embedding model (e.g., Titan Text Embeddings), and store both vectors and original chunk text + metadata. - Mixing vectors from different embedding models breaks similarity comparison; changing the embedding model requires rebuilding or migrating the index.
- Uploading a file to S3 does not make it searchable. An ingestion pipeline must fetch bytes (
- Top-k, metadata filtering, and reranking solve different problems:
- Top-k controls candidate breadth (too large adds noise and cost).
- Metadata filtering enforces applicability and authorization (country, department, effective date) derived from trusted application identity — never from unverified user text. Semantic similarity only measures textual resemblance, not permission.
- Reranking reorders eligible candidates for relevance; it cannot enforce access control or recover a passage dropped before reranking.
- Fixed RAG vs. Agentic RAG:
- A policy-only Q&A service should start with a predictable fixed retrieve-then-answer pipeline.
- Expose retrieval as a Strands tool (agentic RAG) only when an assistant must choose among multiple sources or iteratively refine queries — and cap iterations while comparing against the fixed baseline.
- Diagnosing retrieval vs. generation failures:
- Always inspect the exact passages sent to the model, not just index results. A dropped exception may be caused by chunk truncation or prompt trimming rather than bad search.
- If the full passage reached the model and the exception was still omitted, fix the answer contract (instructions/model), not the search index.
- Explicitly handle insufficient or conflicting evidence instead of allowing confident fabrication.
- Policy updates & consistent version rollouts:
- Detect changed files via document key + version/content fingerprint; re-embed only changed documents and retire/replace obsolete chunks.
- Publish the index and its text/metadata lookup mapping together as one consistent version (shared OpenSearch index or atomic local bundle) so serving instances never read mismatched IDs. Retain effective-dated history if historical queries are required.
- Managed agent hosting with AgentCore Runtime:
- Fits code-based agents needing session isolation without managing VMs, container clusters, or load balancers.
- Wrap the handler with
BedrockAgentCoreAppand its entrypoint decorator, packagerequirements.txt, deploy viaRuntime.configureandRuntime.launch, and invoke with distinct runtime session IDs. - Keep index building out of the request path, attach least-privilege IAM roles (Bedrock, S3, OpenSearch), configure caller auth (IAM or JWT/Cognito), and enforce employee document scope in application code.
Code Reference#
REFUSAL = "I don't have enough verified information in the provided documents to answer that."
def retrieve_with_acl(query_vec, user_groups: list[str], index, min_score: float = 0.35):
# Pre-filtering ACLs inside the vector index guarantees unauthorized chunks never
# enter the LLM context window (system-prompt instructions can be jailbroken).
hits = index.search(query_vec, filter={"allowed_groups": {"$in": user_groups}}, top_k=5)
# -> e.g. for ['engineering']: [Hit(id='runbook-14', score=0.82), ...]
# Pre-LLM confidence gate: if no authorized chunk clears min_score, short-circuit
# with a deterministic refusal instead of letting the LLM hallucinate.
if not hits or hits[0].score < min_score:
# -> e.g. for ['interns']: hits[0].score=0.21 < 0.35 -> returns (None, REFUSAL)
return None, REFUSAL
return hits, None
# Authorized user with strong match (top score 0.82 >= 0.35):
hits, err = retrieve_with_acl(q_vec, ["engineering"], index)
# hits = [Hit(id="runbook-14", score=0.82), ...], err = None
# User lacking group access or low-similarity match (top score 0.21 < 0.35):
hits, err = retrieve_with_acl(q_vec, ["interns"], index)
# hits = None, err = "I don't have enough verified information in the provided documents to answer that."
Project 2 — Personalised Study Assistant (Memory, Checkpoints & Containers)#
Revision Notes#
Reference file: AI Engineering — Interview Workshop.html (Case 2 Q7–Q12; Practice Q18–Q23, Q38–Q39)
Concept#
A personalised tutor must remember a learner's lasting preferences across chats, recall the right conversation after a service restart, isolate learners sharing the same storage, and keep long chats fast and affordable. The key mental model is separating durable memory (what the application stores) from model context (what goes into one model call).
Key Mental Models#
- Three types of memory (conceptual roles, not separate databases):
- Episodic memory: Records specific past events/interactions and their outcomes.
- Semantic memory: Stores durable facts and user preferences (e.g., "Mona likes short explanations with examples").
- Procedural memory: Captures reusable steps or approved processes (critical rules still belong in code).
- Active conversation vs. durable preferences:
- Same-chat follow-ups ("explain that again") rely on recent conversation state; cross-chat preferences rely on a user-scoped memory store (e.g.,
Mem0MemoryTool). - Behind Mem0: a smaller Bedrock model extracts salient facts, Titan embeddings vectorize them, and FAISS (local) or OpenSearch / AgentCore Memory (deployed) stores them for retrieval. These extraction/embedding calls are separate from the main answer generation call.
- Do not save every sentence permanently — store only information with future value, and distinguish a one-time override ("explain this in detail") from a lasting preference change ("use detailed explanations from now on").
- Same-chat follow-ups ("explain that again") rely on recent conversation state; cross-chat preferences rely on a user-scoped memory store (e.g.,
- Memory correction & consolidation:
- When a preference changes, update or retire the outdated record (and its searchable vector) rather than appending a conflicting fact alongside it.
- Always test preference updates in a brand-new chat, because recent turn history in the current chat can mask a stale memory record.
- Strict multi-user isolation:
- Bind memory tools to the authenticated user identity supplied by application code — never expose a freely editable
user_idparameter to the model. - Scope both long-term memory and active conversation/thread ownership. Identifiers (
actor_id,session_id,thread_id) organize records; application checks and IAM enforce authorization. A prompt saying "do not reveal other users' data" is not a security boundary.
- Bind memory tools to the authenticated user identity supplied by application code — never expose a freely editable
- Surviving restarts with durable checkpoints:
- In-memory Python state dies with the process (and an isolated AgentCore Runtime session is not permanent storage).
- For graph workflows (LangGraph), attach
AgentCoreMemorySaverbacked by AgentCore Memory and pass authorizedactor_idandthread_idin configurable invocation settings. Verify by restarting the process and sending only the follow-up ("add 10 to the previous result").
- Deliberate context budgeting for long chats:
- Combine recent turns (sliding window) + compact summary (older decisions/open questions) + targeted memory retrieval + explicit structured state for exact operational values (amounts, calculations, pending confirmations — never trust lossy prose summaries for exact numbers).
- Budget every component (instructions + tools + recent turns + summary + evidence + output headroom) and test against early-fact, correction, and pending-task cases.
- Container deployment on ECS Fargate:
- Ideal when the team already has a FastAPI app in Docker with custom dependencies and wants container-level control without managing VMs.
- Flow: test Docker locally → push to Amazon ECR → define ECS task definition → run Fargate service behind an Application Load Balancer (ALB) with health checks, subnets, and security groups.
- Separate the task execution role (pull ECR image, write CloudWatch logs) from the application task role (call Bedrock, memory stores). Keep secrets and mutable user state outside the container image and task filesystem.
Code Reference#
def run_bounded_agent(llm, tools, messages, max_steps: int = 6, max_tokens: int = 12_000):
# Dual circuit breakers (step cap + cumulative token cap) prevent runaway ReAct
# loops from burning API budget or stalling requests on cyclic tool calls.
tokens_used = 0
for step in range(max_steps):
resp = llm.invoke(messages, tools=tools)
tokens_used += resp.usage_metadata.get("total_tokens", 0)
# -> e.g. step 0: 710, step 1: 1450 (< max_tokens=12_000)
# No tool calls means the model converged on a final user-facing answer.
if not resp.tool_calls:
return resp.text
if tokens_used >= max_tokens:
return "Budget exceeded — returning best partial synthesis."
# Execute each requested tool and append its ToolMessage with matching tool_call_id
# so the next LLM turn can correlate outputs to calls.
for call in resp.tool_calls:
result = tools[call["name"]](**call["args"])
messages.append({"role": "tool", "tool_call_id": call["id"], "content": str(result)})
# -> appends {'role': 'tool', 'tool_call_id': 'call_1', 'content': "..."}
# Explicit escalation fallback when the step budget is exhausted without convergence.
return "Max steps reached — escalating to human review."
# Normal convergence within budget (2 steps, 1,450 tokens):
>>> run_bounded_agent(llm, tools, messages, max_steps=6, max_tokens=12_000)
"Order #4821 was refunded on March 10; receipt emailed to the customer."
# Runaway loop hitting max_steps=6:
>>> run_bounded_agent(llm, tools, messages, max_steps=6, max_tokens=12_000)
"Max steps reached — escalating to human review."
Project 3 — Financial Research Assistant (Multi-Agent Coordination, Latency & Serverless APIs)#
Revision Notes#
Reference file: AI Engineering — Interview Workshop.html (Case 3 Q13–Q18; Practice Q25–Q29, Q36–Q37, Q42–Q44)
Concept#
Multi-agent architectures (e.g., news, finance, and sentiment specialists under a supervisor) must be earned, not assumed. They add model calls, latency, and failure modes, so you justify them against a single-agent baseline, overlap genuinely independent I/O, enforce mandatory business steps in code, and deploy according to workload shape.
How Parallelism Shrinks the Critical Path#
Scheduling independent async workers concurrently via asyncio.gather cuts a 12-second sequential pipeline to a 7-second critical path, deployed on compute matched to statefulness and duration.
Key Mental Models#
- Single agent vs. multi-agent patterns:
- Stay with a single agent when scope is narrow and tools are manageable; poor answers often come from weak retrieval or unclear tool contracts rather than too few agents.
- Supervisor (agent-as-tool): Coordinator delegates subtasks to focused specialists (still Python objects in one app) and synthesizes structured results (findings, sources, timestamps, status) while keeping reported facts distinct from model-generated interpretation.
- Graph (
GraphBuilder): Best when order and validation are mandatory (e.g., fetch finance data → deterministic Python validation node → conditional edge tocompletereport orneeds_review). Never rely on a prompt alone to enforce required business sequences. - Swarm: Best for exploratory peer-to-peer handoffs, provided clear stopping conditions and boundaries exist.
- Voting caveat: Asking multiple agents and taking a majority vote fails when they share the same model, missing evidence, or faulty tool — correlated errors are not independent proof.
- Real data integrations & honest provenance:
- Put external lookups (e.g., Tavily news,
yfinancemarket data) in tested Python@toolfunctions; return source identity, timestamps, and explicitunavailablestatuses rather than turning missing figures into0or claiming prototype feeds are "real time."
- Put external lookups (e.g., Tavily news,
- Concurrency & async pitfalls:
- Writing
async defdoes not make calls parallel; awaiting A then B is still sequential, and a blocking SDK call inside an async function stalls the event loop. - Schedule independent async I/O together (
asyncio.gather), isolate blocking calls, bound concurrency, and confirm overlapping spans in traces.
- Writing
- Resilience when dependencies fail:
- Set both per-dependency timeouts and an overall request budget.
- Use bounded retries with backoff (respecting
Retry-After) only for transient read-only failures. Never blindly retry state-changing actions (a timeout does not prove the action didn't happen). - Add a circuit breaker to fail fast when a downstream provider is clearly down. Carry explicit
unavailablestatus into partial reports (only when the product permits partial output and discloses what is missing).
- Serverless API deployment & scaling patterns:
- One deployment until splitting is justified: Four agents do not need four microservices; deploy the coordinator and workers together in one SAM Lambda container behind API Gateway for short, stateless, bursty reports.
- Warm Lambda reuse vs. request isolation: Reuse safe SDK/model clients outside the handler, but create fresh per-request user/agent state every invocation. Watch the full timeout chain (API Gateway, Lambda, external providers).
- Database scaling: Use class-owned connections or Amazon RDS Proxy to pool connections when concurrent agent tool calls could exhaust relational DB limits, while keeping parameterized queries and caller authorization intact.
- Long-running async jobs: Never hold an HTTP request open for slow document processing. Return an accepted task reference and use S3 events → EventBridge → SQS (with Dead-Letter Queue + CloudWatch alarm) for buffered, idempotent background processing.
Code Reference#
def binary_judge_metrics(human: list[int], judge: list[int]) -> dict[str, float]:
# Decomposing raw agreement into TPR (catching true PASSes) and TNR (catching true
# FAILs) exposes class-imbalance traps where a rubber-stamp judge scores 90% accuracy
# while missing every real failure.
tp = sum(h == 1 and j == 1 for h, j in zip(human, judge)) # -> 4
tn = sum(h == 0 and j == 0 for h, j in zip(human, judge)) # -> 2
fp = sum(h == 0 and j == 1 for h, j in zip(human, judge)) # -> 1
fn = sum(h == 1 and j == 0 for h, j in zip(human, judge)) # -> 1
tpr = tp / max(tp + fn, 1) # sensitivity on PASS (guard against 0 denominator)
# -> 4 / (4 + 1) = 0.8
tnr = tn / max(tn + fp, 1) # specificity on FAIL (critical for safety/eval gates)
# -> 2 / (2 + 1) = 0.6667
return {"agreement": round((tp + tn) / len(human), 3), "tpr": round(tpr, 3), "tnr": round(tnr, 3)}
# -> {'agreement': 0.75, 'tpr': 0.8, 'tnr': 0.667}
from eval_calibration import binary_judge_metrics
human = [1, 1, 1, 0, 0, 1, 0, 1]
judge = [1, 1, 0, 0, 1, 1, 0, 1]
print(binary_judge_metrics(human, judge))
# {'agreement': 0.75, 'tpr': 0.8, 'tnr': 0.667}
Project 4 — Connected Travel Assistant (MCP, A2A & Managed Gateways)#
Revision Notes#
Reference file: AI Engineering — Interview Workshop.html (Case 4 Q19–Q22; Practice Q14, Q30–Q35, Q40–Q41)
Concept#
When an assistant must consume shared tools and collaborate with independently operated agents owned by other teams, protocol choice is driven by the integration boundary: MCP standardizes access to tools and server capabilities, A2A standardizes agent-to-agent task collaboration, and AgentCore Gateway turns existing REST APIs into one managed, authenticated MCP interface.
How MCP, A2A & AgentCore Gateway Fit Together#
Key Mental Models#
- Choosing the right interface:
- FastAPI: Ordinary HTTP web API for standard clients; does not implement MCP discovery.
- MCP (Model Context Protocol): Standardizes discovering and invoking tools (actions), resources (readable content / templates), and prompt templates (reusable instructions). Advanced optional capabilities — negotiated per connection — include sampling (server requests model help via client), roots (client communicates resource boundaries, not an OS sandbox), and elicitation (requesting extra user input).
- A2A (Agent-to-Agent): Standardizes delegating multi-step work to an independently owned and hosted remote agent without importing its private code or tools.
- Composing both: A main assistant can delegate over A2A to a specialist that internally calls its own MCP tools.
- Local
FastMCP(stdio) vs. hosted MCP (HTTP):- In a local prototype,
FastMCPexposes typed tools overstdio(StdioServerParameters); the client initializesClientSession(or StrandsMCPClientinside a context manager), callslist_tools_sync, and keeps the connection alive during execution. - Keep
stdoutstrictly for MCP protocol frames — send logs tostderror you corrupt the transport. stdiois a local child-process transport; moving to a remote service requires a supported HTTP transport and authentication.
- In a local prototype,
- Working with long-running A2A tasks:
- Fetch the Agent Card first to discover service address, skills, auth requirements, and supported modes (an interface description, not proof of trust).
- Send a Message and preserve the returned Task reference. Follow status via supported polling or streaming, relay missing-input requests (e.g., departure city) back to the user on the same task context, and wait for the completed Artifact before claiming success.
- Streaming caveat: Streaming improves perceived responsiveness (time to first token/progress), not total task completion time — never confuse progress updates or an open stream with a confirmed booking.
- Managed API reuse with AgentCore Gateway:
- Describe an existing REST API with an OpenAPI spec (uploaded to S3, never embedding secrets) and register it as a target on AgentCore Gateway so multiple assistants share one MCP endpoint instead of maintaining duplicate wrappers.
- Separate inbound and outbound credentials: Inbound auth (IAM or JWT/Cognito) identifies which caller may invoke the gateway; outbound credentials stored in AgentCore Identity authenticate the gateway to the external provider. The LLM supplies arguments (city), never API keys.
- Scaling to hundreds of tools:
- Dumping hundreds of tool schemas into every prompt inflates token cost and degrades tool-selection accuracy.
- Use semantic tool search (e.g., via AgentCore Gateway) to retrieve a focused subset of relevant tools per request — while remembering that discovery is not authorization (policy and backend checks still govern execution).
Code Reference#
import re
# Lightweight regex redaction runs deterministically in microseconds before logs,
# prompts, or model outputs leave the trust boundary.
PII_PATTERNS = {
"EMAIL": r"[\w.+-]+@[\w-]+\.[\w.-]+",
"PHONE": r"\b\d{10}\b",
}
def redact_pii(text: str) -> str:
# Replacing sensitive spans with typed placeholders preserves sentence structure
# for downstream LLM reasoning while preventing PII leakage into third-party APIs.
for label, pattern in PII_PATTERNS.items():
text = re.sub(pattern, f"[REDACTED_{label}]", text)
# -> EMAIL pass: "Reach me at [REDACTED_EMAIL] or 9876543210 regarding ticket #42."
# -> PHONE pass: "Reach me at [REDACTED_EMAIL] or [REDACTED_PHONE] regarding ticket #42."
return text
from security_pipeline import redact_pii
sample = "Reach me at alice.dev@example.com or 9876543210 regarding ticket #42."
print(redact_pii(sample))
# Reach me at [REDACTED_EMAIL] or [REDACTED_PHONE] regarding ticket #42.
Governance, Safety, Observability & Evaluation#
Revision Notes#
Reference file: AI Engineering — Interview Workshop.html (Case 4 Q23–Q24; Practice Q45–Q50)
Concept#
Production reliability requires defense in depth across content safety, deterministic action policy, and backend validation — paired with distributed tracing, multi-layer evaluation, cost attribution, and an operational incident playbook. A polite, fluent response can still violate spending limits or falsely claim a failed booking succeeded.
Key Mental Models#
- Three distinct control layers (never conflate them):
- Content guardrails (Amazon Bedrock Guardrails): Filter unsafe content or sensitive data patterns in inputs/outputs. They cannot enforce business authority — a polite request for an INR 30,000 booking passes content checks.
- Tool execution policy (AgentCore Policy + Cedar rules): Attached to AgentCore Gateway in enforcement mode (logging alone does not block), evaluating caller identity and structured tool arguments against rules like
amount <= 25000 INRbefore execution. - Application & backend validation: Authenticate callers, require mandatory fields (destination, date) and verified user confirmation (never trust a model-invented confirmation flag), enforce record ownership, and protect backend APIs against direct bypasses around the gateway.
- Logs, traces, and metrics (observability triad):
- Logs: Record discrete events (validation errors, provider failures) tagged with request/task IDs — stripped of secrets and unnecessary PII.
- Traces (OpenTelemetry): Connect spans across main assistant, model calls, gateway requests, retries, and remote A2A tasks with exact timings (exported to Jaeger locally or CloudWatch + AgentCore Observability on AWS).
- Metrics: Aggregate error rates, latency (time to first token and complete-answer time), token usage, cost, and policy decisions over time to drive alarms. HTTP 200 never proves a correct AI outcome.
- Investigating a false success message:
- Correlate the request/task ID across traces to compare the selected tool, actual arguments, returned backend status, and final user wording.
- Pinpoint where status diverged (e.g., wrapper turned an error into plain text, coordinator dropped status, or LLM ignored failure). Enforce that completion claims require verified backend evidence (such as a booking reference).
- Evaluating beyond the final answer:
- Separately verify tool selection, tool arguments, context/evidence use, and final response claims across normal, missing-input, provider-failure, and policy-boundary cases.
- Use deterministic Python assertions for exact invariants (required fields, forbidden tools, status codes).
- Use LLM judges / AgentCore Evaluations with specific rubrics for open-ended qualities, calibrated against human-reviewed examples — running on-demand for pre-release regressions and online for sampled live monitoring.
- Cost optimization without breaking quality:
- Attribute spend per completed task across main generation, memory extraction, embeddings, evaluations, retries, and external APIs.
- Cut waste first (trim irrelevant context/tool schemas, eliminate duplicate calls and unbounded retries, route narrow extraction tasks to smaller models like Haiku where tests confirm parity), always comparing cost, latency, and quality together.
- Incident response for a misbehaving deployed agent:
- Contain: Disable or restrict the affected action path, route to manual review, and snapshot traces, tool outcomes, prompts, and policy versions.
- Diagnose: Trace caller identity, tool calls, arguments, statuses, and policy enforcement (not just final prose).
- Prove & roll out: Add the incident as a regression test, verify boundary cases, re-release under monitoring with a rollback/kill switch, and tighten alerts.
How All Building Blocks Connect#
Revision Notes#
Every project in AI Engineering — Interview Workshop.html layers one core production discipline onto the same foundation:
- Project 1 (Documents — RAG & Runtime): Grounds answers in changing company knowledge via S3 → chunking + metadata → Titan embeddings → FAISS/OpenSearch → Bedrock Claude, enforcing applicability filters before generation and hosting on AgentCore Runtime.
- Project 2 (Personal Study — Memory & Containers): Adds cross-chat user preferences (
Mem0MemoryTool), durable graph checkpoints (AgentCoreMemorySaver), strict user scoping, and context budgeting, packaged in Docker on ECR + ECS Fargate + ALB. - Project 3 (Research — Multi-Agent & Serverless): Introduces specialist teams (supervisor vs.
GraphBuildervs. swarm), tested external tools, parallel I/O (asyncio.gather), bounded resilience (timeouts, retries, circuit breakers), and bursty stateless hosting on API Gateway + Lambda (SAM) (plus EventBridge/SQS for async jobs). - Project 4 (Connected Travel — Protocols, Gateway & Governance): Scales across team boundaries with MCP (tools) and A2A (remote agents), consolidates shared REST APIs behind AgentCore Gateway + AgentCore Identity, enforces business limits via AgentCore Policy (Cedar) alongside Bedrock Guardrails, and closes the loop with OpenTelemetry + CloudWatch / Jaeger and AgentCore Evaluations.
Quick Self-Check Questions#
Self-Check Questions#
Why isn't vector similarity plus reranking enough to prevent a policy assistant from citing another country's leave policy?
Similarity measures textual resemblance and reranking only reorders candidates; neither enforces authorization or applicability. You must derive the employee's scope from trusted application identity and apply metadata filtering before selecting evidence.
What is the difference between saved memory and the model's context window, and how do you keep long chats cheap without losing exact values?
Saved memory is durable external storage (preferences, checkpoints, history), while context is the bounded token budget sent to a single model call. Combine recent turns, a compact summary, targeted memory retrieval, and explicit structured state for exact figures or pending confirmations.
Why does marking functions async def not automatically cut a 12-second multi-agent pipeline (1s route + 3s news + 2s finance + 4s sentiment + 2s synthesis) down to 7 seconds?
async def only enables cooperative pausing; awaiting workers sequentially still takes 12s, and blocking SDK calls stall the event loop. You must schedule independent async calls concurrently (e.g., asyncio.gather), isolate blocking work, and confirm overlapping spans in traces (1 + max(3,2,4) + 2 = 7s).
When should you pick a graph (GraphBuilder) over a supervisor or swarm?
Choose a graph when the business process has mandatory ordering and deterministic validation branches (e.g., validate required financial fields in Python code before report generation, routing incomplete data to needs_review).
How do you decide between AWS Lambda, ECS Fargate, and AgentCore Runtime for hosting an agent?
Use Lambda + API Gateway for short, stateless, bursty requests; ECS Fargate + ALB when you already have a containerized web service (e.g., FastAPI) needing container-level control without VM management; and AgentCore Runtime for managed code-based agent hosting with built-in session isolation and minimal infrastructure overhead.
When should you use MCP versus A2A — and how do they work together?
Use MCP to standardize access to tool capabilities, resources, and prompt templates; use A2A to delegate multi-step tasks to an independently operated remote agent (via agent card, tasks, and artifacts). A host assistant can call a remote specialist over A2A while that specialist internally calls its own MCP tools.
Why can't Bedrock Guardrails alone stop an INR 30,000 automatic booking when the limit is INR 25,000?
Guardrails filter configured content risks (unsafe or sensitive text), not business authority. A polite request passes content filters; enforcing spending limits requires deterministic input/confirmation validation plus AgentCore Policy (Cedar rules) in enforcement mode at the gateway and backend protection against bypasses.
How do you investigate and prevent a "Your booking is confirmed" message when the underlying booking tool actually failed?
Correlate the request/task ID across OpenTelemetry traces (CloudWatch / Jaeger) to compare selected tool, arguments, backend status, and final wording; require verified backend evidence (like a booking reference) before claiming completion; and add a regression test covering tool failure before rolling out under monitoring.