Deploying Code LLMs on Your Enterprise Intranet: A Practical Plan for AI-Assisted Programming
This article explains how to deploy a code large language model on an enterprise intranet to support AI-assisted programming. It covers how to define requirements, a reference architecture, GPU memory planning, inference service design, concurrency estimation, data security controls, evaluation methods, and a phased rollout plan.
1. Why Local Deployment Matters for AI-Assisted Programming
AI-assisted programming has moved from individual tools to team infrastructure. Code completion, unit test generation, defect localization, and code review suggestions all depend on large language model (LLM) inference. The way a model is called determines where code and context flow, so it directly affects a company’s intellectual property and compliance boundaries.
Connecting to a cloud API is simple, but enterprises often face three problems. First, source code and business context must leave the internal network, which security teams often find unacceptable. Second, the API is billed per call, so costs become hard to predict as the engineering organization grows. Third, network fluctuations and service rate limits interrupt developers’ focus and degrade the experience.
Local deployment runs model inference on the company’s own compute, so code data stays inside the internal network. It provides data control and predictable costs. The trade-off is that the company must handle hardware procurement, operations, and model updates itself. Whether to adopt this approach depends on the balance among engineering scale, security level, and operations capability.
2. Defining Requirements and Constraints
Before choosing a solution, the team should turn requirements into measurable metrics rather than decide based on intuition. Common constraints fall into the following categories.
- Data boundaries: Which code may be sent to the model, and which core modules are prohibited from leaving the company.
- Response latency: Code completion typically requires a time to first token in the range of a few hundred milliseconds, while long-form generation, such as suggestions for a full refactor, can tolerate several seconds to several tens of seconds.
- Concurrency: How many developers will send requests at the same time, and how many times higher the peak request volume is than the average.
- Context length: How large a code context window must be supported. Longer context increases memory and compute overhead.
- Availability: The target uptime for the inference service, and whether a fallback plan exists during failures, such as switching to a smaller model or falling back to local static analysis.
After listing these constraints in a table, the team can check each candidate solution against them item by item, instead of debating the architecture repeatedly.
3. Reference Architecture
A typical local coding assistant system can be divided into the following layers:
Developer IDE plugin│▼API gateway (authentication, rate limiting, audit logging)│▼Inference service cluster (batch scheduling, model loading, streaming output)│├── Model weight storage├── Code retrieval index (repository-level context recall)└── Monitoring and alerting (latency, queue length, accelerator memory usage)
Each layer needs clearly defined responsibilities. The IDE plugin only collects context and displays results, and it does not store long-term credentials. The gateway handles identity verification, applies rate limits by team or project, and records request metadata. The inference service focuses on model computation and exposes a unified internal interface. The code retrieval layer recalls relevant file fragments and adds them to the prompt. This step often has a greater effect on final answer quality than the model itself.
4. Hardware and Memory Planning
Hardware planning for the inference service starts with memory. Both the model weights and the intermediate cache used during inference must reside in accelerator memory (VRAM). If memory is insufficient, the model cannot load, or it runs only through frequent swapping, which slows performance sharply.
4.1 Estimating Weight Memory
You can roughly estimate the memory needed for weights with the following formula:
Weight memory ≈ number of parameters × bytes per parameter
For a model with 70 billion parameters:
- Half precision (2 bytes per parameter): about 140 GB
- 4-bit quantization (about 0.5 bytes per parameter): about 35 GB
Quantization significantly reduces memory requirements but causes some loss in quality. Teams should compare results at different precisions on their own code task sets, rather than relying only on the theoretical compression ratio.
4.2 Estimating KV Cache Memory
During generation, the model caches key and value vectors for each processed token. The size of the KV cache is proportional to the context length and the concurrent batch size:
KV cache ≈ 2 × number of layers × number of KV heads × head dimension × context length × batch size × bytes per element
This means that long context and high concurrency both consume memory. When planning, calculate peak usage as target context length × target concurrency, and keep a safety margin. Do not select hardware based on weight size alone.
4.3 Multi-GPU and Parallelism
When a model does not fit on a single card, you need tensor parallelism or pipeline parallelism. Parallelism introduces communication overhead between cards, and the more cards you use, the larger the share of time spent on communication. For short requests such as code completion, horizontal scaling with model replicas is usually more efficient than splitting a single model across cards. A team can first validate the workflow with a single card and a small model, then scale up gradually as the load grows.
5. Key Implementation Points for the Inference Service
5.1 Batching and Scheduling
The throughput of an inference service depends heavily on its batching strategy. Continuous batching lets new requests join the computation queue before earlier requests finish, which can substantially improve accelerator utilization. Combined with a priority queue, latency-sensitive requests such as code completion can be processed first, while long-form generation waits behind them.
5.2 Streaming Output
In programming scenarios, developers want to see the first token as early as possible. The server should support streaming responses, so the client can render output as it arrives. Streaming does not reduce the total amount of computation, but it noticeably reduces the wait time developers perceive.
5.3 Client Example
The following code shows a general-purpose client for an internal inference service. The endpoint, key, and timeout are injected through environment variables to avoid hardcoding. Adjust the response field names to match the API documentation of your actual service.
import osimport timeimport requestsENDPOINT = os.environ["LLM_ENDPOINT"] # Internal inference service endpointAPI_KEY = os.environ.get("LLM_API_KEY", "") # Injected by the secrets management systemTIMEOUT_S = float(os.environ.get("LLM_TIMEOUT_S", "30"))def request_completion(prompt: str, max_tokens: int = 512) -> str:"""Submit a completion request to the internal inference service and return the generated text."""headers = {"Authorization": f"Bearer {API_KEY}","Content-Type": "application/json",}payload = {"prompt": prompt,"max_tokens": max_tokens,"temperature": 0.2, # Code tasks favor low randomness}start = time.monotonic()try:resp = requests.post(ENDPOINT, json=payload, headers=headers, timeout=TIMEOUT_S)resp.raise_for_status()except requests.RequestException as exc:raise RuntimeError(f"Inference request failed: {exc}") from exclatency = time.monotonic() - startprint(f"request latency: {latency:.2f}s")return resp.json()["text"]
The client must handle timeouts and retries. Retries should have a maximum count and use backoff delays, so that a overloaded inference service is not overwhelmed by a flood of retry requests.
6. Estimating Concurrent Capacity
Concurrent capacity determines whether the solution can support the team. Many teams use the number of registered developers as the basis for capacity, but this is not accurate. What you need to estimate is the number of requests being processed at the same moment.
You can use Little’s Law from queueing theory:
Average number of concurrent requests = request arrival rate × average service time per request
Suppose a team submits 120 requests per minute during peak hours, and each request takes an average of 20 seconds to generate. The average number of concurrent requests is:
120 ÷ 60 × 20 = 40
This number determines how many instances or batch slots the service needs to process requests at the same time. In actual planning, add the following adjustments:
- Peak factor: Peak traffic may be 2 to 3 times the average, so capacity should be calculated for peak load.
- Long-tail requests: A small number of very long generations occupy resources for a long time. Set a maximum generation length and apply separate rate limits to them.
- Failover headroom: If one node fails, the remaining nodes must absorb its traffic, so capacity should include redundancy.
Teams should replace these assumed values with real request logs. Without historical data in the early stage, run a small pilot to collect data before setting the production capacity.
7. Data Security and Compliance Controls
Local deployment does not automatically guarantee security. It moves the risk boundary inside the company. The following controls should be put in place at the same time.
- Minimize context: The plugin sends only the code fragments relevant to the current task and never uploads the entire repository.
- Log redaction: Audit logs store request metadata and latency, and automatically filter secrets, personal information, and sensitive identifiers from prompts.
- Access isolation: Access permissions are divided by project, so that certain repositories can be accessed only by requests from specific teams.
- Key management: Inference service credentials are distributed by a central secrets management system and rotated regularly. They are never stored in code repositories or configuration files.
- Model source review: Confirm that the license of each model permits internal use and modification, and record the model version and checksum for traceability.
- Output review: Generated code must go through standard code review and security scanning. Model output must never be merged directly into the main branch.
8. Evaluation Methods
Before launch, establish an evaluation framework and use data to determine whether the solution works. Measure the results at three levels.
Quality metrics: On an internal code task set, measure the compilation pass rate, the unit test pass rate, and human ratings. The task set should cover the languages, frameworks, and coding standards the team actually uses.
Experience metrics: Track time to first token, full response latency (P95 and P99), and the request failure rate. Analyze experience metrics separately by time period and request type.
Adoption metrics: Track the percentage of completion suggestions that developers accept, the percentage kept after editing, and the number of times assistant suggestions were rolled back. The adoption rate reflects the practical value of model output.
The following is a simplified approach for offline evaluation:
def evaluate(cases, generate, run_tests):"""Run generation on an offline task set and compute the test pass rate."""passed = 0for case in cases:code = generate(case["prompt"])if run_tests(code, case["tests"]):passed += 1return passed / len(cases) if cases else 0.0
Update the evaluation set regularly, and keep a holdout set that is never used for tuning. This prevents the metrics from becoming overfitted.
9. Rollout Plan and Common Risks
We recommend a four-phase rollout.
- Pilot phase: Select one or two code repositories and a small group of developers. Use a small-scale model to validate the integration workflow and data boundaries.
- Benchmark phase: Build an offline evaluation set and compare candidate models and quantization schemes to find the right balance between accuracy and speed.
- Scaling phase: Calculate concurrent capacity from real request logs, and complete gateway rate limiting, monitoring and alerting, and fallback strategies.
- Rollout phase: Open access to teams gradually, collect feedback, and keep updating the model and retrieval strategy.
Common risks include the following. First, hardware procurement can take a long time, and delayed capacity planning leads to queuing. Second, frequent model version updates can degrade output quality without notice if no regression evaluation is in place. Third, operations staff may be unfamiliar with the inference service, which slows recovery during failures. Teams should schedule training in advance and bring the inference service into their existing operations processes.
10. Key Decision Points
Local AI-assisted programming suits teams with strict code security requirements, large engineering organizations, and basic infrastructure operations capability. If a team is small and has lower security requirements, using a compliant cloud service directly may be more economical. The decision should rest on concrete values for four dimensions: data boundaries, latency targets, concurrency scale, and total cost of ownership. It should not rest on a general preference for one approach.
