Build a Private AI Assistant on Windows: Integrating LLMs with a Collaboration Platform
This guide walks through building a private AI assistant on a Windows desktop by connecting three components: a conversational LLM service, a collaboration platform used as the daily entry point, and an orchestration layer running locally. It covers prerequisites such as obtaining a model API key with a small amount of credit and setting up a free-tier organization with a bot on a collaboration platform, followed by architecture design, permission scoping, event subscription and verification, session context management, model invocation, security and stability practices, a troubleshooting checklist, and a pre-launch checklist. The approach is vendor-neutral and can typically be validated within an hour.
1. Goals and Use Cases
Building a “private AI assistant” on a Windows desktop comes down to connecting three things: an LLM service that can hold a conversation, a collaboration platform you already use every day as the entry point, and an orchestration layer that runs locally. The requirements reduce to two prerequisites. First, you need an API key for a conversational model with a small amount of usable credit. Second, you need an account on a collaboration platform that lets you create an organization and add bots; a free personal plan is usually enough to validate the setup.
The approach fits three scenarios:
- Personal knowledge Q&A and text processing, such as organizing meeting notes, explaining code snippets, and drafting emails.
- Lightweight automation, such as forwarding a daily report request in a fixed format to the model and writing the result back.
- A prototype of an internal technical support bot for a team.
This guide is not tied to any specific vendor. When cloud-side capabilities are involved, it uses generic categories only, such as “object storage,” “message queue,” “log service,” and “monitoring and alerting.”
2. Architecture and Component Responsibilities
A three-tier structure is recommended: collaboration platform, local gateway, and model service. Clear boundaries make components easy to replace and easy to troubleshoot.
- Access layer: A self-built app and bot on the collaboration platform handle receiving user messages and pushing results back.
- Orchestration layer: A gateway process running on the Windows machine (or an always-on device on the local network) handles signature verification, deduplication, session mapping, rate limiting, and logging.
- Capability layer: The LLM service, called over HTTPS with an API key and billed per token. Start with a small top-up to validate the flow.
Schematic topology and request flow:
User message -> Collaboration platform event callback -> Local gateway (verify/dedupe/session mapping)-> LLM service (chat completion) -> Gateway (trim/redact/rate limit) -> Bot reply
3. Prerequisites: Keys and Credit Planning
The first step is to prepare model-side credentials. Register an account on a compliant LLM platform’s developer console, create an access key, and make a small top-up to activate the calling quota. Beyond the primary model, common industry options also support connecting to other vendors’ compatible interfaces, as long as they provide standard chat completion. This leaves room to swap between options on cost and quality.
Plan the credit “small first, then larger”:
- The initial top-up should cover only a few hundred short conversations, just enough to get the pipeline working.
- Set a per-user daily call limit and an overall budget threshold on the gateway side.
- Log the estimated input and output tokens for each request to build a simple cost dashboard.
The second step is to prepare resources on the collaboration platform side. Use a personal account to create an organization (the personal plan is generally free), then go to the developer console to create a self-built app, enable bot capabilities, and configure the event subscription URL. The most common blocker here: the callback URL must be a publicly reachable HTTPS endpoint, so a direct connection from the local machine will not work. You need either an intranet penetration (tunneling) setup or a lightweight server with a public entry point to forward requests.
4. Step-by-Step Implementation
4.1 Create the App and Scope Permissions
After creating the app in the developer console, request only the necessary permissions: reading and sending messages, and getting the bot’s own information. The smaller the permission set, the simpler the later audit. Store the app credentials (fields such as App ID and App Secret) in local environment variables rather than in the code repository.
4.2 Configure and Verify Event Subscription
When you configure the callback, the platform typically sends a verification request, and the gateway must return the verification value as specified. A minimal skeleton looks like this (illustrative; field names follow the actual platform documentation):
from flask import Flask, request, jsonifyimport os, hmac, hashlibapp = Flask(__name__)APP_SECRET = os.environ["APP_SECRET"]@app.route("/event", methods=["POST"])def on_event():body = request.get_json(force=True)# 1) Platform verification: echo back the challenge as-isif "challenge" in body:return jsonify({"challenge": body["challenge"]})# 2) Event deduplication: use event_id for idempotency# 3) Signature verification (if provided by the platform)# 4) Hand off to the orchestration logicreturn jsonify({"code": 0})
4.3 Session Context and Message Routing
Group chats and direct chats must be handled separately. It is recommended to maintain a sliding-window context keyed by a “session identifier,” capping the number of turns and characters to avoid token bloat:
HISTORY = {} # session ID -> message listMAX_TURNS = 6 # keep the most recent N turnsMAX_CHARS = 4000 # context character limitdef build_prompt(session_id, text):h = HISTORY.setdefault(session_id, [])h.append({"role": "user", "content": text})h = h[-MAX_TURNS:]HISTORY[session_id] = hctx = "\n".join(m["content"] for m in h)[:MAX_CHARS]return ctx
The routing layer should support command prefixes, for example /ask to trigger Q&A, /reset to clear the context, and /help to return usage, so the bot does not become a source of noise in the group.
4.4 Call the Model and Write Back the Result
When calling the model, merge the system prompt with the context, and set a reasonable temperature and maximum output length. Trim the returned result by length and filter sensitive information first, then push it back through the bot message API. If a single output is too long, send it in segments with a sequence number at the end of each to improve readability.
5. Security and Stability Essentials
- Credential management: All keys live only in environment variables or local secret storage. Hardcoding and committing them to version control are prohibited.
- Input validation: Intercept overly long text, malformed JSON, and duplicate events. The gateway should return explicit error codes rather than failing silently.
- Idempotency: Deduplicate by the event’s unique identifier to prevent duplicate replies caused by platform retries.
- Rate limiting and budget: Apply rate limits on both per-user and global dimensions, and degrade to a notice message when a threshold is reached.
- Data minimization: Do not persist conversation content by default. If auditing is required, keep only hashes and metadata, with a defined retention period.
- Observability: Connect a log service and monitoring/alerting, and track trends in callback failure rate, model call latency, and token consumption.
6. Troubleshooting Checklist
- Callback verification fails: Usually the response body format or field names do not match. Print the raw request body and compare it against the documentation first.
- The bot does not reply: Check whether permissions have been published and are in effect, and whether event subscription points to the latest URL.
- High reply latency: Usually caused by overly long context or too large a maximum output. Tighten the window and lower the maximum output length.
- Abnormal credit consumption: Check for a trigger loop (the bot’s reply triggering its own event) and filter the bot’s own messages on the gateway side.
- Intranet penetration drops: Configure a watchdog process and auto-reconnect for the forwarding path, and set an alert on the callback success rate.
7. Pre-Launch Checklist
- Permissions are minimized and the app has been published.
- The callback URL is publicly reachable with a valid certificate.
- Keys exist only in environment variables, with no leaks in the repository.
- Idempotency, rate limiting, and budget thresholds are all enabled.
- Logging and alerting are observable, and failures can be located.
- A one-click degradation switch is in place so the bot automatically enters a read-only notice mode on anomalies.
Following this path, from registering a key to the bot having usable conversational ability, validation can typically be completed within an hour. After that, iterate gradually based on real usage feedback.
