Prev Next

AI / AI Harness engineering Interview questions

Last updated

1. What is AI harness engineering? 2. What is an agent harness? 3. What are the core components of an agent harness? 4. What is the agent loop? 5. What is a tool in an agent harness? 6. Define a tool schema? 7. What is the role of the system prompt in a harness? 8. What is a stop condition in an agent loop? 9. What is a sandbox in an agent harness? 10. What is context management in a harness? 11. What is an evaluation harness? 12. What is a permission system in an agent harness? 13. What is a hook in an agent harness? 14. What is the Model Context Protocol (MCP)? 15. What is agent memory in a harness? 16. List common failure modes of AI agents? 17. What is the difference between a model and a harness? 18. How do you use a scratchpad or todo list in a harness? 19. How does a harness handle tool call errors? 20. How does context compaction work? 21. Why do we use subagents? 22. When should you use a workflow instead of an autonomous agent? 23. How does prompt caching affect harness design? 24. Why is idempotency important for agent tools? 25. How do you design good tool descriptions? 26. What is the difference between short-term and long-term agent memory? 27. How do you limit runaway agent loops? 28. How does human-in-the-loop approval work in a harness? 29. Why should tool outputs be truncated or paginated? 30. How do you build an eval set for an agent? 31. What is the difference between offline evals and online monitoring? 32. How does a harness stream model output and tool calls? 33. Why are structured outputs useful in a harness? 34. How do you trace and log agent runs? 35. How do you manage secrets in an agent harness? 36. How do you defend a harness against prompt injection? 37. Explain the execution flow of one agent turn? 38. How do you design a sandbox for code-executing agents? 39. How can you optimize token cost in a long-running agent? 40. How do you troubleshoot an agent stuck in a loop? 41. How does the orchestrator-worker pattern work? 42. How do you make an agent run resumable after a crash? 43. How do you evaluate non-deterministic agent behavior? 44. Which is better: one big tool or many small tools, and why? 45. How do you handle parallel tool calls safely? 46. How do you detect harness regressions after a model upgrade? 47. Explain the internal working of context assembly? 48. How do you design permission tiers for destructive actions? 49. How do you verify an agent's work before it finishes? 50. How do you design a harness that is robust to model changes?

1. What is AI harness engineering?

AI harness engineering is the practice of designing everything around a language model that turns it into a dependable system: the loop that calls it, the tools it can use, the context it sees, the permissions it runs under, and the checks that judge its output.

The model supplies reasoning. The harness supplies control, memory, safety, and feedback. A common shorthand is agent = model + harness.

It matters because two teams using the same model often see very different results, and the gap usually traces back to harness choices such as how errors are reported to the model or how much history is kept.

Take quiz
In the shorthand 'agent = model + harness', what does the harness provide?
the trained weights of the model
only the GPU hardware the model runs on
the loop, tools, context handling, permissions, and checks around the model
Why can two teams using the same model get very different agent results?
each team receives a differently trained copy of the weights
the model refuses to work for more than one team
tokenizers change vocabulary per team
their harness choices, like error reporting and context handling, differ

2. What is an agent harness?

An agent harness is the runtime software that wraps a model and lets it act on a task. It takes a goal, assembles the prompt, calls the model, parses any tool requests, runs those tools, feeds the results back, and repeats until the task is finished or a limit is hit.

Think of it as the "operating system" for the model. The model decides what to do next; the harness decides what is allowed, what the model gets to see, and when to stop.

A coding assistant that reads files, edits them, and runs tests is a typical example. The model never touches your disk directly. The harness performs each action on its behalf and reports the result.

Take quiz
In an agent harness, who actually executes a file edit requested by the model?
the model, directly on disk
the tokenizer
the user's browser by default
the harness, on the model's behalf
Which decision belongs to the harness rather than the model?
what the model is allowed to do and when the run stops
which next token has the highest probability
how attention heads weigh earlier tokens
what the training data contained

3. What are the core components of an agent harness?

Most harnesses are built from the same handful of parts, even when the names differ.

Component What it does
Agent loop Calls the model, runs tool requests, repeats until done
Tool layer Defines and executes actions such as file edits, search, shell, API calls
Context manager Decides what goes into each prompt and what gets trimmed or summarized
Permissions and sandbox Limits what actions can do and where they run
Memory Persists notes and state across steps or sessions
Observability and evals Traces runs and scores outcomes so changes can be tested

If one of these is missing, the gap shows up quickly: no sandbox means risk, no context manager means bloated prompts, no evals means guessing.

Take quiz
Which component decides what goes into each prompt and what gets trimmed?
the context manager
the sandbox
the tool layer
the stop condition
Which part of a harness limits what actions can do and where they run?
memory
permissions and sandbox
the evaluation scorer
the tokenizer

4. What is the agent loop?

The agent loop is the repeating cycle at the center of a harness: send context to the model, read its response, run any requested tool, append the result, and call the model again.

flowchart TD
  A["Build prompt"] --> B["Call model"]
  B --> C{Tool call requested?}
  C -- Yes --> D["Run tool"]
  D --> E["Append result to context"]
  E --> A
  C -- No --> F["Return final answer"]

The loop ends when the model replies without a tool request, or when a safeguard such as a turn limit or budget cap fires. Everything else in the harness exists to make this loop safe, cheap, and useful.

Take quiz
When does the basic agent loop normally end?
after exactly one model call, always
when the tool returns any output at all
when the model replies with no tool request, or a limit fires
After a tool runs, what does the loop do with its result?
discards it to save tokens
sends it straight to the user without the model seeing it
appends it to the context and calls the model again
stores it only in the model weights

5. What is a tool in an agent harness?

A tool is a function the harness exposes to the model so it can act beyond generating text. Examples are reading a file, running a shell command, querying a database, or calling a web API.

The model never runs a tool itself. It emits a structured request naming the tool and its arguments, and the harness validates the request, executes it, and returns the output as the next message.

Each tool needs a clear name, a description of when to use it, and an input schema. Those three things are all the model has to go on when choosing between tools.

Take quiz
What does the model produce when it wants to use a tool?
a structured request naming the tool and its arguments
the compiled binary of the tool
a direct database connection
What does the model rely on to choose between available tools?
the tool's source code, which it always reads
the order tools were registered in, nothing else
a hidden ranking assigned by the GPU
each tool's name, description, and input schema

6. Define a tool schema?

A tool schema is a machine-readable description of a tool: its name, a plain-language description, and the JSON Schema for its inputs. The harness sends it to the model and later uses it to validate the arguments the model returns.

{
  "name": "read_file",
  "description": "Read a UTF-8 text file and return its contents.",
  "input_schema": {
    "type": "object",
    "properties": {
      "path": { "type": "string", "description": "Relative file path" }
    },
    "required": ["path"]
  }
}

Validating against the schema before execution catches malformed calls early, and the error message can be fed back so the model corrects itself.

Take quiz
Besides guiding the model, what else is a tool's input schema used for?
compressing the prompt
encrypting the tool output
training the model online
validating the arguments before the tool executes
Which three items make up a typical tool schema?
name, description, and input schema
name, GPU type, and learning rate
author, license, and version only
prompt, temperature, and seed

7. What is the role of the system prompt in a harness?

The system prompt sets the model's standing instructions for the whole run: its role, rules, tone, and how to use the available tools. It is the first and most stable part of every request.

In a harness it often does more than a chat prompt would. It states conventions such as "read a file before editing it", explains when to ask the user versus proceed, and points to project rules loaded from a file.

Because it sits at the front of every call, keeping it stable also helps prompt caching. Putting changing details like the current time inside it can break the cache on every turn.

Take quiz
Why should a harness avoid putting changing values like timestamps early in the system prompt?
it makes the model forget its name
the API rejects any prompt containing numbers
it changes the prompt prefix and breaks prompt caching
What is the system prompt mainly used for in a harness?
storing the output of each tool call
standing role, rules, and tool-usage conventions for the whole run
holding only the user's latest question
defining the model's tokenizer

8. What is a stop condition in an agent loop?

A stop condition is a rule that ends the loop. Without one, an agent can keep calling tools indefinitely.

Harnesses usually combine several:

  • Natural finish - the model answers without requesting a tool.
  • Turn limit - a maximum number of model calls.
  • Budget cap - a ceiling on tokens, cost, or wall-clock time.
  • Explicit signal - a "done" tool or a failed verification gate.

When a limit fires, a good harness reports why it stopped and what was completed, rather than failing silently.

Take quiz
Which is an example of a budget-based stop condition?
ending the run once a token or cost ceiling is reached
stopping because the model said hello
stopping because the font changed
What should a harness do when a turn limit ends the run?
silently discard all progress
restart the loop forever
report why it stopped and what was completed
delete the tool schemas

9. What is a sandbox in an agent harness?

A sandbox is an isolated environment where the agent's actions run, so a mistake or a malicious instruction cannot damage the host machine or reach data it should not.

Typical isolation layers include containers or virtual machines, a restricted filesystem view, limited CPU and memory, and controlled network access. A common pattern is a throwaway workspace with the project copied in and outbound traffic blocked or allow-listed.

The sandbox is a hard boundary enforced by the operating system. That makes it more reliable than a prompt that merely asks the model to be careful.

Take quiz
Why is a sandbox more reliable than a prompt telling the model to be careful?
models always obey prompts perfectly
the operating system enforces it regardless of what the model outputs
prompts are encrypted and sandboxes are not
Which is a typical sandbox control?
giving the agent root on the production server
sharing the host's SSH keys by default
disabling all logging
allow-listing outbound network destinations

10. What is context management in a harness?

Context management is deciding what the model sees on each call. The context window is finite, and every message, tool result, and file read competes for the same space.

The harness controls this by loading only what is needed, trimming bulky tool output, summarizing older turns, and pulling in documents on demand instead of upfront.

Done well, the model stays focused and costs stay low. Done badly, the prompt fills with stale logs, relevant details get buried, and quality drops well before the hard token limit is reached.

Take quiz
Why can quality drop even before the context window is completely full?
the model deletes its own weights
the API silently switches to a smaller tokenizer
relevant details get buried among stale or bulky content
Which technique is part of context management?
loading documents on demand instead of all upfront
adding every available file to every prompt
never trimming tool output
repeating the system prompt ten times

11. What is an evaluation harness?

An evaluation harness is the test rig that runs a model or agent against a fixed set of tasks and scores the results. It gives you a repeatable number instead of a gut feeling.

It typically contains the task set, a runner that executes each task in a clean environment, and graders. Graders can be code (unit tests, exact match), rules, or another model acting as judge.

Use it before and after any change to the prompt, tools, or model version. If the score moves, you know the change mattered; if it does not, you avoided shipping a placebo.

Take quiz
What is the main benefit of running an evaluation harness before and after a change?
it shows whether the change actually moved a repeatable score
it makes the model larger
it removes the need for any tools
Which of these can act as a grader in an evaluation harness?
only a human reading every run live
unit tests, exact-match rules, or a judge model
the sandbox's CPU temperature
the system prompt itself

12. What is a permission system in an agent harness?

A permission system decides which actions an agent may take automatically, which need approval, and which are never allowed.

A common layout uses three tiers. Read-only actions such as listing files run freely. Reversible writes may be allowed within a project folder. Destructive or external actions, like deleting data, pushing code, or sending email, ask a human first or are blocked.

Rules are usually expressed as allow and deny lists on tool names and arguments, for example "allow git status, deny rm -rf". The principle behind it is least privilege: give the agent only what the task needs.

Take quiz
Which action would typically require approval or be blocked in a permission system?
listing files in the project folder
deleting data or sending email on the user's behalf
reading a README
What principle underlies a good permission system?
maximum privilege so the agent never gets blocked
privileges based on how confident the model sounds
least privilege: grant only what the task needs
one shared admin token for everything

13. What is a hook in an agent harness?

A hook is a piece of your own code the harness runs automatically at a defined point in the agent's lifecycle, such as before a tool call, after a tool call, or when the agent finishes.

Because hooks are ordinary code, they are deterministic. They can block a dangerous command, run a formatter after every file edit, log an audit entry, or force a test run before the agent is allowed to say it is done.

That is the key difference from prompt instructions. A prompt requests a behavior; a hook guarantees it.

Take quiz
What is the key difference between a hook and a prompt instruction?
a hook is slower because it retrains the model
a prompt is always enforced and a hook never is
a hook runs as deterministic code, while a prompt only requests behavior
Which is a realistic use of a post-tool-call hook?
rewriting the model's weights
changing the user's password
disabling the context window
running a code formatter after each file edit

14. What is the Model Context Protocol (MCP)?

The Model Context Protocol is an open standard for connecting AI applications to external tools and data sources. Instead of writing a custom integration for every pairing of app and service, a service exposes an MCP server and any MCP-capable client can use it.

A server can offer tools (actions), resources (readable data), and prompts (reusable templates). The harness acts as the client: it discovers what the server offers, lists those tools to the model, and routes calls back to the server.

The practical benefit is reuse. One database or ticketing server works across many harnesses, and your harness gains new capabilities without new glue code.

Take quiz
In MCP, what role does the harness usually play?
the client that discovers and calls the server's tools
the server that stores training data
the tokenizer for tool names
What problem does MCP mainly reduce?
writing a custom integration for every app and service pairing
the cost of GPU hardware
the need for system prompts
the length of model outputs

15. What is agent memory in a harness?

Agent memory is any information the harness keeps outside a single model call so the agent can continue work or learn across sessions. The model itself remembers nothing between calls; it only sees what the harness sends.

The simplest form is the running conversation. Beyond that, harnesses persist notes to files, keep a task list, store summaries of earlier sessions, or index past material for retrieval.

A practical example is a project instructions file that is loaded at the start of every session, so conventions like the test command survive restarts.

Take quiz
Why does a harness need to provide memory at all?
the model stores every chat in its weights automatically
the model itself remembers nothing between separate calls
memory is only needed for image models
Which is a simple form of persistent agent memory?
the GPU's L2 cache
a project instructions file loaded at the start of each session
a random seed
the browser's back button

16. List common failure modes of AI agents?

Most agent failures fall into a few repeatable patterns. Knowing them tells you what to build guards for.

  1. Infinite or looping behavior - repeating the same failing call.
  2. Wrong tool or bad arguments - often from vague tool descriptions.
  3. Context overflow or drift - losing the original goal in a long run.
  4. Premature completion - claiming success without verifying.
  5. Hallucinated results - inventing file contents or API responses.
  6. Unsafe actions - destructive commands or prompt injection from tool output.
  7. Compounding errors - one early mistake spreading through later steps.
Take quiz
An agent says a task is done without running any check. Which failure mode is this?
context overflow
premature completion
tokenizer mismatch
sandbox escape
A vague tool description most often leads to which failure?
a faster model
lower GPU usage
choosing the wrong tool or passing bad arguments
automatic prompt caching

17. What is the difference between a model and a harness?

The model is the trained network that predicts text from a prompt. The harness is the software around it that decides what the prompt contains, what actions are possible, and what happens with the output.

Model Harness
Learned weights; fixed at inference time Ordinary code you write and can change any day
Produces text and tool requests Executes tools, enforces permissions, manages state
Improves via training by the provider Improves via prompts, tools, context rules, and evals
Stateless between calls Holds memory, history, and budgets

This split is why you can often raise reliability without touching the model at all.

Take quiz
Which statement correctly separates the harness from the model?
the harness is ordinary code you can change, while the model's weights are fixed at inference
the harness contains the trained weights
the model executes shell commands directly
Which of these can you improve by changing only the harness?
the number of parameters in the model
the model's pretraining data
the model's vocabulary size
how errors and tool results are presented to the model

18. How do you use a scratchpad or todo list in a harness?

A scratchpad gives the agent a place to write down its plan and progress outside the flow of tool output. The simplest version is a todo tool or a notes file the model can read and update.

The agent writes the steps at the start, marks each one as it finishes, and re-reads the list when the context grows long. That keeps the original goal in view and makes it harder to skip steps.

The harness can also surface the list back to the user as live progress, and persist it so a resumed run knows what is already done.

Take quiz
What is the main benefit of a todo list for a long-running agent?
it increases the model's parameter count
it keeps the plan and progress visible as the context grows
it replaces the need for tools
What extra use can the harness make of a persisted todo list?
resuming a later run with knowledge of what is already done
training a new model overnight
removing the system prompt
hiding errors from the user

19. How does a harness handle tool call errors?

The best default is to return the error to the model as a normal tool result, clearly marked as an error, instead of crashing the run. Models are good at reading "file not found" and trying a different path.

A few rules make this work well:

  • Write actionable messages: say what failed and what a valid call looks like.
  • Separate transient errors (timeouts, rate limits), which the harness retries with backoff, from logic errors, which the model must fix.
  • Validate arguments against the schema first so malformed calls never reach the tool.
  • Cap consecutive failures so the agent cannot retry the same broken call forever.
Take quiz
What is the usual best way to report a tool failure to the model?
crash the entire run immediately
hide it and pretend the call succeeded
return it as a clearly marked error result the model can react to
Which error type should the harness typically retry automatically with backoff?
arguments that fail schema validation
transient errors such as timeouts and rate limits
a tool that does not exist
a permission denial

20. How does context compaction work?

Compaction shrinks the history when it nears the window limit while keeping what the task still needs. The harness asks the model (or a cheaper one) to summarize older turns, then replaces them with that summary and keeps the most recent turns verbatim.

A good summary preserves decisions made, file paths touched, open problems, and the next step. It drops raw logs and dead ends.

A lighter technique is clearing old tool results while leaving the model's own reasoning and the call records in place. Large outputs are usually the biggest space-eaters, so this alone buys a lot of room.

Compaction is lossy by nature, so critical facts are better stored in a notes file the harness reloads.

Take quiz
What should a good compaction summary preserve?
decisions, touched file paths, open problems, and the next step
every raw log line verbatim
only the very first user message
Why are large tool results a good first target when freeing context?
they contain the model's weights
they can never be regenerated by rerunning a tool
they usually occupy the most space and are often no longer needed
removing them improves the tokenizer

21. Why do we use subagents?

A subagent is a separate model run with its own fresh context, started by the main agent to handle one focused job. The main agent receives only the final answer, not the dozens of intermediate tool calls.

The main benefits are:

  1. Context isolation - a search through 40 files does not clutter the main thread.
  2. Parallelism - independent investigations can run at the same time.
  3. Specialization - a subagent can have its own prompt and a narrower toolset.

The tradeoff is cost and coordination. More model calls use more tokens, and the subagent only knows what the parent writes in its brief, so a vague brief gives vague results.

Take quiz
What does the parent agent normally receive back from a subagent?
the subagent's entire raw context
the subagent's final answer, not its intermediate tool calls
the subagent's model weights
What is a key tradeoff of using subagents?
they make parallel work impossible
they remove the need for any tools
they always reduce total cost
more tokens spent and dependence on a clear brief from the parent

22. When should you use a workflow instead of an autonomous agent?

Use a workflow when the steps are known in advance and the path rarely changes. Use an agent when the number and order of steps depend on what the model discovers along the way.

Workflow Autonomous agent
Fixed code path with model calls at set points Model chooses the next action in a loop
Predictable cost and latency Variable cost and latency
Easy to test step by step Needs end-to-end evals
Good for extract, classify, summarize, route Good for open-ended coding or research

A sensible rule is to start with the simplest design that works, often a single model call, and add loop autonomy only when a fixed flow genuinely cannot cover the cases.

Take quiz
Which task suits a fixed workflow better than a free-running agent?
debugging an unfamiliar codebase with unknown steps
researching an open-ended question across many sources
classifying incoming support tickets into a known set of categories
What is a typical cost of choosing an autonomous agent over a workflow?
less predictable cost and latency
it can never use tools
it needs no testing at all
it always finishes in one call

23. How does prompt caching affect harness design?

Prompt caching lets the provider reuse the processed prefix of a prompt across calls, so repeated content is cheaper and faster. It only works when the beginning of the prompt is byte-identical to a previous request.

That shapes the harness:

  • Put stable content first: system prompt, tool definitions, project rules.
  • Append new messages at the end; do not rewrite or reorder earlier history.
  • Keep tool lists stable, since changing them mid-run can invalidate the cache.
  • Put volatile data such as the current time later in the prompt, not in the prefix.

In long agent loops, where the same large prefix is sent on every turn, this can cut cost and latency substantially.

Take quiz
Where should volatile data like the current time go to preserve the cache?
late in the prompt, after the stable prefix
at the very top of the system prompt
inside every tool name
What must be true for a cached prompt prefix to be reused?
the user must be the same person's age
the beginning of the prompt must match the earlier request exactly
the model must be asked a different question each time
the prompt must be shorter than 100 tokens

24. Why is idempotency important for agent tools?

An idempotent operation gives the same end result no matter how many times it runs. This matters because agents retry: after a timeout, a crash, or a confused model turn, the same call may be issued twice.

If a "create invoice" tool is not idempotent, one retry can bill a customer twice. If it accepts an idempotency key, the second call is recognized and returns the original result.

Prefer tools shaped as "set status to paid" over "toggle status". For non-idempotent actions like sending email, add a confirmation step or a dedupe check.

A simple test: run the tool twice with the same input and confirm the second run changes nothing.

Take quiz
Why do agent tools face duplicate calls more often than ordinary code?
models cannot count to one
retries after timeouts, crashes, or confused turns are common
the API forbids unique requests
Which tool design is safer under retries?
'toggle status' with no checks
'append one more charge' with no key
'set status to paid' rather than 'toggle status'
'send email' with no dedupe

25. How do you design good tool descriptions?

The description is the only guidance the model has for choosing a tool, so write it like a short instruction to a new colleague.

  1. State what the tool does and when to use it versus similar tools.
  2. Describe each parameter, including format and an example value.
  3. Note limits, such as "returns at most 50 results".
  4. Use clear names like search_orders_by_email rather than query2.
  5. Return concise, readable output, not raw dumps.

When an agent picks the wrong tool, the first fix is usually to improve the description, not to add prompt text elsewhere.

Read the descriptions cold: if a new teammate could not pick the right tool from them, the model cannot either.

Take quiz
When an agent keeps choosing the wrong tool, what is usually the first fix?
retrain the model from scratch
increase the sandbox memory
rewrite the tool description to say when to use it versus similar tools
Which tool name is clearest for the model?
query2
do_thing
tool_final_v3
search_orders_by_email

26. What is the difference between short-term and long-term agent memory?

Short-term memory is what sits in the current context window: the conversation, tool results, and any loaded files. It disappears when the session ends or when the history is trimmed.

Long-term memory is stored outside the window and brought back when relevant, such as notes files, a database of past decisions, or a vector index of earlier documents.

Short-term Long-term
Lives in the context window Lives in files, databases, or indexes
Lost on session end or trimming Survives across sessions
Always visible to the model Visible only after the harness retrieves it

The harness decides what gets promoted from short-term to long-term, and what gets loaded back.

Take quiz
Where does short-term agent memory live?
in the current context window
in the model's pretrained weights
in the GPU firmware
What must happen before long-term memory can influence the model?
the harness has to retrieve it and place it in the context
the model must be retrained overnight
the user must retype it each time
nothing, it is always automatically visible

27. How do you limit runaway agent loops?

Layer several guards, because any single one can be bypassed.

  • Hard turn limit on model calls per run.
  • Budget caps on tokens, dollars, and wall-clock time.
  • Repeat detection: if the same tool call with the same arguments appears several times, interrupt with a message or stop.
  • Progress checks: stop if several turns pass with no new files changed or no new information.
  • Tool timeouts so one hung call cannot stall the loop.

When a guard triggers, stop gracefully with a summary and a clear reason so a human can pick up from there.

Log every guard trigger, because frequent hits usually point to a prompt or tool problem rather than a one-off.

Take quiz
Which guard directly catches an agent repeating the same failing call?
repeat detection on identical tool calls and arguments
a larger font in the UI
a longer system prompt
a faster GPU
Why combine several loop guards instead of relying on one?
the API requires exactly five guards
any single guard can be bypassed or fail to trigger
guards make the model smarter
one guard always costs more than five

28. How does human-in-the-loop approval work in a harness?

Before running a risky action, the harness pauses the loop, shows the user exactly what the agent wants to do, and waits for approve, deny, or edit. Only then does it execute and continue.

The pause point is usually a permission check inside the tool layer. The pending call is shown with its real arguments, such as the full shell command, not a vague summary.

Good designs avoid approval fatigue. Safe, reversible actions run automatically, and users can approve a pattern for the session so they are not clicking through the same prompt fifty times. A denial should go back to the model as a result so it can choose another route.

Take quiz
What should the approval prompt show the user?
only the model's name
a vague summary with no details
the exact action and arguments the agent wants to run
What happens to a denied action in a well-built harness?
the whole session is deleted
the action runs anyway after a delay
the denial is returned to the model so it can try another route
the denial is hidden from the model

29. Why should tool outputs be truncated or paginated?

Tool results go straight into the context window. One unbounded cat of a large log or a database query returning 100,000 rows can fill the window, raise cost, and push the real task out of focus.

The harness should cap output size and tell the model what was cut, for example: "Showing lines 1-200 of 8,431. Use the offset argument for more." That lets the model fetch the next page only if it needs it.

Other helpful options are filtering at the source (a grep instead of reading the whole file), returning summaries with an ID for details, and saving huge output to a file while returning only the path.

Take quiz
Why is an unbounded tool output a problem?
it can fill the context window and bury the real task
it makes the model's weights drift
it breaks the internet connection
What should a truncation message tell the model?
nothing, to keep it brief
that the file does not exist
to stop all work
what was cut and how to request more

30. How do you build an eval set for an agent?

Start from real work, not invented puzzles. Pull 20 to 50 tasks from actual usage or bug reports, since a small set of realistic cases beats a large synthetic one.

  1. Write each task with a clear success criterion that can be checked by code where possible, such as a passing test or a matching database state.
  2. Include easy, typical, and hard cases, plus a few that should be refused or escalated.
  3. Run every task in a clean environment so runs do not contaminate each other.
  4. Keep failures: every production bug becomes a new eval case.

Grow the set over time, and keep a held-out portion so you do not overfit your prompts to the examples you tuned on.

Take quiz
Where should the first eval tasks come from?
random trivia questions
real usage and actual bug reports
model-generated nonsense strings
What is a good habit for production bugs when maintaining evals?
turn each bug into a new eval case
delete the eval that failed
ignore bugs not caused by the model
rerun the same passing cases only

31. What is the difference between offline evals and online monitoring?

Offline evals run on a fixed, known task set before release. They answer "did this change make things better or worse?" and are repeatable, so they work well as a gate in CI.

Online monitoring watches real traffic after release. It answers "what is actually happening for users?" and catches things your test set never imagined.

Offline evals Online monitoring
Fixed task set, known answers Live, unpredictable traffic
Run before shipping Run continuously after shipping
Catch regressions from changes Catch drift and unseen failure types

You need both. Online findings, such as a new failure pattern, feed back into the offline set.

Take quiz
Which question do offline evals answer best?
what are users doing right now?
which new unseen failure appeared last night?
did this change make the agent better or worse on known tasks?
How do online findings improve the offline eval set?
they replace the offline set entirely
new failure patterns found in production are added as cases
they are never reused
they are deleted after one day

32. How does a harness stream model output and tool calls?

Streaming means the harness reads the model's response as a series of events instead of waiting for the full message. Text appears for the user token by token, and tool call arguments arrive in fragments.

The harness accumulates those fragments, parses the arguments only once the call block is complete, and then runs the tool. Parsing early risks reading half-finished JSON.

Streaming improves perceived latency a lot, and it lets the UI show tool activity as it happens. It also needs careful handling of dropped connections: if a stream breaks mid-call, the harness should discard the partial tool call and retry rather than execute it.

Take quiz
When should the harness parse streamed tool call arguments?
once the tool call block is complete
as soon as the first character arrives
never, they are always ignored
What should happen to a half-received tool call if the stream drops?
it is executed with whatever arrived
it is saved as a permanent memory
it is discarded and the request retried, not executed
it is shown to the user as the final answer

33. Why are structured outputs useful in a harness?

Harness code needs to read the model's answer reliably. Free text forces fragile string parsing, while structured output, such as JSON conforming to a schema, can be consumed directly.

They help in three places: extracting fields for downstream code, producing routing decisions such as a category or next step, and forcing a tool call to match its input schema.

Still validate on receipt. Even with schema enforcement, values can be wrong in meaning, like a date in the wrong year, so add semantic checks and a retry path that returns the validation error to the model.

Many APIs support schema-constrained output or forced tool calls, which fixes the format while the content still needs checking.

Take quiz
What is the main advantage of structured output over free text for harness code?
it removes the need for a model
it can be consumed directly without fragile string parsing
it guarantees every value is factually correct
Why still validate schema-conforming output?
JSON can never be parsed
validation makes the model faster
schemas are ignored by all models
values can be valid in shape but wrong in meaning

34. How do you trace and log agent runs?

Treat each run as a trace, with one span per model call and one per tool call. Record the inputs, outputs, latency, token counts, and any errors, all tied to a run ID.

The minimum useful record is: the exact prompt sent, the raw model response, each tool call with arguments and result, stop reason, and cost. Without the exact prompt, you cannot reproduce a bad run.

Redact secrets and personal data before storing. Then use traces to replay failures, compare runs before and after a change, and mine real failures for new eval cases.

Sampling is fine at high volume, but always keep full traces for failed or flagged runs.

Take quiz
Why must the exact prompt be stored in an agent trace?
to reduce the model's size
because logs must be as large as possible
without it you cannot reproduce or explain a bad run
What should happen to sensitive values before traces are stored?
they are redacted
they are stored in plain text for convenience
they are emailed to the team
they are put into the system prompt

35. How do you manage secrets in an agent harness?

The core rule: the model should never see a secret it does not need to see. Anything in the context can be echoed back, logged, or leaked by a prompt injection.

  • Keep API keys in the harness or a secrets manager, and inject them into tool calls at execution time, so the model only names the tool.
  • Give the sandbox short-lived, narrowly scoped credentials instead of long-lived admin keys.
  • Scan tool output and traces for key patterns and redact them.
  • Block the agent from reading credential files such as environment dumps or key stores.

Rotate keys regularly and revoke any that appear in a trace, since logs often outlive the run.

Take quiz
Where should an API key be injected so the model never sees it?
into the tool call by the harness at execution time
into the system prompt
into the user's first message
What kind of credentials should a sandboxed agent receive?
permanent admin keys
short-lived, narrowly scoped ones
shared personal passwords
no credentials ever, even when the task needs one

36. How do you defend a harness against prompt injection?

Prompt injection happens when untrusted content, such as a web page, an email, or a tool result, contains instructions the model mistakes for the user's. No prompt wording fully prevents it, so defense has to be built into the harness.

  1. Treat external content as data. Label it clearly as untrusted and tell the model not to follow instructions found inside it. This lowers the risk but is not a guarantee.
  2. Apply least privilege. An agent summarizing web pages should not hold write access to your repository or mail.
  3. Break the dangerous combination. Risk peaks when one session has private data, untrusted input, and a way to send data out. Remove at least one of the three.
  4. Gate sensitive actions. Sending data externally, spending money, or deleting something requires human approval showing the real arguments.
  5. Restrict egress. Allow-list network destinations so stolen data has nowhere to go.
  6. Isolate with subagents. Let a low-privilege subagent read untrusted content and return only a plain summary.

Then test it: keep a set of known injection payloads in your evals and run them after every change.

Take quiz
Which combination makes prompt injection most dangerous in one session?
a short system prompt and a large model
private data, untrusted input, and a way to send data out
a fast network and a slow disk
Why is telling the model to 'ignore instructions in documents' not enough by itself?
models cannot read instructions at all
it makes the sandbox crash
it lowers the risk but cannot guarantee the model will comply
the instruction is removed by the tokenizer
Which defense stops stolen data from leaving even if the model is tricked?
allow-listing outbound network destinations
making the system prompt longer
using a bigger context window

37. Explain the execution flow of one agent turn?

A single turn is one pass through the loop. The details vary, but the sequence is consistent.

sequenceDiagram
  participant H as Harness
  participant M as Model
  participant T as Tool
  H->>H: Assemble prompt (system, history, tools)
  H->>M: Send request
  M-->>H: Response with tool_use block
  H->>H: Validate args and check permissions
  H->>T: Execute tool
  T-->>H: Result or error
  H->>H: Truncate, redact, append to history
  H->>M: Next request

Step by step: the harness builds the prompt from the stable prefix plus recent history, calls the model, and reads the response. If it contains a tool request, the harness validates the arguments against the schema, runs the permission check, and executes the tool in the sandbox.

The result is then post-processed: truncated if large, scanned for secrets, and wrapped as a tool result message. Hooks may fire before and after execution. Finally the harness checks stop conditions (turn limit, budget, final answer) and either loops again or returns.

Take quiz
Which step happens between receiving a tool request and executing it?
retraining the model
rewriting the system prompt
validating arguments and checking permissions
What does the harness do to a tool result before adding it to history?
encrypts it with the model's weights
sends it only to the user and not the model
deletes it unless it is short
truncates, redacts secrets, and wraps it as a tool result message

38. How do you design a sandbox for code-executing agents?

Assume the code the agent runs is untrusted, because it may come from a mistaken model or an injected instruction. Design for containment first, convenience second.

  • Isolation boundary: use a container with a restricted profile, or a microVM for stronger separation. Run as a non-root user.
  • Filesystem: mount only the project workspace read-write, and everything else read-only or absent. Never mount home directories or credential stores.
  • Network: default deny. Allow-list package registries or specific APIs when truly required.
  • Resources: cap CPU, memory, disk, process count, and run time so a runaway loop cannot take the host down.
  • Lifecycle: make environments disposable and reset between tasks so state does not leak across runs.
  • Secrets: pass only short-lived, scoped credentials.

Log every command and its output. A sandbox you cannot audit gives you containment but no visibility into what actually happened.

Take quiz
Which network default is safest for a code-executing sandbox?
deny all outbound traffic, then allow-list what is required
allow all outbound traffic
allow only inbound traffic from the internet
Why make sandbox environments disposable and reset between tasks?
to make the model larger
so state and files do not leak from one run to another
because containers cannot be reused technically
Which mount policy fits a sandboxed coding agent best?
the whole home directory read-write
project workspace read-write, everything else read-only or absent
the host's credential store read-only
the root filesystem read-write

39. How can you optimize token cost in a long-running agent?

In an agent loop the whole context is resent on every turn, so cost grows with history length times the number of turns. Most savings come from keeping that context small and stable.

  1. Cache the prefix. Keep system prompt and tool definitions stable and in front so cached reads apply.
  2. Trim tool output. Paginate, filter at the source, and clear stale results.
  3. Compact history before it grows large, preserving decisions and next steps.
  4. Delegate noisy work to subagents so intermediate calls never enter the main context.
  5. Route by difficulty. Use a smaller model for simple steps like classification and a stronger one for planning.
  6. Load tools lazily. Hundreds of tool definitions in every prompt cost tokens even when unused.

Measure before and after on your eval set. A cheaper run that fails more often is not a saving.

Take quiz
Why does cost grow quickly in a long agent loop?
the model's weights grow every turn
the full context is resent on each turn
the tokenizer adds a fee per tool
What should you verify after applying a cost optimization?
that the model name changed
that task success on your evals did not drop
that the logs are shorter
that the sandbox uses less disk only

40. How do you troubleshoot an agent stuck in a loop?

Start with the trace, not the prompt. Read the last ten or so turns and look at what actually repeats.

  1. Same call, same arguments? Check the tool result. An unhelpful error like "failed" gives the model nothing new, so it retries. Make the message specific.
  2. Different calls, no progress? The goal may be unclear or unreachable. Check whether the success condition is verifiable and whether a needed tool or permission is missing.
  3. Context drift? In long runs the original goal gets buried. Re-inject the task or a todo list and consider compaction.
  4. Flip-flopping between two states? Two instructions probably conflict, such as "keep changes minimal" and "make all tests pass".

Fix the root cause, then add a guard: repeat detection, a progress check, and a turn cap. Finally, save the failing run as an eval case so the loop cannot come back unnoticed.

Take quiz
An agent retries one call that returns only 'failed'. What is the best first fix?
increase the temperature
delete the system prompt
make the error message specific and actionable
What often causes an agent to flip-flop between two states?
a too-fast network connection
too many CPU cores
two conflicting instructions in its prompt or rules
too short a tool name
What should you do with a failing run once fixed?
delete the trace immediately
disable logging
ignore it since it is fixed
add it as an eval case to prevent regressions

41. How does the orchestrator-worker pattern work?

An orchestrator agent breaks a task into subtasks, hands each to a worker agent, and then combines the results. Workers run with their own context and a narrow toolset, and return concise findings.

flowchart TD
  U["User task"] --> O[Orchestrator]
  O --> W1["Worker: research A"]
  O --> W2["Worker: research B"]
  O --> W3["Worker: write tests"]
  W1 --> S[Synthesize]
  W2 --> S
  W3 --> S
  S --> R["Final answer"]

It fits problems where subtasks are independent and the breakdown is not known upfront, such as researching several sources at once.

The weak points are the handoffs. A worker only knows what the orchestrator writes in its brief, so briefs need the goal, constraints, and expected output format. Parallel workers editing the same files can also conflict, so give them separate areas or serialize writes.

Costs are higher than a single agent, so use it when the parallel speedup or context isolation clearly pays for itself.

Take quiz
Why is the orchestrator's brief to each worker so important?
the worker only knows what the brief contains
workers share the orchestrator's full memory automatically
workers ignore briefs and guess
Which risk appears when parallel workers edit the same files?
the files are encrypted automatically
the model weights are overwritten
the files become read-only forever
conflicting changes unless writes are separated or serialized

42. How do you make an agent run resumable after a crash?

The idea is to persist enough state that a fresh process can pick up where the old one stopped, instead of restarting from zero.

  1. Checkpoint after each turn. Save the message history, tool results, todo list, and run metadata to durable storage.
  2. Record tool intent before execution and the outcome after. On restart you can tell whether the last tool call finished.
  3. Make tools idempotent or use idempotency keys, so replaying an uncertain step does not duplicate effects.
  4. Keep side effects visible. Store IDs of created resources so the resumed run can find them.
  5. Version the state format so older checkpoints still load after a harness update.

On resume, reload the checkpoint, check the last uncertain step, and continue the loop. Keep the original budgets so a crash does not reset your spend limits.

Take quiz
Why record tool intent before executing a tool?
it makes the model respond faster
after a crash you can tell whether the call may have completed
it removes the need for any checkpoints
What makes replaying an uncertain step safe?
idempotent tools or idempotency keys
deleting the history first
disabling the sandbox
using a larger model

43. How do you evaluate non-deterministic agent behavior?

The same agent can pass a task once and fail it the next time, so a single run tells you little. Evaluate by repetition and by outcome.

  • Run each task several times. Report the pass rate rather than one pass or fail.
  • Use pass@k when one success among k attempts is enough, as in a tool that proposes several fixes. Use a stricter all-k-pass measure when reliability matters, such as customer-facing automation.
  • Grade outcomes, not exact paths. Agents reach the same result via different steps, so check final state, passing tests, or database contents.
  • Use model graders carefully. A judge model suits subjective qualities, but spot-check it against human labels.
  • Track variance. A high average with wide swings is still a risky agent.
Take quiz
When is an all-k-pass metric more appropriate than pass@k?
when one lucky success among many is enough
when the task has no success criterion
when reliability matters and every attempt must succeed
Why grade outcomes rather than exact step sequences?
steps are never recorded
agents can reach the same correct result by different paths
outcomes cannot be checked by code
exact steps are always identical
What is a sensible check on a judge model grader?
trust it without review
use it only on tasks with unit tests
spot-check its scores against human labels
let it grade its own earlier output only

44. Which is better: one big tool or many small tools, and why?

Neither wins everywhere. The tradeoff is between model decision-making cost and capability coverage.

Few broad tools Many narrow tools
Short tool list, less prompt space Long tool list uses more tokens
Model must craft complex arguments, such as raw SQL or shell Arguments are simple and easy to validate
Hard to restrict precisely Easy to permission each action separately
Flexible for unexpected needs Clear intent, easier to audit

A broad shell tool is flexible but hard to constrain. A narrow get_order_status tool is easy to secure and understand but covers only one case.

A practical approach is to start with a small set of well-described tools for the common actions and keep one general escape hatch behind approval. If the model keeps mis-choosing between near-duplicates, merge them. If it keeps building complex arguments badly, split them.

Take quiz
What is a main advantage of many narrow tools?
each action is easier to validate, permission, and audit
the tool list is always shorter
they cover every unexpected need
What is a main weakness of one very broad tool such as a raw shell?
it cannot execute anything
it needs no description
it is hard to restrict precisely
it always runs faster

45. How do you handle parallel tool calls safely?

Models can request several tools in one response. Running them concurrently saves time, but only when they do not interfere.

  1. Classify tools: mark read-only tools as safe to run in parallel. Tools that write or change shared state run one at a time.
  2. Check dependencies. If one call needs another's output, the model should request it in a later turn, not the same one.
  3. Avoid write conflicts. Two parallel edits to the same file can overwrite each other, so lock or serialize them.
  4. Return results in a matching order, each tied to its call ID, so the model can pair request and result.
  5. Isolate failures. One failed call should return an error result without cancelling the others.

Apply permission checks to each call individually, not to the batch as a whole.

Take quiz
Which tool calls are generally safe to run in parallel?
two edits to the same file
read-only calls that do not touch shared state
calls where one needs the other's output
How does the model match results to its parallel requests?
by guessing from the length of output
by the alphabetical order of tool names
by the time of day
by the call ID attached to each result

46. How do you detect harness regressions after a model upgrade?

A new model can behave differently even when your harness is unchanged: it may call tools more or less often, follow instructions more literally, or respond at a different length. Treat every upgrade as a change that needs testing.

  1. Run your full eval set on old and new models with the same harness, and compare pass rate, cost, turns, and latency.
  2. Diff the traces. Look at tool-call patterns, retries, and where runs end, not only final scores.
  3. Audit old prompt workarounds. Instructions added to fix a weakness in the old model, like repeated "double-check" lines, can over-correct on a stronger one.
  4. Roll out gradually. Send a small share of traffic to the new model and watch online metrics before switching fully.

Keep the old model selectable so you can roll back quickly.

Take quiz
Why audit prompt workarounds after a model upgrade?
new models ignore all prompts
workarounds are required to be kept forever
instructions written for the old model's weaknesses may now over-correct
What is a safe rollout approach for a new model?
send a small share of traffic first and watch online metrics
switch all traffic instantly with no monitoring
delete the old model configuration
disable the eval set

47. Explain the internal working of context assembly?

Context assembly is the step where the harness builds the exact prompt for each model call. It is the most influential piece of harness code, because the model can only act on what it is shown.

A typical order, from most to least stable:

  1. System prompt with role and rules.
  2. Tool definitions, sometimes loaded only for tools likely to be needed.
  3. Project memory such as an instructions file.
  4. Conversation history, with older turns summarized or cleared.
  5. Fresh retrieved material like files or search results for this step.
  6. Volatile details such as the current time or working directory.

The assembler enforces a token budget. When the total exceeds it, the harness trims in a planned order: stale tool results first, then compaction of older turns. It never trims the system prompt or the latest user request.

Keeping the stable parts first and appending new content at the end also preserves the prompt cache from one call to the next.

Take quiz
Which part is trimmed first when the context exceeds its budget?
stale tool results
the system prompt
the latest user request
Why are stable parts placed first in assembled context?
models read only the first line
it preserves the prompt cache between calls
stable parts use zero tokens
the order has no effect at all

48. How do you design permission tiers for destructive actions?

Group actions by reversibility and blast radius, then attach a policy to each group.

Tier Examples Policy
Read-only list files, search, read logs Auto-allow
Reversible write edit files in a git workspace Auto-allow in scope, easy to undo
Hard to undo delete branches, drop tables, deploy Require approval
External or irreversible send email, pay, publish Approval with exact arguments, or block

Policy should be evaluated on the real arguments, not just the tool name. git push to a feature branch and to main are different risks.

Add safety nets that make approval less critical: work on branches or copies, take snapshots before destructive steps, and keep an audit log. Default to deny for anything unclassified, and let users widen rules deliberately.

Take quiz
What two factors define the permission tiers?
model size and context length
reversibility and blast radius
font and color of the UI
Why evaluate policy on real arguments instead of only the tool name?
tool names are always secret
arguments are never available
the same tool can be low or high risk depending on its arguments
all arguments are always equally safe
What default is safest for an unclassified action?
allow automatically
run it and ask later
skip logging it
deny until it is deliberately allowed

49. How do you verify an agent's work before it finishes?

Do not rely on the model saying "done". Build a verification gate that must pass before the harness accepts completion.

  1. Programmatic checks first. Run tests, linters, type checkers, schema validation, or a script that inspects the resulting state. These are fast, cheap, and objective.
  2. Feed failures back. If a check fails, return the output to the model and continue the loop with a retry limit.
  3. Use a model-based review for fuzzy criteria such as tone or completeness, ideally with a separate reviewer that has a fresh context and a clear rubric.
  4. Enforce with a hook. A completion hook that runs the checks guarantees they happen, rather than hoping the prompt triggers them.

Where a task cannot be verified automatically, say so, and route it to human review.

Take quiz
Why prefer programmatic checks before model-based review?
they are always subjective
they cannot run in a sandbox
they are fast, cheap, and objective
How can you guarantee verification runs before completion?
ask politely once in the system prompt
hope the model remembers
run it only on weekends
enforce it with a completion hook

50. How do you design a harness that is robust to model changes?

Models improve and change, so a harness tuned too tightly to one model's quirks becomes a liability.

  • Keep the model behind an interface. Isolate provider calls so you can swap or route models without touching the loop.
  • Prefer simple, general scaffolding. Heavy rules and rigid step-by-step flows can hold back a stronger model. Add structure only where evals show it helps.
  • Tag every workaround with the failure it fixes, so you can test removing it on the next model.
  • Rely on evals, not intuition. A solid eval set lets you re-validate quickly after each change.
  • Use deterministic enforcement (hooks, sandbox, permissions) for safety, since these do not depend on model behavior.
  • Keep prompts and tool descriptions in versioned config, not scattered in code.

The goal is a harness that gets better, not worse, when a more capable model is dropped in.

Take quiz
Why tag each workaround with the failure it was added to fix?
so you can test removing it when a newer model arrives
tags make the model run faster
workarounds must never be removed
Which safety mechanism is independent of model behavior?
deterministic enforcement such as a sandbox or permission rules
a polite request in the prompt
the model's own promise to behave
a longer system prompt
What is the benefit of keeping the model behind an interface?
the model weights become smaller
you can swap or route models without changing the agent loop
tools stop being needed
evals become unnecessary
«
»

Comments & Discussions