From Q&A to Delivery: Engineering Practices for Long Context and Agentic Coding

    This article examines how AI assistants are shifting from answering questions to delivering verified outcomes, and what it takes to engineer that transition. It covers why long context is essential for code-centric agentic work, along with the practical constraints of attention dilution, cost, context bloat, and noise. It then explains configurable reasoning effort with adaptive routing, a reliable agentic loop of planning, execution, verification, and rollback, context compression and long-term memory strategies for long sessions, and metrics for evaluating a "digital worker." A reference cloud architecture and three common pitfalls round out the discussion, giving engineering teams a practical blueprint for building trustworthy coding agents.

    1. The Shift in Positioning: From “Answering Questions” to “Delivering Results”

    Over the past two years, most teams have used large models in a simple “one question, one answer” mode: asking the model to explain a piece of code, polish some copy, or suggest the cause of an error. The session ends, the context is cleared, and the task is back to zero. This mode has a low value ceiling because it leaves the hardest parts to the human — the human breaks down the task, moves information around, verifies results, and organizes the next question.

    The agentic direction that the industry has been pushing recently essentially pulls this pipeline inside the model: the model itself runs a loop of task planning → tool invocation → result observation → self-correction, continuing until the goal is reached or an exit condition is triggered. The difference between this kind of assistant and a chatbot lies not in “answering better,” but in three structural capabilities:

    1. Autonomous planning: breaking a vague goal like “produce a competitive analysis” into an executable sequence of subtasks (research, data gathering, cleaning, comparison, drafting), and dynamically adjusting the plan during execution.
    2. Long-horizon execution: staying aligned with the goal after dozens of tool calls, without drifting from the original intent because an intermediate step failed.
    3. Verifiable output: the deliverable is not a piece of text, but file changes that have been tested, compiled, and validated.

    It is worth emphasizing that these three points are exactly the main pain points in engineering practice today. A model that “talks well” is not necessarily one that “works well,” because the latter demands an order of magnitude more in context management, error recovery, and cost control.

    2. Ultra-Long Context: Capability Leaps Coexist with Engineering Constraints

    2.1 Why Long Context Is a Hard Requirement for Agentic Scenarios

    The traditional approach relies on retrieval-augmented generation (RAG) to chunk knowledge and feed it to the model, but code-related tasks are naturally unsuited to chunking: a single refactor needs to see the upstream and downstream of the call chain, interface definitions, test assertions, and build configuration all at once. Once the context window reaches the million-token scale, the way of working changes fundamentally:

    • Whole-repository visibility: bringing the project directory structure, key module source code, and dependency lists into context at once significantly improves the accuracy of cross-file reasoning.
    • Long-document handling: specifications, design documents, and incident reports running to hundreds of pages can be analyzed as a whole, rather than being summarized in segments and then stitched back together.
    • Long-session memory: multi-day development sessions can continue, reducing the repeated cost of “re-explaining the background every time.”

    2.2 Four Constraints That Must Be Faced Head-On

    Long context is no free lunch, and engineering must deal with it directly:

    Constraint How It Shows Up Mitigation Approach
    Attention dilution Key information is ignored when it sits in the middle of the context (commonly called “lost in the middle”) Place core instructions and the current goal at the beginning and end; reorder and re-emphasize key fragments
    Linear cost growth Input tokens directly determine cost and latency Context budgeting, on-demand injection, layered summarization
    Context bloat Tool return values (logs, dependency trees, compile output) quickly fill the window Truncate return values plus structured extraction, keeping only fields relevant to the decision
    Noise pollution Irrelevant history leads the model astray Session segmentation; rebuild the working context when switching tasks

    One practical principle: manage the context budget explicitly rather than waiting for it to overflow. Allocate a quota each to the system prompt, task state, code retrieval results, and tool output, and when a limit is exceeded, compress the “heaviest” parts first.

    3. Tiered Reasoning Effort: Teaching the Model to Match Effort to the Task

    Deep reasoning comes at a cost. On simple tasks, the same model “thinks longer” and produces over-analysis, slower responses, and higher costs; on tasks like architecture design and diagnosing tricky defects, insufficient reasoning effort directly produces wrong solutions. Therefore, configurable reasoning effort has become a foundational engineering capability for agentic systems, and the industry commonly adopts a four-tier design:

    • Low: intent recognition, format conversion, small single-file changes — pursuing the lowest latency and cost.
    • Medium: routine business logic implementation, unit test generation.
    • High (often the default): cross-module changes, code review, scenarios that require weighing multiple implementations.
    • Max: architecture selection, complex concurrency/consistency defect investigation, long-chain performance optimization.

    More important than “manual tier selection” is adaptive routing: the system, rather than the user, decides how much reasoning budget the current request needs. A workable routing implementation looks roughly like this (illustrative pseudocode, with generic interface names):

    1. def route_effort(task: Task, ctx: Context) -> str:
    2. """Select a reasoning effort tier based on task complexity and context signals."""
    3. # 1. Explicit signals take priority: a tier specified by the user / CI pipeline
    4. if task.explicit_effort:
    5. return task.explicit_effort
    6. # 2. Risk signals: raise the tier for production config, data migration, or access changes
    7. if task.touches({"prod", "migration", "iam", "billing"}):
    8. return "max"
    9. # 3. Scale signals: cross-file change volume and retrieval hit range
    10. if len(task.target_files) >= 8 or ctx.retrieval_hits > 20:
    11. return "high"
    12. # 4. Historical signals: many past retries on similar tasks mean the default tier is insufficient
    13. if ctx.retry_count_for_similar >= 2:
    14. return "high"
    15. # 5. Downgrade simple, deterministic tasks to save latency and cost
    16. if task.kind in {"format", "rename", "comment", "extract"}:
    17. return "low"
    18. return "medium"

    Two companion design details matter here. One is tiered retry with fallback: when the highest tier fails repeatedly, fall back to an intermediate result and hand it to a human for confirmation, avoiding runaway spending. The other is a cost guardrail: set token budgets for a single session and a daily account, and automatically downgrade with an alert as the threshold approaches.

    4. A Reliable Agentic Coding Loop: Plan, Execute, Verify, Roll Back

    A coding agent that can work over the long term needs a structurally complete chain of four stages.

    Planning stage: first produce an explicit task list (rather than diving straight in), where each item must be verifiable — for example, “add boundary cases for interface X and bring coverage above a threshold.” Externalizing the list as a file is a key means of resisting forgetting in long sessions — after the context is compressed, the goal still exists.

    Execution stage: the toolset should be minimal with clear boundaries, typically covering four categories: file read/write, command execution, dependency queries, and test runs. All side-effect operations (writing files, executing commands, calling external interfaces) go through a unified gateway, making it easy to apply permissions and auditing.

    Verification stage: this is the dividing line between agentic systems and “generating code snippets.” After each change, objective validation is triggered mandatorily — compile, static analysis, unit tests. The model corrects itself based on the failure output, forming an inner loop of “change — verify — change again.” An agent lacking a verification step is essentially still an untrustworthy text generator.

    Rollback stage: all changes happen in an isolated branch or container workspace with disposable snapshots retained; once the maximum retry count or budget ceiling is reached, abandon the workspace and hand the intermediate findings back to a human as a report.

    On security, three bottom lines must be clear: least privilege (read-only by default, with write permission granted by directory whitelist), sandbox isolation (run with restricted resource quotas on a container platform, blocking access to production networks and credentials), and no leakage of sensitive information (inbound masking of keys, tokens, and internal network addresses).

    5. Context Compression and Long-Term Memory: The Pivot for Stable Long Sessions

    Faced with a million-token window, engineering practice usually does not “stuff in everything that fits,” but instead applies compression strategies:

    • Rolling summarization: after each subtask is completed, compress that segment of conversation and tool output into a three-part summary of “conclusion + key evidence + open questions,” replacing the original content.
    • Key-point extraction: large tool return values such as logs and dependency trees keep only the fields and lines relevant to the current decision.
    • Layered memory: the short-term workspace holds current files and code snippets; the mid-term task list holds progress; long-term knowledge is retrieved from an external knowledge base and backfilled on demand, without staying resident in context.
    • State snapshots: after a session is interrupted, recover from the task list plus workspace diff rather than relying on conversation history.

    The benefits of this mechanism are twofold: it reduces the risk of attention dilution in long sessions, and it turns token consumption from “growing unbounded with session length” into “growing controllably with task size.”

    6. How to Evaluate a “Digital Worker”

    Chat-style evaluation methods (response fluency, human ratings) cannot measure agentic capability. Four categories of metrics are recommended:

    1. End-to-end task success rate: on a set of real tickets, the proportion that passes all validations in one shot.
    2. Number of human interventions: how many human corrections are needed on average to complete a task — the metric closest to ROI.
    3. Resource cost per task: average token consumption × unit price + execution time, to be read together with the tier routing strategy.
    4. Failure recoverability: the self-recovery rate after injecting faults (compile errors, missing dependencies, network timeouts) and the reasonableness of the abandonment strategy.

    Add one security metric: the interception rate of unauthorized and high-risk operations — that is, whether the sandbox correctly blocks actions such as writing to production, deleting data, or sending sensitive information externally.

    7. A Reference Cloud Architecture

    When building such a system inside an enterprise, a complete chain can be assembled from common cloud capabilities without building all the infrastructure yourself:

    • Model inference service: handles inference requests, tiering cost and effectiveness by pairing different model specifications with each effort tier.
    • Container platform: spins up an isolated agent execution environment for each session, destroyed as soon as the task ends.
    • Object storage: holds artifacts, snapshots, evaluation datasets, and task lists.
    • Message queue: makes long-running tasks asynchronous, avoiding tying up the synchronous request path.
    • Logging and monitoring/alerting: records every tool call and reasoning tier to build an observable call chain, and sets threshold alerts for cost anomalies and unauthorized attempts.
    • Credential management: centrally manages model keys and code repository tokens, with the agent side obtaining only short-lived credentials.

    Baidu AI Cloud’s value in these scenarios lies in providing the above capabilities as standard cloud services, so teams can focus on the agent’s planning strategy, tool gateway, and evaluation system rather than rebuilding the underlying infrastructure. For specific product capabilities and quotas, refer to the official documentation.

    8. Three Common Pitfalls

    • Pitfall 1: Longer context is always better. Without budget management and information reordering, a million-token context can actually achieve lower accuracy than a few tens of thousands of carefully selected tokens.
    • Pitfall 2: Always use the highest reasoning tier. Over-reasoning drags down latency and cost on simple tasks and introduces unnecessary plan changes. Tier routing matters more than the tier ceiling.
    • Pitfall 3: Connecting to a production repository without a sandbox. Once an agent can execute commands, the permission boundary is the only line of defense; automation without isolation and auditing shifts risk from people to an uncontrollable program.

    Conclusion

    The term “digital worker” has become popular because it accurately describes a shift in the center of capability: the model is no longer just a called function, but a delegated executor. For this metaphor to hold, four pieces must be completed on the technical side — controlled long context, a routable reasoning budget, an execution loop with verification, and an observable, rollback-capable runtime environment. The former determines the ceiling; the latter determines whether it can truly go to production.