Building a Private Knowledge Base AI Agent on Windows and Integrating It with Collaboration Tools

    This guide walks through building a self-hosted knowledge base AI agent on Windows and connecting it to a team collaboration platform. It covers the five-layer architecture, hardware and software prerequisites, deploying a local inference service with an OpenAI-compatible API, document ingestion and chunking, vector indexing, RAG orchestration with hybrid retrieval, webhook and long-connection integration patterns, security and permission design, operations monitoring, cost control, and a phased rollout plan. The focus is on keeping internal documents within the network while making the assistant auditable, low-latency, and accessible from everyday chat tools.

    1. Requirements and Solution Positioning

    As data compliance requirements become stricter, more teams want to deploy large language model capabilities inside their own environment rather than relying entirely on external services. Typical requirements include: internal documents must not leave the intranet, the question-answering pipeline must be auditable, response latency must be predictable, and the assistant should be embedded directly in the communication tools employees already use.

    Architecturally, a usable “dedicated AI worker” usually consists of five layers:

    1. Interaction layer: employees ask questions through an instant collaboration platform (such as the team communication tool commonly used in the organization);
    2. Access layer: handles message callbacks, identity verification, session routing, and rate limiting;
    3. Orchestration layer: intent recognition, prompt assembly, tool invocation, and multi-turn context management;
    4. Model layer: local inference services that host the language model and related embedding models;
    5. Data layer: document parsing, chunking, vector indexing, metadata storage, and permission mapping.

    It is worth emphasizing that local deployment does not mean “stuffing everything onto one machine.” A reasonable approach is to first clarify the concurrency scale and data volume, then decide which components to localize and which can use general cloud capabilities (for example, object storage for cold data archiving, a logging service for audit trails, and monitoring and alerting for service health observation).

    2. Environment Preparation and Prerequisites

    When using Windows as a development or small-scale production environment, it is best to verify the baseline conditions up front to avoid repeated rework later.

    Hardware and operating system

    • The operating system should preferably be Windows 10/11 Pro or Windows Server 2019 or later, which makes it easier to enable full virtualization and security policy capabilities;
    • Memory is the primary bottleneck: for a 7B-class quantized model, 16GB is the recommended starting point; for 14B and above, 32GB or more is recommended;
    • VRAM determines inference throughput: without a discrete GPU you can rely on CPU inference, but the time to first token will rise noticeably, which is better suited to low-frequency internal Q&A scenarios;
    • Reserve at least 50GB of disk space for model weights, vector indexes, and logs.

    Software dependencies

    • Either WSL2 or a native environment works, but containerized deployment (for example, a Docker-based orchestration approach) is better for version isolation and fast rollback;
    • You need a Python runtime, a package management tool, and an inference service framework that exposes an OpenAI-compatible interface, so upper-layer applications do not need to care about the underlying inference implementation;
    • If intranet document synchronization is involved, also confirm the availability of a file sharing protocol (SMB/NFS) or a synchronization client.

    A typical dependency list looks like this:

    1. Python >= 3.10
    2. Inference service framework (exposes a /v1/chat/completions compatible interface)
    3. Vector database (embedded local or standalone deployment both work)
    4. Document parsing libraries (support PDF / Word / Markdown / HTML)
    5. Process supervision and log rotation tools

    3. Deploying the Local Model Inference Service

    For the model layer, the recommended approach is to “support a standard interface.” The core benefit is that the upper-layer orchestration code is decoupled from the specific inference engine, so switching models or adjusting the quantization strategy later does not require rewriting business logic.

    Service startup example (generic form)

    1. # Start the local inference service in an OpenAI-compatible manner
    2. python -m inference_server \
    3. --model-path ./models/your-model \
    4. --host 0.0.0.0 \
    5. --port 8080 \
    6. --max-model-len 8192 \
    7. --temperature 0.3

    Understanding the key parameters

    • max-model-len determines the context length that can be processed in a single request. It directly affects multi-turn conversation and long-document Q&A capability, and it also sets the upper limit on VRAM usage;
    • temperature should be kept low in knowledge Q&A scenarios (0.1–0.4) to improve the factual accuracy and stability of answers;
    • If embedding capability is needed, deploy a separate embedding model service. A common practice is to choose a small-parameter model with good Chinese semantic retrieval performance, which can meet offline index-building needs using only the CPU.

    Windows-specific considerations

    • When a path contains Chinese characters or spaces, some inference frameworks fail to load; it is recommended to use short English paths for model directories;
    • The Windows firewall may block external access by default, so you need to explicitly allow an inbound rule for the corresponding port in the advanced security settings;
    • If you use WSL2, pay attention to port mapping: after a service inside WSL listens on 0.0.0.0, the Windows host can usually access it directly via localhost; for cross-machine access, you need to configure port forwarding on the host side.

    4. Building the Knowledge Base: From Documents to Retrievable Context

    The value of a local agent depends largely on knowledge base quality rather than model parameter size.

    Step 1: Document ingestion and cleaning

    • Supported formats: PDF, Word, Excel, Markdown, HTML, and plain text;
    • Issues to handle: scanned PDFs need OCR, header and footer noise must be removed, table structures must be reconstructed, and duplicate content must be deduplicated;
    • It is recommended to retain document metadata (source, department, classification level, last updated time) to prepare for later permission filtering.

    Step 2: Chunking strategy

    Chunking is the key variable for retrieval quality. Common practice:

    1. from langchain.text_splitter import RecursiveCharacterTextSplitter
    2. splitter = RecursiveCharacterTextSplitter(
    3. chunk_size=500, # number of characters per chunk
    4. chunk_overlap=80, # overlap region to avoid semantic truncation
    5. separators=["\n\n", "\n", "。", ";", ""]
    6. )
    7. chunks = splitter.split_text(raw_document)

    Rule of thumb: for Chinese technical documents, chunk_size of 400–700 is recommended, with an overlap ratio of 15%–20%. Chunks that are too large reduce retrieval precision, while chunks that are too small leave the context incomplete.

    Step 3: Vectorization and indexing

    • Use the local embedding service for batch vectorization, and enable batching (batch size 16–64) to improve throughput;
    • Vector database selection: for data volumes within a hundred thousand chunks, an embedded vector database is sufficient; beyond a million chunks or when multiple instances need to share data, consider a standalone vector retrieval service;
    • After the index is built, always run a “recall test”: prepare 20–30 real business questions and check whether the Top5 hits include the correct document.

    Step 4: Retrieval-Augmented Generation (RAG) orchestration

    1. def answer(question, session_id):
    2. # 1. Query rewriting: resolve references using multi-turn context
    3. rewritten = rewrite_query(question, session_id)
    4. # 2. Hybrid retrieval: vector recall + keyword recall
    5. docs_vector = vector_store.search(rewritten, top_k=5)
    6. docs_keyword = bm25.search(rewritten, top_k=3)
    7. # 3. Deduplication and reranking
    8. candidates = rerank(deduplicate(docs_vector + docs_keyword))
    9. # 4. Assemble the prompt
    10. prompt = build_prompt(candidates, rewritten)
    11. # 5. Call the local inference service
    12. return llm_client.chat(prompt, temperature=0.3)

    Hybrid retrieval (vector + keyword) is often more stable than vector-only retrieval in real business scenarios, especially when product model numbers, part numbers, or proprietary abbreviations are involved, where keyword recall can significantly reduce missed hits.

    5. Integration with the Team Collaboration Platform

    This is the key step that determines whether the whole solution actually gets used. There are usually three integration approaches, in increasing order of complexity:

    Approach 1: Webhook event subscription

    Most team collaboration platforms provide an event callback mechanism. The basic flow:

    1. Create an application in the platform’s developer console and obtain the application credentials;
    2. Configure the event subscription URL; the platform pushes user messages to your service via HTTP POST;
    3. The server completes signature verification and deduplication (based on message ID), then asynchronously dispatches to the orchestration layer;
    4. After processing, call the platform’s message sending API to reply to the user.

    Integration skeleton example

    1. from flask import Flask, request, jsonify
    2. import hmac, hashlib, threading
    3. app = Flask(__name__)
    4. APP_SECRET = "***"
    5. PENDING = set()
    6. @app.route("/callback", methods=["POST"])
    7. def callback():
    8. body = request.get_json()
    9. # 1. Signature verification to prevent forged requests
    10. ts = request.headers.get("X-Ts", "")
    11. sign = request.headers.get("X-Sign", "")
    12. raw = ts + "\n" + APP_SECRET + "\n" + request.data.decode()
    13. expect = hmac.new(APP_SECRET.encode(), raw.encode(), hashlib.sha256).hexdigest()
    14. if sign != expect:
    15. return jsonify({"error": "invalid signature"}), 401
    16. # 2. Message deduplication to avoid duplicate replies caused by platform retries
    17. msg_id = body.get("message_id")
    18. if msg_id in PENDING:
    19. return jsonify({"code": 0})
    20. PENDING.add(msg_id)
    21. # 3. Process asynchronously and return 200 immediately to prevent the platform from timing out and retrying
    22. threading.Thread(target=handle_message, args=(body,)).start()
    23. return jsonify({"code": 0})

    Approach 2: Long-connection mode

    Some platforms offer a long-connection (WebSocket-like) integration method. The advantage is that no public IP or reverse proxy is required, which is especially suitable for pure intranet or home broadband environments. The downside is that the application side must maintain connection heartbeats and automatic reconnection logic.

    Approach 3: Bot commands + card messages

    In addition to plain text replies, it is recommended to also support structured cards:

    • Card title: a summary of the question;
    • Card body: the answer content plus citation sources (document name + section);
    • Card buttons: “View original,” “Transfer to human,” “Report inaccuracy.”

    Displaying citation sources is extremely important—it significantly lowers the cost for users to stay alert to model hallucinations, and it also creates a positive feedback loop for knowledge base construction.

    6. Security Boundaries and Permission Design

    Local deployment is often misunderstood as “inherently secure.” In reality, without proper design, it can more easily lead to unauthorized access.

    • Identity mapping: connect collaboration platform accounts with the knowledge base permission system, and inject permission filtering conditions at the retrieval stage rather than filtering content after generation;
    • Sensitive information masking: apply regex replacement to ID numbers, phone numbers, and key-type information before it enters the model, then restore or mask it again on the output side;
    • Prompt injection protection: strip instructions from user input, isolate the system prompt from user content, and prevent the model from being induced through document content to leak system configuration;
    • Audit trails: fully record the triple of “asker—retrieved documents—final answer,” persist it to a local logging service, and keep it for no less than 180 days;
    • Network isolation: do not fully open the inference service port to the office network segment; use a gateway for unified authentication and rate limiting.

    7. Operations Monitoring and Quality Evaluation

    Runtime metrics

    • Time to first token (TTFT) and overall response time;
    • Retrieval hit rate (whether the Top5 contains the annotated answer);
    • Session resolution rate and transfer-to-human rate;
    • GPU/memory/VRAM usage curves.

    Quality evaluation method

    It is recommended to build an offline evaluation set of 100–300 items, covering single-hop factual Q&A, multi-hop reasoning, refusal scenarios (when the knowledge base has no answer, it should explicitly refuse rather than fabricate), table queries, and other types. After each adjustment to the chunking strategy or prompt, run a regression round and observe changes in accuracy.

    Common troubleshooting order

    1. Platform callback not responding → check public reachability, firewall rules, and signature verification logic;
    2. Replies going off-topic → check whether retrieval recall is correct, and print the candidates content to confirm;
    3. Response timeout → check whether max-model-len is set too large, causing VRAM overflow or queuing;
    4. Garbled Chinese text → standardize on UTF-8 encoding, and note the default code page issue in the Windows console.

    8. Cost and Control Strategy

    The explicit cost of a localized solution is hardware investment; the hidden cost is operations manpower. Recommended control strategies:

    • Tiered routing: route simple chitchat and fixed-format queries to a small model or rule templates, and route complex reasoning to a large model;
    • Caching layer: apply semantic caching to high-frequency identical questions and return directly on a hit; in practice this significantly reduces inference load;
    • Context compression: when multi-turn conversations exceed a threshold, summarize the history to avoid linear token growth;
    • Cold data tiering: keep the vector index of low-frequency documents locally, and archive the full set of original documents to object storage, balancing cost and compliance.

    For teams trying this for the first time, a three-phase approach is recommended to avoid excessive upfront investment:

    Phase 1 (1–2 weeks): deploy the inference service on a single machine plus ingestion of documents in a single format, and get the “ask—retrieve—answer—with citations” loop working in the collaboration platform to validate basic usability.

    Phase 2 (3–4 weeks): add multi-format parsing, permission mapping, audit logs, and monitoring and alerting to form a minimum production version that can be offered as a service.

    Phase 3 (ongoing): establish an evaluation set and regression mechanism, and gradually add tool invocation capabilities (such as querying internal tickets, schedules, and reports), evolving the assistant from a “Q&A bot” into a “task-executing assistant.”

    It is worth noting that opening up tool invocation capabilities should strictly follow the principle of least privilege: set a separate visibility scope and call frequency limit for each tool, and write-operation tools must include a secondary confirmation step.

    10. Summary

    Building a private AI assistant in a Windows environment and connecting it to a team collaboration platform is not technically an insurmountable barrier. The real challenges concentrate in three areas: the data governance quality of the knowledge base, the orchestration details of retrieval and generation, and the completeness of the permission and audit system. Doing these three things solidly is what turns a local agent from a “novelty toy” in the demo stage into a productivity tool that can be relied on daily. If elastic scaling or multi-region deployment is needed later, the inference service can be containerized and migrated to a container platform, combined with object storage and a logging service for unified governance, achieving better scalability while preserving data sovereignty.