Troubleshooting Unexpected Strings and Repetitive LLM Responses

    Learn how to diagnose unexpected control tokens, garbled characters, and looping responses in LLM applications. This guide covers browser-based chat, local inference, and API deployments, with checks for decoding, encoding, model files, chat templates, sampling settings, context management, and service-layer retries.

    LLM output quality directly affects usability in question answering, operations support, and knowledge retrieval. Two common failure patterns are:

    • Unexpected strings: Responses contain control tokens, escape sequences, square replacement characters, or unusual code-like fragments.
    • Repetitive responses: The model repeats the same sentence or paragraph in a loop.

    These problems can occur together, but they may originate in different layers of the application. Start by distinguishing browser-based chat issues from local inference or API issues. Then investigate decoding, character encoding, model files, chat templates, sampling settings, context management, and service-layer retries.

    1. Unexpected Strings and Control Tokens

    1.1 Browser-Based Chat Applications

    An online chat application typically consists of a frontend, a backend inference API, and a model inference engine. Unexpected strings displayed to users are not necessarily generated as ordinary response text. They may reflect unfiltered control tokens, rendering problems, or an overloaded conversation context.

    Unfiltered inference control tokens

    LLMs often use special tokens to mark role boundaries, delimit reasoning blocks, or represent padding during training and inference. Normally, the backend or frontend removes these tokens before displaying a response.

    If this processing fails, internal markers may appear as angle-bracketed strings, unusual code-like sequences, or invisible characters.

    Browser encoding or cache problems

    If the page does not interpret responses with consistent character encoding, some characters may appear as replacement symbols, squares, or unresolved Unicode escape sequences.

    A corrupted or outdated cache can also cause frontend scripts to become incompatible with a newer API response format, breaking token-filtering logic.

    Overloaded conversation context

    Long conversation histories can exhaust the available context window and disrupt generation. In some cases, internal role delimiters may appear in the response. Starting a new conversation can provide a quick way to test whether accumulated context is involved.

    1. Clear the conversation history and start a new session to rule out context contamination.
    2. Clear the browser cache, try private browsing mode, or test another major browser.
    3. Add a prompt constraint such as: “Return plain text only. Do not include control tokens, special symbols, or escape sequences.”
    4. If the problem persists, apply consistent control-token cleanup on the server before returning responses, with secondary filtering and fallback handling for abnormal characters in the frontend.

    1.2 Local Inference, API Calls, and Private Deployments

    In local inference and API-based deployments, unexpected strings are often associated with decoding options, model-file integrity, transport encoding, or chat-template configuration.

    Special tokens are not skipped during decoding

    When generated token IDs are decoded into text, special tokens should be explicitly skipped. Otherwise, role delimiters, padding tokens, and other internal markers may be printed directly.

    Enable the decoder’s option to skip special tokens, and add server-side output cleanup where necessary.

    Model files are damaged or incomplete

    Missing shards, corrupted weights, or incompatible versions can cause abnormal output, including garbled text, in quantized-model deployments.

    Download the complete model again, verify file hashes, and confirm that the inference engine supports the model format.

    Inconsistent transport encoding

    Incorrect response encoding or unintended transcoding by an intermediary proxy can leave text corrupted or escape sequences improperly displayed.

    Use consistent encoding across requests and responses, set Content-Type: application/json; charset=utf-8, and inspect gateway, proxy, and client-side parsing behavior.

    Missing or incompatible chat templates

    If messages are not formatted according to the model’s expected chat template, internal markers may leak into the response.

    Use the official template or a compatible standard template rather than an incomplete custom format. Clearly define system, user, and assistant role boundaries.

    The following pseudocode illustrates generation and output processing:

    1. ids = model.generate(
    2. prompt,
    3. temperature=0.7,
    4. top_p=0.9,
    5. repetition_penalty=1.35,
    6. max_new_tokens=512,
    7. presence_penalty=0.6
    8. )
    9. text = decode(ids, skip_special_tokens=True)
    10. text = sanitize_output(text) # Filter control tokens, abnormal escapes, and repeated segments

    2. Repetitive Responses and Generation Loops

    2.1 Sampling Configuration

    Sampling settings are a common contributor to repetitive output:

    • Temperature too low: Generation becomes highly conservative and may repeatedly select common words or phrases.
    • top_p too low: A narrow candidate-token pool can encourage repeated token choices.
    • No repetition penalty: Previously generated content receives no explicit repetition-based penalty.
    • Excessive max_new_tokens: A large generation allowance can let a response continue into repetition after useful content has been exhausted.
    • Insufficient presence_penalty: The configuration may provide too little encouragement to introduce new content.

    For general question answering and technical operations support, the following values can serve as an initial baseline:

    Parameter Starting value
    temperature 0.7
    top_p 0.9
    repetition_penalty 1.3–1.4
    max_new_tokens 512
    presence_penalty 0.6

    Technical documentation tasks may need a higher output limit, but it should not be unnecessarily large. These settings are a starting point, not a universal solution. Tune them for the task and use logs to track repetition and truncation rates.

    2.2 Context Limits and Contaminated History

    Context-window pressure can contribute to both unexpected strings and repetitive generation. Repeated questions, conflicting instructions, or earlier malformed responses in the conversation history may reinforce an unwanted pattern.

    To address this:

    • Limit the number of retained conversation turns.
    • Use a sliding window, summarized history, or segmented processing.
    • Deduplicate repeated inputs.
    • Keep system instructions distinct from the current task.
    • Remove conflicting instructions and abnormal outputs from retained history.

    2.3 Prompt and Task Design

    Open-ended prompts without stopping conditions, output structure, or length constraints can encourage repetitive elaboration.

    Specify requirements such as:

    Answer in bullet points. State each point only once. Do not repeat content. Stop after presenting the conclusion.

    For long-document tasks, summarize individual sections before producing a combined summary. For reasoning-oriented tasks, request only the final conclusion and the supporting rationale needed to understand it, rather than unnecessary elaboration.

    2.4 Service-Layer Retries and Streaming

    Repeated text does not always originate in model generation. Streaming, connection retries, proxy caches, and concurrent request queues can introduce duplicate segments.

    For example, after a streaming connection fails, a retry may append content that was already delivered if retry handling is not idempotent. A malfunctioning proxy cache may also return an earlier segment again.

    Recommended safeguards include:

    • Idempotent retry handling.
    • Output deduplication.
    • Validation when resuming interrupted streams.
    • Gateway logs containing request identifiers and output-segment sequence numbers.

    3. A Layered Troubleshooting Workflow

    Use a consistent sequence to isolate the source of the problem.

    Step 1: Identify where the issue appears

    Determine whether the anomaly is visible only in the browser or is also present in the API response. This helps distinguish display problems from backend or inference problems.

    Step 2: Inspect the raw response

    Check whether the response already contains control tokens, garbled text, or repeated segments before frontend rendering.

    Step 3: Validate decoding and deployment configuration

    Review:

    • Special-token handling during decoding.
    • Response encoding headers and intermediary transcoding.
    • Model-file hashes and version compatibility.
    • Chat-template completeness and role boundaries.

    Step 4: Review generation and context settings

    Inspect sampling parameters, output limits, conversation length, repeated inputs, and conflicting instructions.

    Step 5: Check service-layer behavior

    Investigate retries, stream reconnection, proxy caching, and duplicate segment assembly.

    Step 6: Monitor output quality continuously

    Useful metrics include:

    • Special-token occurrence rate.
    • Repeated n-gram ratio.
    • Output truncation rate.
    • Average output length.

    For inference services running on Baidu AI Cloud, general-purpose logging, monitoring and alerting, and object storage can support ongoing observation of abnormal output, along with hash verification and version management for model files.

    Conclusion

    Unexpected strings and repetitive responses rarely have a single universal cause. Effective prevention combines display-layer filtering, server-side cleanup, special-token skipping during decoding, consistent encoding, compatible chat templates, tuned generation parameters, controlled conversation history, and idempotent retries.

    A layered approach makes failures easier to reproduce, observe, and verify through regression testing while reducing the likelihood that malformed or duplicated output reaches users.