Back to exam

NCP-AAI Cheatsheet

Agentic AI

Download free PDF

Agent architecture and orchestration

Agents, workflows and service boundaries

  • **Workflows** follow predefined steps and branches. **Agents** choose actions dynamically from goals, context and observations. Combine deterministic controls with adaptive decisions where useful.
  • **Modular services** separate planning, tools, retrieval and inference behind explicit interfaces. They support independent testing, replacement and scaling, but add network and operational overhead.
  • **Single-agent systems** simplify coordination. Add specialized agents when distinct expertise or parallel work justifies communication cost, additional failure paths and state synchronization.
  • **Multimodal models** interpret supported text, image or audio inputs. Validate modality support, preprocessing, extraction accuracy and output schema; an orchestration framework alone does not supply vision capabilities.

Coordination and task delegation

  • **Sequential pipelines** pass structured results between dependent roles, such as researcher, writer and validator. Use **parallel execution** for independent subtasks and join their results explicitly.
  • **Hierarchical coordination** gives a supervisor responsibility for planning and delegation. **Peer coordination** distributes decisions but needs rules for conflicts, agreement and termination.
  • **Graph orchestration** represents steps as nodes and transitions as edges. Conditions, loops, fan-out and joins express adaptive workflows; bound recursion, retries and total execution cost.
  • **Event-driven messaging** decouples producers and consumers. Topics route work to appropriate specialists; durable brokers, acknowledgments and replay support recovery. Consumers must tolerate duplicate delivery.

Shared state and reliable handoffs

  • **Structured handoffs** carry task ID, goal, status, inputs, results and dependencies. Correlation IDs connect messages to the same workflow and expose delayed or missing transitions.
  • **Shared memory** makes relevant context available across agents. Define ownership, access controls and conflict resolution; sharing a store does not automatically synchronize plans.
  • **Coordination tracing** follows state transitions, message timing, redundant work and task allocation. Individually correct outputs can still produce an incorrect overall workflow.

Prompting, planning and memory

Prompts that define the task

  • Specify the **objective**, context, constraints, required evidence and output format. For summaries, request key findings, limitations and conclusions rather than a vague instruction to understand the text.
  • **Few-shot examples** demonstrate tool names, valid arguments, expected results and error handling. Keep examples consistent with the live tool schema and representative of difficult cases.
  • For **translation**, provide a domain glossary, target audience, intended tone and approved parallel examples. For **brand voice**, define vocabulary, tone and style criteria separately from engagement metrics.
  • **Temperature**, **top-p** and **top-k** affect sampling diversity. Lower randomness can reduce variation but cannot guarantee correctness or identical runs across changing models and services.

Planning, acting and revising

  • **Task decomposition** turns a goal into manageable steps with dependencies and completion criteria. Replan when new observations invalidate assumptions; use tools for calculations and external facts.
  • **ReAct** alternates planning, action and observation until completion. Persist tool results and intermediate task state so later actions use actual evidence rather than imagined outcomes.
  • **Reflection** critiques a result and uses feedback for revision. **Reflexion** adds feedback from prior attempts to later attempts; retries still need external checks and stopping conditions.
  • **Chain-of-thought prompting** can encourage decomposition, but plausible explanations can contain errors, especially in weaker models. Validate results and actions; fluent reasoning text is not proof.

Conversation state and persistent memory

  • **Short-term memory** holds current conversation and working state. **Long-term memory** stores selected facts, preferences and prior outcomes across sessions. Retrieve only context relevant to the current task.
  • Use **key-value or relational storage** for exact facts and statuses, **vector retrieval** for semantic recall, and **knowledge graphs** for explicit relationships. Apply user and tenant isolation to every lookup.
  • **Session-scoped checkpoints**, such as LangGraph checkpointers keyed by thread ID, persist typed workflow state. Serialize selectively and load on demand; coordinate concurrent writes within a session.
  • **Sliding windows** bound context cost; **summaries** retain older information compactly. Measure recall, lost facts, retrieval latency and context utilization. Correct stale preferences and enforce retention rules.
  • **Fine-tuning**, including **LoRA**, changes model behavior through learned parameters. **RAG** supplies external knowledge at inference time. Training does not replace session memory or guarantee retention of every past interaction.

Knowledge integration and tool use

RAG foundations and freshness

  • **RAG** retrieves external evidence and includes it in generation context. A typical pipeline ingests, cleans, chunks, embeds and indexes documents, then retrieves evidence for each query.
  • Preserve **metadata**, document identity and access permissions. Check duplicates, missing fields and stale content; restrict retrieval before exposing sensitive evidence to the model.
  • Separate **indexing**, **retrieval** and **generation** services when independent scaling and updates are useful. Event-driven updates reduce staleness, but freshness still depends on ingestion and indexing lag.
  • Use current **APIs or SQL queries** for authoritative live values. Cache only where freshness and authorization allow; invalidate or expire cached results when source data changes.

Retrieval, reranking and fusion

  • **Embeddings** support semantic similarity search. **Keyword retrieval** preserves exact terms; **hybrid retrieval** combines complementary signals. Tune chunk boundaries and retrieval depth against representative questions.
  • **Query expansion** adds useful terms or alternative formulations to improve recall. Preserve the original intent and evaluate whether expansion introduces irrelevant results.
  • **Reranking** scores a candidate set against the query and prioritizes relevant evidence before generation. It can improve precision but adds latency and cannot recover documents absent from the candidate set.
  • **RAG-Fusion** generates multiple query variants, retrieves their result lists and combines rankings using **reciprocal rank fusion**. Deduplicate results and control query drift before assembling context.

Tool selection and structured contracts

  • Describe each **tool** with its purpose, allowed inputs, argument schema and result structure. Use distinct descriptions and examples to help the model select a calculator, search service or API correctly.
  • **Schema validation**, such as Pydantic models, checks argument types and required fields before execution and validates returned data afterward. Syntactic validity does not establish factual accuracy or authorization.
  • Expose tools through **standardized interfaces** and wrappers that own authentication, timeouts, retries and exception handling. Allowlist operations and constrain side effects independently of model instructions.
  • Treat **tool outputs** as external data. Track intermediate results explicitly, verify units and timestamps, and use independent fact checks where accuracy matters.

Changing APIs and uncertain data

  • For **schema evolution**, combine validated contracts with versioned adapters and explicit field mappings. Accept compatible additions deliberately; quarantine missing or incompatible critical fields instead of silently guessing.
  • Parse **event logs** using documented structure, separating metadata from payload. Update tool specifications and parsers together, then test representative action sequences after API changes.
  • **Confidence scores** from an external API may be uncalibrated. Validate them against labeled cases, combine independent evidence and measure threshold errors before trusting them for decisions.

Evaluation and iterative improvement

Measure outcomes and failure slices

  • Build a **benchmark pipeline** with representative tasks, explicit rubrics and stable test conditions. Compare agent versions on the same inputs and record prompt, model, tool and configuration changes.
  • Measure **task completion**, factual accuracy, relevance, completeness and **tool-use accuracy**. Report latency, token cost and throughput separately; frequent tool use is not necessarily effective tool use.
  • Use **stratified evaluation** across agent variants, query difficulty, user groups and time periods. Aggregate scores summarize performance but can hide rare failures, severe errors and regression in a subgroup.
  • Align metrics with the **business objective**: on-time delivery, correct escalation or resolved support issues. Fast completion and cost savings can mask poor outcomes when the metric misses the actual requirement.

RAG evaluation and LLM judges

  • Evaluate **retrieval quality** separately from **generation quality**. Context recall and precision assess evidence retrieval; faithfulness checks support in context, while answer relevance checks whether the response addresses the question.
  • **Synthetic question-answer pairs** broaden coverage at lower authoring cost. Validate their correctness, difficulty and diversity, and retain realistic human-written cases and a held-out evaluation set.
  • An **LLM-as-a-judge** needs a precise rubric, examples and calibration against human judgments. If irrelevant responses receive high scores, inspect the judge prompt and test cases before changing the production model.
  • **RAGAS** provides evaluation methods for RAG and agent behavior. Evaluation scores help find weaknesses; they do not replace runtime enforcement, comprehensive safety testing or human accountability.

Experiments and actionable feedback

  • **Ablation studies** vary one component while holding others fixed. **A/B tests** compare complete variants under controlled assignment; track quality, user experience and cost alongside sampling parameters.
  • Categorize **user feedback** by accuracy, clarity, completeness, tone and workflow failure. Prioritize by severity, frequency and impact, then test changes with version tracking and regression checks.
  • Inspect **dialogue transcripts** for repeated questions, lost context and unresolved concerns. Use rubric-based human review for tone, brand voice and nuanced language that similarity scores may miss.
  • Test **multi-step consistency**, intermediate actions and repeated runs as well as final outputs. Trace missed escalations or ignored signals to prompts, tools, memory or benchmark gaps before selecting a fix.

NVIDIA deployment and performance

Know each component's role

  • **NeMo Agent Toolkit** connects reusable tools and agents across frameworks and provides workflow profiling and evaluation. Use it alongside orchestration frameworks to find costs at agent and tool boundaries.
  • **NVIDIA NIM** packages optimized inference services in containers with APIs. Match runtime profiles to model and GPU requirements. **NIM Operator** manages supported NIM deployment and lifecycle tasks on Kubernetes.
  • **TensorRT** optimizes neural-network inference; **TensorRT-LLM** specializes in LLM inference. **Triton Inference Server** serves models through supported backends and manages inference scheduling and model instances.
  • **NeMo RL** supports reinforcement-learning post-training. **NeMo Guardrails** applies programmable interaction policies. Keep training, inference serving, workflow state and policy enforcement as distinct responsibilities.

Kubernetes scaling and availability

  • Use **containers**, load balancing and Kubernetes deployments for repeatable service operations. **HPA** changes pod replica counts; **Cluster Autoscaler** provisions or removes eligible nodes to meet scheduling demand.
  • Scale inference with **queue depth**, request rate, latency and relevant GPU metrics through supported metrics adapters. CPU utilization alone can miss GPU saturation. Reserve capacity for model loading and traffic bursts.
  • **Readiness probes** stop traffic reaching unready replicas; **startup probes** accommodate model loading. Use rolling updates, sufficient replicas and zone distribution to reduce disruption during maintenance and failures.
  • **Multi-region deployments** reduce geographic latency and support regional recovery. Plan traffic failover, state replication and data locality; autoscaling cannot by itself guarantee a latency target or zero downtime.
  • **Kubernetes** suits long-running service orchestration, self-healing and elastic replicas. **Slurm** suits scheduled HPC and batch workloads. Choose for workload requirements rather than assuming one scheduler is universally superior.

Batching, concurrency and model precision

  • **Triton dynamic batching** combines compatible requests for throughput. Tune maximum batch size and queue delay against tail latency; waiting for a larger batch can increase response time.
  • **Model instance groups** control concurrent model copies and device placement. More instances consume memory and can contend for GPU resources; benchmark instance count, batching and request concurrency together.
  • **Ensembles** express inference dataflow between models. Profile sequential dependencies, modality preprocessing, model loading and inter-model transfers; parallelize only independent work.
  • **Reduced precision** and **quantization** can lower memory use and improve performance. Validate task quality, calibration needs and hardware support. A container does not make every compiled engine portable across GPU configurations.

Match resources to workload

  • Use a **model router** to send simple tasks to smaller suitable models and difficult tasks to stronger models. Scale reasoning, embedding and reranking services independently when their loads differ.
  • Profile **Nemotron or other model variants** on the target GPU tier, such as A100 or H100, before allocating resources. **Multi-GPU inference** helps large workloads but adds communication cost; more GPUs do not guarantee lower latency.
  • **MIG** partitions supported GPUs into isolated instances for compatible workloads. Match partition memory and compute to model needs; assess packing efficiency and capacity limits before enabling it.
  • Use **Nsight Systems** for detailed CPU/GPU timeline analysis and **DCGM** for GPU telemetry. Track cost per successful task and attribution by agent type alongside utilization, batching and service quality.

Observability, resilience and maintenance

Trace the complete request

  • Combine **metrics**, **logs** and **distributed traces**, using OpenTelemetry instrumentation where supported. Correlate workflow, session and tool IDs to follow a request across services.
  • A **latency waterfall** separates preprocessing, retrieval, model queueing, generation, tools, guardrail checks and response formatting. Optimize the measured bottleneck while preserving end-to-end quality.
  • Monitor **p50/p95/p99 latency**, throughput, error rates, queue depth, GPU utilization and memory. **Prometheus** collects metrics and **Grafana** visualizes them; configure actionable alerts around service objectives.
  • For **empty responses under load**, inspect inference logs, GPU memory exhaustion, timeouts and queue limits. Correlate slow requests with traffic shape and resource contention rather than relying on averages.

Bound failures and recover safely

  • Set **request timeouts** and an overall task deadline. Retry eligible transient failures with **exponential backoff**, jitter and a bounded attempt count; respect rate-limit guidance and distinguish permanent errors.
  • A **circuit breaker** stops repeated calls to a failing dependency, then probes for recovery. Combine it with concurrency limits and graceful fallback to avoid cascading failures.
  • Use **idempotency keys** or deduplication for retryable actions with side effects. Do not repeat a payment or write merely because its response timed out; reconcile uncertain outcomes first.
  • Run **failure injection** for timeouts, rate limits, server errors, malformed data and schema changes. Verify recovery, fallback messages and task completion; never present an unavailable result as successful.

Version, release and diagnose drift

  • Version **model artifacts**, prompts, tool contracts, retrieval indexes and guardrail configuration. Use CI/CD, pre-release evaluations, staged rollout and a tested rollback path across deployment regions.
  • **NGC** distributes NVIDIA artifacts; the **Triton model repository** organizes served models and versions. Artifact storage alone does not implement a safe release or automatic rollback policy.
  • When quality declines, inspect **tool inputs and outputs**, endpoint error rates, retrieval freshness and traffic changes. Compare with the prior baseline before retraining or changing sampling parameters.

Safety, privacy and responsible AI

Semantic policies and enforcement

  • **Semantic guardrails** assess meaning and intent rather than only blocked keywords. Combine input checks, retrieval checks, permitted tool actions, output checks and behavioral monitoring.
  • **NeMo Guardrails** can integrate around an existing agent workflow, including LangChain-based applications. Enforce policy at the relevant boundary; a required check must complete before a protected action or response is released.
  • A **classifier branch** can assess risk independently of the main generation prompt. Validate false positives, false negatives and emerging attack patterns; classifiers need maintenance and cannot guarantee safety.
  • Test **prompt injection**, adversarial inputs and policy bypass across agent handoffs and retrieved content. Track violation severity and guardrail coverage; parallelize only checks whose dependencies allow safe enforcement.

Fairness, privacy and auditability

  • Measure **bias** using representative groups, counterfactual cases and task-specific harms. **Demographic parity** compares selection rates; **equalized odds** compares error rates conditional on true outcomes. Interpret trade-offs in context.
  • Mitigate biased behavior with better data, targeted evaluations, training and runtime controls. Removing protected fields or adding a prompt instruction alone may leave proxy discrimination and unequal error rates.
  • Apply **data minimization**, purpose limitation, access controls and defined retention. Pseudonymize identifiers where useful, protect data in transit and at rest, and manage applicable consent and deletion requirements.
  • **Audit trails** record actions, data access, artifact versions, policy decisions and human interventions. Redact sensitive content and restrict log access; indiscriminate full-session logging can itself expose private information.

Human oversight and decision transparency

Review, intervene and retain accountability

  • **Human-in-the-loop** design provides review and intervention at meaningful decision points. Require explicit approval before consequential actions where policy demands it, and preserve the reviewed proposal with the approval record.
  • Show **evidence**, key assumptions, uncertainty and a concise decision rationale. Record observable plans, tool calls and state changes for traceability; raw model reasoning or attention maps are not reliable explanations.
  • Provide clear **accept**, **modify**, **reject**, pause and override controls. Record the reviewer, changes and rationale, and revalidate an action if its underlying data changes before execution.
  • Use **escalation rules** for uncertainty, missing evidence, policy violations and sensitive cases. Confidence thresholds require calibration and should complement mandatory review requirements.

Interfaces and feedback that improve trust

  • Use **layered interfaces**: concise decision summaries first, then drill-down to evidence, risk factors and workflow status. Make intervention controls visible and explain the likely impact of a change.
  • Capture **contextual feedback** at the decision or suggestion being reviewed. Link corrections to the relevant agent version and failure category before using them in an evaluation or improvement cycle.
  • Evaluate **intervention effectiveness**, correction patterns, explanation clarity and user trust alongside task outcomes. Reviewers need time, relevant evidence and authority for oversight to be effective.