AI question and answer streaming content word-by-word rendering method based on dual-state management and control
By using a dual-state control-based AI question-and-answer streaming content word-by-word rendering method, the problems of disordered question-and-answer content and resource leakage in existing technologies are solved. Stable rendering and security control are achieved in multi-concurrency scenarios, and traceable parameter tuning is supported.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-12-29
- Publication Date
- 2026-04-14
AI Technical Summary
In the context of streaming AI-powered question-and-answer sessions on multi-threaded web pages, existing technologies lack full-process state control over individual questions and answers, leading to disordered content order, resource leaks, and security risks. They also fail to establish a configurable and traceable balance between content rhythm, page performance, and security compliance.
A word-by-word rendering method for AI question-and-answer streaming content based on dual-state control is adopted. By generating record identifiers, thinking state containers and answer state containers are constructed. Combined with buffers, rendering rhythm parameters and evidence chain records, the method realizes full set parsing of server-side events by field, semi-package splicing and timed word-by-word rendering.
In scenarios with long-connection streaming and multi-round concurrency, it maintains the consistency of question and answer content order, reduces content loss and duplicate rendering, controls memory usage and rendering load, reduces security risks, and supports retrospective tuning of rule parameters.
Smart Images

Figure CN121858809A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of AI question-answering front-end streaming rendering technology, specifically to a word-by-word rendering method for AI question-answering streaming content based on dual-state control. Background Technology
[0002] With the widespread deployment of large-scale AI question-answering systems on web pages, current mainstream implementations typically employ long-connection-based text stream interfaces, such as server-side event-driven push methods or chunked text stream methods, continuously sending content generated by the backend model to the browser in fragment form. The frontend generally decodes the text in the order the fragments arrive and directly appends it to page nodes, using simple timing mechanisms to simulate word-by-word or line-by-line presentation to enhance the sense of immediacy in the interaction. In these existing solutions, the frontend focuses more on how quickly to display the content pushed by the server, often maintaining only a simple state bound to page nodes, lacking a fine-grained, structured abstraction and traceable description of the entire lifecycle of the question-answering process.
[0003] In real-world deployment scenarios, AI-powered question-and-answer sessions often coexist as multiple parallel conversations on the same page. Server-side output is characterized by uncertain length, overlapping semantic stages (e.g., thinking prompts, formal answers, status information, and termination signals are mixed in the same stream), and significant network quality fluctuations. Current technologies typically render front-ends by directly splicing fragments: the rules for handling partially enclosed characters, out-of-order sequences, repeated fragments, and heartbeat fragments are relatively crude. There's a lack of a unified approach to establishing independent buffers, sequential indexes, and idempotent constraints around each question and answer, which easily leads to problems like content truncation, out-of-order presentation, duplicate rendering, and infinite buffer growth under high concurrency. Simultaneously, the page side often maintains only one layer of visible nodes, carrying both dynamic content from the "thinking stage" and stable content from the "answer stage," lacking layered containers for different stages. This makes it difficult to dynamically adjust the word-by-word rendering rhythm based on browser frame rate, page reflow time, and the length of the rendering queue, resulting in a trade-off between user experience and page performance.
[0004] Furthermore, existing front-end streaming rendering solutions have significant shortcomings in handling complex content formats and abnormal situations. On the one hand, for streaming text containing markup languages, such as question-and-answer content with code block tags, list tags, or rich text tags, existing solutions often immediately convert to page structure upon character arrival, lacking buffering and padding mechanisms for unclosed tags. This can easily lead to frequent reflows, structural errors, and even security risks. Potential script injection and illegal attributes are often handled with simple filtering, lacking evidence chains linked to configuration and rule versions. On the other hand, when faced with illegal encoding, network interruptions, or limited character set support from older browsers, existing solutions typically only retry at the interface layer or interrupt the current session. They lack a tiered degradation and statement-level rendering strategy, as well as unified version management and quantifiable evaluation methods for behaviors such as reconnection counts, buffer shrinkage, and rendering pace tightening.
[0005] In summary, the core deficiency of current technology can be summarized as follows: In streaming scenarios for multi-concurrent web AI question-and-answer sessions, existing front-end rendering technologies lack a state management framework that spans the entire process from data reception, fragment splicing, word-by-word display, content convergence, and resource recycling, all centered around a single question and answer. This framework fails to establish a configurable and traceable balance between content rhythm, page performance, resource consumption, and security compliance. Without resolving this core issue, high-concurrency question-and-answer scenarios are prone to rendering stutters, content misalignment, resource leaks, and unclear security boundaries. Furthermore, it hinders subsequent verification and iterative optimization of parameter versions and rule adjustments based on evidence chains, leaving room for improvement in developing more refined dual-state management and streaming word-by-word rendering solutions. Summary of the Invention
[0006] To address the shortcomings of existing technologies, this invention provides a method for rendering AI question-and-answer streaming content word by word based on dual-state control, in order to solve the problems mentioned in the background.
[0007] To achieve the above objectives, the present invention provides the following technical solution: a method for rendering AI question-and-answer streaming content word by word based on dual-state control, comprising: S1. When a question-and-answer request is received, a record identifier is generated, the corresponding dual-state control object is initialized, a thinking state container and an answer state container are established and bound to a streaming transmission channel. S2. Based on the preset field set, parse the fragment data returned by the server, write the fragments with the same record identifier into the buffer, fill in the half package according to the splicing rules, and output the complete content unit when the cache threshold is exceeded; S3. When outputting content units, the fragments are first written into the virtual node of the thinking state container, and then enqueued word by word according to the rendering rhythm parameters, and then submitted to the visible area of the page according to the timer rhythm. S4. When the end marker is detected, switch the controlled object to the answer state, merge the unpresented content in the thinking state container into the answer state container, and complete the convergence of the question and answer content in this round. S5. When there are multiple record identifiers on the same page, maintain their respective managed objects and timers, clean up the buffer and invalid page nodes according to the timeout threshold, and limit the upper limit of cache capacity. S6. When encountering illegal encoding, unclosed tags, or network interruption during parsing, a degradation strategy is triggered to refresh the content at the statement level and record the sampling results, providing a basis for subsequent adjustments to the rendering rhythm and error handling parameters.
[0008] Furthermore, S1 includes: When receiving an AI-generated question-answering request, the page generates a record identifier based on the session time, page source tag, and random string, and constructs a dual-state management object for the record identifier in local memory; A dual-state management object must include at least a thinking state container, a response state container, rendering pacing parameters, a configuration version number, a sampling flag, and a retry count limit. The front-end constructs a request message based on the Q&A interface contract. The request message carries a record identifier, question content, session context summary and identity token, and establishes a long-connection text stream channel through a persistent connection. The backend distributes events according to record identifiers and sends fragment data with event type field, record identifier field, sequence number field, content fragment field and heartbeat flag field in the event path. The event type field is limited to thinking stage, response stage, status prompt and end mark. At the start of the Q&A session, the front-end and back-end respectively record the configuration version number, record identifier, and time information to form a chain of evidence.
[0009] Furthermore, S2 includes: When the question-and-answer request enters the continuous return phase, the dual-state control object parses the fragments carrying record identifiers one by one according to the complete set of fields, writes the fragments with the same record identifier into the buffer divided by the record identifier, and establishes a sequential number index for each record identifier; When the number of characters reaches a preset threshold, the characters in the buffer arranged by sequential number index are merged into content units. When the boundary of a natural sentence is parsed, the characters in the buffer arranged by sequential number index are merged into content units, and the auto-incrementing number and the set of source fragment numbers are recorded on the content unit. When content units with the same auto-incrementing number are received within a short time window, only the content unit that was last merged is retained. When fragments with duplicate sequential numbers are received within a short time window, the duplicate fragments are discarded. When there are still empty sequential slots at the end of the short time window, the corresponding error number is recorded. Each buffer has a capacity limit. When the capacity reaches the limit, the thinking stage fragments are discarded first and the answer stage fragments are retained to maintain the continuous presentation of the visible area.
[0010] Furthermore, S3 includes: When the front-end dual-state control object obtains a complete content unit in the buffer, the content unit is attached to the virtual node in the thinking state container; The content unit is split into character segments of a predetermined length and written into the character queue to be presented maintained by the virtual node; The timer retrieves character segments sequentially from the head of the character queue to be rendered according to the rendering rhythm parameters, and appends the character segments to the corresponding visible nodes in the response status container.
[0011] Furthermore, the rendering rhythm parameters are dynamically adjusted according to the time interval between the previous round of character segment submissions, the page rendering time after the previous round of character segments are written to visible nodes, and the browser's current frame rate. When the closing and merging conditions are met, the dual-state control object pushes the remaining characters in the virtual node to the visible node of the answer state container within a single timer cycle, and locks the rendering rhythm parameters, the threshold of the character queue to be presented, and the closing and merging conditions by configuring the version number. Write the configuration version number and record identifier to the log.
[0012] Furthermore, S4 includes: When the end marker corresponding to the record identifier is detected based on the event type field, stop writing characters to the thought state container of that record identifier; Traverse the virtual nodes in the thought state container, number them sequentially, and merge them into content units with a set of source fragment numbers; Based on the filtering rules in the configuration version, complete the unclosed tags in the content units and remove fragments containing script tags, and generate security audit logs; Write the content units sequentially into the stable nodes of the response status container, and label them with record identifier, sequence number and configuration version number; Mark the record identifier as the end state and reclaim the corresponding virtual node and buffer resources; When the end marker arrives again, only log entries are appended and no more content units are migrated.
[0013] Furthermore, S5 includes: When there are multiple record identifiers on a single page, the front end maintains a dual-state control object and a timer instance for each record identifier. The resource scheduler allocates the upper limit of buffer capacity, the upper limit of the queue to be rendered, and the upper limit of timer trigger frequency for each record identifier based on the available memory of the page, the parallel rendering capability, and the number of active record identifiers. The resource scheduler monitors the heartbeat flags of each record identifier and will terminate the process if no heartbeat flag is received within a preset time window; Mark the corresponding record identifier as the inactive record identifier, and release the characters in the buffer that have not formed content units in turn; Delete virtual nodes in the thinking state container, reclaim auxiliary nodes in the answering state container, and retain only stable text nodes.
[0014] Furthermore, S6 includes: When a dual-state control object detects illegal encoding during character decoding, it replaces the abnormal byte with a placeholder according to the character mapping rules of the configured version and writes it to a log carrying a record identifier and configuration version number. When an unclosed tag is detected during tag parsing, the rendering mode of the record identifier is switched to a sentence-level strategy, and the content units are written to the answer status container sentence by sentence according to punctuation. When the network is interrupted, reconnection is performed according to the reconnection parameters agreed upon in the configuration version via a timer. If reconnection fails, the record is marked as interrupted, prompt text is inserted into the response status container, and relevant parameters are written into the evidence chain storage.
[0015] Compared with the prior art, the present invention has the following beneficial effects: 1. By generating record identifiers for each question and answer on the front end and constructing a dual-state management object containing a thinking state container, an answer state container, a buffer, and word-by-word rendering rhythm parameters, the server-side event fragments are parsed by field, semi-packaged splicing, content unit merging, and timed word-by-word rendering is performed. This ensures that the question and answer content order remains consistent, the text presentation is continuous and smooth, and content loss, repeated rendering, and page jitter are reduced even in long-connection streaming return and multi-round concurrent scenarios.
[0016] 2. By introducing a resource scheduler on the page side, quota management is implemented for buffers and timers under multiple record identifiers. Combined with illegal encoding replacement, granular rendering of unclosed statements, network interruption reconnection, and evidence chain traceability mechanism composed of configuration version number and sampling flag, memory usage and rendering load can still be controlled, content security risks can be reduced, and the retrospective optimization of rule parameters and problem reproduction can be supported when browser performance is limited or network quality fluctuates. Attached Figure Description
[0017] Figure 1 This is a flowchart illustrating a word-by-word rendering method for AI question-and-answer streaming content based on dual-state control, according to the present invention. Detailed Implementation
[0018] The technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of the present invention, and not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.
[0019] Example: A method for rendering AI question-answering streaming content word by word based on dual-state control, comprising: S1. Upon receiving a question-and-answer request, generate a record identifier, initialize the corresponding dual-state management object, establish a thinking state container and an answer state container, and bind them to a streaming transmission channel. The specific implementation is as follows: In a typical web-based question-and-answer scenario, the front-end runtime environment is a browser page that supports script execution and long-connection text stream decoding, applicable to desktop browsers and mobile terminals with similar capabilities. When an AI-generated question-and-answer request arrives, the page first generates a unique record identifier based on the current session time, the page source marker, and a high-entropy random string. The record identifier refers to a marker string that distinguishes each question-and-answer transaction within the same session. It can be encoded by concatenating the timestamp, source marker, and random string to prevent duplication before the browser is refreshed.
[0020] The frontend constructs a dual-state management object for this record identifier in local memory space. The dual-state management object refers to the aggregate structure used to constrain a single question and answer in the frontend lifecycle. In the main implementation form, it includes at least the following fields: thinking state container, answer state container, rendering rhythm parameters, configuration version number, sampling flag, and retry count limit. The thinking state container refers to the set of hidden nodes that carry the streaming character queue and is used to temporarily store content fragments that have not yet been stably output to the page. The answer state container refers to the set of visible nodes that are finally stably presented to the user and is used to carry the text content after the convergence of this round of question and answer. The rendering rhythm parameters refer to the parameter group that controls the time interval of the word-by-word rendering rhythm and the batch submission scale. The configuration version number refers to the version identifier of the current frontend script and backend service contract. The sampling flag refers to the boolean field that indicates whether this question and answer is included in the performance and experience evaluation. The retry count limit refers to the maximum number of attempts allowed in network reconnection and interface resending scenarios.
[0021] The front-end constructs a request message based on the pre-agreed Q&A interface contract. The request must include at least a record identifier, question content, session context summary, and identity token. A long-connection text stream channel is established using a persistent connection based on the Hypertext Transfer Protocol. In the main implementation, the back-end uses a server-side event push long-connection method to continuously return fragment data. In another implementation, a text stream method based on chunked transmission can be used to achieve continuous return. As long as the record identifier and field meaning remain consistent, it can be considered an alternative implementation.
[0022] After receiving a question-and-answer request, the backend distributes the event according to the record identifier, establishing an independent event path for each question and answer. Each segment sent in the path contains an event type field, a record identifier field, a sequence number field, a content segment field, and a heartbeat flag field. The event type field is limited to four categories in the interface contract: thinking stage, answering stage, status prompt, and end marker, which are used to identify the semantic stage to which the current segment belongs. The record identifier field is used to correspond one-to-one with the frontend dual-state management object. The sequence number field is used to represent the sequential position of the current segment in this round of question and answer. The content segment field is used to carry the text content of this push. The heartbeat flag field is used to mark whether the segment is only used to keep the connection active.
[0023] The Q&A interface locks the set of parameter fields and the default value range at the protocol level. It agrees to return the minimum set of error numbers in three situations: missing parameters, identity verification failure, and temporary service closure. Upon receiving the corresponding error number, the frontend performs a limited number of retry attempts or terminates the current Q&A session. To ensure the traceability of parameter and rule versions, the frontend writes the configuration version number, record identifier, and local time to the behavior log at the start of each Q&A session. The backend synchronously records the same set of identifiers and server-side time. In the preferred implementation, these two logs can be merged into a single evidence chain record, used to lock the field configuration of the dual-state management object and the rule version of the server-side event push when reproducing the current Q&A session.
[0024] The applicable boundaries of this implementation are that the front end needs to have the ability to decode the server-side event push text stream or chunked transmission text stream and drive the timer, and the back end needs to have the ability to split events and generate event fragments according to record identifiers. In another implementation, the front end can also indirectly establish a streaming connection through the gateway component, and the gateway completes the long connection negotiation with the back end. As long as the meaning of the fields of the dual-state control object and the generation caliber of the record identifier are consistent, this method can realize dual-state control and word-by-word rendering of the entire question-and-answer process in the above forms.
[0025] S2. Based on the preset field set, parse the server-returned fragment data, write fragments with the same record identifier into the buffer, pad the incomplete packet according to the splicing rules, and output the complete content unit when the cache threshold is exceeded. The specific implementation is as follows: After the question-and-answer request enters the continuous return phase, the front-end dual-state management object parses each fragment returned by the server via a long connection, based on the complete set of fields locked in the interface contract, and groups fragments with the same record identifier into the corresponding buffer. In this implementation, the buffer is defined as a container of character sequences divided by record identifier, used to store content fragments that have been decoded and partially packaged characters that have not yet been fully assembled; partially packaged characters refer to the beginning and end residual character sequences that failed to form a complete semantic unit in a fragment transmission.
[0026] To constrain the order of fragment combination, a sequential number index is maintained in memory for each record identifier. This index represents a mapping relationship where the sequential number is the key and the fragment's position in the buffer is the value, used to rearrange out-of-order fragments within a short time window. The entire field set includes at least an event type field, a record identifier field, a sequential number field, and a content fragment field. The control logic executes a semi-packet concatenation rule based on the agreed-upon delimiter, event type field, and sequential number: when a fragment only carries an event type field, the event type is written to the status flag corresponding to the current record identifier, and no content is written to the buffer; when a fragment only carries a content fragment field, the content fragment is attached to the most recently valid event type and concatenated with existing characters in the buffer according to the sequential number index; when a fragment carries both an event type field and a content fragment field, the event type status is updated, and the content fragment is written to the buffer according to its sequential number.
[0027] The buffer sets a character count threshold for each record identifier. When the character count is below the threshold, the control logic remains in a temporary state and only updates the half-packet splicing progress. When the character count reaches the threshold or a natural sentence boundary is detected, the characters in the buffer arranged by sequential number index are merged into a complete content unit. A complete content unit refers to a stable text segment that can directly enter the subsequent word-by-word rendering queue. An auto-incrementing number and a set of source segment numbers are recorded on this content unit to support subsequent idempotent strategies and traceability capabilities.
[0028] In this implementation, the idempotency strategy is achieved through both auto-incrementing numbers and the source fragment number set: when a content unit with the same auto-incrementing number is received again within a short time window, the control logic only retains the content unit that was last merged, marking the previous merge result as invalid, thereby avoiding duplicate rendering and duplicate statistics; for fragments with obviously duplicate sequential numbers, the duplicate fragments are directly discarded based on the source fragment number set. The short time window refers to the local observation period set around a certain record identifier, within which out-of-order fragments are allowed to be delayed in completion. Once the sequential gap is not completed after the specified time, the corresponding fragment is considered as ineffective content in this round of session. The dual-state control object records the lost position, record identifier, auto-incrementing number, and preset error number in the log, so as to review network quality and server behavior during subsequent version adjustments.
[0029] To control front-end memory usage, a maximum capacity is set for the buffer corresponding to each record. When the buffer reaches its limit, fragments in the "thinking stage" that have not yet entered the word-by-word rendering queue are prioritized for deletion. These "thinking stage" fragments refer to content fragments whose event type field is "thinking stage" and which have not yet been merged into complete content units. This strategy ensures that "answer stage" fragments are prioritized for retention under resource constraints, avoiding noticeable breaks in the user-visible area. In this implementation, the visible area refers to the set of nodes in the browser page that have been attached to the answer state container. Clearing only content from the buffer that has not entered the visible area reduces the risk of screen flickering.
[0030] This step is applicable in actual production environments to scenarios involving multi-source server event streams and text streams based on chunked transmission. As long as the server can guarantee the monotonicity of the record identifier field and the sequence number field, the front end can restore stable content units through the above buffer mechanism and idempotent strategy, providing continuous text for subsequent word-by-word rendering.
[0031] In a preferred embodiment, the character count threshold can be set to roughly correspond to the number of characters required for several natural sentences, the short time window can be set to the cumulative duration of several heartbeat cycles, and the upper limit of the buffer capacity can be set to the estimated peak capacity of a single session in a high-concurrency scenario. Engineers can optimize the above parameters according to the browser's available memory and network fluctuations to maintain the continuity of content unit generation and the stability of page rendering under high-concurrency access.
[0032] S3. When outputting content units, the fragments are first written to the virtual node of the thinking state container, and then queued word by word according to the rendering rhythm parameters. Finally, they are submitted to the visible area of the page according to the timer rhythm. The specific implementation is as follows: In a typical web page scenario, when a complete content unit is generated in the buffer corresponding to a record identifier, the dual-state management object prioritizes attaching this content unit to a virtual node in the thinking state container, rather than directly writing it to the visible area of the page. A virtual node refers to an intermediate-level node reserved in the document structure. This node does not enter the visible area initially; it is used to carry the queue of characters to be rendered and to track the rendering load of the record identifier in the current session.
[0033] The queue of characters to be presented refers to a sequence of characters arranged in sequential order, describing the range of content that needs to be displayed character by character over a period of time. The rendering cadence parameter describes the maximum number of characters allowed to be pushed to the answer status container per unit time, the timer's trigger period, and the batch size of characters for each trigger; it is the core configuration for controlling the speed of character-by-character display on the front end. The timer refers to a time-driven mechanism that is triggered at fixed intervals in the browser environment; in this method, it is used to drive the character-by-character display operation corresponding to each record identifier.
[0034] In the primary implementation mode, after generating a complete content unit, the dual-state control object splits the content unit into several character segments and writes them sequentially into the character queue to be presented maintained by the virtual node. Based on three dimensions—the time interval of the previous submission action, the rendering time of the page after the character segments were written to the visible node in the previous round, and the current frame rate of the browser—the rendering rhythm parameters are dynamically adjusted: when the length of the character queue to be presented is less than the preset short queue threshold and the browser idle time is higher than the preset level, the rendering rhythm parameters can be set to a smaller character interval and a shorter timer period, so that the user perceives a continuous and smooth character-by-character presentation; when the queue length exceeds the long queue threshold or the page reflow time is detected to be close to the performance boundary, the rendering rhythm parameters are adjusted to a larger character interval and a slightly longer timer period, and some character segments are postponed to a later period for submission to avoid page stuttering caused by a single update.
[0035] Each time the timer is triggered, the dual-state control object takes a small segment of characters from the head of the character queue to be presented maintained by the virtual node, attaches it to the corresponding visible node in the answer state container, and records the sequence number and timestamp of this segment of characters in the attributes of the visible node, so that the display order and rhythm trajectory within the same record identifier can be restored when backtracking is needed later.
[0036] To prevent long content from waiting too long at the end, the dual-state control object preferably sets a closing and merging condition. When an end marker is detected in the event stream corresponding to the record identifier and the number of remaining characters in the virtual node is lower than the closing threshold, the remaining characters are pushed to the corresponding node of the answer state container all at once within a time interval, so that the content can be quickly stabilized at the end.
[0037] The rendering rhythm parameters, queue thresholds, and termination conditions mentioned above are all locked by the configuration version number. The configuration version number is written to the log along with the record identifier at the start of the question and answer session, which is used to form a chain of evidence between the parameter version and the user experience observation results.
[0038] Preferably, in desktop browser scenarios, the timer period can be set to the order of tens of milliseconds, and the number of characters submitted in a single instance can be set to one or more characters. In scenarios where mobile terminal performance is weaker, the timer period and single submission interval can be appropriately increased within the same implementation framework to ensure stable page display even under performance constraints. In the preferred implementation, by comparing the character loss rate, median page reflow time, and user frame rate distribution under different rendering rhythm parameter combinations, a set of parameter combinations that can meet the latency upper limit requirements on most devices can be selected and solidified into a configuration version, thereby making this step replicable and verifiable in actual deployment.
[0039] S4. When the end marker is detected, switch the controlled object to the answer state, merge the unpresented content in the thinking state container into the answer state container, and complete the convergence of the question and answer content in this round. The specific implementation is as follows: In actual web AI question-and-answer scenarios, when the aforementioned dual-state control object is continuously receiving segments, it identifies the end marker corresponding to a certain record identifier based on the event type field, that is, it determines that the current round of question-and-answer content of the record identifier has been sent. At this time, the internal operating mode of the record identifier is switched from the thinking state to the answering state, which is used to consolidate the intermediate content in the thinking state container into a complete text that is stably presented in the answering state container.
[0040] The thinking state container is the aforementioned collection of hidden nodes that carries the queue of characters to be rendered, mainly storing virtual nodes that are still in the process of being rendered word by word; the answer state container is the aforementioned collection of visible nodes that are stably displayed on the page, used to carry text content that has been formatted and security filtered; virtual nodes refer to the intermediate layer nodes in the thinking state container used to cache content units and the queue of characters to be rendered, and they themselves do not directly enter the page viewport.
[0041] After the end marker arrives, the dual-state control object first freezes the rendering rhythm of the thinking state container corresponding to the record identifier, and no longer adds new characters to the queue to be rendered. Then, it traverses the virtual nodes that have not yet entered the visible area in the thinking state container, and merges the characters in each virtual node into content units according to their sequential numbers. A content unit refers to a continuous character segment formed based on the aforementioned buffer and sequential numbering rules. Each content unit has a set of sequential numbers and source segment numbers to maintain idempotency and sequential relationship.
[0042] After the content units are formed, the front end performs a unified cleaning of the content to be migrated to the answer state container according to the filtering rules fixed in the configuration version: For detected unclosed mark fragments, such as code block mark fragments and list mark fragments, they are closed by combining context characters in the thinking state container, so that the migrated content is presented in a structurally complete form in the answer state container, reducing the jitter caused by repeated page layout; For fragments judged by the rules to have script injection risk, such as fragments containing inline script tags and fragments containing event handling attributes, they are escaped, replaced or directly removed according to the constraints in the configuration version. At the same time, a security audit record is generated in the log, and the record identifier, timestamp, configuration version number and filtering result are written into the evidence chain, corresponding to a traceable trajectory of a security decision.
[0043] After the above cleaning is completed, the dual-state control object sequentially writes the content units into newly created stable nodes in the answer state container according to their sequential numbers. Stable nodes refer to node entities that are permanently retained in the answer state container and can be directly rendered by the browser. During the writing process, each stable node is labeled with its corresponding record identifier, sequential number, timestamp, and configuration version number to maintain contextual relationships in subsequent multiple rounds of question and answer. When all content units have been migrated and the answer state container forms a continuous text region, the state of the record identifier is marked as the end state. Only the stable nodes in the answer state container and a few necessary statistical fields, such as total number of characters, rendering start and end time, number of times the filtering rule is hit, and retry count, are retained for subsequent performance evaluation and parameter adjustment. The virtual nodes and buffer resources corresponding to the record identifiers in the thinking state container are marked as recyclable resources and are released uniformly by the resource management module when the conditions are met.
[0044] To ensure idempotency, when network fluctuations cause the end marker of the same record identifier to arrive repeatedly, the dual-state control object makes a judgment based on the record identifier and the end state marker. It only performs the content migration action when the record identifier completes convergence for the first time. Subsequent end markers are only appended to the log record and no longer repeatedly migrate or rewrite the stable nodes in the response state container, thereby avoiding duplicate merging or disordered order of the final state text.
[0045] The aforementioned convergence process requires the front-end environment to have the ability to continuously decode long-connected text streams and rewrite page node attributes, and the back-end environment to ensure the semantic consistency of the end marker and the stability of the event type field values. Preferably, developers can set the target time for detecting convergence completion of the end marker in the configuration version to be on the order of several hundred milliseconds, for example, on the order of three hundred milliseconds; set the target threshold for the filter rule hit rate to be close to the level where all suspicious segments are identified, for example, with a target range of over 90%; and set the upper limit of the retry count for idempotency judgment to a limited number of times, for example, to complete the status consistency confirmation within three attempts. The specific values mentioned above can be obtained through gray-scale testing based on actual terminal performance and business compliance requirements, and then fixed in the configuration version to achieve parameter version locking and long-term traceability in the evidence chain.
[0046] S5. When multiple record identifiers exist on the same page, maintain their respective managed objects and timers, clean up the buffer and invalid page nodes according to the timeout threshold, and limit the upper limit of cache capacity. The specific implementation is as follows: Based on the aforementioned steps, when multiple record identifiers are used for parallel question and answer within a single page, the front end maintains an independent dual-state management object and timer instance for each record identifier, and coordinates them uniformly through an integrated resource scheduler.
[0047] The resource scheduler refers to the resource management module deployed in the front-end script. It is used to allocate and dynamically adjust the upper limit of the buffer capacity of each record identifier, the upper limit of the queue length to be rendered in the thinking state container, and the upper limit of the timer trigger frequency based on the available memory of the page, the parallel rendering capability supported by the browsing environment, and the number of currently active record identifiers. This ensures that the page maintains acceptable latency and stability in high-concurrency question-and-answer scenarios.
[0048] In this step, the buffer still refers to the character sequence container divided by record identifiers and used to temporarily store fragment characters and content units. The queue to be rendered refers to the set of characters in the thinking state container that have not yet been pushed to the answer state container. The resource scheduler monitors the current occupancy ratio and queue length of each buffer. When a record identifier does not receive a fragment with a heartbeat flag within a specified time window, the record identifier is marked as an inactive record identifier, and cleanup operations are performed in sequence: first, the characters in its buffer that have not formed content units are released, then the corresponding virtual nodes are deleted from the thinking state container, and finally the auxiliary nodes used to temporarily mark the state in the answer state container are reclaimed. Only text nodes that have been stably written to disk and have reading value are retained to reduce the front-end memory and reflow burden.
[0049] The heartbeat flag here refers to a specific marker field used to indicate that the server connection is still active. Its occurrence frequency and time interval are uniformly agreed upon by the interface contract. Preferably, a consecutive absence of several heartbeat flags can be set as a deactivation criterion. For record identifiers that have already converged, when the visible node corresponding to the response state container moves out of the viewport with page scrolling and remains invisible for a preset duration, the resource scheduler allows for morphological degradation of the node, compressing the rich text structure into a simplified plain text form, retaining only necessary paragraph and sequence marker fields to reduce subsequent rendering and layout overhead.
[0050] To avoid contention for rendering capabilities among multiple record identifiers, the resource scheduler only allows timer instances, not exceeding the quota, to be active within any given time slice. The remaining timer instances are suspended and woken up in a round-robin fashion by the scheduler based on factors such as the record identifier's creation time, the remaining length of the rendering queue, and the current page interaction load. This limits instantaneous rendering concurrency and controls the overall refresh rate. In scenarios with dense cross-session questioning, the resource scheduler can also establish a global index based on record identifiers and sequence numbers to identify questions with highly similar content within a short time window. Multiple repeated questions and answers are merged into a single valid record identifier. A deduplication strategy is applied to the dual-state management objects corresponding to previous record identifiers, retaining only the answer state container node corresponding to the latest question and answer. Historical nodes are downgraded to read-only digests and their relationships are registered in the log.
[0051] Preferably, the upper limit of buffer capacity, the inactivation determination time window, the timer concurrency quota, and the invisible duration required for downgrading to plain text can be uniformly managed through configuration versions, and the version number, record identifier, and resource reclamation event are written into the log to form an evidence chain for resource allocation and deduplication strategies, providing a basis for adjusting the threshold in different terminal environments, and making this step reproducible in desktop browsers, mobile embedded containers, and embedded terminals.
[0052] S6. When encountering illegal encoding, unclosed tags, or network interruptions during parsing, a degradation strategy is triggered. Content is refreshed at the statement level, and sampling results are recorded. This provides a basis for subsequent adjustments to the rendering rhythm and error handling parameters. Specifically, the implementation is as follows: When the dual-state managed object encounters unexpected situations such as illegal encoding, unclosed tags, or network interruptions during character decoding and tag parsing, a tiered degradation strategy is triggered according to the pre-locked configuration version. This ensures that the question-and-answer session maintains readable word-by-word rendering capability on the front end and leaves complete evidence for subsequent parameter tuning. Illegal encoding here refers to byte sequences that cannot be mapped to valid characters when decoded according to the agreed character set. The character mapping rule refers to the pre-agreed "byte-to-placeholder" correspondence in the configuration version. Placeholders refer to substitute characters that occupy a fixed width on the page and do not carry business meaning, used to indicate missing content without affecting subsequent text rendering.
[0053] In real-world web page scenarios, when the front-end detects illegal encoding in a streaming segment of a record identifier, it prioritizes replacing the corresponding position with a placeholder according to the character mapping rules. Simultaneously, it writes the encoding information of the original byte sequence, the occurrence position, and the current configuration version number into the log entry of that record identifier, and sets the sampling flag of that record identifier to a pending analysis state. If a large number of illegal encodings continuously appear for the same record identifier within a certain observation window (an observation window is a sliding window based on time), the control logic will mark that record identifier as a high-risk session. In subsequent segment reception stages, it will proactively tighten its buffer capacity limit and rendering rhythm parameters, increase the word-by-word rendering interval, and shorten the total reconnection attempt time to reduce the consumption of browser resources.
[0054] For cases where the markers are not closed, an unclosed marker refers to a text paragraph in which the paired boundary markers detected in the thinking state container do not have a closing marker within a reasonable character range. If the dual-state control object does not capture the corresponding closing position in the set observation window, it will switch the rendering mode of the current record marker from the per-byte queue strategy to the sentence granular strategy. The sentence granular strategy means that the content unit is divided into a series of sentences according to the natural tone boundaries such as periods and question marks, and then written into the answer state container sentence by sentence. In this mode, the front end prioritizes ensuring that the paragraphs that have been closed form a relatively stable area in the answer state container, and appropriately fills in or truncates suspected unclosed segments, thereby reducing repeated page reflows and maintaining the overall reading continuity.
[0055] In a network interruption scenario, a network interruption refers to the failure to receive a heartbeat flag multiple times on a long connection channel, and the underlying connection status being determined as disconnected by the browser. The frontend initiates multiple rounds of reconnection attempts for the current record identifier through a timer, according to the reconnection count and backoff interval agreed in the configuration version. The backoff interval refers to the gradually increasing waiting time between each reconnection. When all reconnection attempts fail, the dual-state management object updates the internal state of the record identifier to the interrupted state, appends a prompt text to the answer state container, indicating that this round of question and answer has not been completed completely, and writes the number of reconnection attempts, the sequence number of the last successful segment, the current rendering rhythm parameters, and the sampling marker to the log for subsequent statistical analysis.
[0056] To quantify the impact of the aforementioned degradation strategy on page performance, after the system goes live or the rules are adjusted, multiple batches of user access can be simulated through an automated program. While maintaining the basic consistency between the backend model and the question set, observation indicators such as the first character presentation time, the entire completion time, the number of repeated requests, the average memory usage, and the number of times suspected script fragments were intercepted are collected for each record. These are then compared and evaluated in conjunction with the number of samplings and confidence intervals. The comparison results, along with the corresponding configuration version number, rule change description, and sampling markers, are written into the evidence chain storage. The evidence chain storage refers to a persistent space used to store parameter versions, observation indicators, and log fragments for long-term preservation, facilitating the restoration of the parameter combinations and degradation behaviors at the time when retracing a specific session.
[0057] Preferably, under a set of representative working conditions, the character-by-character rendering rhythm can be set to an interval of several tens of milliseconds between each character, the upper limit of the buffer capacity of a single record identifier can be set to several thousand characters, the number of reconnections can be set to several times, and the number of record identifiers that are active on a single page at the same time can be limited to a few dozen. In another alternative approach, while keeping the dual-state control, idempotent strategy, order constraint and deduplication strategy unchanged, the statement granularity strategy can be extended to a word-granularity strategy. That is, in the thinking state container, the characters are first divided into word sequences based on the local dictionary, and then the timer is driven to advance the rendering to the answer state container according to the word sequence. As long as version locking and evidence chain traceability are still performed through record identifiers, configuration version numbers and sampling tags, those skilled in the art can complete the engineering deployment and parameter adjustment for specific web page scenarios based on the above disclosure.
[0058] The above description is merely a specific embodiment of this application, but the scope of protection of this application is not limited thereto. Any variations or substitutions that can be easily conceived by those skilled in the art within the scope of the technology disclosed in this application should be included within the scope of protection of this application. Therefore, the scope of protection of this application should be determined by the scope of the claims.
Claims
1. A method for rendering AI question-and-answer streaming content word by word based on dual-state control, characterized in that, include: S1. When a question-and-answer request is received, a record identifier is generated, the corresponding dual-state control object is initialized, a thinking state container and an answer state container are established and bound to a streaming transmission channel. S2. Based on the preset field set, parse the fragment data returned by the server, write the fragments with the same record identifier into the buffer, fill in the half package according to the splicing rules, and output the complete content unit when the cache threshold is exceeded; S3. When outputting content units, the fragments are first written into the virtual node of the thinking state container, and then enqueued word by word according to the rendering rhythm parameters, and then submitted to the visible area of the page according to the timer rhythm. S4. When the end marker is detected, switch the controlled object to the answer state, merge the unpresented content in the thinking state container into the answer state container, and complete the convergence of the question and answer content in this round. S5. When there are multiple record identifiers on the same page, maintain their respective managed objects and timers, clean up the buffer and invalid page nodes according to the timeout threshold, and limit the upper limit of cache capacity. S6. When encountering illegal encoding, unclosed tags, or network interruption during parsing, a degradation strategy is triggered to refresh the content at the statement level and record the sampling results, providing a basis for subsequent adjustments to the rendering rhythm and error handling parameters.
2. The method for rendering AI question-answering streaming content word by word based on dual-state control as described in claim 1, characterized in that, S1 includes: When receiving an AI-generated question-answering request, the page generates a record identifier based on the session time, page source tag, and random string, and constructs a dual-state management object for the record identifier in local memory; A dual-state management object must include at least a thinking state container, a response state container, rendering pacing parameters, a configuration version number, a sampling flag, and a retry count limit. The front-end constructs a request message based on the Q&A interface contract. The request message carries a record identifier, question content, session context summary and identity token, and establishes a long-connection text stream channel through a persistent connection. The backend distributes events according to record identifiers and sends fragment data with event type field, record identifier field, sequence number field, content fragment field and heartbeat flag field in the event path. The event type field is limited to thinking stage, response stage, status prompt and end mark. At the start of the Q&A session, the front-end and back-end respectively record the configuration version number, record identifier, and time information to form a chain of evidence.
3. The method for rendering AI question-answering streaming content word by word based on dual-state control according to claim 1, characterized in that, S2 include: When the question-and-answer request enters the continuous return phase, the dual-state control object parses the fragments carrying record identifiers one by one according to the complete set of fields, writes the fragments with the same record identifier into the buffer divided by the record identifier, and establishes a sequential number index for each record identifier; When the number of characters reaches a preset threshold, the characters in the buffer arranged by sequential number index are merged into content units. When the boundary of a natural sentence is parsed, the characters in the buffer arranged by sequential number index are merged into content units, and the auto-incrementing number and the set of source fragment numbers are recorded on the content unit. When content units with the same auto-incrementing number are received within a short time window, only the content unit that was last merged is retained. When fragments with duplicate sequential numbers are received within a short time window, the duplicate fragments are discarded. When there are still empty sequential slots at the end of the short time window, the corresponding error number is recorded. Each buffer has a capacity limit. When the capacity reaches the limit, the thinking stage fragments are discarded first and the answer stage fragments are retained to maintain the continuous presentation of the visible area.
4. The AI question-answering streaming content word-by-word rendering method based on dual-state control according to claim 1, characterized in that, S3 include: When the front-end dual-state control object obtains a complete content unit in the buffer, the content unit is attached to the virtual node in the thinking state container; The content unit is split into character segments of a predetermined length and written into the character queue to be presented maintained by the virtual node; The timer retrieves character segments sequentially from the head of the character queue to be rendered according to the rendering rhythm parameters, and appends the character segments to the corresponding visible nodes in the response status container.
5. The method for rendering AI question-answering streaming content word by word based on dual-state control according to claim 4, characterized in that: The rendering rhythm parameters are dynamically adjusted based on the time interval between the previous round of character segment submissions, the page rendering time after the previous round of character segments are written to visible nodes, and the browser's current frame rate. When the closing and merging conditions are met, the dual-state control object pushes the remaining characters in the virtual node to the visible node of the answer state container within a single timer cycle, and locks the rendering rhythm parameters, the threshold of the character queue to be presented, and the closing and merging conditions by configuring the version number. Write the configuration version number and record identifier to the log.
6. The method for rendering AI question-answering streaming content word by word based on dual-state control according to claim 1, characterized in that, S4 includes: When the end marker corresponding to the record identifier is detected based on the event type field, stop writing characters to the thought state container of that record identifier; Traverse the virtual nodes in the thought state container, number them sequentially, and merge them into content units with a set of source fragment numbers; Based on the filtering rules in the configuration version, complete the unclosed tags in the content units and remove fragments containing script tags, and generate security audit logs; Write the content units sequentially into the stable nodes of the response status container, and label them with record identifier, sequence number and configuration version number; Mark the record identifier as the end state and reclaim the corresponding virtual node and buffer resources; When the end marker arrives again, only log entries are appended and no more content units are migrated.
7. The AI question-answering streaming content word-by-word rendering method based on dual-state control according to claim 1, characterized in that, S5 include: When there are multiple record identifiers on a single page, the front end maintains a dual-state control object and a timer instance for each record identifier. The resource scheduler allocates the upper limit of buffer capacity, the upper limit of the queue to be rendered, and the upper limit of timer trigger frequency for each record identifier based on the available memory of the page, the parallel rendering capability, and the number of active record identifiers. The resource scheduler monitors the heartbeat flags of each record identifier and will terminate the process if no heartbeat flag is received within a preset time window; Mark the corresponding record identifier as the inactive record identifier, and release the characters in the buffer that have not formed content units in turn; Delete virtual nodes in the thinking state container, reclaim auxiliary nodes in the answering state container, and retain only stable text nodes.
8. The AI question-answering streaming content word-by-word rendering method based on dual-state control according to claim 1, characterized in that, S6 include: When a dual-state control object detects illegal encoding during character decoding, it replaces the abnormal byte with a placeholder according to the character mapping rules of the configured version and writes it to a log carrying a record identifier and configuration version number. When an unclosed tag is detected during tag parsing, the rendering mode of the record identifier is switched to a sentence-level strategy, and the content units are written to the answer status container sentence by sentence according to punctuation. When the network is interrupted, reconnection is performed according to the reconnection parameters agreed upon in the configuration version via a timer. If reconnection fails, the record is marked as interrupted, prompt text is inserted into the response status container, and relevant parameters are written into the evidence chain storage.