LLM Programming and Security Capabilities: Evolution and Engineering Implementation

    This article explores the evolution of large language model (LLM) capabilities in programming and security auditing, alongside their engineering implementation. It covers the shift from project-based delivery to API call monetization, the progression of programming tasks from single-file completion to cross-file refactoring, the role of LLMs in assisting security audits and threat modeling, and key considerations for commercialization, including API cost optimization, CI/CD integration, and risk management.

    1. From Project-Based to Pay-Per-Call

    The revenue structure of the LLM industry is shifting. Early delivery often relied on project-based models requiring extensive custom development, making it difficult to accumulate sustainable revenue. Today, open platforms, API calls, and subscription models are becoming the primary forms, directly linking revenue to usage volume.

    Industry reports and vendor financials can verify changes in revenue structure and call volume. This article does not cite specific growth rates, as the statistical periods, sample scopes, and calculation criteria for these data vary. To determine whether a “simultaneous increase in call volume and average price” stems from a capability premium, at least three factors must be confirmed: whether the statistical period is consistent, whether the sample covers the same group of users, and whether the price calculation applies to the same model version. Without this information, this phenomenon can only be viewed as a market observation, and one cannot directly deduce the causal conclusion that “improved model capabilities lead to revenue growth.”

    From a technical perspective, the appeal of the API call model lies in its ability to scale with user size. Enterprises shifting from one-time system purchases to pay-per-call typically means the model is integrated into R&D workflows, such as code review, test generation, or documentation generation. Consequently, call costs become ongoing operational expenses that require continuous management, rather than one-time investments.

    2. Frontier Programming Capabilities: From Completion to Engineering Collaboration

    The programming capabilities of LLMs have exceeded single-line completion. Under favorable conditions, models can read multiple files, understand the calling relationships between modules, and propose cross-file modification schemes. However, with greater capability comes harder-to-detect failures, making it essential to define the boundaries for each type of task.

    The table below compares three common task types:

    Task Type Typical Input Typical Output Common Failure Modes Human Intervention Points
    Single-file completion Current file and code near cursor Function or code snippet Ignoring existing utility functions in the project, reinventing the wheel Check naming, dependencies, and style
    Cross-file modification Multiple source files, interface definitions Multi-file patches Missing updates to callers, interface version mismatch Review diffs file by file, run tests
    Architecture-level refactoring Architecture docs, module dependency graphs, test suites Phased migration plan Unclear goals leading to over-refactoring Confirm scope first, then merge in batches

    2.1 Context Window Does Not Equal Correctness

    Expanding the context window allows the model to see more code simultaneously, but this does not guarantee correct results. The model might focus on the wrong aspects or treat irrelevant old code as current logic. In practice, stuffing an entire codebase into the context at once often increases costs and distracts the model. A more effective approach is to provide only the files, interface definitions, and error messages directly relevant to the task.

    2.2 Debugging and Code Review Example

    The code below demonstrates how to prompt a model to review code and return structured results. This is sample code; you must replace the API endpoint and model name, and adjust request fields according to your provider’s documentation.

    1. import os
    2. import json
    3. import requests
    4. API_URL = os.environ["LLM_API_URL"] # Service provider's API endpoint
    5. API_KEY = os.environ["LLM_API_KEY"] # Read from environment variables, do not hardcode
    6. MODEL = os.environ.get("LLM_MODEL", "your-model-name")
    7. TIMEOUT_SECONDS = 60
    8. def build_prompt(code_snippet: str, context: str) -> str:
    9. return (
    10. "You are a senior engineer. Please review the code below, focusing on security flaws and performance bottlenecks.\n"
    11. "Return only in JSON format, containing the field issues (a list, each item containing line, severity, description) "
    12. "and suggested_patch (the fixed code).\n\n"
    13. f"Project context:\n{context}\n\nCode snippet:\n{code_snippet}"
    14. )
    15. def call_llm(prompt: str) -> str:
    16. headers = {
    17. "Authorization": f"Bearer {API_KEY}",
    18. "Content-Type": "application/json",
    19. }
    20. payload = {
    21. "model": MODEL,
    22. "messages": [{"role": "user", "content": prompt}],
    23. "max_tokens": 2000,
    24. "temperature": 0,
    25. }
    26. resp = requests.post(API_URL, headers=headers, json=payload, timeout=TIMEOUT_SECONDS)
    27. resp.raise_for_status()
    28. return resp.json()["choices"][0]["message"]["content"]
    29. def parse_response(raw: str) -> dict:
    30. try:
    31. data = json.loads(raw)
    32. except json.JSONDecodeError:
    33. return {"ok": False, "error": "Model output is not valid JSON", "raw": raw}
    34. return {"ok": True, "data": data}
    35. def review_and_refactor(code_snippet: str, context: str) -> dict:
    36. try:
    37. raw = call_llm(build_prompt(code_snippet, context))
    38. except requests.RequestException as exc:
    39. return {"ok": False, "error": f"Call failed: {exc}"}
    40. result = parse_response(raw)
    41. result["needs_human_review"] = True # All outputs must go through human review
    42. return result

    When using this code, note the following points:

    • The example assumes the service is compatible with common chat completions APIs. Field names may differ across providers.
    • Setting temperature to 0 helps reproduce results but does not guarantee identical output every time.
    • All results include the needs_human_review flag. Review comments and patches must be read by humans and pass tests before merging.

    3. Network Security Capabilities: Assisting Audits, Requiring Verification

    The performance of LLMs in security audits is noteworthy, but there is no complete public explanation for the source of these capabilities. The model may have learned patterns from code and vulnerability-related texts during pre-training, but actual performance depends on the model version, prompt design, and toolchain. Therefore, this capability should be understood as auxiliary judgment rather than a reliable automated conclusion.

    3.1 Static Code Auditing

    Models can help identify injection, cross-site scripting (XSS), privilege bypass, and insecure deserialization. Based on the code’s data flow, it can prompt whether user input reaches dangerous functions before filtering. For logical vulnerabilities, the hit rate varies by project and language; this article does not provide specific false positive rates, as teams should measure these based on their own samples.

    The recommended audit process is as follows:

    1. Confirm the audit scope and obtain written authorization from the code owner.
    2. Have the model list suspected issues along with their data flow paths.
    3. Reproduce each suspected issue using manual review, static analysis, or dynamic testing tools.
    4. Record false positive cases and adjust prompts and rules accordingly.
    5. Enter confirmed vulnerabilities into fix tickets and track them with responsible owners.

    3.2 Threat Modeling

    Based on architecture diagrams and business process descriptions, the model can list attack surfaces and potential attack paths. However, it may also miss critical paths or fabricate non-existent components. Threat models must be reviewed by the security team and cannot be directly used as final conclusions.

    3.3 Adversarial Testing and Patch Generation

    Models can assist in generating input samples for fuzz testing and can also propose fix patches for confirmed vulnerabilities. Both tasks have clear risk boundaries:

    • Fuzz test samples can only be used in authorized test environments and with least-privilege test accounts.
    • Test data must be desensitized and must not contain real user information or production keys.
    • Patches generated by the model must not be deployed automatically; they must go through code review, regression testing, and security checks.
    • Fuzz test vectors must not be used on unauthorized systems, including third-party services and others’ infrastructure.

    4. Commercialization Implementation: Cost, Integration, and Risk

    When utilizing LLM capabilities, enterprises typically face issues concerning cost, integration, and compliance. The key points below are organized by “Challenge, Approach, Metric, Risk.”

    4.1 How to Optimize LLM API Costs

    Challenge Approach Metric Risk
    High call volume, high unit price Tier by task: use small models for completion, frontier models for cross-file refactoring and deep audits Call proportion per task tier Small model quality insufficient, requires fallback
    Repeated requests Cache requests for identical code and prompts Cache hit rate, target value set by team based on historical data Cache expires or code changed, still returning old results
    Single input too long Set input length limits, split tasks if exceeded Average input token count, percentage of over-limit requests Splitting loses cross-file relationships
    Unstable model selection Dynamic routing based on task type and token count Routing accuracy, average cost per task Outdated routing rules, leading to quality degradation
    Unpredictable costs Establish cost estimation formulas, reconcile monthly Deviation between monthly cost and budget Inconsistent calculation criteria, distorted results
    Unstable service Set timeout, retry, and fallback strategies Failure rate, average response time Fallback model output quality drops, source needs labeling

    Cost estimation can use the following formula:

    Monthly Cost = Σ (Monthly call count per task × (Input token count × Input unit price + Output token count × Output unit price))

    Call volume, average unit price, and failure rate should be checked monthly, and alert thresholds set for the budget.

    4.2 Integrating Security Audits into CI/CD

    Embedding audits into the R&D pipeline helps normalize security checks. Consider the following points during integration:

    • Trigger conditions: Trigger security audits when a merge request is created or updated; generate test suggestions during main branch builds.
    • Result presentation: Model conclusions are attached as comments in code reviews and do not block merges by default. Blocking is only set when team-confirmed rules are triggered.
    • Data scope: Only send code snippets related to changes; clear keys, tokens, and personal information before sending.
    • Access control: The audit service uses read-only repository permissions and cannot push code directly.
    • Log retention: Record input summaries, output results, and manual processing conclusions for each call for traceability and improvement.

    4.3 What Are the Common Mistakes

    In practice, the following types of mistakes are common:

    1. Treating model conclusions as facts without reproduction and verification.
    2. Submitting the entire codebase at once, resulting in high costs and scattered results.
    3. Ignoring model version differences, continuing to use old prompts and thresholds after switching versions.
    4. Allowing patches generated by the model to directly enter the main branch.
    5. Sending audit results to unauthorized third-party environments, causing data breaches.

    5. Conclusion

    Under controlled conditions, LLMs can serve as auxiliary components to shorten the time required for certain programming and auditing tasks. Their output requires testing, review, and authorization constraints, and cannot replace the judgment of responsible parties. Developers can start with pilot tests in low-risk areas, recording call costs, false positive rates, and manual correction counts, and then decide whether to expand the scope of use based on this data.