Agentic Models Explained: How They Read Files, Write Code, and Call Tools
This article explains the shift of large language models from conversational Q&A to agentic systems that autonomously work toward a goal, organized around three core capabilities: reading files, writing code, and calling tools. It covers the engineering essentials of long-context and multimodal input handling, structured output, long-horizon autonomous coding with context management and safe tool loops, how to interpret benchmark results across quality and cost, multi-agent collaboration, and the production practices and risk controls needed to deploy these systems reliably. Readers will learn practical patterns for matching model tiers to tasks, managing context in long sessions, and building trustworthy agent infrastructure.
1. From “Conversing” to “Getting Work Done”: The Capability Leap of Agentic Models
The traditional way to use large models was question-and-answer. The agentic paradigm instead requires a model to work continuously toward a goal: reading materials, calling tools, modifying files, running tests, and adjusting the next action based on the results. This kind of work typically spans a dozen or more steps and can stretch across hours. Business expectations have shifted accordingly: users no longer just want to be “told how to do something” — they want “the thing actually done.”
Such models are often summarized as being able to “read files, write code, and call tools.” The phrasing is plain, but it captures three critical capability lines of an agentic system:
- Reading files: turning multimodal materials such as spreadsheets, documents, charts, audio, and video into usable information;
- Writing code: turning a solution into executable, verifiable programs or configuration;
- Calling tools: retrieving, computing, executing, and validating in a real environment.
Task difficulty also varies along a clear gradient. Everyday office work like organizing documents and summarizing data is far less demanding — in terms of reasoning depth and sustained execution — than a cross-module code refactor or a long-running scientific data analysis. This is why a common industry practice is to design model tiers by capability and speed:
- A lightweight tier handles fast, routine execution;
- A complex tier tackles the hardest, most time-consuming projects;
- A balanced tier strikes a balance between complex reasoning and execution efficiency.
For developers, this means you don’t need the strongest model for every task. Instead, you should match the appropriate capability tier to each type of task based on its profile.
2. Reading Files: The Engineering Essentials of Long Context and Multimodal Parsing
2.1 Inputs in Office and Research Settings Are Rarely Just Text
In office and research settings, information comes in many forms:
- Spreadsheets hold large amounts of numerical data and calculation logic;
- PDF documents mix body text, charts, and footnotes;
- Drawings and photographs carry engineering detail;
- Meeting recordings and presentation videos contain spoken information beyond written material.
Extracting only text often leads to one-sided conclusions in a state of “seeming to understand while actually missing things.” Take financial data analysis: hidden decimal places in a spreadsheet, two columns with inconsistent units, or a header misalignment caused by merged cells — any single oversight can distort the aggregated result. Therefore, a model should be able to process spreadsheets, PDFs, charts, audio, and video within a unified context and produce structured results, such as structured reports, presentation frameworks, or data analysis conclusions.
2.2 “Million-Token Context”: You Must Both Use It and Manage It
Current mainstream models can offer long-context windows of hundreds of thousands to even a million tokens. The direct benefit is that the technical documentation of a large project, the core modules of an entire codebase, and multiple research reports can all be brought into the model’s view at once, reducing the information loss that comes from repeatedly chunking and manually extracting key details.
But a large context window does not mean the model uses it well. The industry has widely observed a “mid-context recall degradation” phenomenon: the longer the context, the more easily less-frequently-used background and details get ignored or forgotten during reasoning, alongside “context rot” — the steady accumulation of irrelevant information that interferes with later judgments. Engineering practice typically takes the following measures:
- Front-load key information: place task goals, constraints, and acceptance criteria in prominent positions in the prompt, and restate them periodically throughout the conversation;
- Chunked pre-reading of long text: for very long documents, first generate a structured summary and an index of key sections, then recall the body on demand;
- Retrieval augmentation: use vector databases and keyword search to precisely locate relevant content across large codebases and knowledge bases, rather than stuffing everything into the context;
- Periodic compression: summarize completed historical turns and archive intermediate artifacts, keeping only decision records and key conclusions;
- Task isolation: use separate sessions for different subtasks to avoid irrelevant contexts contaminating each other.
2.3 Structured Output Is the Prerequisite for Reliable Consumption by Downstream Systems
If an agent’s output is a block of free text, it’s hard for downstream systems to use reliably. A more workable approach is: first define the data structure (fields, types, and value ranges), then have the model output according to that structure, and finally validate with a program. It’s also important to establish a principle of “leave it blank when uncertain” — better to flag a missing value than to fabricate one.
import jsonimport refrom dataclasses import dataclass@dataclassclass MetricItem:name: str # Metric name, e.g. "YoY growth"value: float | None # Value; None when it cannot be recognized or is missingunit: str | None # Unit, e.g. "%"source: str # Source annotation: file + page/table locationdef extract_metrics(raw_text: str) -> list[dict]:"""raw_text is plain text parsed from a document, with sources marked as placeholders"""text = raw_text.replace("[[source:", "\n").replace("]]", "")items = []pattern = r"(YoY growth|gross margin|net margin)\D*?(-?\d+(?:\.\d+)?)\s*(%)?"for match in re.finditer(pattern, text):value = float(match.group(2))if match.group(1) == "YoY growth" and not -1 <= value <= 1:continue # Out of a reasonable range; likely a misrecognition, so discarditems.append(MetricItem(name=match.group(1),value=value,unit=match.group(3) or None,source=text[match.start():match.end()],).__dict__)return itemsresult = extract_metrics("In 2024 the company's gross margin was [[source:Annual Report p.12 table 3]] 32.5%")print(json.dumps(result, ensure_ascii=False, indent=2))
Parsing notes
- This assumes the upstream document-parsing step has already stripped headers and footers and converted “source: page/table number” into placeholders. This makes it possible to trace where data came from while preventing the parser from misreading an incidental number as a source.
- In the code,
MetricItemusesvalue: float | Noneto represent a “missing value,” and keeps a source annotation for each number to support traceability and verification.extract_metricsuses a regular expression to extract “metric name + value + unit,” and applies a sanity check for “YoY growth.” Values outside a reasonable range may be misrecognitions and should be discarded for human review.- In production, these rules can be upgraded to “model extraction + program validation.” Complex layouts that rules cannot cover can be handed to the model for parsing, then verified by the program.
2.4 From Drawings to Scenarios, from Images to Data Tables
Two application cases illustrate the value of this kind of continuous processing.
First, an agent reads engineering drawings (containing floor plans, sections, elevations, and dimension annotations), identifies component types, spatial relationships, and dimension information to form structured building parameters, then drives 3D modeling and interactive visualization. The value here is that designers and reviewers can quickly obtain a spatial model they can rotate, section, and measure — without relying on the workflow of specialized modeling software.
Second, an agent starts from a single image, identifies the elements and annotations within it, and builds a spreadsheet containing calculation formulas, used to compute image-processing parameters such as edge detection, depth mapping, and lighting adjustment. The input is just a static image, but the output is a structurally complete data model with formulas that can be recalculated and linked — the user can change any parameter and immediately see how the overall effect changes.
The common thread in both cases: the model isn’t “answering a question,” but rather advancing continuously along the path of “file → intermediate artifact → deliverable,” calling tools at key points to complete transformations. This is precisely the essential difference between an agent and conversational Q&A.
3. Writing Code: From Snippet Completion to Long-Horizon Autonomous Programming
3.1 How Long-Horizon Programming Differs from Snippet Completion
Traditional code assistants are centered on snippet completion. The interaction happens at the current editing location, and the model sees only a limited context. A long-horizon autonomous programming agent faces a different class of tasks:
- Spanning multiple files and modules;
- Requiring repeated test runs and fixes based on failure messages;
- Having to balance “already-satisfied requirements” against “no newly introduced problems.”
In such tasks, the model must not only generate changes but also run tests, analyze errors, and keep fixing until the acceptance criteria are met.
3.2 Context Management in Long Sessions
A long-running programming agent needs a “working memory” mechanism:
- Change log: records which files were modified, why, and the expected effect;
- Verification log: stores the command, result, and failure stack trace of each test;
- Constraint ledger: records the boundary conditions in the requirements that must not be violated.
With these records, the model can avoid wasting context by repeatedly reading the same files, and won’t “forget” constraints established early in a long session. This is fundamentally about using externalized state management to compensate for the limited capacity of a model’s internal memory.
3.3 The Typical Structure of an Autonomous Programming Loop
A basic autonomous programming loop with sound engineering constraints usually includes the following stages:
import subprocessimport jsonWRITE_TOOLS = {"apply_patch", "create_file"} # Tools that require user confirmationSAFE_TOOLS = {"read_file", "search_code", "run_tests", "list_dir"}def should_confirm(call) -> bool:"""High-risk operations that modify files should be confirmed by the user"""return call.name in WRITE_TOOLS or call.arguments.get("delete", False)def run_agent(goal: str, tools: dict, model, max_steps: int = 30):history = [{"role": "system", "content": "Goal and acceptance criteria: all unit tests pass, and no public interfaces are modified"},{"role": "user", "content": goal},]log = [] # Key decisions and verification results, retained when compressing historyfor step in range(1, max_steps + 1):reply = model.chat(history, tools=tools)# No tool call: treat as task completion, output a summary for human acceptanceif not reply.tool_calls:return {"status": "done", "summary": reply.text, "steps": step}for call in reply.tool_calls:if call.name not in SAFE_TOOLS and call.name not in WRITE_TOOLS:result = {"error": f"Tool {call.name} is not on the allowlist"}elif should_confirm(call) and not call.approved:result = {"error": "Execution requires user confirmation", "pending": call.id}else:try:result = tools[call.name](**call.arguments)except Exception as exc:result = {"error": str(exc)}# Return failure messages as-is so the model can locate the problemhistory.append({"role": "assistant", "tool_calls": [call]})history.append({"role": "tool", "content": json.dumps(result, ensure_ascii=False)})# Compress completed history, keeping only the system prompt and key decision logif len(history) > 40:history = history[:2] + history[-6:] + [{"role": "note", "content": json.dumps(log)}]log.append({"step": step, "last_result": result})return {"status": "timeout", "reason": "Maximum step count reached", "log": log}
This loop embodies several key design choices:
- Tool allowlist: only declared tools can be called, preventing the model from invoking unauthorized capabilities;
- Confirmation for high-risk operations: irreversible actions such as file writes and deletions require user confirmation;
- Transparent error return: error messages are passed back to the model as-is so it can locate the problem, rather than guessing on its own;
- Step limit: prevents an endless retry loop from causing costs to spiral out of control;
- History compression: controls context length, retaining decision records rather than all intermediate outputs.
3.4 Task Decomposition: Letting the Model “Walk the Full Chain”
Cross-file refactoring or bug fixes can be decomposed into independently verifiable subtasks:
- Problem localization: run the failing test and identify the first failure point from the stack trace;
- Root cause analysis: search along the call chain for the relevant functions and data structures;
- Minimal fix: modify only the code directly related to the root cause, avoiding “refactoring on the side”;
- Verification: run the unit tests and regression tests for related modules;
- Wrap-up: organize the change notes for code review.
Take the example of “an interface return value that is occasionally empty”: the agent might discover that a certain function fails to add a boundary check under non-standard input; after the fix, tests pass, but regression testing exposes a hidden dependency in an adjacent module. In that case, continuing to fix — rather than hastily converging — is exactly what “walking the full chain” requires.
3.5 Making Good Use of the Tool Environment
An often-overlooked fact in evaluations is that the same model can differ several-fold in task completion rate under different runtime frameworks. This gap comes mainly from the runtime environment, not the model itself:
- Whether tools are complete (can it search code, run tests, view logs);
- How context is organized (are error details and change history retained);
- How failures are retried (are they rerun automatically, is the problem scope narrowed automatically);
- Whether sandbox isolation and access control are in place.
Therefore, when selecting and deploying, “model + tool environment + prompt engineering” should be evaluated and optimized as a whole, rather than comparing the model in isolation.
4. Interpreting Benchmarks: Quality, Cost, and Runtime Framework All Matter
The evaluation landscape for agentic models is evolving rapidly and can broadly be grouped into three categories:
| Evaluation type | Focus | Typical measure |
|---|---|---|
| Multimodal knowledge agent evaluation | Whether it can understand files containing images and charts and produce correct conclusions | Task-quality ranking, together with average cost per task |
| General knowledge and reasoning evaluation | The breadth of the model’s knowledge and reasoning accuracy | Composite score and ranking against similar models |
| Code and terminal task evaluation | Whether it can complete end-to-end tasks such as fixes, refactors, and command-line operations | Task pass rate, along with multi-turn tool-calling ability |
When interpreting these results, three points deserve attention.
First, a single ranking does not mean overall leadership. A model that ranks second on quality but costs several times less per task than the top-ranked one may not be worse in terms of cost-effectiveness. Real deployment requires weighing quality and cost together, not just looking at leaderboard positions.
Second, the cost basis must be consistent. The cost per task usually includes:
- Model inference fees (input and output tokens);
- Tool-calling fees;
- Environment runtime fees (containers, sandboxes, etc.);
- Additional overhead from failure retries.
Different evaluations use different accounting methods, so when comparing, confirm whether retries and environment costs are included. In practice, it’s worthwhile to establish a “total cost per successful task” metric: one that covers all attempts while counting only tasks that ultimately succeed.
Third, different evaluations test different task types. Multimodal knowledge understanding, general reasoning, and code generation belong to different capability dimensions, and their scores cannot be compared horizontally. A more reliable approach is to:
- Fix the test cases and environment;
- Compare combinations of different models and different runtime frameworks;
- Build an evaluation set around your own business scenarios;
- Run periodic regression validation.
Only then can you arrive at selection conclusions with real practical value.
5. Multi-Agent Collaboration: Coordination, Division of Labor, and Parallel Execution
In large engineering tasks, a single agent is often stretched thin. Multi-agent collaboration offers a workable way to organize the work: a stronger model serves as the coordinator, responsible for understanding requirements, breaking down tasks, designing the architecture, and reviewing results; multiple lighter models act as executors, working in parallel on specific file modifications, test writing, and documentation updates.
A typical workflow is as follows:
- Planning phase: the coordinator reads the requirements and the existing code structure and produces a task list (file scope, acceptance criteria, dependencies);
- Execution phase: executors work in parallel according to the task list, with no two modifying the same file;
- Aggregation phase: the coordinator merges the results, runs integration tests, and reassigns tasks when conflicts are found.
There are a few pitfall-prone points in collaboration design:
- Interfaces first: the prerequisite for parallel development is a clear interface contract; otherwise, merge costs rise quickly;
- File ownership: define a “writable file scope” for each task to avoid parallel write conflicts;
- Review closure: the coordinator’s review should not stop at “looks reasonable” but should be based on test results and static analysis;
- Error convergence: executor failure messages need to be returned in a structured form to prevent the coordinator from falling into ineffective retries.
It’s worth stressing that with multi-agent systems, more is not always better. When a task has strong sequential dependencies, little room for parallelism, and high communication overhead, a single agent can be more efficient.
6. Deployment Practice and Risk Control
Turning these capabilities into a stable, reliable production system also requires engineering safeguards in the following areas:
- Tiered scheduling: dynamically route between the lightweight, balanced, and complex tiers based on task complexity and response-time requirements, balancing cost and effectiveness;
- Least privilege: tool calls follow the principle of least privilege; write operations require confirmation by default, and critical operations retain audit logs;
- Sandbox isolation: code execution and file operations run in a controlled environment to prevent misoperations from affecting production systems;
- Observability: record the tool call, token consumption, and elapsed time at each step to make it easier to locate performance bottlenecks and anomalous behavior;
- Human-machine collaboration: keep a human approval step for high-impact, irreversible operations;
- Result validation: use tests, rule-based validation, and sampled human review as the “last gate,” preventing model output from going straight into business decisions;
- Security and compliance: encrypt and enforce access controls on uploaded files and audio/video materials during transmission and storage; stay alert to prompt injection attacks (malicious instructions embedded in documents) and, when necessary, isolate and filter input content.
In actual deployment, you can combine object storage to hold raw materials, message queues to smooth out traffic peaks and troughs, container platforms to provide elastic execution environments, and logging plus monitoring and alerting services to trace the entire process — building a complete agent runtime infrastructure.
7. Conclusion
From “conversing” to “getting work done,” the evolution of agentic models is reshaping the way software development is done. The three capabilities of reading files, writing code, and calling tools correspond respectively to information understanding, solution implementation, and execution validation — together forming the core closed loop by which agents complete tasks.
At the same time, we should stay clear-headed: a long context does not mean “understanding without error,” and a leaderboard ranking does not mean “ready for business use.” What truly determines deployment success is whether task decomposition is sound, whether the tool environment is complete, whether permissions and costs are under control, and whether there is a reliable validation mechanism for results.
For developers and enterprises, the rational path is to: define business scenarios and acceptance criteria, build your own evaluation sets, choose the appropriate capability tiers and runtime frameworks, and lay the groundwork in security, compliance, and observability. Only in this way can agentic models truly become productivity tools rather than a black box that “seems smart but is actually uncontrollable.”
