Migrating Long Conversations to APIs and Open-Source Frontends When Context Limits Hit

    This article explains why long-context conversations hit platform limits, separating attention compute growth from KV cache memory pressure. It also examines frontend quota displays versus server-side enforcement, discusses API-based capabilities, outlines security boundaries for calling APIs directly from open-source frontends, and provides a checklist for exporting and migrating conversation history.

    1. Why Long Conversations Become Limited

    Recently, some users have reported prompts in mobile LLM applications such as: “Due to insufficient compute, long conversations that have exceeded 72 hours are temporarily unavailable; you can export the conversation to another app,” “Content is too long; please delete some content and try again,” and “The number of input edits exceeds the limit.” Developers have tested that a single session can trigger limits at about 148,000 Chinese characters, equivalent to hundreds of thousands of tokens. These figures come from individual tests. Thresholds may differ across models, versions, and plans, so readers should rely on the rules published by the platform.

    Long-conversation limits are not unique to any single application. The longer the context a model processes, the more compute and GPU memory each request consumes. Providers need to serve many users from a limited compute pool, so they use rate limiting, degradation, or caps to maintain overall availability.

    2. Technical Reasons Behind the Limits

    1. Different Growth Patterns for Compute and Memory

    Many articles conflate the compute cost of attention mechanisms with memory usage. These need to be examined separately.

    In the self-attention layers of a Transformer, compute grows roughly quadratically with sequence length. When the model processes the entire input during the prefill stage, it needs to calculate attention scores between every pair of tokens. Therefore, the longer the input, the faster the compute time grows.

    The main source of memory usage is the KV Cache. When the model generates each new token, it needs to read the Key and Value of all previous tokens. To avoid recomputation, the inference system stores them in GPU memory. The size of the KV Cache is approximately:

    2 × layers × KV heads × head dimension × sequence length × bytes per value

    Within a single request, the KV Cache grows linearly with sequence length. The actual size also depends on the model’s number of layers, number of heads, dimensions, and numerical precision, such as FP16 or INT8.

    The long-session problem mainly appears in concurrent scenarios. A single session’s cache may occupy only a small portion of GPU memory, but when many long sessions exist at the same time, their caches accumulate and squeeze available memory. New requests can only queue, and in extreme cases out-of-memory (OOM) errors occur. Providers therefore usually combine paged caching, request scheduling, and concurrency caps to manage memory.

    2. 72-Hour Expiry and Message Caps: Product Strategy, Not Direct Causality

    The 72-hour session expiry and per-session message cap mentioned at the beginning are not directly caused by GPU memory OOM. They are closer to product and cost policies. For example, sessions that remain inactive for a long time may no longer need to retain the full context, which reduces storage and cache costs. A message cap can control the input size of a single request and reduce abuse risk. The platform’s true motivation cannot be judged solely from interface copy, and this article does not make such an assertion.

    To determine which category a limit belongs to, look at the layer where it applies: memory for a single request, quota for a single user, or the concurrency pool for the entire service. The solutions for these three are different.

    3. Frontend Quota Display Is Not a Server-Side Limit

    Some developers have found quota management logic in frontend code. A common implementation works as follows: while the page is visible, it queries the backend for remaining quota every 5 minutes; when the quota reaches zero, it displays a banner and disables the input box.

    1. // Illustrative code: frontend quota status polling
    2. setInterval(async () => {
    3. if (document.visibilityState === 'visible') {
    4. const response = await fetch('/api/v1/quota/status');
    5. const { remaining } = await response.json();
    6. if (remaining <= 0) {
    7. showQuotaBanner('Usage quota reached. Please try again later.');
    8. disableInputBox();
    9. }
    10. }
    11. }, 5 * 60 * 1000);

    This design has two benefits. Periodic polling consumes fewer server resources than a WebSocket long connection, and the frontend prompt gives users advance warning.

    However, frontend code can only determine what the interface displays. Anyone can bypass the interface and call the API directly, so actual quota validation must be performed on the server. If quota is checked only on the frontend, the limit is effectively meaningless. In addition, a 5-minute polling interval means the interface state may lag. For several minutes after the quota is exhausted, requests may still be sent successfully.

    4. Capabilities as APIs and Exporting Conversation History

    Some platforms have begun to expose in-app capabilities as APIs, such as web search, file input, link reading, and voice. Developers can use these interfaces to build Agent workflows or their own applications. This approach extends the platform’s role from a standalone chat application toward an infrastructure service.

    Before integration, check the key information in the following table:

    Check item What to confirm
    Authentication method How keys are generated, their validity period, and permission scope
    Rate limits and quotas Requests per minute, concurrency, and behavior after exceeding the limit
    Billing rules Whether billing is per token, per call, or per capability
    Applicable boundaries Whether streaming output is supported, and limits on file size, audio duration, and similar factors
    Error handling Meaning of error codes and recommended retry strategies

    Specific parameters should follow the platform’s official documentation. This article does not list specific values to avoid content becoming outdated as versions change.

    5. Security Boundaries for Open-Source Frontends Calling APIs Directly

    Some platforms have open-sourced MIT-licensed chat frontend demos. Users can configure the frontend locally or enter their own API key in the browser, and the frontend calls the model API directly. The following code only illustrates the call flow and must not be used directly in production:

    1. // Illustrative code. Do not use directly in production.
    2. async function streamChat(messages) {
    3. const apiKey = localStorage.getItem('USER_API_KEY');
    4. const response = await fetch('https://api.example.com/v1/chat/completions', {
    5. method: 'POST',
    6. headers: {
    7. 'Content-Type': 'application/json',
    8. 'Authorization': `Bearer ${apiKey}`
    9. },
    10. body: JSON.stringify({
    11. model: '<replace with an available model name from the platform documentation>',
    12. messages: messages,
    13. stream: true
    14. })
    15. });
    16. // Parse each data: line chunk by chunk in SSE format, and stop when [DONE] is received.
    17. }

    Pure frontend calls need to handle the following prerequisites and risks:

    1. CORS: The API must allow access from the page origin; otherwise, the browser will block the request.
    2. Key exposure: A key stored in localStorage can be read by page scripts. If the page has an XSS vulnerability, the key may leak.
    3. Permission scope: Set minimal permissions for keys used by the frontend and rotate them regularly.
    4. Proxy approach: When possible, use your own backend or proxy to forward requests, and use short-lived tokens instead of long-lived keys.
    5. Streaming parsing: Handle truncated data chunks, correctly identify the end marker, and retry or notify the user on network errors.
    6. Model availability: Model names change across versions and should be obtained from the official documentation or the model list API.

    6. Conversation History Migration Checklist

    Open-source frontends support importing conversation history from the platform. Exported data is usually in JSON format and includes role, timestamp, and content. An example is shown below:

    1. [
    2. {"role": "user", "content": "Previous discussion...", "timestamp": "2023-11-12T10:00:00Z"},
    3. {"role": "assistant", "content": "Based on your requirements...", "timestamp": "2023-11-12T10:00:05Z"}
    4. ]

    Before migration, check the following:

    • Field completeness: Are role, content, and timestamp all present?
    • Timestamp time zone: Use ISO 8601 format with a time zone consistently to avoid cross-time-zone misalignment.
    • Role mapping: Confirm that the exported roles are mapped consistently to the conversation format expected by the target frontend.