A Practical Guide to Long-Context Processing and Multi-Agent Collaboration with Open-Source LLMs
This guide explores practical engineering approaches for utilizing open-source large language models (LLMs) in long-context processing, multi-agent collaboration, and single-agent code generation. It covers testing effective context windows, designing robust multi-agent systems, evaluating code generation iteratively, setting security boundaries, and assessing key risks during model selection.
Scope Clarification
This article does not specify particular model names or versions; rather, it discusses the general capabilities and engineering practices for a class of open-source large language models (LLMs). All capability assessments mentioned here should be retested on your own tasks and data, as a single demonstration is insufficient for model selection.
1. Long-Context Processing: Test Effective Context Before Deciding Workflows
The context length claimed by a model does not equate to its ability to reliably locate critical information within long documents. A common issue with long-context processing is the “lost in the middle” phenomenon, where facts located in the middle of a document are more likely to be missed or answered incorrectly.
It is recommended to validate this using a “needle test”: embed several verifiable facts at different positions within a long document—such as a specific contract clause number or a financial figure—and then ask questions about them, recording the hit rate for each position. If the hit rate in the middle is significantly lower than at the beginning and end, you should incorporate retrieval or segmented verification into your workflow.
When processing long PDFs like financial reports, there are two common approaches. The first is to feed the entire PDF to the model for end-to-end processing. This is a simple workflow, but issues like cross-page tables and poor scanned document recognition will directly impact the results. The second approach is to first use parsing tools to extract text and tables before passing them to the model. The second workflow is more prevalent and allows each step to be inspected individually. Regardless of the approach, key fields—such as revenue, net profit, and year-over-year growth—should be manually sampled and verified.
During acceptance testing, you can track three metrics: extraction accuracy of key fields, the number of manual corrections, and the processing time per document.
2. Multi-Agent Collaboration: Ideal for Parallel and Verifiable Subtasks
A multi-agent architecture is suitable for scenarios where subtasks are independent, can be executed in parallel, and have results that can be verified item by item. For example, monitoring announcements from multiple companies simultaneously, with each agent responsible for one company and a master agent aggregating the results. If tasks have strong sequential dependencies—for instance, if a subsequent step requires the complete conclusion of the previous one—a multi-agent setup usually just adds scheduling overhead.
When designing a multi-agent system, it is recommended to clarify four things:
- The responsibility boundaries of each role to prevent two agents from doing the same work.
- The input and output formats for each agent; using a fixed JSON structure is ideal for easy verification by the master agent.
- Timeout and retry limits, such as a maximum of two retries per subtask.
- Failure handling strategies, such as degrading to sequential single-agent execution or escalating to a human.
Regarding speed, do not assume that “parallel is always faster.” It is recommended to conduct a baseline comparison: execute the same batch of tasks sequentially with a single agent and in parallel with multiple agents, recording the end-to-end time, failure rate, and number of manual corrections. Only introduce the complexity of multi-agent systems if your tests show a clear benefit.
3. Single-Agent Execution: Evaluating Code Capabilities with Reproducible Methods
The focus of code generation evaluation should be on whether the model can “safely iterate on existing code,” not just whether it can generate complete code in one go. Taking a financial data monitoring web application as an example, you can break down the requirements into several independent tasks and submit them to the model in rounds, rather than requesting everything at once.
Here is a prompt example for a single-round task:
You are a frontend engineer. Please implement a financial data monitoring page in the existing project with the following requirements:1. Display a line chart of the closing prices for the last 30 trading days.2. Display a notification bar at the top of the page when data is updated.3. Only modify the src/components/ directory and do not alter the API files.After completion, list the modified files and provide the result of running npm test.
Each round of tasks should be accompanied by acceptance criteria, for example:
| Feature | Test Method | Pass Criteria |
|---|---|---|
| Line chart rendering | Render using fixed test data | Data point count matches input |
| Update notification | Simulate data refresh | Notification bar appears and disappears after a specified time |
| No API changes | Compare git diff | No changes outside the specified directory |
After each round, record the list of modified files, test results, and failure cases. These records will help you determine whether the model is iterating stably or introducing new side effects.
Regarding resource consumption, the cost of different solutions depends on the billing method—it may be token-based, subscription-based, or reliant on local compute. It is recommended to record the token count or time taken per task and calculate using your own bills, rather than directly citing percentages provided by others.
4. Engineering Practices: Task Decomposition, Division of Labor, and Security Boundaries
1. Task Decomposition Checklist
Before handing a task to an agent, check the following items:
- Are the inputs clear, including data sources, file formats, and field meanings?
- Is the output format defined, such as JSON fields or table column names?
- Are the acceptance criteria executable? Can tests or scripts determine pass or fail?
- Can the subtask be verified independently without relying on implicit assumptions from other subtasks?
- How will failures be handled, including retry counts and conditions for human intervention?
Instructions like “analyze this financial report” are difficult to verify. By breaking it down into three subtasks—“extract income statement data,” “calculate year-over-year growth,” and “summarize risk warnings”—each step can be verified individually.
2. Semantics to Model, Numbers to Program
Models excel at understanding document semantics, summarizing textual information, and making logical judgments. Precise calculations—such as summations, year-over-year comparisons, and ratios—should be handled by deterministic programs, such as database queries or data analysis libraries. Numbers output by the model need to be compared with program results; if there is a discrepancy, the program result should be considered authoritative and flagged for manual review.
3. Boundary Settings and Manual Confirmation
Agents may erroneously execute risky operations during long-chain tasks. It is recommended to set limits in both the system prompt and the execution environment. Operations that should refuse automatic execution and require manual confirmation include:
- Modifying core system configuration files
- Reading or outputting sensitive credentials like keys and tokens
- Deleting data or overwriting existing files
- Sending external emails, messages, or publishing content
- Modifying user permissions
A viable confirmation process is: The agent generates pending operations and writes them to a review list; they are executed only after manual approval, and the execution results are written to an audit log. The audit log should record the timestamp, initiator, input, output, approver, and execution result.
5. Risks to Consider During Model Selection
- License: The license of an open-source model may restrict commercial use, redistribution, or modification. Please refer to the official license text and have it confirmed by legal counsel.
- Data Compliance: If data needs to be uploaded to a third-party service, first assess whether data leaves your jurisdiction and whether the service provider uses the data for training. Sensitive information and financial data should be anonymized before processing.
- Deployment Costs: Local deployment requires considering GPUs, storage, and operational personnel; cloud deployment requires considering inference costs and concurrency limits.
- Hallucination Risks: Models may generate plausible but incorrect numbers or conclusions. Critical data, as well as legal and financial judgments, must be manually reviewed.
FAQ
Can open-source LLMs replace commercial models?
It depends on the specific task. Compare both on your own test set regarding accuracy, time, and cost before deciding on a replacement.
Is multi-agent always faster than single-agent?
Not necessarily. Parallelism can reduce wait times, but task scheduling, context passing, and retries add overhead. Please verify with baseline testing.
What are common mistakes when using them?
- Evaluating model capabilities based on a single demo example.
- Not setting a retry limit, causing tasks to loop indefinitely.
- Letting the model perform precise calculations directly without program verification.
- Writing sensitive credentials like API keys into prompts.
- Not recording changes in each iteration, making it impossible to trace back when issues arise.
Conclusion
Selection conclusions should come from your own test results. First, define tasks and acceptance criteria, then compare model performance using small samples, and finally gradually expand the scope of use while retaining manual review and audit logs.
