Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

Technology handbook

Agentic AI

Start with individual concept cards in Agentic AI with LangChain and LangGraph, then explore Generative AI, RAG, Deep Agents, Guardrails, evaluation, gateways, design patterns, protocols, memory and production agents.

Topics
152
Sections
12

Agentic AI with LangChain and LangGraph

Memory

Memory is information an AI application retains for later use.

  • Short-term memory tracks the current conversation; long-term memory stores selected facts across sessions.
  • Remembering a preference does not retrain the model. Give stored facts an owner and a deletion policy.
  • A tutor remembers your preferred language while keeping today's exercise in conversation state.

Example: A tutor remembers your preferred language while keeping today's exercise in conversation state.

Projects

A project groups related tasks, instructions and reference files into a workspace.

  • Project context helps an assistant reuse relevant background across related conversations.
  • A project is not model training, and uploading a file does not mean every word is included in every request.
  • Keep a product brief, terminology list and design rules together for a documentation project.

Example: Keep a product brief, terminology list and design rules together for a documentation project.

Artifacts

An artifact is a reusable output, such as code, a document or an interactive view, maintained separately from chat.

  • Developers can inspect and revise a concrete deliverable instead of copying scattered message fragments.
  • Previewing generated code does not establish correctness or make it production-ready.
  • Create a calculator interface, revise its validation and export the reviewed implementation.

Example: Create a calculator interface, revise its validation and export the reviewed implementation.

HTML pages

HTML describes a web page's content and structure; CSS styles it and JavaScript adds behavior.

  • AI can draft these files, but semantic markup and accessible interactions still need review.
  • Preview untrusted generated pages in isolation; do not embed secret keys in browser code.
  • Generate a FAQ page using headings and disclosure buttons, then test keyboard navigation.

Example: Generate a FAQ page using headings and disclosure buttons, then test keyboard navigation.

Documents

AI document work includes extracting, summarizing, drafting and revising structured files.

  • Preserve headings, tables and source locations so claims can be checked.
  • Scanned PDFs may need OCR, and extraction can lose table relationships or reading order.
  • Turn meeting notes into an action list with an owner, due date and source note for each task.

Example: Turn meeting notes into an action list with an owner, due date and source note for each task.

Code

AI-generated code is a proposed implementation that needs execution and review.

  • Provide language, dependencies, expected behavior and a small reproducible example.
  • Plausible APIs can be invented; check installed versions and test meaningful edge cases.
  • Ask for a CSV parser, then verify quoted commas, empty rows and malformed input.

Example: Ask for a CSV parser, then verify quoted commas, empty rows and malformed input.

Claude Cowork

Claude Cowork is an agentic workspace for delegating tasks involving files and connected tools.

  • It can carry out multi-step work using the capabilities and access available to the task.
  • An 'AI employee' is a metaphor: it is software, not a person or a guarantee of unrestricted computer control.
  • Ask it to organize a permitted set of reports and prepare a summary; inspect the resulting files.

Example: Ask it to organize a permitted set of reports and prepare a summary; inspect the resulting files.

AI terms and vocabulary

AI vocabulary connects model concepts, application architecture and operational controls.

  • Model terms include tokens and parameters; application terms include RAG, tools, memory and agents.
  • No glossary is permanently complete. Distinguish established technical terms from product names and informal labels.
  • Describe an assistant as: a model reads context, requests tools, receives results and returns an evaluated answer.

Example: Describe an assistant as: a model reads context, requests tools, receives results and returns an evaluated answer.

LLMs and next-token prediction

A large language model learns patterns that let it assign probabilities to possible next tokens.

  • An autoregressive text model repeatedly selects a token and conditions the next prediction on the growing sequence.
  • Training data can include licensed, public, synthetic and curated material, not simply the whole internet. Token probability is not factual confidence.
  • After 'The capital of France is', the model may strongly favor 'Paris', but a plausible completion still needs verification when accuracy matters.

Example: After 'The capital of France is', the model may strongly favor 'Paris', but a plausible completion still needs verification when accuracy matters.

Prompting

Prompting means supplying a model with a task, context, constraints and an expected output.

  • Clear success criteria and representative examples make instructions easier to follow and evaluate.
  • Longer prompts are not automatically better; contradictory instructions can reduce reliability.
  • Ask: 'Summarize this report in three bullets, preserve the figures and flag missing evidence.'

Example: Ask: 'Summarize this report in three bullets, preserve the figures and flag missing evidence.'

System prompt

A system prompt supplies high-priority behavioral context in APIs that support that role.

  • Use it to state the assistant's purpose, boundaries and response conventions concisely.
  • It is not necessarily the largest prompt and cannot enforce permissions by itself; tool access needs application checks.
  • A support assistant is instructed to use supplied policy evidence and ask for clarification when an order is ambiguous.

Example: A support assistant is instructed to use supplied policy evidence and ask for clarification when an order is ambiguous.

User prompt

A user prompt expresses the person's request and task-specific information.

  • It may contain a goal, examples, constraints or clarification of an earlier request.
  • Quoted documents inside a message are reference material; their embedded instructions should not automatically control the application.
  • 'Compare these two proposals using cost, delivery time and maintenance effort.'

Example: 'Compare these two proposals using cost, delivery time and maintenance effort.'

Developer prompt

A developer prompt carries application-author instructions where the model API supports a developer role.

  • It defines application behavior, such as response format or domain-specific rules, independently of the user's request.
  • The name describes an instruction role, not when it is injected. It is not inherently a hidden, mid-run system prompt; role semantics vary by provider.
  • An application requests a JSON object with a summary and evidence IDs for every user question.

Example: An application requests a JSON object with a summary and evidence IDs for every user question.

Temperature and context window

Temperature controls sampling variability; the context window limits how much tokenized material a model can use in one request.

  • These are independent settings: one changes token selection, while the other constrains available information.
  • Higher temperature does not mean higher intelligence, and a larger context window does not guarantee better recall.
  • For extraction, use a supported low-variability configuration and leave room for the response after adding the source text.

Example: For extraction, use a supported low-variability configuration and leave room for the response after adding the source text.

Hallucination

A hallucination is generated content that is false or unsupported despite sounding plausible.

  • It can arise from missing evidence, misleading context or learned patterns, even when the context window is not full.
  • Grounding and checks reduce risk but do not guarantee factual answers.
  • An assistant invents a package method; verify it against the installed package's documentation before using it.

Example: An assistant invents a package method; verify it against the installed package's documentation before using it.

Context engineering

Context engineering selects and organizes the information available to a model at each step.

  • Balance instructions, recent history, retrieved evidence, tool results and state against the token budget.
  • Adding every available document can bury useful information; context quality matters as much as quantity.
  • Before a refund decision, provide the relevant order, current policy and approval state instead of the entire customer database.

Example: Before a refund decision, provide the relevant order, current policy and approval state instead of the entire customer database.

Tokens

Tokens are the units into which a model's tokenizer encodes input and generated text.

  • A token may be part of a word, punctuation or another text fragment; counts vary by tokenizer and language.
  • One token is not always one word. Multimodal inputs use model-specific representations and accounting.
  • Measure a prompt with the target tokenizer instead of estimating cost from word count alone.

Example: Measure a prompt with the target tokenizer instead of estimating cost from word count alone.

Vectors and semantic similarity

A vector is an ordered list of numbers; an embedding vector represents features of some input.

  • Distances or similarity scores can help find items with related meaning in a shared embedding space.
  • Similarity is not proof that two statements are equivalent or true.
  • A query about 'car repairs' can retrieve a passage about 'vehicle maintenance' without exact keyword overlap.

Example: A query about 'car repairs' can retrieve a passage about 'vehicle maintenance' without exact keyword overlap.

Context window management

A context window is the supported token capacity available for a model request and its generation, subject to API limits.

  • Applications manage long histories by trimming, summarizing or retrieving selected material.
  • Not every model uses sliding-window attention. Application history trimming and model attention architecture are different mechanisms.
  • Keep the current task and recent tool results, summarize older discussion and reserve output capacity.

Example: Keep the current task and recent tool results, summarize older discussion and reserve output capacity.

Parameters

Parameters are learned numerical values used by a model to compute its outputs.

  • Training adjusts weights; inference normally uses the resulting fixed weights.
  • Parameter count alone does not establish quality, and learned weights are not a searchable database of exact documents.
  • Two models of similar size can perform differently because their training data, architecture and tuning differ.

Example: Two models of similar size can perform differently because their training data, architecture and tuning differ.

Attention

Attention lets a model weight information from different token positions when forming representations.

  • Query, key and value representations help determine which available tokens influence a position.
  • Attention weights are not a reliable explanation of all model reasoning; causal language models cannot attend to future tokens during generation.
  • In 'The trophy would not fit because it was large', context helps connect 'it' with the relevant object.

Example: In 'The trophy would not fit because it was large', context helps connect 'it' with the relevant object.

Transformers

A transformer is a neural-network architecture built around attention and feed-forward computation.

  • Position information and attention let tokens interact within the allowed context.
  • Decoder-only text models generate sequentially with a causal mask, even though training can process many positions in parallel.
  • A model uses the preceding paragraph to generate a coherent next sentence, one token at a time.

Example: A model uses the preceding paragraph to generate a coherent next sentence, one token at a time.

Training

Training adjusts model parameters to reduce an objective measured over examples.

  • Pretraining learns broad patterns; later training can adapt instruction following or task behavior.
  • Normal conversation does not itself update a deployed model's weights; data retention and later training policies are separate questions.
  • A training run compares predicted tokens with target tokens and updates weights through optimization.

Example: A training run compares predicted tokens with target tokens and updates weights through optimization.

Fine-tuning

Fine-tuning continues training an existing model on selected examples for a narrower objective.

  • It can improve format, style or task behavior when representative training data is available.
  • Use retrieval for frequently changing facts; keep evaluation examples separate from fine-tuning data.
  • Train on reviewed support-label examples, then measure classification quality on held-out tickets.

Example: Train on reviewed support-label examples, then measure classification quality on held-out tickets.

RLHF

Reinforcement learning from human feedback uses human preferences to guide model behavior.

  • A common approach learns a reward model from ranked responses and optimizes a policy using that signal.
  • Not all preference tuning is RLHF; methods such as direct preference optimization use a different training objective.
  • Reviewers prefer helpful, supported answers over evasive or fabricated ones, supplying feedback for alignment training.

Example: Reviewers prefer helpful, supported answers over evasive or fabricated ones, supplying feedback for alignment training.

RAG

Retrieval-augmented generation supplies relevant external evidence to a model before it answers.

  • Retrieve authorized passages, preserve their source IDs and ask the model to answer from that evidence.
  • Retrieval does not modify model weights, and a retrieved passage can still be irrelevant or incorrect.
  • Search the current employee handbook before answering a question about leave policy.

Example: Search the current employee handbook before answering a question about leave policy.

MCP

The Model Context Protocol standardizes how AI applications connect to external capabilities and context.

  • A host connects through clients to servers exposing capabilities such as tools, resources and prompts.
  • A protocol connection does not grant blanket trust or permission; authentication and authorization remain necessary.
  • An assistant uses an MCP server to discover and invoke an approved issue-tracking tool.

Example: An assistant uses an MCP server to discover and invoke an approved issue-tracking tool.

AI agents

An AI agent uses a model to choose actions toward a goal within an application's control loop.

  • Useful implementations combine instructions, tools, state and feedback from the environment.
  • A model plus tools is a helpful starting picture, but reliable execution also needs validation, permissions and stopping rules.
  • An agent investigates a failed build, reads logs, proposes a patch and runs the permitted checks.

Example: An agent investigates a failed build, reads logs, proposes a patch and runs the permitted checks.

Multimodal AI

Multimodal AI works with more than one kind of information, such as text, images or audio.

  • A model's supported input modalities and output modalities can differ.
  • Support for images does not automatically imply support for audio or video.
  • Ask a vision-capable model to describe a chart and compare its visible values with the accompanying text.

Example: Ask a vision-capable model to describe a chart and compare its visible values with the accompanying text.

Reasoning models

Reasoning models are designed or trained to spend additional computation on multi-step problems.

  • They can improve planning or problem solving, with tradeoffs in latency and token usage.
  • Extra computation does not guarantee correctness, and a visible explanation is not necessarily a faithful internal reasoning trace.
  • Use a reasoning-capable model for a constraint puzzle, then independently verify the proposed solution.

Example: Use a reasoning-capable model for a constraint puzzle, then independently verify the proposed solution.

Small language models

Small language models use relatively fewer parameters than larger peers in a given comparison.

  • They can suit focused tasks, local deployment or lower-latency workloads.
  • There is no universal size cutoff; measure task quality, hardware requirements and privacy constraints together.
  • Run a compact classifier locally to route messages, escalating difficult cases to a larger model.

Example: Run a compact classifier locally to route messages, escalating difficult cases to a larger model.

AGI versus ASI

AGI usually refers to broadly capable general intelligence; ASI refers to intelligence exceeding human capabilities across many domains.

  • Both terms describe proposed capability levels rather than a specific software architecture.
  • Definitions and measurement criteria are disputed; fluent conversation alone establishes neither.
  • Assess a system's measured performance on tasks instead of inferring AGI from a convincing demonstration.

Example: Assess a system's measured performance on tasks instead of inferring AGI from a convincing demonstration.

Chunking

Chunking divides source material into smaller units for retrieval or processing.

  • Choose boundaries that preserve meaning and attach document IDs, headings and location metadata.
  • Large chunks can dilute relevance; tiny chunks can lose context. Overlap trades extra storage for continuity.
  • Split a manual by section and paragraph, then test whether real questions retrieve complete instructions.

Example: Split a manual by section and paragraph, then test whether real questions retrieve complete instructions.

Actions

An action is an operation that observes or changes an environment through an application capability.

  • Reading a record and changing that record have different side effects and permission requirements.
  • A proposed action is not a completed action; confirm execution results before reporting success.
  • A calendar assistant distinguishes finding an available slot from actually creating the meeting.

Example: A calendar assistant distinguishes finding an available slot from actually creating the meeting.

Tools

Tools are functions an AI application exposes for specific operations beyond text generation.

  • Give each tool a clear name, argument schema, result contract and bounded permissions.
  • The brain-and-body analogy is useful but imperfect: a model can answer without tools, and tools can run without a model.
  • A weather tool accepts a location and returns measured forecast data for the assistant to summarize.

Example: A weather tool accepts a location and returns measured forecast data for the assistant to summarize.

Structured outputs

Structured outputs constrain a response to a defined shape, commonly a JSON schema.

  • A schema makes outputs easier for software to parse and validate.
  • Valid structure does not prove factual accuracy; handle refusals, incomplete output and domain validation separately.
  • Extract an invoice into supplier, currency and total fields, then check that totals agree with line items.

Example: Extract an invoice into supplier, currency and total fields, then check that totals agree with line items.

Embeddings

An embedding model converts input into a numerical representation useful for matching or grouping.

  • Embed queries and documents using compatible models and compare vectors with a suitable metric.
  • Changing the embedding model may require rebuilding stored vectors; dimensions alone do not ensure compatibility.
  • Embed support articles and a new question to find candidate passages for a RAG answer.

Example: Embed support articles and a new question to find candidate passages for a RAG answer.

Vector databases

A vector database stores vectors and metadata and supports similarity-based retrieval.

  • Approximate nearest-neighbor indexes trade some recall for efficient searches at scale.
  • Apply tenant and document-access filters before exposing retrieved content; similarity ranking is not authorization.
  • Retrieve the closest five permitted product-guide chunks for a customer's question.

Example: Retrieve the closest five permitted product-guide chunks for a customer's question.

LLM APIs

An LLM API lets software submit inputs and receive model outputs over a defined interface.

  • Requests may support messages, streaming, tool definitions and usage reporting, depending on the provider.
  • Keep credentials server-side and handle rate limits, cancellation, timeouts and provider-specific errors.
  • A backend receives a user's question, calls the model and streams the answer to the browser.

Example: A backend receives a user's question, calls the model and streams the answer to the browser.

Zod validation

Zod defines TypeScript-friendly schemas that validate data at runtime.

  • Use parse to obtain validated data or safeParse to handle success and failure explicitly.
  • TypeScript types disappear at runtime; schema validation still does not establish caller permissions.
  • Validate that a tool's quantity is a positive integer before checking stock and creating an order.

Example: Validate that a tool's quantity is a positive integer before checking stock and creating an order.

Tool calling

Tool calling is the model requesting a named operation with structured arguments.

  • The application validates and executes the request, then returns the result so the model can continue.
  • Emitting a tool request is not executing it. Enforce authorization and validate arguments outside the model.
  • The model requests lookupOrder with an ID; the server checks ownership and returns the matching order.

Example: The model requests lookupOrder with an ID; the server checks ownership and returns the matching order.

LangChain.js

LangChain.js provides JavaScript and TypeScript components for model-powered applications and agents.

  • It connects models, messages and tools through reusable interfaces and agent-building abstractions.
  • Check the installed version and provider integration before copying an API example.
  • Build a TypeScript assistant that can request a typed product lookup and explain the returned results.

Example: Build a TypeScript assistant that can request a typed product lookup and explain the returned results.

LangGraph.js

LangGraph.js orchestrates stateful application steps using graph nodes and edges.

  • Explicit state and routing help represent branches, cycles and pauses in a multi-step process.
  • Graph structure does not require multiple agents; nodes can be ordinary deterministic functions.
  • Route a support ticket through classification, retrieval, draft review and a final response node.

Example: Route a support ticket through classification, retrieval, draft review and a final response node.

Memory in LangChain and LangGraph

Agent memory combines thread-scoped state with deliberately stored cross-session information.

  • Use checkpoints for resumable thread progress and a suitable store for durable facts.
  • A thread ID must be scoped to the authorized user; replayed steps must not duplicate side effects.
  • Resume a paused support conversation while retrieving only that user's saved preferences.

Example: Resume a paused support conversation while retrieving only that user's saved preferences.

Human in the loop

Human-in-the-loop design inserts human input or review into an automated process.

  • People can clarify intent, correct state, review evidence or approve an action before execution.
  • Persist the pause and bind the reply to the correct run; do not assume a process will remain in memory.
  • Pause an uncertain invoice classification so an operator can select the correct department.

Example: Pause an uncertain invoice classification so an operator can select the correct department.

Agentic AI: single and multi-agent systems

Agentic AI organizes model-driven decisions and actions into goal-directed applications.

  • Use one agent for a cohesive task or multiple specialized agents when decomposition provides a measured benefit.
  • More agents add coordination cost and failure modes; complexity is not a quality metric.
  • A researcher gathers evidence and a reviewer checks citations before a coordinator assembles the report.

Example: A researcher gathers evidence and a reviewer checks citations before a coordinator assembles the report.

Agents and human responsibility

Agents can automate parts of human work without becoming general replacements for people.

  • Delegate bounded tasks with measurable outcomes and keep accountable owners for consequential decisions.
  • Performance depends on context, tools and task difficulty; autonomy does not imply human judgment or accountability.
  • Let an agent draft a hiring rubric while responsible staff review fairness and make employment decisions.

Example: Let an agent draft a hiring rubric while responsible staff review fairness and make employment decisions.

Workflows

A workflow defines how a task progresses through steps, conditions and outputs.

  • Mix deterministic business rules with model-assisted steps where interpretation is useful.
  • A workflow can contain loops and branches without being a fully autonomous agent.
  • Receive a request, validate its fields, classify it with a model and route it using explicit rules.

Example: Receive a request, validate its fields, classify it with a model and route it using explicit rules.

Human approval

Human approval authorizes a specific proposed operation before it is performed.

  • Show the target, exact arguments and expected effects to the authorized reviewer.
  • Approval for one operation must not silently authorize changed parameters, another user or a later unrelated action.
  • Review the recipient and final email body before permitting the send operation.

Example: Review the recipient and final email body before permitting the send operation.

AI operator versus AI builder

An AI operator uses and supervises AI systems; an AI builder designs and implements those systems.

  • Operators define goals and review results; builders create integrations, controls and evaluation pipelines.
  • These are practical role descriptions, not universal job titles, and one person can perform both.
  • An analyst runs a research assistant while an engineer maintains its retrieval and reporting tools.

Example: An analyst runs a research assistant while an engineer maintains its retrieval and reporting tools.

Acting on a user's behalf

An agent acts on a user's behalf when it executes an authorized operation to advance that user's goal.

  • Carry the real user's identity and scoped permissions into tool execution.
  • Natural-language requests do not bypass access controls; distinguish drafting, proposing and committing changes.
  • A travel assistant compares itineraries, then books only the itinerary authorized by the user.

Example: A travel assistant compares itineraries, then books only the itinerary authorized by the user.

Chatbots versus AI agents

Chatbots focus on conversational responses; agents can choose and execute steps toward a goal.

  • The distinction concerns control and action, not just the presence of a chat interface.
  • An agent can be user-triggered, and a chatbot can call tools; proactive behavior is optional, not the definition.
  • A chatbot explains how to reset a setting; an authorized agent opens the relevant tool and changes it.

Example: A chatbot explains how to reset a setting; an authorized agent opens the relevant tool and changes it.

Core agent loop

A core agent loop observes state, chooses a next step, acts and uses the result to decide what follows.

  • Repeat only while progress is useful and the task remains within its bounds.
  • An agent need not run continuously; stop on completion, errors, missing approval or resource limits.
  • Read a failing test, propose a fix, run the test again and stop when the acceptance criteria pass.

Example: Read a failing test, propose a fix, run the test again and stop when the acceptance criteria pass.

Prompt templates

A prompt template combines stable instructions with named task-specific values.

  • Templates make prompts reusable and easier to version, inspect and evaluate.
  • Variable substitution does not neutralize prompt injection; keep untrusted content distinct from instructions.
  • Fill a summarization template with a document and desired reading level while preserving a fixed output structure.

Example: Fill a summarization template with a document and desired reading level while preserving a fixed output structure.

Debugging and tracing

Debugging finds causes of failures; tracing records the sequence of model, tool and application steps.

  • Inspect the earliest incorrect input or decision, not only the final answer.
  • Redact sensitive values and retain enough metadata to reproduce the failure without exposing secrets.
  • A trace reveals that retrieval returned an obsolete policy before the assistant generated the wrong answer.

Example: A trace reveals that retrieval returned an obsolete policy before the assistant generated the wrong answer.

Multimodal input pipelines

A multimodal pipeline prepares text, images, audio or video for a model that supports those inputs.

  • Preserve timestamps, page references and image detail needed to connect claims with evidence.
  • Transcription and frame selection can omit important information; inspect the original media for critical claims.
  • Summarize a lecture using its transcript and selected slides, citing the relevant timestamps.

Example: Summarize a lecture using its transcript and selected slides, citing the relevant timestamps.

Agent harness

An agent harness is the software environment around a model-driven execution loop.

  • It provides capabilities such as context management, tools, persistence, limits and result handling.
  • A harness is infrastructure, not extra intelligence added to model weights.
  • A coding harness supplies repository access, a test runner, a working directory and a record of completed changes.

Example: A coding harness supplies repository access, a test runner, a working directory and a record of completed changes.

Building agents with existing models

You can build an agent application using an existing hosted or locally deployed model.

  • Your application contributes task context, integrations, execution rules and outcome checks.
  • Training a foundation model and building an application are different engineering projects; neither requires being a large company in principle.
  • Connect an available model to a read-only inventory tool and a review step to create a stock assistant.

Example: Connect an available model to a read-only inventory tool and a review step to create a stock assistant.

Harness engineering

Harness engineering improves the runtime capabilities and controls surrounding an agent.

  • Design reliable tools, context loading, execution isolation and recovery from failed operations.
  • A code reviewer or web search tool is one capability; the harness also governs how and when capabilities run.
  • Add a bounded test runner and clear error results so a coding agent can repair a failure without unlimited retries.

Example: Add a bounded test runner and clear error results so a coding agent can repair a failure without unlimited retries.

Loop engineering

Loop engineering is an informal term for designing the repeated decision-action-feedback cycle.

  • Define what counts as progress, which errors are retryable and when the process must stop.
  • Loops can start from a user, schedule or event; repeating a failing step without new evidence is not progress.
  • Allow two repair attempts after a failed check, then return the diagnostic evidence for human review.

Example: Allow two repair attempts after a failed check, then return the diagnostic evidence for human review.

Graph engineering

Graph engineering describes designing nodes, state and transitions for an application's control flow.

  • Represent branching, joining and bounded cycles explicitly so execution can be inspected and tested.
  • This is a broad engineering description, not a requirement that every node be an agent or every graph contain multiple loops.
  • Run independent research branches, merge their evidence and route disagreements to a review step.

Example: Run independent research branches, merge their evidence and route disagreements to a review step.

Observability

Observability uses traces, metrics and logs to understand an application's behavior over time.

  • Trace model and tool calls; measure latency, errors, token usage and task outcomes with appropriate instrumentation.
  • Telemetry is not emitted automatically by every agent. OpenTelemetry is a standard; Logfire is Pydantic's observability product, while Pydantic itself is a validation library.
  • Use Langfuse, LangSmith or Logfire instrumentation to identify a slow tool call within an agent run, with sensitive fields redacted.

Example: Use Langfuse, LangSmith or Logfire instrumentation to identify a slow tool call within an agent run, with sensitive fields redacted.

Guardrails

Guardrails are layered checks and restrictions that reduce unwanted inputs, actions or outputs.

  • Input checks inspect incoming material; output checks inspect responses; tool permissions and execution controls constrain actions.
  • No classifier guarantees prevention of prompt injection or data leakage. Keep secrets out of context and enforce resource access in code.
  • Reject an unauthorized document lookup and scan the final answer for disallowed sensitive fields before returning it.

Example: Reject an unauthorized document lookup and scan the final answer for disallowed sensitive fields before returning it.

Evals and feedback

Evals measure application behavior against defined criteria; feedback records judgments or observed problems.

  • Combine deterministic checks, human review and calibrated model judges where each fits the criterion.
  • An LLM judge is only one evaluation method and can be biased or wrong; compare it with human-labeled examples.
  • Evaluate a support agent on answer correctness, citation support, prohibited tool use, latency and cost before releasing a prompt change.

Example: Evaluate a support agent on answer correctness, citation support, prohibited tool use, latency and cost before releasing a prompt change.

Agentic AI with LangChain and LangGraph

Combine model and tool components with explicit state, routing and durable execution.

  • Use LangChain components for model and tool integration.
  • Use graph state and edges to control multi-step execution.
  • Persist checkpoints when tasks must survive interruptions.

Workflows versus agents

Choose fixed control flow when the steps are known and model-directed actions when necessary.

  • Use deterministic steps for known business rules.
  • Delegate uncertain action selection to a model only where needed.
  • Keep approval and termination rules outside model discretion.

Tool-calling agent loops

Validate a tool request, execute it under policy and return the result to the model.

  • Validate tool names and arguments before executing calls.
  • Return tool results with the corresponding call identifier.
  • Bound repeated calls and stop when the goal is resolved.

LangChain agents and middleware

Customize a standard agent using model, tool and context hooks.

  • Create agents with an explicit model and allowed tools.
  • Apply middleware around model or tool execution.
  • Test hook ordering when several middleware layers interact.

LangGraph state and reducers

Model shared state and define how updates merge across graph branches.

  • Declare state fields and their update semantics explicitly.
  • Use reducers to combine concurrent updates to shared fields.
  • Keep non-mergeable writes on separate execution paths.

Checkpoints and human approval

Persist progress and pause consequential actions for explicit review.

  • Save execution checkpoints with a stable thread identifier.
  • Present the proposed consequential action before approval.
  • Resume from saved state with the recorded reviewer decision.

Multi-agent coordination

Delegate bounded work with evidence, ownership and a clear final synthesis contract.

  • Assign each agent a bounded task and output contract.
  • Pass only evidence and permissions needed for that assignment.
  • Reconcile conflicting findings before producing the final answer.

Memory and stop conditions

Retain useful state while enforcing turn, time and spend limits.

  • Separate short-term conversation state from durable memory.
  • Store useful facts with ownership and expiry rules.
  • Enforce maximum iterations, elapsed time and spending.

Generative AI

Generative AI foundations

Explain how a generative model produces outputs from learned patterns and supplied context.

  • Generate text or media from patterns learned during training.
  • Treat fluent output as a candidate, not verified evidence.
  • Evaluate answers against examples from the intended task.

Tokens and context windows

Budget instructions, history, evidence and output within the model's supported context.

  • Count input and output tokens together when budgeting context.
  • Reserve room for tool results and the final answer.
  • Summarize older turns before they displace relevant evidence.

Prompt design and few-shot examples

Specify a task, constraints and examples that make the desired response testable.

  • Separate task instructions, constraints and reference material.
  • Show representative input-output pairs with consistent formatting.
  • Test prompts on edge cases outside the examples.

Structured outputs and validation

Turn model responses into typed data and reject invalid values before using them.

  • Request a schema supported by the selected model.
  • Validate required fields, value ranges and domain rules.
  • Handle refusals or malformed responses before downstream actions.

Multimodal generation

Combine text and supported media while respecting format and model capability limits.

  • Check which image, audio and video formats the model accepts.
  • Preserve media resolution and timestamps needed for the task.
  • Evaluate cross-modal claims against the original input.

Sampling and reproducibility

Understand response variability and test repeated runs rather than trusting a single result.

  • Temperature affects sampling variability, not factual accuracy.
  • Record model version, prompt and generation settings.
  • Repeat evaluations to expose unstable behavior.

Hallucination and grounding

Distinguish fluent generation from claims supported by verifiable evidence.

  • Retrieve authoritative evidence for claims that need verification.
  • Require citations that actually support the associated statement.
  • Abstain when the available evidence cannot resolve the question.

Model selection and adaptation

Compare prompting, retrieval and fine-tuning against a measurable task baseline.

  • Start with a measured prompt-only task baseline.
  • Add retrieval for changing knowledge and fine-tuning for learned behavior.
  • Compare quality, latency and cost on held-out examples.

RAG

RAG architecture

Retrieve evidence before generation and separate retrieval quality from answer quality.

  • Separate ingestion, retrieval and answer-generation stages.
  • Pass selected evidence with source identifiers to the model.
  • Measure missing evidence separately from unsupported answers.

Document ingestion and provenance

Preserve source IDs, versions and access permissions while extracting text.

  • Keep original document IDs and extraction locations.
  • Propagate source access controls into retrieval filters.
  • Re-index modified content and remove deleted material.

Chunking strategies

Compare document-aware splits, chunk size and overlap using actual retrieval questions.

  • Split at meaningful headings or semantic boundaries.
  • Retain enough surrounding text to interpret each chunk.
  • Measure whether overlap improves recall without wasting context.

Embeddings and vector indexing

Index compatible vectors and keep the index synchronized with source changes.

  • Use the same compatible embedding space for queries and documents.
  • Record embedding model and vector dimensions with the index.
  • Rebuild incompatible vectors when changing embedding models.

Hybrid retrieval and reranking

Combine keyword and semantic recall, then rank a bounded evidence set.

  • Combine lexical matching with semantic candidate retrieval.
  • Rerank a limited candidate set using the original question.
  • Apply access filters before supplying evidence to generation.

Query rewriting and decomposition

Improve retrieval with focused subqueries without inventing assumptions about the user.

  • Preserve user constraints while expanding ambiguous search terms.
  • Break compound questions into independently answerable subqueries.
  • Combine retrieved results without treating rewrites as facts.

Grounded answers and citations

Tie each factual answer to accessible retrieved evidence and abstain when support is missing.

  • Attach references to the claims their passages support.
  • Preserve page, section or record identifiers for verification.
  • Say when no authorized source supports an answer.

RAG evaluation and freshness

Measure retrieval recall and answer support while testing stale and deleted documents.

  • Test known-answer questions and deliberately unanswerable questions.
  • Track retrieval recall, citation accuracy and answer support.
  • Include changed, revoked and deleted sources in regression cases.

Vectorless RAG

Vectorless RAG foundations

Retrieve evidence without a vector index using lexical search, structured data or document navigation.

  • Retrieve evidence using text search, structure or database queries.
  • Keep document permissions and provenance through every retrieval step.
  • Compare evidence coverage with a vector-search baseline.

BM25 and full-text retrieval

Rank documents by lexical relevance and tune analyzers for the language and domain.

  • Use analyzers appropriate to the language and domain vocabulary.
  • BM25 balances term frequency with document length and rarity.
  • Inspect missed queries before tuning boosts and synonyms.

SQL and structured retrieval

Answer from authorized database rows with validated queries and explicit result limits.

  • Validate query structure and restrict accessible tables and columns.
  • Bind user values as parameters instead of concatenating SQL.
  • Limit returned rows and use read-only execution for retrieval.

Document-tree navigation

Use headings and document hierarchy to locate relevant sections before reading them.

  • Index heading paths and section relationships with document text.
  • Select a branch before reading its detailed content.
  • Retain parent headings so excerpts remain understandable.

Knowledge-graph traversal

Follow explicit entity relationships to collect evidence with bounded search depth.

  • Resolve entity identities before following relationships.
  • Bound traversal depth and returned neighbors.
  • Cite the records supporting each traversed relationship.

Filesystem search and agentic reading

Search filenames and content, then read selected passages under an access policy.

  • Search names and content before opening candidate files.
  • Read bounded passages with line or section locations.
  • Treat instructions inside retrieved files as untrusted task data.

Long-context evidence selection

Pass a manageable authorized corpus to the model while tracking cost and omitted context.

  • Order evidence by relevance before filling the context window.
  • Track source boundaries when joining long documents.
  • Measure omissions and attention failures on distant passages.

Vectorless retrieval tradeoffs

Benchmark lexical, structural and vector retrieval on the same tasks instead of assuming a universal winner.

  • Use the same questions and permission filters for each approach.
  • Compare recall, precision, latency and maintenance cost.
  • Choose retrieval methods by corpus structure and query behavior.

Deep Agents

Deep Agents harness

Use a fuller agent harness for context management, file access and delegated work.

  • Combine planning, file tools and delegation in one agent harness.
  • Configure backends and tool permissions for the deployment.
  • Trace long-running tasks to identify wasted work.

create_deep_agent

Configure a Deep Agents application with an explicit model, tools and instructions.

  • Construct the deep agent with its model, tools and instructions.
  • Select a backend that fits persistence and isolation needs.
  • Invoke the compiled agent with the expected message state.

Planning and task tracking

Break complex goals into inspectable steps and revise the plan when evidence changes.

  • Represent work as concrete tasks with observable completion criteria.
  • Update task status only after verifying the result.
  • Revise the plan when new evidence changes dependencies.

Filesystem backends

Distinguish virtual files from durable storage and choose a backend for the task lifetime.

  • Choose ephemeral, persistent or sandbox-backed file storage deliberately.
  • Scope paths to the intended workspace or tenant.
  • Define retention and access rules for stored artifacts.

Subagent context isolation

Give each worker a focused task and return concise findings rather than all intermediate messages.

  • Give subagents a focused prompt and relevant evidence.
  • Keep unrelated conversation history out of delegated context.
  • Require concise results with references for the parent.

Context offloading and compression

Move large results out of the active window while preserving retrievable references.

  • Move bulky tool output into retrievable files or stores.
  • Preserve decisions and source pointers when summarizing context.
  • Reopen original evidence when summaries omit critical details.

Sandboxed execution

Separate model-generated code from privileged services and restrict network and filesystem access.

  • Run generated commands in an isolated execution environment.
  • Restrict filesystem, network and resource access explicitly.
  • Review command results before trusting produced artifacts.

Deep-agent recovery and budgets

Test restart behavior and enforce resource limits across delegated work.

  • Persist progress so interrupted runs can resume useful work.
  • Cap model calls, tool retries and execution duration.
  • Report the completed steps when the budget stops a run.

Guardrails

Layered agent guardrails

Combine validation, authorization, isolation and monitoring instead of relying on one filter.

  • Apply checks before model calls, tools and final output.
  • Enforce critical permissions in application code.
  • Log guardrail outcomes for review and tuning.

Prompt-injection boundaries

Treat retrieved documents and tool output as untrusted data that cannot grant new permissions.

  • Separate trusted instructions from retrieved or user-supplied content.
  • Do not let documents grant access or authorize tool actions.
  • Test indirect injections hidden in tool responses.

Input and output validation

Check schemas, policy constraints and supported claims before progressing through the workflow.

  • Validate incoming structure before building prompts or tool arguments.
  • Check generated values against domain constraints after generation.
  • Route invalid results into a bounded repair or failure path.

Tool authorization

Authorize the real caller and resource at the tool boundary regardless of the model's wording.

  • Check the user's permission for each requested tool operation.
  • Scope resource access to the authenticated tenant.
  • Recheck authorization immediately before consequential execution.

PII detection and redaction

Prevent unnecessary personal data from entering model context and telemetry.

  • Identify sensitive fields before writing prompts or logs.
  • Redact or tokenize values while preserving useful structure.
  • Test false positives and missed sensitive values.

Human-in-the-loop decisions

Show the exact proposed action and obtain a scoped decision before executing it.

  • Pause at an explicit decision boundary with saved state.
  • Show reviewers the exact proposed action and relevant evidence.
  • Record approval, rejection or edits before resuming.

Content safety and policy checks

Route uncertain cases through a defined policy without confusing moderation with factual verification.

  • Evaluate inputs and outputs against the application's content policy.
  • Define handling for blocked, uncertain and allowed cases.
  • Reassess policy checks when new tools or media are added.

Adversarial testing

Exercise malicious documents, privilege escalation attempts and data-exfiltration scenarios.

  • Test prompt injection, unauthorized tools and data exfiltration attempts.
  • Include multi-turn attacks and malicious retrieved documents.
  • Turn successful attacks into repeatable regression cases.

LLM Evaluation

LLM evaluation fundamentals

Define success on representative tasks before selecting a scoring mechanism.

  • Define success criteria before choosing evaluation metrics.
  • Separate component tests from complete task evaluations.
  • Record model, prompt, tools and data versions per run.

Golden datasets and splits

Maintain reference examples with held-out cases and provenance for reproducible comparison.

  • Curate representative tasks with expected results or scoring rubrics.
  • Keep training and tuning examples out of the held-out set.
  • Version dataset changes and include hard negative examples.

Deterministic quality checks

Verify schemas, required facts and allowed actions with code where possible.

  • Use exact checks for schemas, calculations and required fields.
  • Verify citations, tool arguments and business invariants programmatically.
  • Report which rule failed instead of one opaque score.

LLM-as-judge calibration

Use explicit rubrics and compare automated scores with human judgments.

  • Write an explicit judging rubric with scored examples.
  • Compare judge decisions with independent human ratings.
  • Monitor position bias and disagreements across task categories.

Retrieval and groundedness metrics

Measure evidence selection separately from whether the final claims are supported.

  • Measure whether retrieval returns the needed evidence.
  • Check that answer claims are supported by supplied passages.
  • Distinguish source relevance from final citation correctness.

Agent trajectory and outcome evals

Check both the actions taken and whether the requested result was actually achieved.

  • Inspect tool sequences as well as the final outcome.
  • Score unnecessary calls, unsafe actions and failed recoveries.
  • Verify external task results instead of trusting agent self-reports.

LangSmith experiments

Compare prompt, model and graph revisions using the same dataset and evaluator definitions.

  • Run a versioned application against a selected evaluation dataset.
  • Attach evaluators and compare experiment results by example.
  • Inspect traces for cases whose scores regress.

Online evaluation and regression gates

Turn production failures into test cases and prevent known regressions from shipping.

  • Sample production traces under appropriate privacy controls.
  • Gate releases on important quality and reliability thresholds.
  • Review drift when real traffic differs from evaluation data.

LLM Gateways

LLM gateway architecture

Place a controlled model-access layer between applications and provider endpoints.

  • Expose a controlled model-access endpoint to applications.
  • Centralize provider credentials, routing and usage accounting.
  • Keep application authorization independent of provider authentication.

Provider routing and model aliases

Select backends through stable application-facing names with capability checks.

  • Map stable application aliases to explicit provider models.
  • Route using required capabilities and deployment constraints.
  • Track alias changes so evaluations remain reproducible.

Fallbacks, retries and circuit breakers

Recover from provider outages without duplicating work or creating retry storms.

  • Retry transient provider failures with bounded backoff.
  • Open a circuit when repeated failures indicate an unhealthy provider.
  • Use fallbacks only when required capabilities remain compatible.

Virtual keys and tenant budgets

Scope model access and spending independently for each application or tenant.

  • Issue tenant-scoped virtual credentials instead of sharing provider keys.
  • Enforce spend limits and revoke compromised credentials.
  • Attribute token usage to the authenticated tenant.

Rate limits and backpressure

Control concurrency and token throughput before upstream quotas are exceeded.

  • Limit concurrent requests and token consumption per caller.
  • Queue only work that can finish within its deadline.
  • Return actionable retry information when capacity is exhausted.

Caching and isolation

Cache only suitable requests with keys that include user access and model configuration.

  • Include model settings and relevant context in cache keys.
  • Separate cached responses by tenant and authorization scope.
  • Avoid retaining sensitive prompts beyond the allowed lifetime.

Gateway logging and redaction

Track request outcomes and usage without collecting unnecessary sensitive content.

  • Record request identifiers, latency, model and usage metadata.
  • Redact credentials and personal data before log storage.
  • Control access and retention for prompts and completions.

Gateway compatibility testing

Check tools, streaming, structured output and errors before claiming provider interchangeability.

  • Test streaming chunks, tool calls and structured-output handling.
  • Exercise cancellation, timeouts and provider-specific error shapes.
  • Run contract tests before changing model aliases or providers.

Agent Design Patterns

ReAct: reasoning and acting

An agent alternates between reasoning about the next step, calling a tool, and reading the observation before deciding again.

  • Interleaves a thought, an action (tool call) and an observation in each iteration.
  • Grounds each decision in fresh tool results instead of one up-front plan.
  • Exposes a readable trace of why each action was taken, which helps debugging.
  • Needs an iteration cap and a clear finish action so the loop terminates.

Answering a question across live systems: A support agent asked "why was order 1042 delayed?" first looks up the order, sees it is waiting on a shipment, queries the carrier API with the tracking number, reads that the parcel is held at customs, and only then answers. Each lookup is chosen from what the previous one returned, which a fixed script could not anticipate.

QHow does ReAct differ from chain-of-thought prompting?

Chain-of-thought reasons in one pass using only what the model already knows. ReAct interleaves reasoning with tool calls, so each step can use new external evidence, which reduces hallucinated facts on knowledge-heavy tasks.

QWhat are the failure modes of a ReAct loop and how do you contain them?

Repeating the same call, drifting off the goal and running up cost. Contain them with a maximum step count, detection of repeated identical calls, a token or cost budget, and an explicit final-answer action the loop checks for.

Plan-and-execute agents

A planner writes the whole multi-step plan first; an executor carries out each step, and the plan is revised only when a step's result requires it.

  • Separates planning (one capable model call) from execution (cheaper, focused calls).
  • Makes progress visible as a checklist that can be reviewed before work starts.
  • Replans on failure or new information rather than at every step.
  • Uses fewer expensive reasoning calls than deciding every step from scratch.

Researching and writing a market brief: Asked for a competitor brief, the planner lists: identify five competitors, collect each one's pricing page, extract plan tiers, compare features, draft the summary. Executors run each step; when one pricing page is behind a login, the planner swaps that step for the competitor's public docs instead of restarting the whole job.

QWhen would you choose plan-and-execute over a ReAct loop?

When the task decomposes into mostly predictable steps and you want lower cost, a reviewable plan or parallel execution. ReAct suits exploratory tasks where the next step depends heavily on the last observation.

QWhat triggers a replan?

A failed step, a result that invalidates a later step's assumption, or new information that changes the goal. Replanning on every step throws away the cost advantage.

Reflection and self-critique

The agent reviews its own draft against explicit criteria, writes a critique, and revises — trading extra calls for higher-quality output.

  • Generates, critiques against a rubric, then revises in a bounded number of rounds.
  • Works best when the critique can use objective signals such as tests, linters or schemas.
  • Can use a different prompt or model as the critic to avoid self-agreement.
  • Stops when the criteria pass or the round limit is reached, not when the model feels done.

Generating code that must pass tests: A coding agent writes a function, runs the unit tests, and feeds the failing assertions back as the critique. The revision targets the exact failures, and the loop ends when the tests pass or after three rounds, at which point the remaining failures are reported to a human.

QWhy can self-critique fail to improve answers?

A model often cannot spot its own factual errors without new evidence, so it may approve or even worsen a wrong draft. Grounding the critique in external checks — test results, retrieved sources, validators — is what makes reflection reliable.

QHow do you keep reflection from becoming too expensive?

Cap the rounds, only reflect on outputs that fail a cheap check, and use a smaller model for the critique where its accuracy is sufficient.

Prompt chaining

A task is split into a fixed sequence of model calls, each consuming the previous output, with programmatic checks between steps.

  • Each call has one narrow job, which makes it easier to prompt and to test.
  • Gates between steps validate intermediate output before the next call runs.
  • Trades latency for accuracy: more calls, but each one is simpler.
  • Is a workflow, not an agent: the code fixes the order of steps.

Producing a translated marketing email: Step one drafts the email from a product brief; a check confirms it mentions the required offer and stays under 150 words; step two translates the approved draft into Spanish; step three adapts tone for the regional audience. A failed check reruns only its step, not the whole chain.

QWhat is the advantage of a gate between chained calls?

It catches a bad intermediate result early, before later calls build on it, and gives a precise place to retry or fail — instead of discovering the problem only in the final output.

QWhen is chaining the wrong choice?

When the steps cannot be known in advance or vary per input; then routing or an agent loop fits better. Chaining also adds latency, so it is unnecessary when a single call already meets the quality bar.

Routing workflows

A classifier step sends each input to the specialised prompt, tool set or model that handles that category best.

  • Separates concerns so each downstream prompt is optimised for one kind of input.
  • Can route by cost: simple requests to a small model, hard ones to a larger one.
  • The classifier can be an LLM call or a traditional model, and it must be evaluated on its own.
  • Needs a fallback route for inputs that match no category.

Triaging customer messages: Incoming messages are classified as billing, technical issue, refund request or general question. Billing goes to an agent with invoice tools, technical issues to one with log-search tools, refunds to a workflow that requires human approval, and general questions to a small, cheap model — so each path stays simple and well-tested.

QHow do you measure whether a router is working?

Evaluate it as a classifier on a labelled set: accuracy and confusion between routes, plus the end-to-end quality of each route. A misroute often hurts more than a weak answer on the right route.

QHow does routing reduce cost?

Most traffic is usually easy. Sending it to a smaller, cheaper model and reserving the expensive model for the hard category cuts average cost without lowering quality where it matters.

Parallelization: sectioning and voting

Independent subtasks run as simultaneous model calls (sectioning), or the same task runs several times and the results are combined (voting).

  • Sectioning splits a task into independent parts that run concurrently, cutting latency.
  • Voting runs the same check several times and aggregates for higher confidence.
  • Each parallel call keeps a narrow focus, which often improves accuracy.
  • Needs a deterministic aggregation step: merge, majority vote or threshold.

Reviewing a pull request: Three calls run at once: one checks security issues, one checks performance, one checks style against the team guide. Separately, the security check is run three times and a finding is reported only if at least two runs agree, which cuts false alarms without slowing the review.

QWhen does voting help, and when does it waste money?

It helps when individual runs are noisy and the cost of a wrong answer is high, such as safety or security checks. It wastes money when outputs are already stable or errors are systematic, since repeated runs then make the same mistake.

QHow is sectioning different from multi-agent systems?

Sectioning is a fixed workflow: code decides the split and the merge. A multi-agent system lets models decide how to divide and coordinate work at run time.

Orchestrator-workers

A central model breaks a task into subtasks at run time, delegates each to a worker call, and synthesises their results.

  • Subtasks are decided by the orchestrator per input, unlike fixed parallelization.
  • Workers get a focused brief and only the context their subtask needs.
  • The orchestrator owns synthesis and decides when the task is complete.
  • Clear briefs and output formats prevent duplicated or overlapping worker effort.

Making a change across a codebase: Asked to rename a configuration option, the orchestrator searches for every file that uses it, then assigns one worker per affected module with the exact files and the new name. It collects their diffs, checks they are consistent, and runs the build once at the end.

QWhat is the main risk in orchestrator-worker designs?

Poor delegation: vague briefs make workers duplicate effort, miss parts or return incompatible results. Give each worker an objective, boundaries, the expected output format and the tools it may use.

QHow does this pattern control context size?

Each worker sees only its subtask, and the orchestrator receives condensed results rather than every worker's full transcript, so no single context window has to hold the whole job.

Evaluator-optimizer loop

One model generates a candidate while a second model evaluates it against clear criteria and returns feedback, repeating until the evaluation passes.

  • Splits creation and judgement into separate roles with separate prompts.
  • Works when evaluation criteria are clear and feedback measurably improves the result.
  • The evaluator returns specific, actionable feedback, not just a score.
  • Bounded by a maximum number of rounds and a pass threshold.

Translating legal text faithfully: A generator translates a contract clause; an evaluator compares it with the source and flags a dropped condition and a mistranslated term. The generator revises with that feedback, and the loop ends once the evaluator finds no meaning changes or after four rounds.

QHow is evaluator-optimizer different from reflection?

Reflection has the same agent critique itself; evaluator-optimizer gives judgement to a separate evaluator, often with its own model or rubric, which reduces the tendency to approve one's own work.

QWhat makes a good evaluator prompt?

Explicit pass/fail criteria, a request for specific evidence for each issue, and a structured output (verdict plus feedback list) that the loop can act on programmatically.

Agent Protocols and Tools

Model Context Protocol (MCP)

An open protocol that lets AI applications connect to external tools, data and prompts through a standard client–server interface.

  • Servers expose three primitives: tools (actions), resources (readable data) and prompts (templates).
  • A host application runs MCP clients, each holding a connection to one server.
  • Uses JSON-RPC messages over stdio for local servers or Streamable HTTP for remote ones.
  • Write a server once and use it from any MCP-compatible host instead of building per-app integrations.

Giving an assistant access to company systems: A team publishes an MCP server for its ticketing system that exposes search_tickets and create_ticket tools plus ticket resources. The same server works in a desktop assistant, an IDE agent and an internal chatbot, and access is controlled in one place through the server's OAuth-based authorization.

QWhat problem does MCP solve compared with plain function calling?

Function calling defines how a model requests a tool inside one application. MCP standardises how tools and data are discovered and served across applications, so N apps and M integrations need N + M implementations instead of N × M.

QWhat security concerns come with MCP servers?

A server can run code or reach data with the user's permissions, and tool descriptions or results can carry prompt injection. Use trusted servers, least-privilege credentials, user consent for sensitive actions and validation of tool output.

Agent2Agent (A2A) protocol

An open protocol for agents built by different vendors to discover each other, exchange messages and delegate tasks without sharing their internals.

  • Agents advertise skills and endpoints in an Agent Card that clients use for discovery.
  • Work is organised as tasks with a lifecycle, exchanging messages and returning artifacts.
  • Built on HTTP, JSON-RPC and server-sent events, with support for long-running tasks.
  • Complements MCP: MCP connects an agent to tools; A2A connects agents to agents.

Delegating across organisations: A travel company's planning agent finds a hotel partner's booking agent through its Agent Card, sends a task to hold a room for given dates, receives status updates while availability is checked, and gets a confirmation artifact back — without either side exposing its prompts, tools or models.

QHow do A2A and MCP differ?

MCP standardises the agent-to-tool connection: a model calls tools and reads resources. A2A standardises agent-to-agent collaboration between independent, opaque agents that negotiate and complete tasks, potentially over long durations.

QWhy does A2A treat remote agents as opaque?

Partners can collaborate without revealing proprietary prompts, tools or data, and each agent stays free to change its implementation as long as it honours the advertised interface.

Tool design for agents

Agents use tools only as well as the tools are named, described and shaped, so tool interfaces deserve the same care as prompts.

  • Give each tool a clear name, a description of when to use it and documented parameters.
  • Prefer a few task-level tools over many low-level endpoints the model must chain.
  • Return concise, relevant results with meaningful errors the model can recover from.
  • Use strict input schemas so malformed calls are rejected before they run.

Replacing a raw API with an agent-friendly tool: An agent struggled with three calendar endpoints (list users, list events, create event). Replacing them with one schedule_meeting tool that takes attendees and a time window, finds a free slot and returns a short confirmation — or a clear "no common slot this week" error — cut failed calls sharply.

QWhy can wrapping every API endpoint as a tool hurt an agent?

Many overlapping low-level tools increase confusion over which to call, consume context with descriptions, and force the model to chain calls correctly. Task-shaped tools encode that chaining in code, where it is reliable.

QWhat should a tool return on failure?

A short, specific error saying what went wrong and what to try instead, such as an invalid date format with the expected format. A stack trace or a generic failure leaves the model guessing.

Computer-use and browser agents

Agents that operate graphical interfaces by viewing screenshots and issuing mouse, keyboard or browser actions when no API is available.

  • Loop over screenshot, decide an action (click, type, scroll), execute, take a new screenshot.
  • Reach legacy or third-party systems that offer no API.
  • Slower and less reliable than APIs, so prefer an API whenever one exists.
  • Must run in an isolated VM or container with limited credentials and human checkpoints.

Filing data into a legacy web portal: An insurer's claims system has no API. A browser agent in an isolated container logs in with a restricted account, fills the claim form from structured data, screenshots the confirmation, and pauses for human approval before the final submit button.

QWhat are the main risks of computer-use agents?

Prompt injection from on-screen content, unintended actions such as purchases or deletions, and credential exposure. Mitigate with sandboxed environments, allow-listed sites, minimal permissions and confirmation for irreversible steps.

QWhy are they less reliable than API-based tools?

They depend on visual layout, timing and pop-ups that change without warning, and each step is a perception task that can misread the screen; an API returns structured, stable data.

Code-executing agents

Agents that write and run code in a sandbox to compute, transform data or call many tools in one step, instead of issuing tool calls one at a time.

  • Code expresses loops, conditionals and data processing that would take many separate tool calls.
  • Keeps large intermediate data in the sandbox instead of the context window.
  • Requires an isolated runtime with resource limits, no secrets and controlled network access.
  • Execution results and errors feed back into the loop for correction.

Analysing a large CSV export: Asked which region's revenue fell most last quarter, the agent writes Python to load a 200 MB export, group by region and quarter, and compute changes. Only the final ten-row table returns to the model, which explains the result — the raw data never enters the context window.

QWhy can code execution be more token-efficient than tool calls?

Filtering, joining and aggregating happen inside the sandbox, so only the result goes back to the model instead of every intermediate tool output passing through the context.

QHow do you run model-written code safely?

In an isolated container or VM with CPU, memory and time limits, a read-only or scratch filesystem, no production credentials and network egress restricted to approved hosts.

Agent skills

Packaged folders of instructions, scripts and resources that an agent loads on demand when a task needs that expertise.

  • Each skill carries a short description that is always visible; the full content loads only when relevant.
  • Bundles procedural knowledge — steps, templates, scripts — instead of repeating it in every prompt.
  • Progressive disclosure keeps the context window small while many skills stay available.
  • Versioned and reviewed like code, because a skill's instructions change agent behaviour.

Standardising report generation: A finance team packages its quarterly-report procedure as a skill: formatting rules, a chart script and a checklist. Any agent asked for a quarterly report loads that skill and follows the same procedure, while agents doing unrelated work never spend context on it.

QHow do skills differ from tools?

A tool is an action the agent calls; a skill is knowledge about how to do a kind of task, which may include instructions, reference files and scripts the agent then runs with its tools.

QWhat is progressive disclosure and why does it matter?

Only skill names and descriptions sit in context until a skill is needed, then its full instructions load. It lets an agent have many capabilities without paying their context cost on every request.

Agent Memory and Context

Context engineering

Deciding exactly what enters the model's context at each step — instructions, tools, retrieved data, history — so it has what it needs and nothing that distracts it.

  • Treats context as a limited budget: more tokens can reduce accuracy as well as raise cost.
  • Selects, compresses and orders information per step rather than appending everything.
  • Includes tool definitions, examples, memory and retrieved documents, not just the prompt.
  • Moves bulky state to files or stores the agent can read back on demand.

Keeping a long-running coding agent on track: After two hours, a coding agent's transcript holds thousands of lines of old test output. Instead of sending it all, each step supplies the task goal, the current plan, the files being edited, the latest test failures and a short summary of decisions so far — and the agent stays focused.

QHow is context engineering different from prompt engineering?

Prompt engineering focuses on wording instructions. Context engineering manages everything the model sees across a multi-step run — which documents, tool results, memories and history to include, compress or drop at each step.

QWhat is context rot?

Model accuracy degrades as the context grows long and cluttered, even within the window limit, because relevant details get lost among irrelevant ones. Curating context counters it.

Short-term and long-term memory

Short-term memory is the working context of the current task; long-term memory persists selected facts across sessions in an external store.

  • Short-term memory lives in the conversation or graph state and ends with the session.
  • Long-term memory is written to a database or vector store and retrieved when relevant.
  • An agent must decide what is worth storing, which avoids saving noise or sensitive data.
  • Stored memories need updates and deletion, or outdated facts keep resurfacing.

A personal assistant that remembers preferences: During one chat a user mentions they are vegetarian and prefer morning meetings. The agent stores these as long-term memories tied to the user ID. Weeks later, booking a team lunch, it retrieves them and suggests a vegetarian-friendly place at 12:00 without being told again.

QWhy not keep the full conversation history as memory?

It grows without bound, costs tokens on every call, buries relevant facts and can exceed the context window. Extracting durable facts into long-term storage scales far better.

QWhat privacy controls should long-term memory have?

Per-user isolation, consent for what is stored, the ability to view and delete memories, retention limits and exclusion of sensitive data such as credentials.

Episodic, semantic and procedural memory

A cognitive-science split for agent memory: episodes (what happened), facts (what is true) and procedures (how to do things).

  • Episodic memory stores past interactions or runs, often as examples to reuse.
  • Semantic memory stores facts about users, entities and the domain.
  • Procedural memory stores how to act — instructions or prompts the agent can refine over time.
  • Each type has its own write trigger, storage format and retrieval method.

An agent that improves at support tickets: A support agent stores successful resolutions as episodes and retrieves similar ones as few-shot examples (episodic), keeps product facts and customer plan details (semantic), and after repeated reviewer feedback updates its own escalation rules in its system instructions (procedural).

QGive an example of procedural memory in an agent.

The agent rewrites part of its own instructions after feedback — for example adding "always confirm the account ID before issuing a refund" — so the behaviour persists in future sessions.

QHow would you retrieve episodic memories?

Embed past episodes and retrieve the most similar to the current task, then insert them as worked examples, filtered by user or tenant and recency.

Agentic RAG

Retrieval driven by an agent that decides whether, where and how often to search, and checks the results before answering.

  • Decides per question whether retrieval is needed at all.
  • Chooses among sources — vector index, SQL, web, APIs — and reformulates queries.
  • Grades retrieved documents and searches again when evidence is missing or weak.
  • Costs more calls and latency than single-shot RAG, so reserve it for hard questions.

Answering a multi-part policy question: Asked whether a contractor in Germany can expense a co-working space, the agent first searches the expense policy, finds that contractor rules live in a separate document, searches that, then queries the HR database for German-specific exceptions — and answers only once each part of the question has supporting evidence.

QHow does agentic RAG differ from standard RAG?

Standard RAG retrieves once with the user's query and answers. Agentic RAG puts retrieval in a loop the agent controls: choosing sources, rewriting queries, judging relevance and retrieving again until the evidence is sufficient.

QHow do you stop an agentic RAG loop from searching forever?

Set a retrieval budget, require a relevance grade before continuing, and let the agent answer with stated uncertainty once the budget is spent.

Prompt caching for agents

Reusing the processed form of a repeated prompt prefix — system prompt, tool definitions, documents — so later calls cost less and respond faster.

  • Agents resend the same long prefix on every loop iteration, which makes caching especially valuable.
  • Only an exact matching prefix is reused, so stable content goes first and changing content last.
  • Cache reads are billed far below normal input tokens; cache entries expire after a time window.
  • Editing tools or the system prompt mid-run invalidates the cache from that point on.

Cutting the cost of a document-review agent: An agent reviews a 100-page contract over twenty tool-using turns. With the contract and tool definitions placed first and cached, each turn re-reads them at a fraction of the input price, and only the new turn's messages are processed in full — lowering both cost and latency for the whole run.

QHow should you order a prompt to benefit from caching?

Put stable content first — tool definitions, system instructions, reference documents — and variable content such as the latest user message last, because only an identical prefix can be reused.

QWhat silently breaks prompt caching?

Anything that changes the prefix: a timestamp in the system prompt, reordered tools, or edits to earlier messages. Each change forces the prefix to be processed again at full price.

Production Agents

Agent observability and tracing

Recording every model call, tool call, input, output, latency and cost of an agent run as a trace, so failures can be found and fixed.

  • A trace is a tree of spans: the run, each model call and each tool call with timings.
  • Captures prompts, tool arguments, results, token usage and errors for each step.
  • Lets you replay failed runs and turn them into evaluation cases.
  • Requires redaction and access controls because traces contain user data.

Debugging an agent that gives wrong refunds: Users report wrong refund amounts. The traces show the agent called the order tool correctly, but the tool returned prices in cents and the model read them as dollars. The team fixes the tool's output format and adds the failing trace to the regression dataset.

QWhy are logs insufficient for debugging agents?

Agent failures arise from sequences of decisions. Flat logs lose the parent–child structure and the exact context the model saw at each step, which a trace preserves for replay and analysis.

QWhich metrics would you track for agents in production?

Task success rate, steps and tool calls per task, latency, token cost per task, tool error rate, escalation or human-handoff rate, and user feedback.

Agent cost and latency budgets

Explicit limits on tokens, tool calls, time and spend per task so an agent's open-ended loop stays affordable and responsive.

  • Sets ceilings for steps, tokens, wall-clock time and money per task, enforced in code.
  • Matches the model to the step: smaller models for routine steps, larger for hard reasoning.
  • Streams partial progress so users are not waiting on a silent long run.
  • Ends gracefully at the budget with the best answer and a clear statement of what is unfinished.

Bounding a research agent: A research agent may use at most 15 searches, 200k tokens and 3 minutes per question. Query rewriting and summaries run on a small model; only the final synthesis uses the large one. When the search budget runs out, it answers from what it has and lists the open questions.

QHow do you reduce an agent's cost without hurting quality?

Cache stable prompt prefixes, route easy steps to smaller models, trim context to what each step needs, cap retries, and measure quality on an eval set after every change.

QWhat should happen when an agent hits its budget?

Stop cleanly, return the best partial result with a note on what is incomplete, and log the event, rather than failing silently or exceeding the limit.

Reasoning models and thinking budgets

Models that spend extra tokens reasoning before answering, with controls to set how much thinking a request may use.

  • Extended reasoning improves multi-step maths, coding, planning and analysis tasks.
  • Thinking tokens add latency and cost, so the effort level should match task difficulty.
  • In agent loops, models can reason between tool calls to interpret results before acting.
  • Simple extraction or classification rarely benefits from deep reasoning.

Choosing effort per step: A data-pipeline agent uses low effort to rename columns and parse dates, but high effort when designing a schema migration that must preserve existing data — spending reasoning where mistakes are costly and saving it everywhere else.

QWhen would you not use a reasoning model?

For latency-sensitive, simple tasks such as classification, extraction or short replies, where extra thinking adds cost and delay without improving accuracy.

QHow does reasoning change prompt design?

Give clear goals, constraints and success criteria rather than step-by-step instructions; the model plans the steps itself, and over-prescribing can reduce quality.

Levels of agent autonomy

How much an agent may decide and do without a human — from suggesting actions, to acting with approval, to acting alone within limits.

  • Suggest-only: the agent proposes and a human executes.
  • Approve-to-act: the agent acts after a human confirms each sensitive step.
  • Act-within-bounds: the agent acts alone inside limits and escalates exceptions.
  • Autonomy is earned per action type, based on measured reliability and the cost of mistakes.

Rolling out an IT-helpdesk agent: In month one the agent only drafts replies for staff. Once evaluations show 95% accuracy on password resets, it performs resets on its own, while account deletions and permission changes still need a technician's approval.

QHow do you decide what an agent may do autonomously?

Weigh reversibility, blast radius and measured accuracy for that action: reversible, low-impact, well-evaluated actions can be autonomous; irreversible or high-impact ones keep a human approval step.

QWhat does escalation look like in a well-designed agent?

The agent recognises low confidence, missing permissions or out-of-policy requests, stops, and hands the case to a human with a summary of what it found and what it attempted.

Sources

  • Agent foundations
  • Retrieval
  • Deep Agents
  • Guardrails
  • Evaluation
  • Full-text retrieval
  • LLM Gateway
  • Building effective agents
  • Model Context Protocol
  • Agent2Agent protocol
  • LangGraph memory

Ask follow-up questions on any topic in your dashboard.

Start learning