3. Methodology
This section explains the methodological framework used in the proposed SRS generating strategy. The process begins with data collection and preparation, followed by topic classification, skeleton document generation, response generation, and reinforcement learning-based refinement. Each stage is designed to transform unstructured user requirements into an SRS document that is organized and semantically aligned while adhering to the target document format. In order to provide reliable, reproducible, and context-aware document generation, the methodology also includes evaluation and quality improvement steps.
Reproducibility means that initially the SRS will be developed from the input of stakeholders. However, improvements provided by the user, analyst, or any other stakeholder can also expand or improve the document in a structurally deterministic way. In short, the stakeholder will use this framework, which uses LLMs, and additional input from any stakeholders can address document improvement through the proposed framework.
3.2. Proposed Framework
Large language models are used in this proposed systematic approach to address the challenges of consistency and validity in document generation. This approach combines the strengths of fine-tuning and few-shot learning while reducing their drawbacks to produce valid documents with the required structure.
Sentence embedding, clustering, topic-based chunking, skeleton document generation, missing-node expansion, and incremental document expansion are all parts of the proposed methodology pipelines. First, a sentence embedding model is used to transform each requirement sentence into a vector representation. Next, requirement sentences that are semantically similar are grouped using clustering. Each cluster represents a topic-level group that may correspond to an SRS section or subsection. Topic-based chunking is performed by assigning each requirement sentence to the most relevant cluster. The SRS skeleton is then constructed using these topic-based chunks, and the system places new or modified requirements into the appropriate document section. The proposed framework has three stages: Topic Classification, Skeleton Document Generation, and Incremental Document Expansion as shown in
Figure 2.
3.2.1. Topic Classification
Topic classification is first performed to classify the input document into different topic-based chunks. In this step, requirement sentences are first converted into embeddings, and clustering is applied to group semantically similar sentences. Each cluster represents a topic or candidate SRS section. Topic-based chunking then places each requirement sentence into the most relevant cluster. This process extracts general and key information from the document. The information contained in a topic-based chunk may overlap with other chunks, and these chunks represent the different sections of the generated document. This classification step structures the content and preserves structural consistency when using LLMs with unstructured input.
Topic-based chunking is a technique used in [
33] to break down long texts into manageable chunks based on their semantic relevance, as shown in
Figure 3.
It begins by sequentially building sentence-level blocks within provided lengths and representing them as nodes in a graph. The text is parsed into different sentences or sub-sentences based on punctuation marks, and these sentence-level blocks are filled until they exceed a certain length before moving on to the next block [
33]. Once the sentence-level blocks are obtained, they are connected in a graph representation of the long text based on a pre-trained sentence embedding model, such as Mini-LLM. The weight representing the semantic similarity between the i-th and j-th sentence-level chunks is calculated using cosine similarity, which calculates the cosine of the angle between two embeddings. A greater degree of resemblance between two chunks suggests that they are closer in topic [
33]. Clustering algorithms are then applied to the graph to identify the underlying topic structure. Within each cluster, the sentence-level blocks are grouped sequentially to obtain the topic-based chunks [
33]. The purpose of clustering is to group related requirement sentences so that each topic-based chunk can be mapped to the appropriate SRS section.
The Topics Table is a simple registry of unique SRS section identities. It is constructed by traversing the hierarchical JSON representation of each SRS document in the corpus. Each section is stored using a canonical section identifier based on the IEEE-style decimal numbering scheme. During inference, this table is merged with a predefined IEEE 830 -based SRS skeleton, which provides fallback section titles for sections that are not present in the training corpus. The final output of the system is a structured SRS document, not a ranked list of retrieved chunks.
This study uses the Topic-based chunking technique to embed requirement sentences in the embedding space using a sentence embedding model. Clustering algorithms are applied to cluster embeddings of sentences. These clusters represent the sections and sub-sections of the document. The sentences within each cluster are grouped together to form a topic-based chunk.
Figure 3 shows the Topic-based chunking, and the colors represent the different topic-based chunks. For K-Means clustering, the value of
k is selected dynamically. In this study,
k is set as the smaller value between the number of query chunks and 7. This ensures that the number of clusters does not exceed the number of available chunks, which is required for K-Means. The upper limit of 7 is used to keep the topic groups close to the main requirement intents and the common high-level organization of SRS documents. This setting prevents repeated K-Means iterations during inference while making the Topic Classification step more efficient for document generation.
In this research, clustering is used as an initial organization stage rather than the only option for final section placement. This is important because some requirements can be ambiguous in a particular domain and appear semantically close to more than one topic. After clustering, the topic-based chunk is compared with the Topics Table, and during expansion, supporting information is extracted from relevant section samples and document context. This helps mitigate the effects of imperfect clustering because the final generated section is determined by the cluster, the predetermined structure of the SRS section, and the contextual information obtained. Additionally, domain-specific examples can be used to improve the sentence embedding model in order to better accurately represent specialized terms.
The Topic-based chunk contains all the sentences in its cluster and the embedding, which is the centroid of the cluster.
3.2.2. Skeleton Document Generation
Following topic classification, a skeleton document is generated. The skeleton document consists of the structure and initial content for each chunk or topic identified in the first step. The structure of the document is defined, and the initial content is inserted, creating a basic outline of the document.
Combining fine-tuning and few-shot learning helps address the limitations of each approach. Fine-tuning enables the LLM to learn syntactic patterns and valid document structures from a dataset of relevant documents. Few-shot learning provides control over the generated structure by presenting examples of the desired structure as context.
However, fine-tuning alone does not provide control over the generated structure, and few-shot learning requires the structure to be known beforehand. This limitation can be overcome by the systematic approach, which generates the document structure before text expansion through topic classification and skeleton document generation.
The document is modeled as a tree data structure, with each child node representing a section of the document and the root node representing the entire document. These sections, in turn, can be further divided into subsections, also modeled as child nodes within the section nodes. The idea of a tree data structure in computer science is comparable to this hierarchical structure, where each node (a section or subsection of the document in this case) can have multiple child nodes (subsections) but only one parent node (the section to which it belongs) [
34].
For every identified topic-based chunk, a corresponding section is established within the document. Using the K-nearest neighbor (KNN) embedding-to-topic classifier, the topic of each chunk is determined. The classifier works by computing the distance between “all topics listed in the Topics Table” and the “embedding of the topic-based chunk”. Subsequently, it selects the nearest neighbor to the topic-based chunk on the basis of these distances. The system maps each topic-based chunk to an SRS section. The cluster-to-topic mapping determines where each topic-based chunk should appear in the SRS hierarchy. If a recognized topic requires parent sections or related nodes that are not yet present in the document tree, the missing nodes are added from the Topics Table. In this way, the document skeleton is completed before detailed text expansion is performed.
The robustness of topic-to-section mapping is supported by using the same sentence embedding model, normalization process, and cosine similarity measure across all datasets. The embeddings of topic-based chunks and Topics Table entries are normalized before comparison, and cosine similarity is used because it compares vector direction rather than raw magnitude. This reduces sensitivity to feature scaling. In addition, topic-to-section mapping is used mainly as an organizational step. The generated section content is still supported by retrieved section examples, document context, and the CQI quality loop, which helps reduce the effect of occasional mapping uncertainty.
Once the sections are delineated, the initial document tree is constructed. This process entails the creation of a root node that represents the entire document, followed by the establishment of child nodes for each section. Furthermore, each section may contain its own set of child nodes, representing sub-sections or subtopics within that particular section [
34].
Each node contains its respective topic-based chunk, as shown in
Figure 4 and if the topic is identified, then the node also contains the information about the topic it belongs to. If the hierarchy in the document tree is incomplete, then the hierarchy is completed for recognized topics by adding nodes from the Topics Table, shown in
Figure 5, until the ancestral relationship is complete for all recognized topics. This step introduces determinism at the document-structure level. Once a requirement sentence is embedded, clustered, and mapped to a topic, it is inserted into the corresponding position in the predefined SRS hierarchy. Therefore, adding or modifying a requirement affects only the related topic-based chunk or section, rather than regenerating the entire document. This step reduces structural variation and helps maintain a stable SRS organization across several updates.
Every topic that the system has recognized is listed in the Topics Table. The use of the Topics Table helps to structure the document around the recognized or learned topics. It has information such as topic name, position in hierarchy, and embedding, which is the cluster’s centroid containing the sentence embeddings for the particular topic.
The tree structure organizes and presents the final SRS document, but it does not strictly limit how requirements are processed. Topic classification and retrieval is responsible for cross-cutting requirements, where the requirement level and document level context are both considered. As a result, requirements related to security, performance, usability, or compliance can still have an impact on several sections via retrieved context, even if they are eventually placed under one primary section in the document tree. The structure remains adaptable because sections can be added, removed, or modified during document generation. Where possible, overlapping content is consolidated to reduce redundancy. This allows the framework to capture requirements that affect more than one section while maintaining an organized structure.
3.2.3. Incremental Document Expansion
The process of adding new data to the nodes of a document tree is known as document expansion. The document can expand incrementally while maintaining structural stability because each node expands individually. Each topic-based chunk is expanded in its corresponding section once the skeleton document has been constructed. The information in the chunk, the topic selected, and the document’s context are all used in the expansion. Since every section or node is expanded individually, The entire document does not need to be regenerated in order to include additional requirements. This helps in maintaining the document structure developed in the skeleton document generation phase.
Instead of generating the entire document at once, incremental expansion expands each node independently, providing determinism in the generation process. This step ensures that the output document maintains consistency and avoids changes to the document structure.
The proposed system uses an approach to expand the information present within the nodes of a document tree. Maintaining consistency and preventing the development of invalid document structures depend on this, especially when the entire context is given to a large language model (LLM) and asked to produce both the document structure and its contents. In contrast, Document Expansion works incrementally, gradually adding new sections and information to the document as needed and verifying its validity at each expansion.
In addition, The concept of incremental expansion has been used in several domains, including information retrieval systems and search engine queries. For example, query expansion techniques aim to improve search results by adding relevant terms to the original query, thereby broadening the scope of the search to include more relevant documents [
35,
36]. This concept is similar to incremental document expansion in that it involves incrementally enhancing the original query or document structure to improve the quality of the output.
With the initial document built in the previous step, we incrementally expand the different sections or nodes of the document tree using the information that the nodes contain. The Response Generation Pipeline is used to expand the nodes. If the output sentences generated during expansions lie in a different cluster of topics, then a new sub-section is created. New sub-sections also go through expansion and are split into sub-sections depending on the expansion output. The incremental document expansion continues until a maximum depth of the document is reached, or a desired number of maximum sub-sections are generated.
A response is generated through the response generation pipeline with a (Command, Context) pair as input, which then replaces the information contained in the node. Three pieces of context are provided to the pipeline. The first piece is retrieved from the Sections dataset based on the node under expansion, which serves as an example that guides the LLM to generate responses pertinent to the node. The second piece is the summarized key information from the most recently generated document, which allows the LLM to access the key information that is present in other nodes. The third piece is the information contained within the node itself, which serves as the main text to be expanded. The Command tells the LLM to expand the third piece of context, considering the information contained in the second piece, and following the style of the first piece of context.
The built context integrates the Sections dataset, the current expansion node, missing nodes, and summarization to produce deterministic results for new requirements.
3.3. Fine-Tuning and Deep Reinforcement Learning
The process of training a pre-trained Large Language Model (LLM) on a particular task or domain is known as LLM fine-tuning. The goal is to leverage the pre-training phase, where the model was trained with a significantly large text corpus, and adapt it to perform better on a specific task [
37,
38].
The system incorporates a sentence embedding model for topic classification and a large language model (LLM) for Document Expansion. In the proposed system, we use a sentence embedding model in topic classification and a downstream LLM in incremental document expansion.
Sentence embedding models transform sentences into numeric vectors that represent their semantic meaning. These models enable sentence comparison based on embeddings and are frequently used in natural language processing operations such as semantic search, text classification, and paraphrase detection. Using a sentence embedding model, sentences are converted by the system into numerical vectors that capture their semantic meaning [
39].
The use of the Mistral-7B model yields high-quality output in LLM-based generation. Mistral-7B performs better than Llama2-13b and Llama2-34b for tasks such as reasoning, math, and code generation [
40]. Mistral-7B was selected because of its robustness as a base model, which we further refine to enhance performance in the generation of software requirements specification (SRS) documents.
To refine the performance of the sentence embedding model in capturing the similarity between unlabeled input sentences and those found in various SRS sections [
41], model fine-tuning is performed using few-shot learning examples. Each example contains a sentence paired with its corresponding section label [
32]. Few-shot learning allows the system to understand the relationship between sentences and sections [
42] on a small number of training samples.
The Response Generation Pipeline is further improved using reinforcement learning. The proposed system continually fine-tunes the LLM using Proximal Policy Optimization (PPO) [
43]. The process of fine-tuning a Large Language Model (LLM) can be formulated as a markov decision process (MDP) [
44], where the trained weights of the LLM serve as the reinforcement learning (RL) policy network. This network predicts the probability distribution over possible next tokens (actions) given the current input (state):
Here, represents the current sequence of tokens (state), and represents the next predicted token (action). The vocabulary of the LLM defines the action space, and the sequence constitutes the state transitions.
A reward model [
3] guides the learning process by assessing the quality and usefulness of the produced content. The goal of training is to learn an optimal policy
that maximizes the expected cumulative reward:
In this expression:
represents the sequence of generated states and actions.
is the reward assigned to each step.
is the discount factor that controls the importance of future rewards.
The proposed formulation allows LLMs to be fine-tuned through reinforcement learning in a structured way, where every token generation event is interpreted as an action in a sequential decision process.
The LLM utilized in Response Generation undergoes continuous refinement using proximal policy optimization (PPO) [
43]. PPO directly optimizes the policy network, which corresponds to the trained weights of the LLM. In contrast, value-based methods such as Q-learning estimate expected returns through a Q-function rather than directly optimizing the policy network [
45].
Significant enhancements have been observed in Topic Classification and Response Generation. The sentence embeddings generated by the sentence embedding model result in more accurately classified sentences, while the performance of the LLM in Response Generation is notably improved, as depicted in Figures 9 and 10.
4. Experimental Setup
Documents from a variety of open-source platforms were gathered for this study, and only documents clearly labeled with open licenses, such as Creative Commons or public domain declarations, were included in the dataset, including the PURE dataset. A labeled dataset was then constructed with section names as labels and the section contents as the corresponding textual instances.
4.1. Dataset Composition and Characteristics
Count: The final corpus consists of 176 structured requirements documents, including the 79 open-licensed documents from the PURE dataset and 97 additional Software Requirements Specification (SRS) documents collected from publicly accessible sources with explicit open-use permissions. A labeled dataset was constructed using section names as labels and the corresponding section content as textual instances. For the Topic Classification stage, these labels were grouped into six topic classes (Topics 1–6).
Requirement Specification Structure: The documents generated and evaluated by the proposed pipeline follow an IEEE 830/ISO 29148-compliant structure. Each document contains up to eight top-level clauses and covers 108 distinct hierarchical section identifiers across 119 unique section types. Among these, 55 section types represent atomic (leaf-level) specification elements.
Requirement Types: The corpus contains both functional and non-functional requirements. Of the 119 section types, 91 correspond to functional requirements (e.g., authentication, data management, and transaction processing), 9 correspond to non-functional requirements, and 19 represent front matter or structural sections. The non-functional categories include performance and load requirements, security requirements, usability and interface requirements, and software quality attributes.
Other Characteristics: The Topic Classification component operates over six topic classes. The experimental results show that the mean classification accuracy improved from approximately 0.52 using the baseline embedding model to approximately 0.87 using the SetFit fine-tuned model across the six topics. Additionally, five documents were held out as a test set containing ground-truth reference texts for baseline comparison and evaluation purposes. The corpus composition used in the proposed pipeline is summarized in
Table 2.
All values reported in
Table 3 are generated directly by the ingestion pipeline document discovery → recursive hierarchy flattening → chunked source loaders → topics-table construction), ensuring that the statistics are fully reproducible from the released parsing code.
We assess the effectiveness of the proposed approach by comparing it with baselines. Instead of training the proposed sentence embedding model on labeled data, which can be costly and time-consuming in terms of data annotation, we used few-shot learning methods as an alternative.
For fine-tuning this selected sentence embedding model, which is utilized in the Topic Classification phase, we employ SetFit (Sentence Transformer Fine-tuning). SetFit is a straightforward and efficient prompt-free framework designed for few-shot fine-tuning of Sentence Transformers [
32]. The fine-tuned model was evaluated on a labeled dataset comprising labeled document sections, and the resulting accuracy improvement is reported in the Results section. Recent research shows that larger models do not always outperform smaller models for specific NLP tasks [
46]. In this work, we utilize Mistral-7B in combination with the structured document generation pipeline (topic classification, skeleton document generation, and incremental document expansion) to achieve efficient and high-quality SRS generation.
In the fine-tuning process of the LLM, we utilize reinforcement learning. Specifically, we employ TRLX (transformer reinforcement learning X) by CarperAI, which is a distributed framework tailored for fine-tuning large language models using reinforcement learning with either a reward function or a reward-labeled dataset. As the number of epochs increases, a decrease in loss is observed, as discussed in the Results section.
5. Results
The results are organized in accordance with the main evaluation objectives and connected to every research question in this study.
5.7. Additional Corpus and Structural Analysis
As shown in
Figure 13, we first performed two rounds of document fetching to validate the system’s first phase. In the first run, a total of 92 documents were processed with a success rate of 97.8%, resulting in an average document length of 5323 characters and a total content length of about 794,696 characters. The second run processed 176 documents. It had a 98.8% success rate. This yielded 877,056 characters and a higher average document length.
To ensure efficient model training, we classify the retrieved documents into structured types. This covers various domains like e-commerce, education, CRM, and healthcare.
This system was trained on 176 structured documents. These covered various SRS topics during the enhanced training phase. A section-level dataset with 1002 sections and an enriched sentence-level dataset with 4425 sentences were created as part of the process. Furthermore, 1354 of the 1594 advanced training examples were used for instruction, and 240 were used for evaluation. The MiniLM (L6-v2) sentence transformer was pre-trained with the help of this systematic approach, providing a strong basis for producing a consistent, context-aware text.
Figure 14 presents a representative system log showing the document ingestion and dataset creation process.
A consolidated view of the document retrieval and model training results is displayed in
Table 15. With a high success rate, 176 structured documents representing different domain documents were processed.
The advanced training phase processed 4425 sentences and 1002 sections, generating 1354 training examples. The sentence transformer (all-MiniLM-L6-v2) achieved impressive evaluation metrics, including a Spearman Correlation of 0.6405 and a mean squared error of 0.0169, confirming that the system’s architecture for structured document generation is initially effective.
The above training examples help the sentence transformer in learning contextual patterns and producing embeddings with meaning. Performance in a generalization test set of 240 examples was used as a measure of performance. These metrics are used to calculate the effectiveness of the model by computing metrics used to measure its efficiency, such as Spearman correlation, R-squared, and Mean Squared Error.
Table 16 compares the main statistics of two batch processing runs of documents, showing a substantial increase in the number of documents, total content length, and extracted sections from Run “A” to Run “B”.
Figure 15 illustrates the clustering procedure by showing how semantically similar sections are grouped into clusters and how topic distributions assist the fine-tuning process.
Complexity scores are represented by average metrics (content length, number of sections, complexity score) grouped by document type across all processed documents in
Table 17, with the plot in
Figure 16 providing information on typical characteristics of different categories of documents.
where
n is the number of documents of a certain type, and
refers to the complexity score for each document in that type.
Figure 16 displays a matrix of common structural patterns in documents that increase structural determinism and reusability. In this approach, the co-occurrence matrix helps us see how often “interface” and “requirements” appear together. As shown in
Figure 17, this information helps in adapting templates for many document kinds, including financial and healthcare.
8. Comparative Analysis
In references [
26,
28], software tools designed to automate requirement engineering are described. These tools facilitate the creation of Software Requirements Specification (SRS) documents through question and template engineering, where users are prompted to respond to pre-defined questions. Similarly, the ‘SRS Automator’ tool, as detailed in [
25], guides users through a series of structured questions via an input form. These questions address a variety of software requirements, such as general descriptions, detailed specifications, initial queries, and room for miscellaneous requirements.
However, previous research indicates a limitation in which the output documents are constrained to a strict format, and the reliance on user interactions required by such tools proves to be resource-intensive in terms of time and effort. As a result, there is an obvious need for a system that runs independently and derives all of its functionality from an initial user requirements document.
To address the difficulties caused by manual querying, our approach uses LLMs to reduce reliance on template engineering and time-intensive user interaction. This approach is based on recent advances in Artificial Intelligence, especially the strong language understanding capabilities of LLMs. The efficiency and accuracy of the document-generating process are greatly improved by these models’ ability to read user needs and produce software requirements specifications appropriately.
This system uses large language models (LLMs) to overcome the limits of traditional document generation. It moves beyond manual questioning and template engineering. This approach aims to alleviate the issues associated with strict output document formats and time-consuming user interaction prompted by predefined questions. The two widely used methods for document generation with LLMs are:
Fine-tuning: This trains the LLM on a diverse dataset of relevant documents. It allows the model to learn the syntactic patterns and valid structures. However, fine-tuning does not provide control over the generated structure.
Few-shot learning: This provides the LLM with a few examples of the desired structure along with the prompt. While it offers control over the generated structure, it requires that you provide an example of structure beforehand, which might not be known at the time.
Both approaches provide no direct control over the generated contents and may generate invalid and widely varying contents over little change in user requirements, making the output inconsistent [
2].
Limitations and Threats to Validity
The study proposes a structured framework for deterministic SRS generation using topic classification, skeleton document generation, and reinforcement learning-based refinement. However, there are several limitations that should be considered while interpreting its results. The dataset may not accurately reflect all industrial domains, organization-specific SRS formats, or safety-critical systems, even though it was expanded beyond the PURE dataset. The evaluation primarily employs automatic measures such as ROUGE, BLEU, METEOR, cosine similarity, BERTScore, classification accuracy, and quality scores. While these metrics indicate relevance to the source documents, they cannot fully evaluate the accuracy, completeness, ambiguity, or practical usefulness of the requirements.
Several factors may vary the results. These include prompts such as requirements from analysts or stakeholders, models, retrieval settings, embedding models, clustering parameters, and preprocessing choices. Human experts remain responsible for validating the intention of the requirements. Run A and Run B were used to compare initial and expanded corpus settings, not as repeated stochastic trials with multiple random seeds. Thus, additional robustness testing is necessary. Key threats to validity include dataset bias, metric selection bias, and implementation dependency. Future work should address these issues by using larger industrial datasets, expert evaluation, more baselines, and repeated robustness tests.
The goal of streamlining and automating software requirements specification (SRS) documents has been achieved on the basis of results. By simply providing the system with raw, unstructured user requirement documents or other text-based documents pertaining to software product development, end users can save a substantial amount of time and resources when creating SRS documents. The system then produces the desired document as output. Users can further optimize the generation process by providing the system with actions that aim to modify the document according to their preferences.
This study presents an integrated document analysis system built on a Python-based framework that combines advanced semantic search and reinforcement learning techniques. The system achieves reliable, contextually aware retrieval by fine-tuning a Sentence-Transformer model and applying a customized preprocessing to raw text data. Reinforcement Learning with proximal policy optimization (PPO) significantly improves output quality through a dynamic feedback loop. The main objective of this architecture is to provide a deterministic and adaptive response system appropriate for activities involving the generation of structured documents.
Overall, this system aims to improve the generation of software requirements specification documents while also reducing costs. By allowing developers to focus on high-level software planning and delegating formalization to the system, it facilitates a more efficient and streamlined workflow.