A Lightweight Proxy for Connecting Chat Apps and Coding Assistants

    This article explains how a lightweight proxy layer can sit between a chat platform and multiple AI capabilities so teams can route requests, run long coding tasks asynchronously, and keep sessions, permissions, and audit trails under control. It covers architecture, model roles, adapter interfaces, async execution, security, observability, deployment, and an acceptance checklist.

    1. From a Working Prototype to Everyday Use

    When a team first connects an intelligent agent to an instant-messaging tool, the goal is usually simple: send one message in a chat window and call a Q&A capability or a coding assistant. A prototype often works quickly. Once it enters real use, problems appear just as quickly.

    Common pain points include:

    1. Capabilities are hard-bound to an entry point. Some platforms bind one account or group to a single native bot capability. Using several agent capabilities then means frequent switching or multiple accounts. More accounts make message routing, identity, and context isolation harder.
    2. Synchronous calls are a poor fit for long tasks. Coding, code review, and complex analysis often take a long time. If the integration layer waits for the result, timeouts, duplicate callbacks, or lost messages become likely.
    3. Chat context and execution context are mixed. Chat context is good for preferences, summaries, and recent dialogue. A coding task needs a task description, constraints, related files, acceptance criteria, and permission boundaries. Feeding raw chat history straight into an execution tool is usually unstable.
    4. There is no unified audit trail. Without a shared record of who started which task, when, which capability was called, how many resources were used, and whether a side-effecting action ran, later troubleshooting and permission management become difficult.
    5. Platform limits slow expansion. Deduplication, signature checks, media handling, user-identity mapping, group versus direct chat differences, and failure retries often take more effort than “calling a model.”

    A better approach is not to keep stacking configuration on the platform’s native bot. Add a lightweight proxy orchestration layer between the chat platform and multiple intelligent capabilities. It owns the shared entry point, message governance, intent routing, task scheduling, result aggregation, and security controls. Chat remains an entry point. Models and coding tools do the work they are good at.

    2. Goals and Boundaries

    A practical lightweight proxy should at least:

    • Accept chat, Q&A, summarization, coding tasks, and deep analysis through one entry point;
    • Route by intent to different models or tools instead of sending every request to the same large model;
    • Support asynchronous tasks, progress updates, retries, and human confirmation;
    • Isolate multiple users, groups, and tenants so contexts do not leak into each other;
    • Sandbox high-risk capabilities such as code execution, command execution, and file access;
    • Provide logs, metrics, tracing, and audit records;
    • Stay simple to deploy and easy to extend later.

    Non-goals should be explicit. The lightweight proxy does not train models and does not replace a professional coding tool. It is more like a dispatch desk: it turns natural-language requests from chat into structured tasks, hands them to a suitable model or tool, and formats the result into a readable reply.

    3. Overall Architecture

    A useful logical architecture has six layers.

    3.1 Chat integration layer

    This layer receives message events, verifies the source, deduplicates events, parses message types, downloads or caches media, identifies group versus direct chats, and converts platform messages into a single internal message object.

    It should focus on three things:

    • Signatures and replay protection. Accept only trusted callbacks. Reject messages whose timestamps are too old.
    • Idempotent deduplication. Platforms may retry callbacks. Deduplicate by event ID so the same task is not executed more than once.
    • A unified message shape. Platforms differ in message format, rich text, and media fields. Internally, normalize them into standard fields such as text, images, files, quotes, and conversation IDs.

    3.2 Session and context layer

    A session should at least include tenant, user, group, topic, recent messages, historical summary, user preferences, permission role, and current task state.

    Do not append the full chat history to the model without limit. A better pattern is short-term raw text plus a long-term summary plus structured memory. Preferences such as “code review should look only at the change scope” or “lead with the conclusion” belong in memory. Casual chat should be summarized so the context does not grow without bound.

    3.3 Routing and intent layer

    The router decides the user’s intent: ordinary Q&A, file summary, information extraction, coding task, code review, deep analysis, or an administrative action.

    Prefer rules first and a model second:

    • Match explicit command prefixes first, such as /code, /review, /summarize, and /ask;
    • Cover frequent cases with stable rules, such as phrases that mean “review the change,” “generate tests,” or “explain this error”;
    • If rules cannot decide, call a lightweight model for intent classification;
    • For high-risk or high-cost tasks, ask the user to confirm before submission.

    3.4 Capability and model layer

    This layer includes a fast model, a multimodal understanding model, a coding execution agent, retrieval tools, and workflow tools. Each capability is registered through a common adapter interface and selected by the router.

    3.5 Task execution layer

    Long tasks must not block the message-handling thread. Use a task queue, a state machine, and an execution sandbox:

    • Return a confirmation as soon as the task is submitted;
    • Run the task in the background, moving through queued, running, succeeded, failed, canceled, and timed out;
    • Support progress reports and status queries;
    • Limit CPU, memory, runtime, and network access in the execution environment;
    • Store artifacts in controlled storage and return them through authenticated access.

    3.6 Observability and security layer

    Record the request trace, routing result, model calls, tool calls, task state, error codes, resource use, and human confirmations in one place. Redact secrets, tokens, personal data, and file-content summaries in logs.

    4. The Critical Path: From Message to Task

    A typical message follows this flow:

    1. The integration layer verifies the signature and deduplicates the event.
    2. The session is loaded from the user, group, and topic.
    3. If the session already has a running task, queue the new one or tell the user to wait, according to policy.
    4. The router decides the intent.
    5. Light tasks take the fast-reply path.
    6. Heavy tasks become structured tasks and are submitted to an execution agent.
    7. After the background task finishes, the result is summarized, redacted, and formatted.
    8. The user is replied to, and the audit record is written.

    Illustrative pseudocode:

    1. on_message(event):
    2. verify_signature(event)
    3. if duplicate(event.id):
    4. return ok
    5. session = load_or_create_session(event)
    6. intent = route(event.content, session.summary)
    7. if intent in ["chat", "summarize", "extract"]:
    8. context = trim_context(session, event.content)
    9. reply = fast_model.answer(context, media=event.media)
    10. send_reply(event, reply)
    11. return ok
    12. if intent in ["code_task", "review", "deep_analysis"]:
    13. task = normalize_task(intent, event, session)
    14. confirm = require_confirmation(task)
    15. if confirm and not task.confirmed:
    16. send_reply(event, "This task will run actions. Confirm to continue.")
    17. return ok
    18. job = adapter.submit(task, idempotency_key=event.id)
    19. send_reply(event, "Task accepted: " + job.public_id)
    20. return ok

    The idea is simple: reply to fast requests synchronously and run complex requests asynchronously. Separate routing from execution, and separate message intake from tool calls.

    5. Model Roles: A Fast Model at the Door, Stronger Capability for Deep Work

    Sending every request to the strongest model looks simple, but it creates three problems: higher latency, higher cost, and no guarantee of a more stable workflow. A stronger model does not automatically schedule tasks more reliably. Experience depends more on routing, context trimming, tool-interface constraints, and failure recovery.

    Split work by task type.

    5.1 Use a fast model for assistant-style work

    A fast model fits:

    • Message classification and intent detection;
    • Short answers and information extraction;
    • Conversation summaries, to-do lists, and meeting notes;
    • Shallow understanding of images, screenshots, and document excerpts;
    • Task-template generation and result formatting;
    • Turning natural language into a structured task description.

    These tasks need speed and predictable cost. A fast model is usually the right owner of the entry layer, so users get immediate feedback in chat.

    5.2 Send deep analysis and coding work to a specialized execution agent

    Code generation, defect localization, change review, architecture analysis, and complex log investigation should go to a dedicated coding agent or a higher-reasoning workflow.

    Do not pass the chat transcript through unchanged. Generate a structured task, for example:

    1. Task type: change review
    2. Goal: check whether this change introduces null dereferences, out-of-bounds access, or compatibility issues
    3. Inputs: change summary, affected files, related test results
    4. Constraints: do not change business logic; output only a problem list and suggestions
    5. Acceptance criteria: each issue includes location, cause, impact, and suggestion
    6. Output format: a structured list ordered by severity

    The execution agent then receives a clear goal instead of a vague chat context. The main agent orchestrates and summarizes; it does not do every detailed inference itself.

    6. A Common Adapter and Multi-Capability Routing

    One entry point can call many capabilities only if the adapter interface is stable. Each capability should at least implement:

    1. validate(task) -> validation result
    2. submit(task, context, idempotency_key) -> task identifier
    3. status(job_id) -> current state
    4. progress(job_id) -> progress information
    5. result(job_id) -> structured result
    6. cancel(job_id) -> cancellation result

    This has three benefits:

    • A new capability only needs a new adapter; the message entry point stays unchanged;
    • Every task shares status, timeout, and cancellation semantics;
    • Canary releases, rate limits, and failure isolation become easier.

    Routing can mix prefixes and natural-language intent:

    • /ask: ordinary Q&A;
    • /summarize: summarize a file or a conversation;
    • /review: code review;
    • /code: code generation or repair;
    • /analyze: deep analysis.

    Users can also write in natural language and let the router decide. If confidence is too low, the system should ask a follow-up question instead of calling an expensive capability by mistake.

    When a platform account can be bound to only one capability entry, use one proxy entry for all requests and route internally. Separate groups, users, and topics by tenant ID and permission role. Do not keep a separate account for every capability. If strong isolation is required, create separate logical instances in configuration rather than mixing every context into one session.

    7. Asynchronous Tasks and the Long-Task Experience

    Coding tasks often run for minutes or longer. Waiting synchronously makes the experience poor. Use an asynchronous task model:

    • Confirm immediately that the task was accepted;
    • Return a short task identifier;
    • Push progress by stage, without flooding the chat;
    • On completion, return a conclusion summary, key changes, risks, and next actions;
    • On failure, return an actionable reason, not only “execution failed”;
    • Support timeout cancellation and manual stop;
    • Stay idempotent under duplicate callbacks so the same task is not run twice.

    Use a shared set of states: queued, running, waiting for confirmation, succeeded, failed, canceled, and timed out. Record the time, actor, and error code for every transition so failures can be diagnosed.

    Format results for chat: conclusion first, then only the necessary detail. Put code or long logs in an attachment or a collapsed section. Sort multiple suggestions by severity. Express actions that need confirmation with a clear button or a text command.

    8. Security, Permissions, and Audit

    Once chat is the entry point, the security boundary is harder than with a local tool, because messages can come from different users, groups, or even external guests. At a minimum:

    1. Map identity to permissions. A chat user must map to an internal role. Being able to send a message in a group must not grant code-execution rights.
    2. Use least privilege. Different capabilities use different credentials. A coding agent should access only the repositories it needs. The execution environment should deny sensitive networks and credentials by default.
    3. Confirm high-risk actions. Deleting files, changing production configuration, or running commands with side effects requires a second confirmation.
    4. Execute in a sandbox. Code execution, command execution, and dependency installation should run in isolation, with limits on resources, time, files, and network access.
    5. Protect sensitive data. Do not log tokens, secrets, or personal information. Redact or warn when a user accidentally sends sensitive content.
    6. Block replay and privilege escalation. Verify callback sources, limit request rate, and isolate cache, tasks, and artifacts by tenant.
    7. Keep an auditable trail. Record who started which task, which capability was called, whether it was confirmed, what result was produced, and how long it is retained.

    9. Observability and Quality Evaluation

    A useful agent system is not defined by a successful demo. Measure it continuously:

    • Intake: message volume, deduplication hits, signature failures, callback latency;
    • Routing: intent distribution, rule hit rate, classification confidence, misroute feedback;
    • Execution: task success rate, average duration, timeout rate, cancellation rate, retry count;
    • Cost: model calls, tool calls, resource use, and cost by task type;
    • Security: blocked privilege violations, sensitive-data hits, human confirmation rate, abnormal executions;
    • Experience: time to first response, task-completion notification delivery, and failure complaints.

    Evaluation sets should cover real cases: ordinary Q&A, vague requests, long tasks, timeouts, tool failures, insufficient permissions, repeated sends, concurrent users in a group, and media input. An end-to-end drill with simulated tools and a sandbox before launch is more valuable than testing model answers alone.

    10. Configuration Sketch

    The following is a neutral configuration sketch. It shows routing, model roles, and task confirmation without depending on a specific platform:

    1. gateway:
    2. verify_signature: true
    3. dedupe: enabled
    4. stream_reply: true
    5. router:
    6. rules:
    7. - match: prefix("/review")
    8. target: code_review_agent
    9. - match: prefix("/summarize")
    10. target: fast_summarizer
    11. - match: contains("generate tests")
    12. target: code_agent
    13. fallback: intent_classifier
    14. models:
    15. secretary:
    16. capability: fast_multimodal
    17. timeout: short
    18. purpose: [routing, summary, extraction, short_answer]
    19. deep_worker:
    20. capability: high_reasoning
    21. timeout: long
    22. purpose: [complex_analysis, coding_task]
    23. agents:
    24. code_review_agent:
    25. mode: async
    26. require_confirmation: true
    27. sandbox: strict
    28. code_agent:
    29. mode: async
    30. require_confirmation: true
    31. sandbox: strict
    32. observability:
    33. trace: enabled
    34. audit: enabled
    35. redact_sensitive_data: true

    The configuration itself is not the point. The point is to fix the mechanisms: message governance, intent routing, capability adapters, asynchronous execution, and security audit.

    11. Deployment and Growth

    Early on, do not chase a complex architecture. A single service can own intake, routing, and session management, with the task queue, cache, and object storage as replaceable components. As volume grows, split the integration layer, the scheduler, and the execution worker pool.

    Keep the integration layer as stateless as possible so it can scale horizontally. Store session state, task state, and deduplication records outside the process. Deploy execution agents separately and restrict their permissions. Store artifacts and logs separately.

    If you use Baidu AI Cloud, the modules above can be hosted with general building blocks such as cloud hosts or containers, object storage, logging, and monitoring alerts. Size them from concurrency, message peaks, task duration, artifact size, and compliance needs. The architecture depends on unified intake, routing, and security isolation, not on any one proprietary interface.

    12. Common Pitfalls and an Acceptance Checklist

    Common pitfalls:

    • Messages “get through,” but deduplication and idempotency are missing;
    • Long tasks are waited on synchronously, causing timeouts and duplicate submissions;
    • Chat history is used directly as the coding-task input, without structured constraints;
    • Chat context and execution context are not separated;
    • One high-end model handles every request, ignoring latency and cost;
    • There is no task state machine, so failures cannot be recovered;
    • The execution environment is over-privileged, with no sandbox or human confirmation;
    • Logs store sensitive data, and the audit boundary is unclear;
    • Multiple groups and tenants share one session space, so contexts leak across each other.

    At acceptance, check that:

    • A repeated callback for the same message runs only once;
    • A long task can return asynchronously and report progress;
    • High-risk actions require confirmation;
    • Permissions for different users and groups are isolated;
    • A routing error can be corrected by a person;
    • Execution failures return an actionable reason;
    • Logs are redacted;
    • Adding a capability means adding an adapter, not changing the core path.

    13. Closing

    A lightweight proxy that unifies chat and multiple intelligent capabilities separates the chat entry point from task execution. The integration layer sends and receives messages reliably. The router understands intent. A fast model handles everyday assistant work. A specialized execution agent handles deep tasks. Security and observability keep the system controllable.

    Users then do not need to know how many models or tools sit behind one chat entry. They only state what they need. The team does not maintain a separate account and a pile of configuration for every capability. It evolves the system through shared routing, asynchronous tasks, and audit. Compared with merely “getting it connected,” this design is aimed at staying usable, maintainable, and extensible over time.