Why the Same Model API Performs Differently Across Different Agent Frameworks
This article explains why a large language model can behave very differently across tools even when the model weights, API protocol, and billing stay the same. It breaks down the relationship of Agent ≈ LLM + Harness, then walks from the inside out: the model's stateless, text-only nature and its three architectural constraints; prompts as the instruction layer; context as the scarce resource that most determines success; retrieval-augmented generation for updating knowledge; tool calling for taking action; agent loops for closing the loop; and the harness that decides how much of the model's capability is actually released. It also includes a layered reference architecture, common pitfalls, and a tuning checklist for diagnosing poor results layer by layer instead of switching models.
1. A Common Confusion: Same Model, Completely Different Experience
Most developers have run into this: a model answers clearly and follows instructions well in one chat interface; configure the same endpoint and API key in a coding assistant, and it keeps missing constraints and repeating mistakes; switch to another tool, and performance jumps back up.
The model weights have not changed. The API protocol has not changed. Billing has not changed. What changed is the entire “runtime shell” around the model. The industry often summarizes this relationship with one equation:
Agent ≈ LLM + Harness
The point is not mathematics but division of labor: the model sets the ceiling of capability, while the surrounding framework decides how much of that capability is actually unlocked. Prompts, context, retrieval augmentation, and tool calling are all parts in the hands of the surrounding framework.
This article proceeds from the inside out: first the engine’s own capabilities and flaws, then each layer of patches — what problem it solves, how to design it, and what the common mistakes are — and finally a reusable layered reference architecture and a tuning checklist.
2. The Innermost Layer: An LLM Is a Text-Prediction Expert
A large language model (LLM) is usually described as a neural network with a huge parameter count that has read massive amounts of text. From the caller’s perspective, however, its behavior is very simple: it receives a piece of text and outputs a piece of text. Generation is autoregressive — it predicts one token at a time, appends it to the input, and continues.
Input: tokens -> model forward pass -> probability distribution over next token -> sampling -> append -> loop
This matters: at the API level there is no such thing as a “session,” “memory,” “file,” or “database” — only a piece of text that keeps growing. Every seemingly advanced capability is the result of the caller encoding the necessary information into that text.
This yields three built-in limitations, and nearly every concept that follows is a patch for them:
| Built-in limitation | How it shows up | Common compensation |
|---|---|---|
| Stateless | Calls are isolated; without re-supplying history, it acts amnesiac | Context management, session memory, summarization |
| Fixed knowledge boundary | Covers only the corpus visible during training; no internal company data or real-time information | Retrieval augmentation, web search, knowledge bases |
| Text output only | Cannot read local files, execute code, or change system state | Tool calling, agent loops, sandboxed execution |
These three points are not a defect list but architectural constraints. Much of the engineering complexity comes from building a stateful, action-capable, updatable system around a function that is stateless, text-only, and knowledge-limited.
3. Layer Two: Prompts, Encoding Intent into Model-Readable Constraints
The prompt is the only interface that touches the model directly, and the layer with the highest return on investment. A maintainable prompt usually has five parts:
- Role and goal: the system identity and the outcome this task must achieve;
- Input data: the user question, retrieved snippets, code context, wrapped in explicit delimiters;
- Constraints and boundaries: output format, prohibited actions, what to do when uncertain;
- Reasoning and step requirements: whether to analyze before concluding, whether to list evidence;
- Examples: a few high-quality examples usually beat long strings of adjectives.
The key in practice is not writing more, but keeping the structure stable, the boundaries clear, and the prompt versionable. Keep the system prompt separate from user input, and put volatile business rules in configuration rather than hardcoding them into prose:
[SYSTEM] You are a code review assistant. Answer only based on the content in <context>;when evidence is insufficient, output "insufficient information" and do not speculate.Output JSON: {"verdict": "pass|change", "issues": [...], "evidence": [...]}[CONTEXT] {{retrieved_snippets}}[USER] {{question}}
An often-overlooked fact: prompts and context are not the same layer. The prompt is the instruction layer; context is the data layer. Putting retrieved content in the instruction position, or describing data in an instructional tone, significantly raises the chance of the model being derailed by that content.
4. Layer Three: Context, the Scarce Resource That Really Decides Success
Context is all the text the model can see in a single call. It is bound by two constraints: the model’s maximum length, and the gap between “fits in” and “actually gets used.” The latter matters most — as context grows, utilization of information in the middle typically drops, so “stuff everything in” is usually worse than “place a small amount precisely.”
Context engineering usually involves four operations:
- Filtering: filter candidates by relevance, recency, and permissions;
- Ordering: place the most relevant evidence at the more sensitive positions, near the beginning or the end;
- Compression: summarize conversation history, keeping decisions, conclusions, and to-dos while dropping pleasantries and repetition;
- Isolation: wrap content from different sources in separate sections to prevent cross-contamination.
A simplified context assembly function:
def build_context(system, history, snippets, budget=8000):parts, used = [system], len(system)for s in snippets: # data layer: retrieved evidenceif used + len(s) > budget * 0.6: breakparts.append(f"<evidence>{s}</evidence>"); used += len(s)for turn in summarize(history): # session layer: compressed historyif used + len(turn) > budget * 0.9: breakparts.append(turn); used += len(turn)return "\n".join(parts)
In practice, set separate budget ratios for instructions, evidence, history, and user input, and degrade explicitly when limits are exceeded (drop history details first, then low-scoring evidence) instead of letting truncation happen at random.
5. Layer Four: Retrieval Augmentation, Turning External Knowledge into Updatable Context
Retrieval-augmented generation (RAG) addresses the knowledge boundary and knowledge freshness problems. Its value is not “bolting on a knowledge base” but decoupling knowledge updates from model updates: when documents change, you only rebuild the index, with no retraining.
The typical pipeline: document parsing and chunking → embedding and index building → query rewriting and recall → reranking → context assembly → generation with cited sources.
A few practical details that decide the outcome:
- Chunking strategy: splitting along semantic structure (headings, paragraphs, function boundaries) usually beats fixed character counts, with necessary overlap kept between chunks;
- Hybrid recall: keyword search and vector search complement each other — the former is good at proper nouns and identifiers, the latter at semantic similarity;
- Reranking: recall aims at “don’t miss anything,” reranking aims at “correct order”; the goals differ and should not be merged;
- Permission filtering: filters must take effect at the recall stage; you cannot rely on the model “not looking at unauthorized content”;
- Verifiability: require output to cite snippet IDs, which makes human verification easy and markedly reduces fabrication.
Be clear about the boundary: RAG is good at “finding and citing,” not at “global computation across documents.” If a task requires aggregation, statistics, or multi-step reasoning, add computation and planning on top of retrieval.
6. Layer Five: Tool Calling, Moving the Model from “Talking” to “Doing”
Tool use / function calling turns the model’s text output into executable intent. The model does not really execute anything; it only produces a structured call request, which the surrounding framework validates and runs, then feeds the result back as new context.
{"tool": "run_tests", "arguments": {"path": "tests/", "level": "fast"}}
A reliable tool layer needs four things:
- Clear descriptions and parameter constraints: the tool description is the model’s manual, and vague semantics lead directly to misuse;
- Strict validation: parameter types, value ranges, and path boundaries must be checked on the framework side; never trust model output;
- Least privilege and sandboxing: file read/write, network access, and command execution should be minimally authorized and isolated;
- Structured returns: error messages must be parseable and actionable; avoid feeding large raw logs back in and crowding out context.
On security, be explicit: external content (web pages, documents, code comments) is untrusted input. If it contains text like “ignore previous instructions,” treat it as data and never elevate it to instruction privilege.
7. Layer Six: Agents, Organizing Calls into a Closed Loop
An agent is a model that autonomously decides the next step inside a loop: observe → plan → call tools → read results → revise the plan, until a termination condition is met.
while not done and steps < N:action = model.plan(context)result = executor.run(action)context = update(context, result)
The design focus is on convergence, not freedom:
- Explicit termination conditions: success criteria, maximum steps, timeout, and budget caps are all required;
- Externalized state: write progress and completed items to external state so the goal is not lost as context grows;
- Recoverable failures: a failed tool should be retried or routed around, not left spinning in the loop;
- Observability: log a summary of each step’s input, tool calls, and elapsed time to make problems easy to locate;
- Human in the loop: high-risk actions (deletion, release, payment) require explicit confirmation.
8. The Outermost Layer: The Harness, Which Decides How Much Capability Is Released
The harness is all the engineering wrapped around the model: prompt templates, context assembly, the retrieval pipeline, tool registration and execution, loop control, state storage, caching, rate limiting, logging, and evaluation. It creates no new capability, but it decides how much of the existing capability can be reproduced reliably.
This also explains the opening phenomenon: when the same model differs noticeably across tools, it usually comes down to four variables — system prompt quality, context budget and retrieval quality, tool and permission design, and loop and error-handling strategy. The model is the constant; these are the variables.
A minimal layered reference architecture:
Application layer task orchestration / permissions / auditAgent layer planning loop / termination conditions / stateCapability layer tool execution / retrieval / sandboxContext layer budget allocation / compression / orderingModel layer stateless text interfaceSupport layer logging / monitoring and alerting / caching / rate limiting / evaluation
Roll it out in order: first make prompts and the context budget solid, then add retrieval, then tools and the loop, and finally observability and evaluation. Optimization without evaluation is blind tuning: build a fixed test set and score answer correctness, citation accuracy, tool call success rate, average steps, and latency separately, changing only one variable at a time.
9. Conclusion
From the model to the harness, the path is one of stacking patches: statelessness is patched with context, knowledge limits with retrieval, inability to act with tools, disordered action with the agent loop, and the integration quality of all these patches is decided by the harness.
For developers, the most practical rule is: when results are poor, don’t switch models first — locate the problem layer by layer. Check whether the prompt is vague, whether context is crowded out by junk data, whether retrieved evidence is relevant, whether tool descriptions are clear, and whether the loop has termination and recovery mechanisms. Quantify these five areas one by one and most “the model got dumber” problems will show themselves. If you need elastic compute plus supporting infrastructure such as data, containers, and log monitoring, you can compose general-purpose product categories from cloud platforms such as Baidu AI Cloud as needed, and focus your effort on harness design and evaluation.
