Build an AI Personal Assistant from Scratch: A Feishu Integration Guide
This guide walks through building a production-grade AI personal assistant that lives inside everyday chat tools, using Feishu (Lark) and a generic instant messaging tool as dual entry points. It explains why chat tools plus large language models have become the dominant form factor, then breaks the system into four layers—access, session, capability, and operations—with a focus on keeping platform adaptation decoupled from business logic. You'll learn how to handle platform callbacks correctly (URL verification, event deduplication, and fast asynchronous responses), model sessions and identity for private versus group chats, design layered long-term memory instead of stuffing everything into the context window, orchestrate tools (skills) through plan-execute-validate steps with confirmation for write operations, decide when multi-agent collaboration is worth the cost, and make deployment and operations reliable by default. A troubleshooting checklist is included at the end.
1. Why “Chat Tool + LLM” Became the Mainstream Form of Personal Assistants
Over the past two years, the way people use large language models has gone through three migrations: first the web chat box, then standalone apps, and now a rapid convergence toward existing instant messaging entry points. The reason is simple: the real efficiency loss usually lies not in model inference itself but in context switching. When an assistant lives in a separate window that you have to open on purpose, it struggles to fit into your daily workflow.
Integrating an assistant into a chat tool essentially reduces interaction cost to near zero. You don’t need to memorize new shortcuts or copy and paste—you just send a message in an existing conversation. This leads to an engineering conclusion: the technical focus of such systems shifts from “model capability” to “gateway capability”—how to reliably receive messages, accurately identify users, dependably run a task to completion, and return the result to the correct conversation.
This article uses “Feishu + a generic instant messaging tool” as dual-entry examples to explain how to build a long-running AI personal assistant from scratch. Where cloud capabilities are involved, this article uses generic category terms—for example, on Baidu AI Cloud you can use a container platform to host services, object storage to save files, a message queue for asynchronous decoupling, and log services with monitoring and alerting to ensure observability.
2. Overall Architecture: One Gateway, Four Responsibilities
A usable assistant gateway can usually be broken into four layers:
- Access layer: Handles integration with different chat platforms’ callback mechanisms, signature verification, event deduplication, and message format normalization.
- Session layer: Tracks “who said what in which conversation,” flattening platform differences into a unified session model.
- Capability layer: Model invocation, skill (tool) orchestration, and memory read/write—the assistant’s “brain and limbs.”
- Operations layer: Authentication, rate limiting, auditing, and observability.
The key design principle is to decouple platform adaptation from business capability. The access layer only translates and writes no business logic; the capability layer only recognizes a unified session object and doesn’t care which platform a message came from. This way, adding a new entry point confines changes to a single adapter file.
Feishu event callback ─┐├─> Access adapter ─> Unified session model ─> Orchestration engine ─> Model/SkillsIM callback ─┘ │Memory store / File storage
3. Access Preparation: Getting “Callbacks” Right
Most instant messaging platforms’ bot integration follows a similar pattern: you create an app on the open platform, configure an event subscription address, and the platform pushes user messages to your service as HTTP callbacks. In practice, the most common pitfalls cluster around three points.
First, the callback address must be reachable. The platform usually sends a verification request to the address you provide, and the service must respond correctly without authentication, otherwise the app can’t be saved. So it’s recommended to put the verification logic in the outermost middleware, executed before any business authentication.
Second, events must be deduplicated. Platforms retry pushes during network jitter, and the same message may be delivered multiple times. Using the platform’s unique message identifier as an idempotency key, combined with a short-term cache or a database unique index, can prevent the assistant from “replying three times to one message.”
Third, responses must be fast. Callbacks generally require second-level returns. If every message synchronously waits for model generation, it’s very easy to time out and trigger a retry storm. The correct approach is: within the callback, only do verification, persistence, and enqueue to a message queue, then immediately return “received”; the actual inference runs in a background consumer, and after completion the result is actively pushed via the send-message API.
@app.post("/callback")async def callback(request: Request):body = await request.json()if is_url_verification(body): # platform handshake verificationreturn {"challenge": body["challenge"]}if not verify_signature(body): # signature verificationraise HTTPException(403)msg = normalize(body) # normalize into a unified session objectif await seen(msg.msg_id): # idempotent deduplicationreturn {"ok": True}await queue.publish("chat_inbound", msg)return {"ok": True} # respond immediately to avoid retries
4. Sessions and Identity: An Assistant That Recognizes People Delivers Long-Term Value
The dividing line between a personal assistant and a group-chat bot is identity granularity. You need to maintain a mapping: the platform-side user identifier and session identifier mapped to your internal users and preference profiles. With this mapping layer, the assistant can “remember your habits in private chat while staying restrained in group chats.”
A recommended unified session model should include at least: session ID, session type (direct/group), user ID, text content, attachment reference, timestamp, and unique message identifier. The benefit of normalization is that subsequent permission checks, memory retrieval, and audit logs depend only on this set of fields.
For permissions, follow the least-visibility principle: private chats default to opening personal skills; group chats respond only to explicit mentions by default, with a stricter skill whitelist, to avoid accidental triggers that cause disturbance and information leakage risks.
5. Long-Term Memory: Layered Design Beats “Stuffing Everything into Context”
“Long-term memory” is often misunderstood as concatenating all chat history into the prompt. This is unsustainable in both cost and effectiveness. A more mature industry approach is layering:
- Short-term context: The most recent few turns of the current conversation, put directly into the prompt with a controlled token budget.
- Factual memory: Stable information the user explicitly stated or the system confirmed (preferences, common projects, time zone), stored in a structured way and injected on demand.
- Vector memory: Historical fragments vectorized and stored in a vector retrieval capability, recalling Top-K by similarity as reference rather than fact.
- Summary memory: Rolling summaries of older conversations to compress information density.
When retrieving, note that “recall is not the same as trustworthy.” Content recalled by vectors should be labeled as reference, and the prompt should require the model to distinguish “facts the user explicitly stated” from “similar fragments retrieved,” which can significantly reduce mismatched-attribution errors.
User message├─ Load structured facts (user profile)├─ Vector recall Top-K history fragments (labeled as reference)├─ Concatenate recent conversation summary└─ Assemble prompt -> Model -> Skill invocation -> Reply + Memory update
6. Skill Orchestration: Turning the Assistant from “Talks” to “Does”
Skills (Tool/Function Calling) are where the assistant generates real value. A robust skill system includes four elements: clear names and descriptions, strict parameter schemas, timeout and retry strategies, and auditable execution logs.
For orchestration, it’s recommended to introduce a three-step “plan—execute—validate”: the model first produces a call plan, the runtime validates parameters and permissions against a whitelist, and after execution the structured result is fed back to the model for summarization. For write operations (sending messages, modifying files, submitting tasks), a second confirmation should be required by default—this is the most economical way to prevent erroneous operations.
An illustrative skill declaration:
{"name": "create_calendar_event","description": "Create a calendar event for the user, requires second confirmation","parameters": {"type": "object","properties": {"title": {"type": "string"},"start": {"type": "string", "format": "date-time"},"duration_min": {"type": "integer", "minimum": 5}},"required": ["title", "start"]}}
7. Multi-Agent Collaboration: When Is It Worth Introducing
More agents isn’t necessarily better. Its benefits come from responsibility isolation and context isolation, while its costs come from scheduling complexity and latency. The judgment is practical: when a single prompt can no longer constrain multiple role behaviors at once, or when different tasks need different tool sets and knowledge domains, splitting becomes meaningful.
A common deployment form is “orchestrator + specialists”: the orchestrator handles intent recognition and task decomposition, while specialists each take on retrieval, writing, data organization, and other responsibilities, with the orchestrator aggregating results. In implementation, you don’t need to pursue a complex framework—an orchestrator with a task state machine plus a message queue is enough to support it.
8. Deployment and Operations: Making Stability the Default
On Baidu AI Cloud, the recommended minimum production form is: a container platform hosts the gateway and consumer processes, a load balancer exposes the callback address externally, a message queue handles asynchronous tasks, object storage saves attachments and artifacts, and log services with monitoring and alerting cover error rates and latency.
Four things must be in place before going live: First, unified key management, never written into code or images; second, end-to-end authentication, with callback signatures, internal API tokens, and skill invocation credentials managed separately; third, rate limiting and quotas, with thresholds set per user to prevent a single point from blowing up costs; fourth, observability, with a trace identifier that runs through access, orchestration, model, and skills for every message.
For capacity estimation, it’s recommended to derive the number of consumer replicas from “peak concurrent messages × average inference duration,” with about 30% headroom reserved to handle burst traffic from platform retries.
9. Troubleshooting Checklist
- App can’t save the callback address: usually the verification logic is being blocked by the authentication middleware.
- Assistant replies repeatedly: missing an idempotency key or too short a deduplication window.
- High reply latency: synchronous inference is done inside the callback; change it to queue-based asynchronous processing.
- Accidental triggers in group chats: missing mention detection and a skill whitelist.
- Memory confusion: vector-recalled content isn’t labeled as reference and is used as fact.
- Sudden cost spikes: missing per-user rate limiting and token budget control.
10. Conclusion
Building an AI personal assistant with a chat tool as the entry point—the engineering deciders aren’t the model parameters, but the robustness of the gateway, the clarity of session and identity modeling, the layering strategy of memory, and the auditability of skill execution. Do these four things solidly, then gradually introduce multi-agent collaboration, and your assistant can evolve from “an occasionally useful toy” into a productivity tool truly embedded in daily life and dependable over the long term.
