Long Context and Agent Code: Capability Boundaries and Cost Control

    This article records an internal test of a new-generation large language model (LLM) tasked with product planning, frontend development, and bug fixing for a financial data monitoring web application. It explores the practical limits of long context processing, the implementation of agent self-iteration loops, and the differences between single-agent and multi-agent frameworks. Furthermore, it provides formulas for estimating API costs and strategies for quota management, along with essential risk, compliance, and automation guidelines.

    What We Tested and What We Didn’t

    This article documents an internal test: handing the same set of requirements to a new-generation large language model (LLM) to complete the product planning, frontend setup, and test fixing of a financial data monitoring web application. The accessed model is uniformly referred to as the “tested model” throughout the text, and the conclusions apply only to the API version and task conditions at the time of testing. This article does not compare benchmark scores from different vendors, nor does it discuss model training details. Readers wishing to reproduce the results need to substitute their own available model APIs and validate with their own task sets.

    How Far Can Long Context Processing Go?

    The tested model can receive relatively long documents in a single input to parse financial statements, legal contracts, and other materials. However, “supporting long input” only means the text can be fed in; it does not mean every paragraph is accurately understood. During validation, focus on the following four aspects:

    • Context length: The nominal maximum input from the API documentation is the upper limit, but the actual reliable range is usually lower. Teams should find the length where “information starts getting lost” on their own documents.
    • Document type: Parsing quality varies greatly among plain text, text transcribed from scanned documents, multi-column layouts, and tables containing merged cells.
    • Truncation and retrieval: Documents exceeding the limit should be segmented first, then relevant paragraphs should be selected using keyword or vector retrieval before being fed into the model.
    • Result verification: Amounts, dates, and clause numbers extracted by the model must be verified item by item against the original text and cannot be directly entered into accounts.
    Document Type Common Risks Recommended Practices
    Plain text contracts Clause numbering misalignment Verify against original text by number after extraction
    Financial statements (tables) Column misalignment due to merged cells Convert to structured tables first, then pass to the model
    Transcribed scanned docs Number recognition errors Perform secondary verification on amount fields
    Ultra-long annual reports Loss of information in distant paragraphs Segment and retrieve, then summarize

    How to Implement Agent Self-Iteration

    In a local environment, the tested model can read error logs, locate defects, and generate fix patches, forming a “test, feedback, fix” loop. The pseudocode below illustrates the structure of this loop. It cannot be run directly; you need to implement model, execute, init_environment, and update_state yourself.

    1. # Pseudocode: Requires self-implemented dependency functions and must run in an isolated sandbox
    2. MAX_ITER = 5
    3. def agent_iteration_loop(task_prompt: str, max_iter: int = MAX_ITER):
    4. state = init_environment() # Create an isolated working directory and record a git snapshot
    5. for step in range(max_iter):
    6. plan = model.plan(task_prompt, state) # Generate the next action
    7. result = execute(plan, sandbox=True) # Only execute whitelisted commands
    8. verdict = model.evaluate(result) # Determine success or failure based on test output
    9. if verdict.is_success:
    10. return result.output
    11. state = update_state(verdict, result) # Keep the current error info and prepare for the next round
    12. rollback_to_snapshot(state) # If still failing after max iterations, rollback to snapshot
    13. raise RuntimeError(f"Failed within {max_iter} iterations, rolled back, manual intervention required")

    There are three requirements for implementation. First, execute can only access the working directory; network and system-level write permissions are disabled by default. Second, record a snapshot before the start of each round to allow rollback on failure. Third, a maximum iteration limit and a maximum budget limit must be set simultaneously; the loop must stop if either is triggered.

    Common issues and handling methods during iteration are as follows:

    • Context overflow: Stuffing the complete log back into the prompt every round causes output quality to drop noticeably in later rounds. Solution: Only retain the last error and the relevant code segments.
    • Tool call failure: Parameter format mismatches the function signature. Solution: Define a JSON Schema for each tool and validate before calling.
    • Insufficient permissions: No write permissions inside the container, or dependencies cannot be installed. Solution: Install dependencies in advance and restrict writable directories.
    • Invalid fixes: The model repeatedly modifies the same line. Solution: Stop the loop and switch to manual processing if the same error occurs for two consecutive rounds.

    Single Agent vs. Multi-Agent: What Are the Differences?

    In multi-task scenarios like financial intelligence analysis, the multi-agent (Swarm) framework has higher stability requirements. Under a single-agent setup, the tested model can follow complex system prompts well and maintain reasoning coherence when encountering environmental changes. It can also adjust commands based on the operating system and dependency versions, provided that environment detection results are explicitly passed into the prompt; the model cannot guess the local machine’s state out of thin air.

    Observation Dimension Single Agent Multi-Agent (Swarm)
    Instruction following Usually stable when prompts are short Prompts of different roles interact, requiring separate testing
    Exception recovery Low cost of re-execution after failure An error in one role may cause cascading downstream failures
    Context consumption Grows linearly with iterations Grows faster when roles share context
    Key metrics Task pass rate, average iterations Role handover success rate, loop counts

    During testing, it is recommended to fix the task set (no less than 20 tasks), fix the model version, and record the input and output token counts for each call. This article does not provide fixed numerical values because the variance between different task sets is large; teams need to measure using their own data.

    How to Calculate Costs and Quotas

    The call cost of large models is usually billed by token, and the unit prices for input and output are often different. The cost of an agent task can be estimated using the following formula:

    Cost per task = Average iterations × (Input tokens per iteration × Input price + Output tokens per iteration × Output price)

    Since failed tasks also incur costs, the effective cost needs to be divided by the task pass rate:

    Effective cost = Cost per task ÷ Task pass rate

    For example, assume the input price is 0.002 currency units per 1K tokens, and the output price is 0.008 currency units per 1K tokens (these are sample numbers; please refer to the platform’s billing page for actual rates). A task runs an average of 5 iterations, with 20,000 input tokens and 2,000 output tokens per iteration. The cost per iteration is 0.056 currency units, and the cost per task is 0.28 currency units. If the task pass rate is 60%, the effective cost is approximately 0.47 currency units. This shows that the pass rate has a greater impact on the total cost than the unit price.

    When choosing an inference platform, check the following verifiable conditions rather than just looking at marketing claims:

    • Whether the requests per minute (RPM) limit and daily quota meet the needs of concurrent iterations.
    • Whether it throttles, queues, or charges on a pay-as-you-go basis when the quota is exhausted.
    • Whether it provides a Service Level Agreement (SLA) and compensation rules in case of failure.
    • Whether it supports exporting usage bills for cost accounting by task.

    When the quota is exhausted, downgrade processing in the following order:

    • Switch low-risk steps like parsing and summarization to a smaller model, reserving the large model for planning and fixing.
    • Write task states to disk and resume from the breakpoint when the quota recovers, avoiding rerunning all steps.
    • Set a daily budget and issue an alert when usage reaches 80%.
    • Use exponential backoff when retrying to prevent multiple tasks from retrying simultaneously and instantly maxing out the quota.

    Risk and Compliance Guidelines

    • Data security: Before financial data and contract text enter a third-party API, confirm the data processing agreement and log retention period. Sensitive fields such as ID numbers and account numbers must be desensitized first.
    • Cost out of control: Automated iteration loops must set iteration and budget limits and retain call logs.
    • Basis for model comparison: Record the model version, test date, and test conditions. Judgments of pros and cons without this information are not suitable for procurement decisions or external promotion.
    • Code quality: Generated code needs human review and unit testing. Logic involving fund calculations and permission checks should be reviewed with emphasis.

    Conclusion: When to Automate and When to Review

    Tasks with high repetition, testable via automated verification, and with low error costs can be handed over to agents for iterative execution. Content involving fund settlement, contract clause interpretation, or external commitments should retain a manual review process. Teams can first test a small task set to determine the pass rate and single-task cost before deciding the scope of automation.