Multi-Platform LLM Assistant Architecture: Unified Sessions, Streaming Events, and Tool Governance
This article describes an engineering architecture for deploying large language model assistants across web, mobile, and desktop clients. It explains why a multi-platform assistant should be treated as a server-orchestrated session system rather than a direct model API wrapper, and covers layered architecture, unified streaming event protocols, session and context management, controlled tool execution, security and compliance, observability, and release stability. The goal is to help developers reuse core capabilities across clients while maintaining consistency, security, and operability.
Multi-Platform LLM Assistant Architecture: Unified Sessions, Streaming Events, and Tool Governance
1. Problem Background and Capability Boundaries
A large language model assistant is not simply a wrapper around a model API. It is an application system composed of client adaptation, an access gateway, session orchestration, model services, tool execution, security policies, and operational observability. Web, mobile, and desktop clients differ significantly in interaction patterns: web clients emphasize immediate rendering and sharing, mobile clients are constrained by network jitter, battery, and input methods, while desktop clients focus more on stable long connections, local file handling, and system-level shortcuts. If each client connects directly to model services, the system is likely to suffer from inconsistent protocols, difficult permission convergence, duplicated context storage, and hard-to-diagnose failures.
From an engineering perspective, the assistant should therefore be abstracted as a session system orchestrated centrally on the server. Clients should only collect input, render streaming results, and handle interaction states. The server should handle authentication, context construction, model invocation, tool execution, content safety, and auditing. The core abstractions can be summarized as five object types: sessions, messages, events, tools, and policies. A session defines the boundary of a multi-turn interaction; messages record user input and assistant output; events describe incremental states during streaming transmission; tools encapsulate controlled external capabilities; and policies constrain model behavior, data access, and tool permissions.
For deployment, general cloud infrastructure can be used: container platforms for stateless services, object storage for large files and archived records, logging services for runtime logs, and monitoring and alerting for key metrics. If deployed in a general-purpose cloud environment such as Baidu AI Cloud, teams should also prefer general-purpose capabilities and avoid binding business logic to specific interface details.
2. Overall Architecture Layers
A layered architecture is recommended so that change points are isolated within clear boundaries.
- Client adaptation layer: Implement input components, message rendering, reconnection, and local caching for web, mobile, and desktop clients. Clients should not hold long-term model credentials, only short-lived access tokens.
- Access gateway layer: Handle identity authentication, tenant identification, rate limiting, idempotency keys, protocol conversion, and request routing in a unified way. The gateway should hide client differences and convert requests from different clients into unified session events.
- Session service layer: Maintain session metadata, message ordering, context windows, and concurrency locks. The session service should guarantee write ordering within the same session and avoid context corruption caused by simultaneous input from multiple clients.
- Orchestration service layer: Responsible for system instruction assembly, context trimming, model invocation, tool selection, result injection, and final output. The orchestration layer is the main location for business policies.
- Model service layer: Provide a unified abstraction for model invocation, including timeouts, retries, degradation, quotas, and result normalization. Different model capabilities should be exposed through a unified event protocol so that clients do not need to perceive underlying differences.
- Tool execution layer: Register tools, validate parameters, check permissions, isolate execution, control timeouts, and record audits.
- Security and observability layer: Cover input and output filtering, sensitive information masking, prompt injection protection, log desensitization, metric collection, and distributed tracing.
In the data flow, a client submits a user message, and the gateway completes authentication and generates a request identifier. The session service writes the message and acquires a session lock. The orchestration service builds context and invokes the model. Model output is returned as an incremental event stream. If a tool call is triggered, the tool execution layer executes it within the authorized scope and injects the result. After the final event, the session lock is released and an audit record is written.
3. Unified Event Protocol and Streaming Output
The key to multi-platform access is a stable event protocol. A single assistant response should be abstracted as an ordered event stream containing at least start, incremental text, tool call, tool result, error, and end events. Each event should carry a session identifier, message identifier, sequence number, and timestamp. Clients merge events by sequence number and may discard or wait to reorder out-of-order events. Streaming output can use HTTP streaming responses or long-connection protocols. The former is simple to implement and traverses networks well, while the latter is better suited to scenarios with frequent bidirectional interaction. In either case, the system should support reconnection, historical event replay, and idempotent consumption.
Example pseudocode:
Event definitions:start(sessionId, messageId, seq)delta(seq, text)tool_call(seq, toolName, arguments)tool_result(seq, ok, summary)error(seq, code, retryable)end(seq, finishReason)Server processing:onUserMessage(sessionId, input):lock(sessionId)context = buildContext(sessionId, input)emit startresult = orchestrate(context)for chunk in result.stream:emit delta(chunk.text)if result.toolCall:emit tool_call(...)toolResult = executeToolWithPolicy(...)emit tool_result(...)emit endunlock(sessionId)
During client rendering, avoid triggering a full re-layout for every incremental event. Incremental appending and throttled rendering are recommended. For mobile clients on weak networks, allow a “non-streaming fallback”: if streaming is interrupted repeatedly, switch to a one-time response and notify the user. Desktop clients can cache recent session events to quickly restore UI state. The server should return the same result for duplicate submissions of the same message or return an explicit conflict state, preventing repeated billing and duplicate side effects caused by repeated clicks.
4. Session and Context Management
Context management directly determines answer quality and cost. Session data should be divided into short-term context, long-term summaries, and retrieval-augmented materials. Short-term context retains the most recent turns and key system instructions. Long-term summaries are periodically compressed by the server from historical messages, preserving facts, preferences, and unfinished tasks. Retrieval-augmented materials are injected after filtering by tenant and user permissions. Context trimming should follow a priority order: security policies and system instructions first, recent user intent second, historical summaries third, and low-relevance retrieval snippets last.
The same session may be accessed by multiple clients simultaneously, so a session lock or version number is needed. When writing a message, validate the version number and return the latest state on conflict. Context construction should follow a pure functional approach: input the session state and current message, and output an auditable list of context segments so that issues can be reproduced.
Pseudocode:
buildContext(session, currentInput):segments = []segments += systemPolicy(session.tenant)segments += recentMessages(session, limit=N)segments += summaryIfNeeded(session.history)segments += retrieveAuthorizedDocs(currentInput, session.user)return trimByTokenBudget(segments, budget)
After trimming, record a summary of trimmed segments and the trimming reason, but do not log sensitive original text. For long-document scenarios, files can first be stored in object storage, and only controlled references and summaries should be injected into context, avoiding repeated transmission of large original passages.
5. Tool Invocation and Permission Control
Tool invocation gives the assistant query, computation, and action capabilities, but it also amplifies security risks. When registering a tool, declare its name, purpose, parameter schema, timeout, whether it has side effects, and required permissions. The orchestration service can only select tools that are registered and included in the tenant allowlist. Before tool execution, parameter validation and permission checks are mandatory. Tools with side effects should require user confirmation or approval and use idempotency keys to prevent duplicate execution.
Pseudocode:
toolSpec = {name: "query_metric",description: "Query metrics within the authorized scope",parameters: { type: "object", required: ["metric", "range"] },timeoutMs: 3000,sideEffect: false,requiredScope: "metric:read"}executeToolWithPolicy(call, user):spec = registry.get(call.name)require(spec in tenantWhitelist)require(user.scopes contains spec.requiredScope)validate(call.arguments, spec.parameters)if spec.sideEffect and not confirmed(call):return needConfirmationreturn sandboxExecute(spec, call.arguments, timeout=spec.timeoutMs)
Tool results should be treated as untrusted input. Before entering the model context, perform structured sanitization and length limits to prevent malicious content in tool results from inducing the model to ignore system policies. Tool execution should run in an isolated environment, restrict network and file access, and record the caller, parameter summary, result status, and latency.
6. Security, Compliance, and Content Governance
Security governance should cover four stages: input, orchestration, output, and auditing. On the input side, identify sensitive information and mask it when necessary. On the orchestration side, prevent prompt injection, clarify the priority of system instructions, and do not treat user input such as “ignore the above rules” as a high-priority instruction. On the output side, perform content filtering and citation validation. On the audit side, record key operations without logging unnecessary original text.
Multi-platform security policies need to be differentiated. Web clients should use short-lived tokens and origin validation. Mobile tokens should be revocable and bound to device state. Desktop local caches should be encrypted, and sensitive context should be cleared on exit. Data isolation should be implemented between tenants, and retrieval and tool invocation must carry tenant boundaries. Logs, traces, and metrics should record only identifiers and summaries, not complete prompts or original tool results. For high-risk tools, human approval and secondary confirmation should be supported.
7. Observability and Stability
Observability should be built around the request chain. Recommended metrics include request volume, error rate, first-event latency, streaming interruption rate, tool call success rate, context length distribution, retry count, and degradation count. Logs should include request identifiers, session identifiers, tenant identifiers, model invocation stages, and error codes. Distributed tracing should connect the gateway, session, orchestration, model, and tool execution. Alerts should distinguish client-side errors from server-side errors to avoid mistaking user network problems for service failures.
During releases, use versioned protocols and feature flags. New models, new prompt strategies, and new tools should first be rolled out to a small percentage of tenants, and error rates and interruption rates should be observed before broader rollout. Clients should support protocol compatibility: older clients should ignore unknown event types rather than crash. The server should retain a rollback path to ensure that configuration errors can be recovered quickly. Capacity planning should focus on concurrent streaming connections, context length distribution, and peak tool invocation volume, not only average request volume.
8. Conclusion
The engineering focus of a multi-platform LLM assistant is not merely “connecting to a model API.” It is about establishing unified session semantics, a stable event protocol, controlled tool execution, strict security boundaries, and an observable operations system. By isolating client differences through layered architecture, unifying context and permissions through server-side orchestration, improving interaction experience through streaming events, and controlling evolution risks through canary releases and rollback, developers can reuse core capabilities across web, mobile, and desktop clients while keeping the system stable, secure, and maintainable.
