Open-Source LLMs: Closing the Gap and Building a Terminal Agent

    This article explains how to verify benchmark claims about open-source LLMs, reviews the technical routes used in the anti-distillation era, and describes the core loop of a terminal agent. It includes a Python example that generates code, executes it, and corrects it with real execution feedback, followed by guidance on deployment and model selection.

    1. Verify Benchmark Data Before Discussing the Gap

    There is a lot of discussion about open-source LLMs catching up with closed-source models, but many articles only provide rankings and scores. Before citing those numbers, readers should confirm four things: which evaluation organization produced the data, the name of the leaderboard, the test date, and how the score was calculated.

    The same model can rank very differently across leaderboards. Some leaderboards combine multiple tasks, some test only code, some allow models to call tools, and some do not. A difference of a few points may simply come from different prompts or tool configurations. Therefore, a statement such as “the gap has narrowed to a few points” is meaningful only when both sides are compared under the same settings.

    For predictive claims, such as “is expected to enter the top ranks of a certain leaderboard,” the source and publication date of the prediction should be noted. A prediction is not a result, and readers should not treat it as an established fact.

    If you plan to use a model in your own project, the most reliable approach is to re-evaluate it on your own task set. You can collect dozens of tasks from real work scenarios and record the pass rate, average number of correction rounds, and cost per run for each task. These data points are more useful than public leaderboards for determining whether a model fits your use case.

    2. Technical Routes for Open-Source Models in the Anti-Distillation Era

    Distillation refers to training a smaller model on data generated by a stronger model. In the past, many open-source models relied on this approach to improve quickly. When closed-source providers restrict bulk scraping of outputs and strengthen reviews of usage terms, training pipelines that depend on distillation become constrained, and model capability improvements may slow down.

    Facing this limitation, open-source teams have focused on three main directions.

    The first is multi-source construction of synthetic data. Teams no longer rely only on answers from another model. They use rules to generate questions and use programs to check whether answers are correct, for example by compiling code, running unit tests, or validating mathematical expressions. Multiple models can also cross-check each other to filter out clearly incorrect samples.

    The second is the application of reinforcement learning. Reinforcement learning from human feedback (RLHF) and reinforcement learning from AI feedback (RLAIF) can provide clearer reward signals for reasoning and code tasks. The more granular the reward model, the easier it is for the model to learn whether each reasoning step is correct, rather than only whether the final wording looks acceptable.

    The third is improvement in architecture and inference efficiency. Methods such as sparse attention and more efficient long-context processing can reduce memory usage and speed up inference on tasks involving large codebases.

    It is important to note that “not relying on distillation” does not mean “fully autonomous.” Open-source models still use public web pages, open-source code, human annotations, and other data, and training details vary by model. To determine a model’s data sources, rely on the official model card and technical report rather than media summaries.

    3. The Basic Loop of a Terminal Agent

    A terminal agent is a program that can understand a natural language task, break it into commands or code, execute them in a controlled environment, read the results, and adjust based on those results. Its core strength is not producing a perfect answer in one shot, but being able to correct itself based on execution feedback.

    A minimal usable agent usually contains four steps: generate code, execute code, observe output, and correct code. The model itself cannot determine whether code will actually run, so it must rely on execution results. Therefore, the quality of the execution environment and error feedback directly determines the agent’s effectiveness.

    This loop also has clear boundaries. A model may still fail after multiple correction rounds, may get stuck in repeated modifications, or may generate dangerous commands. The loop must therefore set a maximum number of rounds and restrict permissions before execution.

    4. Code Example: Generate-and-Correct Loop with Real Execution Feedback

    The example below demonstrates a minimal loop. It calls an open-source model service compatible with the OpenAI API format, asks the model to generate a Python script, runs the script in a temporary directory, and passes real error messages back to the model for correction. The sample log in the example is generated by the program, and the script output is also checked; it passes only when the expected IP address is present.

    Before use, set the environment variable LLM_API_KEY. Do not hardcode API keys in code or commit them to version control.

    1. import os
    2. import re
    3. import subprocess
    4. import tempfile
    5. import time
    6. import requests
    7. API_URL = os.environ.get("LLM_API_URL", "https://api.example.com/v1/chat/completions")
    8. API_KEY = os.environ.get("LLM_API_KEY")
    9. MODEL_NAME = os.environ.get("LLM_MODEL", "your-open-source-model")
    10. MAX_ROUNDS = 3
    11. RUN_TIMEOUT = 10
    12. MAX_LOG_CHARS = 2000
    13. EXPECTED_TEXT = "192.168.1.10"
    14. SAMPLE_LOG = (
    15. "2026-11-24 10:00:01 login from 192.168.1.10\n"
    16. "2026-11-24 10:02:33 request from 10.0.0.5\n"
    17. )
    18. SYSTEM_PROMPT = (
    19. "You are a senior software engineer agent. "
    20. "Output only one complete Python code block, with no explanation. "
    21. "If the user provides error information, analyze the cause and output the corrected complete code."
    22. )
    23. def call_model(messages, retries=3):
    24. if not API_KEY:
    25. raise RuntimeError("LLM_API_KEY environment variable is not set")
    26. headers = {"Content-Type": "application/json", "Authorization": f"Bearer {API_KEY}"}
    27. payload = {"model": MODEL_NAME, "messages": messages, "temperature": 0.2, "max_tokens": 1024}
    28. for attempt in range(1, retries + 1):
    29. try:
    30. resp = requests.post(API_URL, headers=headers, json=payload, timeout=60)
    31. except requests.RequestException:
    32. if attempt == retries:
    33. raise
    34. time.sleep(2 ** attempt)
    35. continue
    36. if resp.status_code == 200:
    37. return resp.json()["choices"][0]["message"]["content"]
    38. if resp.status_code in (429, 500, 502, 503) and attempt < retries:
    39. time.sleep(2 ** attempt)
    40. continue
    41. raise RuntimeError(f"API request failed: HTTP {resp.status_code}")
    42. def extract_code(text):
    43. match = re.search(r"```(?:python)?\n(.*?)```", text, re.S)
    44. return match.group(1) if match else text
    45. def run_code(code):
    46. """Run generated code in a temporary directory and return (passed, log)."""
    47. with tempfile.TemporaryDirectory() as workdir:
    48. with open(os.path.join(workdir, "sample.log"), "w", encoding="utf-8") as f:
    49. f.write(SAMPLE_LOG)
    50. script_path = os.path.join(workdir, "task.py")
    51. with open(script_path, "w", encoding="utf-8") as f:
    52. f.write(code)
    53. try:
    54. proc = subprocess.run(
    55. ["python3", script_path],
    56. cwd=workdir,
    57. capture_output=True,
    58. text=True,
    59. timeout=RUN_TIMEOUT,
    60. )
    61. except subprocess.TimeoutExpired:
    62. return False, "Execution timed out"
    63. log = (proc.stdout + proc.stderr)[-MAX_LOG_CHARS:]
    64. passed = proc.returncode == 0 and EXPECTED_TEXT in proc.stdout
    65. return passed, log
    66. def agent_workflow(task):
    67. messages = [
    68. {"role": "system", "content": SYSTEM_PROMPT},
    69. {"role": "user", "content": task},
    70. ]
    71. for round_no in range(1, MAX_ROUNDS + 1):
    72. reply = call_model(messages)
    73. code = extract_code(reply)
    74. passed, log = run_code(code)
    75. print(f"Round {round_no}: {'passed' if passed else 'failed'}")
    76. if passed:
    77. return code, log
    78. messages.append({"role": "assistant", "content": reply})
    79. messages.append({
    80. "role": "user",
    81. "content": f"Code execution failed. Output:\n{log}\nPlease fix it and output the complete code.",
    82. })
    83. raise RuntimeError(f"Execution did not pass after {MAX_ROUNDS} rounds")
    84. if __name__ == "__main__":
    85. final_code, output = agent_workflow(
    86. "Write a Python script that reads sample.log in the current directory, extracts all IP addresses, and prints them line by line."
    87. )
    88. print("Final code:\n", final_code)
    89. print("Run output:\n", output)

    Several design choices in this code are worth noting. The API key is read from an environment variable, and logs output only execution results without printing request headers. Network requests have timeouts and retry only temporary errors. Execution success is determined by both the exit code and the expected output, rather than only by whether the model returned text. The number of correction rounds is capped to avoid unlimited loops and cost consumption.

    However, the example still runs model-generated code directly on the host machine, which is unacceptable in production. In a real deployment, the execution step should be placed in a disposable container, with networking disabled, a non-root user, limits on CPU, memory, and runtime, and only necessary directories mounted.

    5. Deployment and Model Selection

    Parameter count determines the lower bound of weight memory usage. As a rough estimate, weight memory is approximately the parameter count multiplied by the number of bytes per parameter: about 2 bytes for FP16, 1 byte for INT8, and 0.5 bytes for INT4. For a 70B-parameter model, FP16 weights require about 140 GB, while INT4 quantization reduces this to about 35 GB. Additional space is also needed for KV cache, activations, and the runtime framework, so actual usage is usually higher.

    Quantization can reduce costs, but it may affect code generation and reasoning quality. Use your own task set to compare pass rates before and after quantization.

    Self-hosting and cloud APIs each have suitable scenarios. Self-hosting is appropriate for teams with compliance requirements, high call volumes, and the ability to handle operations. Cloud APIs are suitable for rapid validation and scenarios with fluctuating call volumes. When comparing the two, calculate operational labor, idle GPU costs, and per-call pricing together.

    Components such as logs, object storage, monitoring, and alerting can be connected through standard HTTP interfaces or function calling. Before integration, clarify the parameter format and permission scope of each tool.

    Agents should be granted capabilities according to the principle of least privilege. Operations such as deleting data, publishing deployments, and changing permissions should require human confirmation. Every command and output should be recorded for auditing and traceability.

    Common mistakes include: adopting leaderboard rankings directly without validating on your own tasks; failing to set timeouts and retries, so the entire workflow stalls when rate limits occur; writing API keys into code or logs; tracking only the final pass rate without measuring correction rounds and cost; and failing to run regression tests after a model upgrade, causing existing workflows to fail silently.

    6. Conclusion

    Open-source models have come close to leading closed-source models on some public evaluations, but the exact size of the gap depends on the leaderboard, tasks, and test settings. It cannot be judged from a single number. For developers, the more important step is to validate models on their own task sets and add execution feedback, permission restrictions, and human confirmation to agents. Only then can the cost advantages of open-source models translate into reliable engineering gains.