Implementing Enterprise LLMs: From Scenario Selection to Risk Management

    This article explores the practical steps for deploying large language models (LLMs) in enterprise environments. It covers scenario prioritization, a layered architecture design, and risk control strategies for NL2SQL and RAG implementations. Additionally, it provides best practices for API calls, audit logging, compliance, and a pre-launch checklist to ensure secure and effective LLM adoption.

    I. Prioritize Scenarios Before Selecting Models

    Before deployment, filter scenarios using three questions: How high is the cost of errors? Does the data already exist and is it accessible? Can the results be quickly verified by humans? Based on these questions, the priorities are as follows.

    Scenario Cost of Errors Data Foundation Manual Verification Difficulty Recommendation
    Report Q&A (NL2SQL) Low to Medium Structured business databases Low, can be directly compared with source tables Priority
    Knowledge retrieval for decision support (RAG) Medium Internal documents, research reports Medium, requires referencing original text Second batch, conclusions confirmed by humans
    New media content production Medium Relies on topic selection and material licensing Medium, requires editorial review Define copyright and review processes first
    Agricultural pest and disease diagnosis High Images and field records often incomplete High, requires judgment by agricultural technicians Use as reference only

    Model selection should also align with the scenario. Teams can use their own test samples to compare accuracy, response time, cost per call, and whether data leaves the jurisdiction. Vendor-published numbers are for reference only and should not be the sole basis for selection.

    II. Layered Architecture Checklist

    The system is recommended to be split into the following seven layers, each with a single responsibility to facilitate model replacement and independent testing.

    • Access Layer: Handles authentication, request rate limiting, and input length limits.
    • Orchestration Layer: Manages prompt templates, schema injection, call timeouts, and retries.
    • Model Layer: Commercial or open-source models called via a unified gateway, allowing model switching without changing business code.
    • Retrieval Layer (for RAG): Vector database, metadata filtering, and document filtering by user permissions.
    • Execution and Protection Layer (for NL2SQL): SQL parsing, whitelist validation, read-only accounts, row count, and timeout limits.
    • Permissions and Audit Layer: Records user, query, generated SQL or retrieved snippets, model version, and error codes.
    • Evaluation Layer: Standard question sets, regression testing, and metrics dashboards.

    III. NL2SQL: Reducing Incorrect Queries with Multi-Layer Protection

    LLMs can convert questions like “Query the top 10 products by sales in the East region for the previous quarter” into SQL, enabling business personnel to retrieve data without writing code. However, models make mistakes, such as incorrect field mapping, missing time filters, or mapping “sales” to a tax-inclusive field.

    Relying solely on prompts cannot control these errors; multi-layer protection is required.

    1. Set a schema whitelist, only providing tables and fields allowed for querying to the model, along with field comments.
    2. Perform syntax parsing before execution. Only allow SELECT statements; reject DDL, DML, and multiple statements. The result row limit can be set to 1000, and query timeout to 30 seconds, adjusted according to report scale.
    3. Use a read-only database account and grant SELECT permissions to whitelisted tables at the database layer. Application code should not rely on its own permission checks, nor should it use superuser accounts.
    4. Sensitive fields like phone numbers and national ID numbers should be marked as forbidden for direct querying in the schema, or only return masked results.
    5. Spot-check results; high-impact reports published externally should be reviewed by data analysts.
    6. If the model cannot generate valid SQL or the result is empty, the system returns a prompt and transfers to manual processing without speculative completion.

    These measures only reduce the error rate but cannot eliminate it entirely. Teams need to build an evaluation set to measure performance.

    The calculation for execution accuracy is as follows: Execution accuracy = Number of questions where the generated SQL execution result matches the standard result ÷ Total number of questions. Standard results are manually written by data analysts using the same criteria.

    The evaluation set should ideally contain no fewer than 200 items. This is an empirical value, not an industry standard. Questions should cover main business reports and include error-prone questions, such as field ambiguity, time ranges, and tax-inclusive vs. tax-exclusive criteria. After every model change or prompt modification, run the full set again. When accuracy drops, rollback the configuration first, then investigate the cause.

    IV. RAG: Evaluating Retrieval and Answer Quality

    Retrieval-Augmented Generation (RAG) stores historical decision records, industry research reports, and other documents in a vector database. When a question is asked, the system first retrieves relevant snippets and then passes them to the model to generate an answer. The answer can reference relatively recent materials and trace back to the original text, but effectiveness depends on retrieval quality.

    During evaluation, focus on three metrics, calculated as follows.

    • Recall = Number of relevant snippets retrieved ÷ Total number of human-annotated relevant snippets, usually calculated for the top k results.
    • Faithfulness = Number of conclusions in the answer that can find support in the retrieved materials ÷ Total number of conclusions in the answer.
    • Citation Coverage = Number of key figures and judgments with sources ÷ Total number of key figures and judgments in the answer.

    Teams need to establish a baseline first. The baseline can be the time spent manually compiling intelligence, or the answer quality when asking directly without retrieval. Only by comparing on the same set of questions can it be demonstrated whether RAG improved efficiency or quality. This article does not provide specific improvement percentages, as results depend on data quality, document scale, and question types, and must be measured on your own data.

    Vector database selection can be compared using the following table.

    Comparison Dimension Questions to Confirm
    Data scale and query latency Under the target data volume, can P95 latency meet interactive needs?
    Metadata filtering Can it filter by department, date, and confidentiality level?
    Permission isolation Is data from different departments or customers logically or physically isolated?
    Persistence and backup Do backup frequency and recovery time meet requirements?
    O&M cost Self-hosted or managed? What are the labor and financial costs?
    Data location Does the storage location comply with data export regulations?

    Conclusion: If the data volume is not large and the team already has a relational database, start by using the database’s built-in vector extension. Evaluate a dedicated vector database when data volume and concurrency are high.

    V. API Call Example: Timeouts, Retries, and Key Management

    The following example demonstrates how to write timeouts, retries, and backoff. It is only for read-only generation requests. Write operations should not be retried directly to avoid duplicate execution.

    1. import os
    2. import random
    3. import time
    4. import httpx
    5. API_KEY = os.environ["LLM_API_KEY"] # Read from environment variables or key management service, not hardcoded in code
    6. API_URL = os.environ["LLM_API_URL"] # Model interface address, also injected via configuration
    7. TIMEOUT_S = 20 # Single request timeout (seconds)
    8. MAX_RETRIES = 3 # Max retry count, excluding the initial request
    9. BACKOFF_BASE_S = 1.0 # Exponential backoff base: 1s, 2s, 4s
    10. RETRYABLE_STATUS = {429, 500, 502, 503, 504}
    11. def call_llm(payload: dict) -> dict:
    12. headers = {"Authorization": f"Bearer {API_KEY}"}
    13. for attempt in range(MAX_RETRIES + 1):
    14. wait = BACKOFF_BASE_S * (2 ** attempt) + random.uniform(0, 0.5) # Add jitter to avoid simultaneous retries
    15. try:
    16. resp = httpx.post(API_URL, json=payload, headers=headers, timeout=TIMEOUT_S)
    17. if resp.status_code in RETRYABLE_STATUS and attempt < MAX_RETRIES:
    18. time.sleep(wait)
    19. continue
    20. resp.raise_for_status()
    21. return resp.json()
    22. except (httpx.TimeoutException, httpx.TransportError):
    23. if attempt == MAX_RETRIES:
    24. raise
    25. time.sleep(wait)
    26. raise RuntimeError("unreachable")

    Do not log request headers and full keys. Logging error codes and latency is sufficient.

    Key management essentials are as follows.

    • Store keys in environment variables or a cloud provider’s key management service. Do not hardcode them in code repositories or configuration files in plaintext.
    • Assign independent keys to each service and set usage limits to prevent a single service leak from affecting the entire system.
    • Rotate keys periodically based on security policies, e.g., every 90 days.
    • If a leak is suspected, immediately revoke the old key and check call logs.

    Audit logs should be able to trace every call. It is recommended to record request time, user ID, original question, generated SQL or retrieved snippet IDs, number of result rows, model version, latency, and error codes. Sensitive information like phone numbers and national ID numbers in logs must be masked before writing.

    Copyright and compliance essentials are as follows.

    • Only import authorized documents into the RAG knowledge base, and record the source, authorization scope, and validity period. Research reports usually restrict external forwarding and should not be provided wholesale to external users.
    • When answers cite original text, retain source annotations. Cited content should be limited to what is necessary to explain the viewpoint.
    • New media content production needs to record material sources. Editorial review is required before external publication; unverified figures and images should not be used directly.
    • Before cross-border data transmission, confirm relevant regulatory requirements. If data is sensitive, you can choose models deployed locally.

    VII. Pre-Launch Checklist

    • Scenarios have been prioritized by cost of errors and manual verification difficulty.
    • The evaluation set has at least 200 items, covering main reports, with standard answers provided manually.
    • SQL whitelist, read-only account, row count, and timeout limits have been configured at the database layer.
    • Sensitive fields have been masked or forbidden from direct querying.
    • Timeout, retry, and backoff parameters have been set, and keys are not present in the code.
    • Audit logs can trace back to users and model versions.
    • Full regression testing has been completed after every model or prompt change.
    • The authorization scope of knowledge base documents has been confirmed.

    VIII. Boundaries for Smart Agriculture and New Media

    Smart agriculture and new media content production are not prioritized as initial scenarios. An incorrect diagnosis in agricultural pest and disease identification can cause direct economic losses. Model output can only serve as a reference; final judgment must be made by agricultural technicians. New media content production requires clarifying topic review, material authorization, and publishing accountability before assessing efficiency gains.

    This article does not promise any specific accuracy or efficiency improvement percentages. Concrete numbers must be measured on the team’s own data and evaluation sets.