Open-Source LLM Deployment Guide: From Model Selection to API Integration

    This guide covers how to choose an open-source LLM for a given workload, build minimum viable RAG and code-assistance use cases, prepare GPU and software dependencies, serve a model with vLLM, troubleshoot common deployment errors, and integrate the local API into production code with timeouts and retries.

    1. How to Choose an Open-Source LLM

    Before selecting a model, confirm whether three model characteristics match your task.

    1. Mixture of Experts (MoE)

    A Mixture of Experts architecture activates only part of its expert parameters during each inference pass. The compute per pass is lower than that of a dense model with the same total parameter count, so throughput and cost are often better. However, the weights of all experts still need to fit in GPU memory. Memory requirements do not scale down in proportion to the number of activated parameters. When estimating GPU memory, use the total parameter count, not the active parameter count.

    2. Long Context Window

    The maximum context length stated in a model card is only a theoretical upper bound. Longer contexts consume more GPU memory for the KV cache and increase time to first token. Test the model with your own long documents, and check recall of key information, GPU memory usage, and response time before deciding to rely on long context.

    3. Reasoning Capability

    Models trained with reinforcement learning often perform better on math and multi-step coding tasks, but their reasoning chains increase output token counts and response time. These models are suitable for complex problems, but not necessarily for high-frequency simple Q&A.

    The most reliable basis for model selection is your own evaluation set. Prepare 50 to 100 real business questions, record each candidate model’s accuracy, average latency, and cost per call, and then make a decision.

    2. Core Application Scenarios and Minimum Viable Approaches

    1. Knowledge Base and Customer Support

    Enterprise knowledge bases commonly use retrieval-augmented generation (RAG). A minimum viable workflow has six steps:

    1. Document splitting: Split documents by heading or fixed length, for example about 500 characters per chunk with 50 characters of overlap between adjacent chunks, to avoid cutting key sentences.
    2. Vectorization: Use an embedding model to convert each text chunk into a vector and write it to a vector database.
    3. Retrieval: Convert the user question into a vector and retrieve the top-k most similar text chunks.
    4. Re-ranking: Use a re-ranking model to score the candidate chunks and keep only the highest-scoring ones.
    5. Generation: Pass the question and the retained chunks to the LLM, and require the model to answer only based on the provided material.
    6. Citation validation: Check whether citation numbers in the answer correspond to real chunks. If the material contains no supporting evidence, the model should reply, “No relevant information was found in the provided materials.”

    2. Code Assistance and Developer Productivity

    Private deployment keeps source code on the enterprise internal network. The model can be used for code completion, unit test generation, code review, and natural language to code. Generated code must be reviewed by a human and must pass tests before it is merged into the main branch.

    3. Content Generation and First-Draft Assistance

    LLMs can generate copy, video script outlines, and multilingual drafts. Creators provide core points and an outline, the model produces a first draft, and humans then verify facts and wording. This approach shortens first-draft time, but fact-checking still requires human work.

    3. Pre-Deployment Checklist

    1. Environment Preparation and Dependency Configuration

    Before deployment, confirm three resources: GPU memory, driver and CUDA versions, and the Python environment.

    GPU memory estimation: Weight memory is approximately the parameter count multiplied by the number of bytes per parameter. FP16 uses 2 bytes per parameter, so a 32B model requires about 64 GB of GPU memory for weights. After INT4 quantization, each parameter uses about 0.5 bytes, so the same model requires about 16 GB for weights. You also need to reserve space for the KV cache and runtime overhead. Actual usage should be measured after the model is loaded.

    Driver and CUDA: Run nvidia-smi to view the highest CUDA version supported by the driver. The CUDA version used by the installed PyTorch must be compatible with the driver. Follow the official instructions for the inference framework when choosing installation commands; do not manually mix versions.

    1. nvidia-smi
    2. python3 -m venv llm-env
    3. source llm-env/bin/activate
    4. pip install vllm
    5. python -c "import torch; print(torch.cuda.is_available(), torch.version.cuda)"

    The second command creates a virtual environment to avoid dependency conflicts. The last command confirms that PyTorch can detect the GPU. The environment is usable only when the output is True.

    2. Model Weight Download and Verification

    Download weights from the official model repository and read the license first. Commercial terms vary significantly across models, so confirm the authorization scope before commercial use.

    After downloading, compute the file hash and compare it with the officially published value to confirm file integrity:

    1. sha256sum /models/your-model/model.safetensors

    If the hash does not match, download the file again. Do not load it directly.

    3. Inference Framework and Startup Command

    Common inference frameworks include vLLM, SGLang, llama.cpp, and Ollama. vLLM is suitable for multi-GPU service deployment, llama.cpp is suitable for environments with limited GPU memory or CPU-only environments, and Ollama is suitable for quick trials. The following example uses vLLM:

    1. vllm serve /models/your-model \
    2. --served-model-name your-local-model-name \
    3. --tensor-parallel-size 2 \
    4. --max-model-len 32768 \
    5. --gpu-memory-utilization 0.90 \
    6. --host 127.0.0.1 \
    7. --port 8000 \
    8. --api-key "$LLM_API_KEY"

    Parameter descriptions:

    • --tensor-parallel-size: The number of GPUs for tensor parallelism. It should equal the number of GPUs participating in inference. Set it to 1 for a single GPU. Multi-GPU parallelism expands available GPU memory, but inter-GPU communication adds overhead, so throughput may not scale linearly.
    • --max-model-len: The maximum context length allowed for a single request. This directly affects KV cache usage. If GPU memory is insufficient, lower this value first.
    • --gpu-memory-utilization: The proportion of GPU memory that the framework may use. Setting it too high may cause OOM; setting it too low wastes GPU memory.
    • --host 127.0.0.1: Listen only on the local address. If the service must be exposed externally, control access through a reverse proxy and gateway instead of opening the port directly.
    • --api-key: Read from an environment variable to avoid writing the key into command history or scripts.

    Some models require the --trust-remote-code parameter. Before enabling it, review the custom code in the model repository and confirm that nothing is abnormal before loading the model.

    After the service starts, use curl to check the model list:

    1. curl http://127.0.0.1:8000/v1/models -H "Authorization: Bearer $LLM_API_KEY"

    A JSON response containing the model name indicates that the service is available.

    4. Common Errors and Handling

    • CUDA out of memory: Lower --max-model-len or --gpu-memory-utilization, switch to a quantized version, or add more GPUs.
    • CUDA driver version is insufficient: The driver version is lower than what PyTorch or CUDA requires. Upgrade the driver, or install a version that matches the current driver.
    • Address already in use: The port is occupied. Run ss -ltnp | grep 8000 to find the process using it.
    • 401 Unauthorized: The Bearer key in the request header does not match the --api-key startup parameter.
    • Model loading fails with a trust_remote_code message: Add the parameter as described in the model card, and review the code first.
    • First response is very slow: Startup requires loading weights and warming up the computation graph. Measure latency after warmup for more accurate results.

    4. API Integration Example and Production Notes

    The following example shows how to call a locally deployed service from business code. It makes three adjustments: the key is read from an environment variable, the request body is sent with json=payload, and timeout and retry logic are included.

    1. import os
    2. import time
    3. import requests
    4. API_URL = os.getenv("LLM_API_URL", "http://127.0.0.1:8000/v1/chat/completions")
    5. API_KEY = os.getenv("LLM_API_KEY", "")
    6. MODEL_NAME = os.getenv("LLM_MODEL_NAME", "your-local-model-name")
    7. RETRY_STATUS = {429, 500, 502, 503, 504}
    8. def chat(messages, max_retries=3, timeout=(5, 60)):
    9. headers = {"Content-Type": "application/json"}
    10. if API_KEY:
    11. headers["Authorization"] = f"Bearer {API_KEY}"
    12. payload = {
    13. "model": MODEL_NAME,
    14. "messages": messages,
    15. "temperature": 0.7,
    16. "max_tokens": 1024,
    17. }
    18. for attempt in range(1, max_retries + 1):
    19. try:
    20. resp = requests.post(API_URL, headers=headers, json=payload, timeout=timeout)
    21. except requests.RequestException:
    22. if attempt == max_retries:
    23. raise
    24. time.sleep(2 ** attempt)
    25. continue
    26. if resp.status_code == 200:
    27. return resp.json()["choices"][0]["message"]["content"]
    28. if resp.status_code in RETRY_STATUS and attempt < max_retries:
    29. time.sleep(2 ** attempt)
    30. continue
    31. # Log only the status code, not the response body, to avoid leaking user data in logs
    32. raise RuntimeError(f"Request failed with status code: {resp.status_code}")
    33. raise RuntimeError("Retry limit exceeded")
    34. if __name__ == "__main__":
    35. answer = chat([
    36. {"role": "system", "content": "You are a professional technical documentation assistant."},
    37. {"role": "user", "content": "Summarize the deployment checklist in three bullet points."},
    38. ])
    39. print(answer)