Implementing Knowledge QA and Spreadsheet Automation with Locally Deployed LLMs
Deploying a large language model locally is only the first step toward building practical AI applications. This article explores how to transition from basic model inference to production-ready business applications, focusing on knowledge question-answering (QA) and spreadsheet automation. It covers architectural best practices, separating inference from business logic, integrating spreadsheets safely, handling batch processing, ensuring data security, and validating outputs before execution. By following a phased implementation approach, developers can build reliable, auditable, and secure local LLM applications.
1. Local Deployment is Just the Starting Point
Successfully deploying a local LLM usually means the model files are loaded, and the inference service can receive inputs and return text. However, there is still a significant gap between this and “stably handling business tasks.”
For example, the model can explain a piece of text but may not understand internal corporate reimbursement policies; it can generate analytical opinions but may not know the currency unit in the current spreadsheet; it can offer operational suggestions but cannot autonomously gain permissions to modify business data.
Therefore, after local deployment, the focus should shift from “how to start the model” to three more practical questions:
- What data can the model access?
- Through what entry points does the model participate in the workflow?
- How are output results validated, logged, and securely used?
By addressing these three questions, you can gradually build knowledge QA, document processing, spreadsheet-assisted analysis, and controlled process automation, rather than stopping at a simple chat window.
2. Tasks Suitable for Local LLMs
2.1 Enterprise Internal Knowledge QA
After organizing policy documents, operation manuals, project materials, and FAQs into a knowledge base, the system can first retrieve relevant snippets and then let the model answer questions based on the retrieval results. This approach is commonly known as Retrieval-Augmented Generation (RAG).
It does not involve “training all files into the model,” but rather supplements the model with context relevant to the question during each query. The advantage is that when documents are updated, the knowledge source can be refreshed by re-parsing and re-indexing, without needing to retrain the model each time.
However, retrieving materials does not guarantee a correct answer. The system must still display citation sources, explicitly state when information is insufficient for unsupported questions, and avoid mixing different versions of policies.
2.2 Text Processing in Spreadsheets
Spreadsheets contain not only numerical values but also frequently store customer feedback, item descriptions, product details, and ticket records. The model is well-suited to handle the unstructured text within them, for example:
- Compressing lengthy remarks into brief summaries;
- Tagging issue types according to a predefined classification system;
- Extracting dates, locations, items, and responsible persons from descriptions;
- Generating draft replies for human review based on existing content;
- Generating preliminary explanations and troubleshooting suggestions for anomalous data.
For these tasks, raw data and model results should be placed separately to avoid overwriting source data. Tasks like classification and field extraction should also enforce a fixed output structure to reduce the impact of free-text on subsequent processing.
2.3 Data Analysis Assistance
The model can explain metric definitions, help organize analytical ideas, and translate pre-calculated results into natural language reports. However, for tasks involving amount summation, percentage calculations, and statistical tests, deterministic calculation logic should be prioritized.
A more robust division of labor is:
The calculation module is responsible for obtaining accurate results, while the model is responsible for explaining the results, organizing the expression, and proposing hypotheses to be verified.
Do not simply send large amounts of numbers to the model and assume it can reliably perform all calculations. For missing values, duplicate records, time scopes, and unit conversions, rules should also be clarified before analysis.
2.4 Controlled Business Process Assistance
When API permissions and audit mechanisms are complete, the model can also assist in generating ticket content, organizing approval materials, drafting notifications, and filling in business fields.
However, “generating content” and “executing actions” must be separated. Operations involving sending messages, deleting records, modifying amounts, or submitting approvals should be validated by business rules and require human confirmation when necessary. Model output should not directly serve as the authorization basis for high-risk operations.
3. Recommended Architecture: Separating Inference, Knowledge, and Business Entry Points
A maintainable local application can be organized using the following pipeline:
Spreadsheet or Business Page↓Business Adapter Layer↓Permission Validation & Input Check↓Knowledge Retrieval & Context Assembly (enabled on demand)↓Local Model Inference Service↓Result Parsing, Validation & Auditing↓Return to Business Entry or Write to Result Area
Each layer bears different responsibilities:
Inference Service Layer: Responsible for loading the model, handling requests, and generating outputs. It should not directly hold high-privilege credentials for all business systems.
Knowledge Retrieval Layer: Responsible for document parsing, chunking, indexing, and recall. It should retain document sources, versions, update times, and access permissions to facilitate tracing the basis of answers.
Business Adapter Layer: Responsible for unifying APIs, managing timeouts, controlling concurrency, standardizing error messages, and shielding differences in underlying inference interfaces.
Business Entry Layer: Can be a button in a spreadsheet, an internal page, or a business system component. It primarily collects inputs, displays results, and guides user confirmation, and should not carry complex security logic.
For single-user verification, layers can be temporarily simplified; once entering a multi-user scenario, authentication, rate limiting, and auditing should be implemented as early as possible.
4. Environment Preparation: Assessing Actual Task Requirements
4.1 Selecting Models and Resource Allocation Based on Tasks
Model selection should not only look at parameter size but also consider task type, available memory, accelerator resources, context length, and concurrency requirements.
Larger models usually require more resources, but that does not mean they are more suitable for all scenarios. Tasks like fixed-label classification and short text extraction can first be validated with models requiring fewer resources; complex reasoning and long document understanding require focused testing on quality and response time.
Quantization can reduce the storage and runtime resource requirements of model weights, but may affect output quality. In actual use, runtime overhead and context caching must also be considered; you cannot estimate whether resources are sufficient based solely on the model file size.
4.2 Verifying Basic Inference Service Capabilities
Before connecting to spreadsheets or a knowledge base, independently confirm:
- The service can start and stop normally;
- Chinese (or other target language) inputs and outputs have no encoding anomalies;
- Both short and long questions return normally;
- The client provides a clear prompt after a request timeout;
- Exceptions like service restarts or insufficient resources are not misjudged as normal answers.
API paths, authentication methods, and request fields should follow the documentation of the actual deployed components; do not assume different services share the same protocol.
4.3 Knowledge Base Requires Separate Retrieval Components
The responsibilities of generative models and text vectorization components are different. The former organizes answers, while the latter is typically used to convert text into searchable vector representations; they cannot be assumed to substitute for one another.
When processing documents, try to preserve titles, chapter relationships, and source information. Content in tables, scanned files, and images may require additional parsing; parsing errors will directly affect subsequent retrieval quality.
Chunking is not “the shorter the better.” Too short can easily lose semantics, while too long may introduce too much irrelevant content; adjustments should be made based on document structure and test questions.
5. Spreadsheet Integration Practice: Starting from a Single Cell
The minimum viable application can adopt the following layout:
- Input area: User question or text to be processed;
- Result area: Model-generated content;
- Status area: Waiting, processing, success, or failure;
- Tracking area: Request ID, processing time, and error summary.
Initially, only process one record; add batch capabilities after validation is complete.
5.1 Constructing Requests Using Standard Serialization
Do not directly concatenate cell contents into the request string. Inputs may contain quotes, newlines, and backslashes, and manual concatenation can easily cause format errors.
Below is illustrative pseudocode independent of specific software, not an interface definition for an existing service:
InputContent = ReadSpecifiedInputArea()If InputContent is empty:DisplayStatus("Please input content first")ExitRequestObject = {"TaskType": "TextQA","InputContent": InputContent}RequestBody = StandardSerialize(RequestObject)Response = SendRequest(Address = ReadServiceAddressFromSecureConfig(),Credentials = ReadAccessCredentialsFromSecureStorage(),Body = RequestBody,Timeout = ReadTimeoutSettingsFromConfig())If Response indicates success:ResultObject = StandardParse(ResponseBody)ValidateResultStructure(ResultObject)WriteTextToResultArea(ResultObject)Else:DisplayErrorSummary()LogRequestID()
Field names, request formats, and return structures should be explicitly defined by the business adapter layer. The example illustrates the processing sequence and should not be directly regarded as a universal protocol for any inference service.
5.2 Prioritize Non-Streaming Calls
Non-streaming calls typically return the complete result after generation finishes, making them easy to parse, validate, and write to spreadsheets, suitable for initial validation.
Streaming calls return content in segments, which can improve the waiting experience for long answers, but the client must continuously read and process events. If it waits for the entire request to finish before reading the full response, the real-time display effect is lost.
Therefore, whether to use streaming output should be determined by interaction needs, not just by the API name.
5.3 Streaming Responses Cannot Be Parsed as a Single Ordinary Object
Streaming responses may contain multiple events, mixing text increments, statuses, end markers, and error messages. Correct handling usually requires:
- Identifying event boundaries according to the protocol;
- Distinguishing content events from control events;
- Parsing text increments or complete snapshots according to the service definition;
- Checking the end status;
- Displaying partial completion differently from full completion.
You cannot simply delete prefixes and concatenate all fragments together; otherwise, problems like repeated text, omitted content, or mistakenly writing error messages as answers may occur.
5.4 Add State Management for Batch Tasks
Calling row by row is intuitive, but synchronous execution may block the spreadsheet interface and leave difficult-to-determine processing states after a mid-way failure.
During batch processing, states such as pending, processing, success, and failure should be saved for each record, and input summaries or task IDs should be logged for easy checkpoint restarts. Retries should only target appropriate errors and be limited in number to avoid service overload.
For tasks that trigger business writes, idempotent mechanisms should also be designed to prevent duplicate submissions caused by retries.
6. Validation Before Writing Results
A successful API return does not mean the content meets business requirements.
If the task is classification, check if the output belongs to allowed labels; if the task is field extraction, check required fields, date formats, and numerical ranges; if the task is knowledge QA, check if citations exist and if the cited content supports the answer.
In addition, consider the constraints of the spreadsheet itself:
- Long text may exceed cell capacity;
- Newlines and control characters may affect display;
- Content starting with specific symbols might be interpreted as formulas;
- Batch writes may overwrite manual edits.
Content from the model or external text should be written as plain text and escaped if necessary. Long answers can be split into a dedicated result area or saved as a standalone document, retaining a reference in the spreadsheet.
7. Local Deployment Does Not Equal Inherent Security
Local deployment can reduce reliance on external inference services, but whether data is truly kept internal also depends on document parsing, vectorization, logging, update checks, and other external connections.
The following measures should be strictly implemented:
Limit Network Exposure. For single-machine use, prioritize restricting access to localhost; if LAN sharing is necessary, configure authentication, network access control, and appropriate transport protection.
Properly Manage Credentials. Do not hardcode long-term access credentials in shared spreadsheets or scripts, nor distribute them directly through ordinary cells.
Enforce Permission Filtering Before Retrieval. Users should only retrieve documents they have permission to access. You cannot recall all content first and then rely on prompts asking the model to keep secrets.
Prevent Prompt Injection. Text within documents might masquerade as operational instructions. The system should treat retrieved content as material to be analyzed, not as commands that can override security rules.
Control Log Content. Logs are for troubleshooting and auditing, but unnecessary saving of complete sensitive inputs, access credentials, and personal information should be avoided.
8. How to Determine if the Application is Ready for Production
Acceptance testing should be based on test sets built around real tasks, not just demo effects. Test content should at least cover normal questions, no-answer questions, permission-restricted questions, overly long inputs, and service exceptions.
It is recommended to evaluate separately:
- Task Quality: Classification accuracy, field completeness, and whether the answer basis is sufficient;
- User Experience: Wait times, failure prompts, and manual correction costs;
- Operational Stability: Resource usage under concurrency, failure rate, and recovery capability;
- Security: Permission isolation, sensitive information protection, and operation auditing.
When evaluating, clear pass criteria should be established, and records of model, prompt, document version, and configuration changes should be retained. Otherwise, even if quality fluctuations are discovered, it is difficult to locate the cause.
9. Recommended Implementation Phases
Local LLM applications are best advanced in phases.
Phase 1: Complete single text input, invocation, and result display to ensure the pipeline is usable.
Phase 2: Add standard parsing, result validation, timeout handling, and status prompts to give the tool basic reliability.
Phase 3: Integrate knowledge retrieval, supplement source citations, document updates, and permission control.
Phase 4: Introduce batch tasks, queue scheduling, monitoring alerts, and controlled business operations.
A truly valuable local deployment is not about giving the model the most features, but allowing it to continuously complete a class of verifiable tasks within clear data, permission, and quality boundaries. Starting with knowledge QA and spreadsheet automation to solve specific problems first, and then gradually expanding the workflow, is usually more robust than building a massive, all-in-one intelligent system from the start.
