Why the Same LLM API Produces Different Results: Understanding the Agent Harness
The same language model can perform very differently across applications because its results depend on more than model capability. This article explains how prompts, context, memory, retrieval, tools, and execution controls work together in an agent harness. It also shows how to evaluate these systems for task quality, cost, safety, and reliability.
1. The Same Model Does Not Mean the Same System
A language model may explain a problem clearly in a chat interface yet repeatedly edit the wrong files when connected to an AI coding tool. In a different runtime framework, it may locate the fault and fix it successfully. These differences do not necessarily mean the underlying model has changed.
The model is the reasoning and generation component of a larger system. What users ultimately receive also depends on the information the application supplies, how it describes the task, which tools it allows, how it handles execution results, and when it considers the task complete.
The runtime framework that coordinates these elements is commonly called a harness. In this article, an agent harness refers to the mechanisms that organize and control the model’s operation.
An AI application can be understood as the following loop:
User goal↓Harness: assembles inputs, manages state, controls execution,and handles exceptions↓Model: interprets the current input and generates a responseor proposed action↓Tools and external environment: retrieve information, read files,execute tasks, and return results↓Harness updates state and decides whether to call the model againor end the task
However, using the “same API” does not guarantee identical experimental conditions. Model versions, sampling settings, output limits, hidden system instructions, request routing, and server-side processing can all affect performance. Before comparing applications, confirm whether these conditions are consistent, then examine the harness.
The more precise conclusion is this: the model provides foundational capabilities, while the harness influences whether those capabilities are applied consistently, effectively, and safely to a particular task. A harness cannot guarantee performance beyond the model’s capabilities, but it can reduce losses caused by missing inputs, uncontrolled execution, and inadequate feedback.
2. LLMs: The Generation Core, Not a Complete Execution System
Large language models, or LLMs, learn statistical patterns and complex relationships during training. At inference time, they generate tokens incrementally based on the current input. A token is a basic unit of information processing and does not necessarily correspond to a word or character.
“Predicting the next token” describes the generation mechanism of common language models, but it should not be mistaken for simple mechanical word completion. Large-scale training enables language understanding, knowledge expression, code generation, and reasoning to varying degrees. Models can still make factual errors, overlook constraints, and reason incorrectly.
From an application engineering perspective, three boundaries are particularly important:
| Boundary | Practical meaning | Common supporting mechanisms |
|---|---|---|
| Limited state across requests | Independent inference requests generally do not automatically receive the full content of previous interactions | Session state, context management, external memory |
| Incomplete internal knowledge | Training-derived knowledge may be outdated and does not include private enterprise information | Retrieval-augmented generation, external queries |
| No direct control over external environments | Generating a tool-call request is not the same as executing an operation | Tool executors, permission management, task orchestration |
These boundaries do not mean that every model service lacks memory or can return only text. Services may support multimodal inputs, structured outputs, tool-calling protocols, or server-side session management. The important distinction is which capabilities come from the model, which come from the API service, and which are implemented by the application.
For example, a model can produce a structured request to read a file. An external executor typically performs the actual read. The system must also enforce file access permissions, validate paths, and return the results.
3. Prompts and Context: Instructions Are Not the Same as Evidence
Prompts: Tell the Model What to Do
A prompt primarily expresses the task objective, role expectations, constraints, and output requirements.
Consider several ways to request code analysis:
- “Explain this code” defines an open-ended task.
- “Identify issues that could cause duplicate writes and explain their triggering conditions” directs the analysis.
- “Provide repair recommendations only; do not modify files” establishes an action boundary.
- “Report the issue location, cause, proposed fix, and validation method” specifies the deliverable.
A good prompt is not necessarily a long prompt. It should reduce ambiguity and express important requirements as verifiable conditions. For complex tasks, it should explain at least:
- What the task is trying to accomplish.
- Which information and tools may be used.
- Which operations are prohibited.
- What criteria define completion.
- What to do when information is insufficient.
Prompts cannot replace missing facts. Asking a model to “carefully inspect the entire project” without providing relevant code or file access is unlikely to produce a reliable result.
Context: The Information Available in the Current Request
Context is the information the model can use in its current request. In typical applications, it includes task instructions, user questions, conversation history, document excerpts, code, and tool results.
Prompts and context are therefore not separate containers. A prompt is usually part of the context. The distinction is one of emphasis: a prompt specifies expected behavior, while context encompasses all the information available for the current inference.
Context management is not simply about supplying more content. The key questions are:
- Does the context contain the evidence needed to solve the current problem?
- Is the information sufficiently current?
- Are conflicting versions present?
- Are irrelevant details obscuring critical constraints?
- Does the input leave enough room for the response and subsequent tool interactions?
For coding tasks, relevant functions, call sites, error logs, and test results are often more useful than indiscriminately supplying an entire code directory.
Memory: Saving State Does Not Mean Replaying Everything
Agent memory usually means that an application stores information externally and retrieves it as needed. This can include recent conversations, task progress summaries, verified facts, and user preferences.
Memory must distinguish information by source and validity. “The user explicitly prohibited changes to configuration files” can be stored as a constraint. “The model suspects the cache is responsible” must remain an unverified hypothesis rather than becoming an established fact in a later summary.
A sound memory mechanism records provenance, time, and confidence, and supports updates or removal. Otherwise, incorrect conclusions can become increasingly entrenched across interactions.
4. RAG: Finding Evidence, Not Retraining the Model
Retrieval-augmented generation, or RAG, typically retrieves relevant information from external sources and adds it to the context to support response generation.
A typical pipeline is:
Document collection → Cleaning and chunking → Indexing→ Candidate retrieval → Ranking and filtering→ Context assembly → Response generation
Retrieval can use keyword matching, vector similarity, or a combination of both. Different methods suit different information types. Error codes, configuration keys, and function names often require exact matching. Questions with different wording but similar meaning may benefit from semantic retrieval.
RAG performance depends on the entire pipeline, not merely on whether a vector index is used.
Common failures include:
- Chunking separates a definition from its exceptions.
- Retrieval returns documentation for an outdated version.
- Similar excerpts fill the context while an essential rule is omitted.
- Content the user is not authorized to access appears in the answer.
- The model cites a source but draws a conclusion that the source does not support.
Improvements should address document versions, source identifiers, permission filtering, retrieval coverage, and evidence supporting the answer. When evidence is insufficient, the system should allow a response such as “The available material is insufficient to confirm this,” rather than forcing a conclusion.
RAG should also be distinguished from general tool use. Retrieval can be performed through a tool, but not all tools retrieve information. Running tests, submitting an approval request, and updating records are different kinds of external operations.
5. Tools: Turning Proposed Actions into Controlled Operations
Tools are operational interfaces between the model and its external environment. Examples include:
- Reading a specified file.
- Querying business data.
- Searching a knowledge base.
- Running tests.
- Generating a patch.
- Initiating an authorized business operation.
A reliable tool interface defines its input structure, parameter meanings, return format, permission scope, and failure states. The model proposes a call; the executor validates the request and performs the operation.
Model-generated parameters must not be treated as trusted input. File paths require validation, query scopes need limits, and writes require permission checks. Actions with external consequences may need additional confirmation.
Tool design also affects task performance. A general-purpose tool that can perform arbitrary operations offers flexibility but may increase the impact of mistakes. Tools with clearly defined responsibilities are easier to validate and audit.
Error feedback matters as well. “Execution failed” offers little guidance. Messages such as “Target file does not exist,” “The current account has no write permission,” or “The test found an unexpected return type for empty input” provide useful evidence for the next decision. Feedback should remain concise and avoid exposing sensitive data.
6. Agents: Goal-Directed Feedback Loops
An agent is generally a system that works toward a goal by selecting actions based on its current state, calling tools, and using feedback to continue making progress.
An agent is not simply one model call with an elaborate prompt, nor must it run with unlimited autonomy. Its defining features are some degree of action selection and a feedback loop:
Understand the goal → Select the next step → Execute a tool→ Observe the result → Update state → Continue or stop
For a code repair task, that loop might involve:
- Reading the error information and forming an initial hypothesis.
- Locating relevant files and the call chain.
- Inspecting the implementation and tests.
- Proposing a minimal change.
- Running validation.
- Adjusting the change based on failures.
- Summarizing the changes, evidence, and remaining risks.
“Agent = LLM + Harness” is a useful engineering shorthand, not a strict industry-wide definition. Systems differ in their expectations for planning, autonomy, and tool use. A fixed process can also call models and tools, but when predefined steps control the entire process, AI workflow is often a more appropriate description.
Hybrid designs are common in practice. An outer workflow fixes permissions, stages, and acceptance criteria, while the model can choose retrieval and analysis steps within those boundaries. This preserves flexibility while making risk easier to control.
7. The Harness: How the Entire Loop Operates
A harness is not a single prompt. It is a collection of runtime mechanisms. When applications using the same model perform differently, the differences often appear in the following areas.
Input Construction
The harness determines how system instructions are organized, which historical messages are retained, which documents enter the context, and what content is compressed.
One system might send only “Fix this error.” Another might also provide error logs, relevant functions, call sites, and prohibited modification areas. The actual working conditions presented to the model are already different.
State and Plan Management
Complex tasks require records of completed steps, unresolved issues, and verified facts. Without them, an agent may repeatedly search the same file or forget an original constraint after several rounds.
Plans should adapt to feedback, but unverified guesses must not automatically become facts.
Execution Control
The harness limits tool calls, runtime, and resource consumption. It handles timeouts and exceptions and determines when to retry, fall back, or request human assistance.
Retries must account for idempotency. Read-only queries are generally easier to retry. Writes, notifications, and external submissions require safeguards against duplicate side effects.
Security Boundaries
External documents, web pages, and files may contain text intended to change system behavior. The harness should treat that content as data to process, not automatically elevate it into higher-authority instructions.
Prompts can remind the model to respect boundaries, but actual permission isolation should also be enforced by the executor. This includes restricting accessible directories, isolating execution environments, protecting credentials, and requiring approval for high-risk operations.
Completion Criteria
“The model says it is done” is not sufficient evidence of completion. The system should use observable criteria, such as:
- Whether the specified tests pass.
- Whether changes remain within the allowed scope.
- Whether key conclusions are supported by source material.
- Whether the output follows the agreed structure.
- Whether unresolved blockers remain.
The harness makes these requirements operational throughout the task.
8. A Coding Example: Why Two Harnesses Produce Different Results
Suppose a user asks an agent to fix an edge-case bug in a data-processing function and explicitly prohibits changes to the public interface.
A weaker harness might send only the current file to the model and directly accept the generated patch. The model cannot see callers or tests and has no opportunity to validate the result. The patch may fix a local error while changing the return structure and breaking other modules.
A more capable harness would:
- Read the relevant function and its call sites.
- Retrieve existing tests and interface contracts.
- Preserve “Do not change the public interface” as an ongoing constraint.
- Restrict the modification scope.
- Run validation after generating the patch.
- Return a summary of test failures to the model.
- Stop and report when evidence is insufficient or the budget is exhausted.
The difference is not that the model mysteriously became smarter. It received more complete evidence, clearer boundaries, and more useful feedback.
The following pseudocode illustrates the process; it does not represent a particular product API:
state ← initialize task, permissions, budget, and acceptance criteriawhile task is not finished and budget is not exhausted:input ← task requirements + relevant evidence + verified statedecision ← call_model(input)if decision contains a tool request:check permissions, parameters, and riskexecute toolrecord results in state with source informationelse:check whether the response meets acceptance criteriaif criteria are met:finishelse:obtain missing information or request human assistanceoutput results, validation evidence, and unresolved issues
9. Evaluation: Turning Experience Gaps into Diagnosable Problems
Optimizing an AI application requires more than a handful of successful examples. Build an evaluation set that represents real tasks and, wherever possible, hold the model version, inference settings, initial information, permissions, and resource budget constant.
Evaluation metrics can be grouped into four categories:
| Dimension | What to examine |
|---|---|
| Outcome quality | Whether the task is actually completed, the answer is correct, and constraints are satisfied |
| Process quality | Whether retrieval finds key evidence, tool parameters are correct, and ineffective actions are repeated |
| Cost efficiency | Number of calls, input and output volume, runtime, and tool execution costs |
| Safety and reliability | Unauthorized operations, sensitive data exposure, exception recovery, and duplicate side effects |
The final answer alone rarely reveals where a failure occurred. Preserve the execution records needed for diagnosis: summaries of each round’s inputs, retrieval sources, tool requests, execution results, state changes, and termination reasons. Apply data minimization, redact sensitive information, and control access to these records.
Once a problem is located, change one component at a time. For example, keep the model fixed while changing context selection, or keep the inputs fixed while adding test feedback. This makes it possible to identify which component caused the improvement.
Generated outputs are stochastic, so run each task multiple times where practical. Examine success rates, variability, and recurring failure modes. A harness should be judged not only by whether it completes a task, but also by whether it does so consistently at an acceptable cost and risk.
10. Conclusion: Reliable AI Applications Depend on the System Loop
The main concepts fit together as follows:
- LLM: interprets inputs and generates responses or proposed actions.
- Prompt: expresses objectives and constraints.
- Context: provides the information currently available to the model.
- Memory: stores state and restores it when needed.
- RAG: supplies external evidence.
- Tool: executes controlled operations.
- Agent: forms a goal-directed action and feedback loop.
- Harness: organizes and constrains the overall runtime process.
Different experiences with the same model API often arise because the surrounding systems create different working conditions. Longer prompts, more documents, and broader tool permissions do not inherently produce better results.
The reliable path is to provide relevant, trustworthy information, use tools with clear responsibilities, feed execution results back into decision-making, and verify completion against independent acceptance criteria. When these elements form a stable loop, model capabilities are more likely to become deliverable, reproducible, and auditable results.
