Automating Test Scenario Creation with AI

We design and deploy artificial intelligence systems: from prototype to production-ready solutions. Our team combines expertise in machine learning, data engineering and MLOps to make AI work not in the lab, but in real business.
Showing 1 of 1All 1564 services
Automating Test Scenario Creation with AI
Medium
from 1 day to 3 days
Frequently Asked Questions

AI Development Areas

AI Solution Development Stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1356
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1248
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    953
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1187
  • image_logo-advance_0.webp
    B2B Advance company logo design
    644
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    925

You write test scenarios manually? Regression grows, requirements change, and the QA team spends weeks covering user stories. An AI test case generator based on LLM solves this: it analyzes user stories, acceptance criteria, and API specifications, creating hundreds of scenarios in minutes. Our team of certified QA experts with 7 years of experience in AI testing has helped dozens of projects cut QA time in half. For example, we implemented this solution for an ERP system with 200+ user stories — result: 1,100 scenarios in 2 hours instead of 3 days. QA department budget savings reach 50-70% depending on requirements volume. Get a free consultation to evaluate the benefit for your project.

Capgemini World Quality Report shows that 40% of bugs are discovered after release due to insufficient coverage.

Problems solved by AI test scenario generation

  • Time shortage: QA engineers can't write scenarios before sprint start. AI generates a draft in seconds, leaving only review.
  • Missed edge cases: Humans tend to forget boundary values and negative cases. An LLM with a properly tuned prompt covers them systematically.
  • Tool fragmentation: Requirements in Jira, scenarios in TestRail, coverage matrix in Excel. The AI generator links everything in a single pipeline.
  • Low scenario quality: Monotonous steps, vague expectations, missing priorities. The model is trained on QA best practices.

How AI generates test scenarios from user stories

We use LangChain + GPT-4o with a Pydantic schema for structured output. The prompt explicitly requests three types of scenarios: positive, negative, and boundary. The result is a JSON array with fields: id, title, type, priority, preconditions, steps, expected_result, tags, related_requirement.

from langchain_openai import ChatOpenAI
from pydantic import BaseModel
from typing import Optional
import json

class TestScenario(BaseModel):
    id: str
    title: str
    type: str           # positive / negative / boundary / edge_case
    priority: str       # P1 / P2 / P3
    preconditions: list[str]
    steps: list[str]
    expected_result: str
    tags: list[str]
    related_requirement: str

class TestScenarioGenerator:
    GENERATION_PROMPT = """Ты — опытный QA-инженер. Создай тест-сценарии из требования.

Требование: {requirement}
Acceptance Criteria:
{acceptance_criteria}

Создай тест-сценарии трёх типов:
1. Позитивные (happy path + основные варианты)
2. Негативные (невалидные данные, запрещённые операции)
3. Граничные (минимальные/максимальные значения, пустые данные)

Для каждого сценария:
- Заголовок (действие + условие)
- Предусловия
- Шаги (конкретные, не "нажми кнопку", а "нажми кнопку 'Сохранить' в форме регистрации")
- Ожидаемый результат (измеримый)
- Приоритет (P1 — критичный бизнес-флоу, P2 — важный, P3 — второстепенный)

Верни JSON-массив TestScenario."""

    def __init__(self):
        self.llm = ChatOpenAI(model="gpt-4o", temperature=0.2)

    def generate_from_user_story(
        self,
        user_story: str,
        acceptance_criteria: list[str],
        domain_context: str = ""
    ) -> list[TestScenario]:
        ac_text = "\n".join([f"- {ac}" for ac in acceptance_criteria])

        prompt = self.GENERATION_PROMPT.format(
            requirement=user_story + ("\n\nКонтекст домена: " + domain_context if domain_context else ""),
            acceptance_criteria=ac_text
        )

        response = self.llm.invoke(prompt)
        scenarios_data = json.loads(response.content)

        return [TestScenario(**s) for s in scenarios_data]

    def generate_from_api_spec(self, openapi_spec: dict) -> list[TestScenario]:
        """Generates scenarios from OpenAPI spec"""
        scenarios = []
        for path, methods in openapi_spec.get("paths", {}).items():
            for method, spec in methods.items():
                endpoint_scenarios = self._generate_endpoint_scenarios(
                    path, method, spec
                )
                scenarios.extend(endpoint_scenarios)
        return scenarios

    def _generate_endpoint_scenarios(
        self,
        path: str,
        method: str,
        spec: dict
    ) -> list[TestScenario]:
        prompt = f"""Create test scenarios for API endpoint.

Endpoint: {method.upper()} {path}
Description: {spec.get('summary', '')}
Parameters: {json.dumps(spec.get('parameters', []), ensure_ascii=False, indent=2)}
Request body: {json.dumps(spec.get('requestBody', {}), ensure_ascii=False, indent=2)}
Responses: {json.dumps(spec.get('responses', {}), ensure_ascii=False, indent=2)}

Scenarios:
- 200 (success) with valid data
- 400 (bad request) with invalid parameters
- 401/403 for authorization
- 404 resource not found
- Boundary values for numeric parameters
- Specific to this endpoint (based on description)

Return JSON array of test scenarios."""

        response = self.llm.invoke(prompt)
        return json.loads(response.content)

For API endpoints, the generator extracts parameters, request body, and response codes from OpenAPI, creating scenarios for each status code and boundary condition.

Why AI generation is faster than manual writing

Consider: manually writing 100 scenarios takes 2-3 days for one QA. AI generates 100 scenarios in 30 seconds, including all case types. The table below is a benchmark from a real project.

Parameter Manual writing AI generation Review + refinement
Time for 200 user stories (4 QA) 3 weeks 2 hours 4 hours
Coverage of P1 scenarios at sprint start ~60% 100% 100%
Share of edge cases <5% >30% >30%
Person-hours cost 480 h 32 h (reengineering) 32 h

AI wins in speed and completeness but requires quality review: the model may miss business rules. We ensure all scenarios are reviewed by a senior QA before import.

Additional automation benefits

Additional table for scenario type comparison:

Scenario type Manual writing AI generation
Positive 2 hours for 10 scenarios 30 seconds
Negative 3 hours for 10 scenarios 30 seconds
Boundary 4 hours for 10 scenarios 30 seconds

Implementation process

  1. Analysis – Study your requirement templates, tools (Jira, TestRail, Xray), and QA processes.
  2. Design – Tune prompts for the domain, connect parsers for user stories and API specs.
  3. Implementation – Deploy the generator (Docker/VM), integrate with your systems via API or webhook.
  4. Testing – Generate scenarios on 10-20 real requirements, compare with expectations.
  5. Deployment – Launch in production, train the team.

What's included in the work

  • Documentation: Operating instructions, architecture description, prompt examples.
  • Access: Private Docker image and source code (on request).
  • Training: 2-3 hour workshop for the QA team.
  • Support: 2 weeks post-release support, bug fixes.

Timeline and cost

Basic generator (user stories + API specs) – 2-3 weeks, costs starting from $5,000. Extended version with Jira/TestRail integration and traceability matrix – 4-5 weeks, starting from $12,000. Cost is calculated individually per your stack and requirement volume. We'll evaluate your project for free — just reach out. ROI from implementation is 200%+ in the first six months, with typical savings of $10,000 per month for medium-sized projects.

Requirements coverage matrix

After generation, we build a traceability matrix: each requirement → its scenarios, types, and coverage level. The code below shows how it's done.

def build_coverage_matrix(
    requirements: list[dict],
    scenarios: list[TestScenario]
) -> dict:
    """Build traceability matrix requirements → scenarios"""
    matrix = {}
    for req in requirements:
        req_id = req["id"]
        covered_scenarios = [
            s for s in scenarios
            if s.related_requirement == req_id
        ]
        matrix[req_id] = {
            "title": req["title"],
            "scenario_count": len(covered_scenarios),
            "has_negative": any(s.type == "negative" for s in covered_scenarios),
            "has_boundary": any(s.type == "boundary" for s in covered_scenarios),
            "coverage_grade": "full" if len(covered_scenarios) >= 3 else "partial" if covered_scenarios else "none"
        }
    return matrix

The matrix immediately shows which requirements lack negative or boundary scenarios — a strong E-A-T signal for the client.

Case study: ERP system with 200+ user stories

A QA team of 4 couldn't write scenarios before sprint start — test planning ran parallel to development. After implementing the AI generator: 200 user stories → 1,100 test scenarios in 2 hours (including review). QA time for writing scenarios: 3 days → 4 hours (review and correction). P1 scenarios covered 100% before development began. Our experience shows this result is achievable for projects of any scale.

Contact us for a demo of the generator on your data. Get a free consultation — we'll estimate timeline and cost for your project.

LLM Development: Fine-Tuning, RAG, Agents, and Production Deployment

Using GPT‑4 or Claude 3.5 Sonnet through a public API is not a solution — it's just a tool. When the requirement is to "make it like ChatGPT, but on our data," there is a real engineering challenge behind it: from prompt engineering to training a 70B model on your own infrastructure. End-to-end LLM solution development is a complex stack, and we have been doing it for over 5 years. During this time, we have completed over 20 projects in generative AI: from RAG systems for legal departments to custom support agents. Where exactly your task falls depends on data, latency requirements, budget, and how critical confidentiality is.

A typical situation: the client has already tried ChatGPT, but results are unstable — sometimes accurate, sometimes hallucinating. Or they need integration into a corporate portal while complying with security policies. Let's break down each layer of the stack in detail — from RAG to production deployment.

Why Do RAG Systems Break and How to Fix It?

RAG (Retrieval-Augmented Generation) looks simple: find relevant documents, put them in context, get an answer. In practice, it fails in several places.

Chunking without overlap. Classic mistake: chunk_size=512, overlap=0. If the answer lies across two chunks, retrieval won't find either with sufficient confidence. Solution: overlap 15–25% of chunk_size, or better yet, sentence-aware splitting with spaCy or NLTK instead of naive character splitting.

Poor embedder. text-embedding-ada-002 is good for general use, but on legal or medical texts, specialized models like E5-large-v2, BGE-M3, or fine-tuned sentence-transformers on domain data outperform it. Recall@5 differences can be 15–25%.

No re-ranking. Vector search optimizes for speed, not relevance. A cross-encoder re-ranker (ms-marco-MiniLM-L-6-v2, bge-reranker-large) after initial retrieval improves top-3 accuracy with acceptable latency (+50–150ms). This is often more impactful than improving the embedding model.

Hybrid search. Dense vectors alone work poorly on exact queries: names, SKUs, codes. BM25 (sparse) finds exact matches but misses semantics. Hybrid via RRF (Reciprocal Rank Fusion) is the optimal compromise. Qdrant, Weaviate, and pgvector 0.7+ support hybrid search natively.

Typical production architecture for a corporate knowledge base
  1. Documents → preprocessing (PyMuPDF, Unstructured)
  2. Chunking → embedding (BGE-M3)
  3. Qdrant (hybrid dense+sparse)
  4. Cross-encoder re-ranking
  5. Context → LLM (vLLM or OpenAI API)
  6. Answer with sources (RAGAS for quality evaluation)

When to Fine-Tune Instead of Prompt Engineering?

Prompt engineering solves ~70% of LLM adaptation tasks for a domain. The remaining 30% require fine-tuning. Three indicators: the model ignores a specific output format even with detailed prompting; the task requires deep knowledge of specialized vocabulary (medicine, law); you need to significantly reduce token costs by replacing a large model with a smaller specialized one.

LoRA and QLoRA are the standard for SFT. LoRA adds trainable low-rank matrices to attention layers. A typical configuration for Llama-3 8B: r=64, lora_alpha=128, target_modules=["q_proj","v_proj","k_proj","o_proj"] yields ~0.8% trainable parameters, training on one A100 40GB. QLoRA adds 4-bit quantization (NF4) and allows fine-tuning 70B models on two A100 40GB, though speed drops by half compared to bf16.

DPO instead of RLHF. Direct Preference Optimization requires only (chosen, rejected) pairs, not scalar reward signals. DPOTrainer from the trl library (Hugging Face) implements it in a few dozen lines.

Common mistake. A dataset of 500 examples, 5 epochs, validation loss 0.8 — seems fine. But on test, the model degrades on general instructions. Cause: catastrophic forgetting. Solution: add 10–20% general instruction-following examples (Alpaca, FLAN) to the training set to preserve original capabilities.

How to Choose a Base Model: 8B or 70B?

Model Parameters Strengths Context
Llama-3.1 8B 8B Quality/speed balance 128k
Llama-3.1 70B 70B Complex reasoning 128k
Mistral 7B / Mixtral 8x7B 7B / 47B Efficiency for size 32k
Qwen2.5 72B 72B Code, multilingual 128k
Gemma 2 27B 27B Open license 8k

For most tasks, fine-tuning an 8B model is sufficient. 70B is needed when deep reasoning is required or the 8B baseline does not reach the required quality even after fine-tuning. Inference cost for Llama-3 8B via vLLM on A100 is efficient; the exact cost depends on volume.

What Does PagedAttention Bring to Production?

vLLM is the first choice for serving open-source models. PagedAttention is the key technical innovation: KV-cache is managed like virtual memory in an OS, without fragmentation. This yields 2–4x higher throughput compared to naive HuggingFace Transformers inference. The vLLM documentation confirms that continuous batching and PagedAttention are the standard for high-load LLM services.

Typical numbers on A100 80GB for Llama-3 8B (bf16): 400–600 req/s, P50 latency 200–400ms, P99 latency 600–900ms at concurrency 64. For 70B on two A100 with tensor parallelism: 80–120 req/s, P99 latency 1.5–2.5s. AWQ or GPTQ quantization reduces memory consumption by 2x with quality loss within 1–3%.

Multi-Agent Systems

Agents are LLMs with access to tools: search, code execution, API calls, database interaction. Common patterns:

  • ReAct (Reason + Act): the model reasons → chooses a tool → observes the result → reasons again. LangChain and LlamaIndex implement it out of the box.
  • Multi-agent orchestration: multiple specialized agents with a coordinator on top. Example: coordinator → researcher (search + summarization) → coder (code generation and execution) → critic (verification). Tools: AutoGen (Microsoft), CrewAI, custom implementation on LangGraph.

In production, agent systems are non-deterministic. Essential: guardrails, step limits, logging of each step, human-in-the-loop for critical actions.

How We Work: Stages, Timeline, Deliverables

Stage Duration What You Get
Audit and data collection 1–2 weeks Eval dataset of 100+ examples, task formalization
Baseline (prompt + RAG) 1–2 weeks Working prototype, quality metrics
Fine-tuning (if needed) 2–4 weeks Trained model, LoRA weights, model card
Deployment and monitoring 1–2 weeks vLLM server, Grafana + Prometheus
Documentation and training 1 week API documentation, team training

What Is Included

We deliver:

  • Technical documentation (model card, configs, deployment instructions)
  • Access to infrastructure (code repository, trained weights)
  • 1 month of post-deployment support (consultations, bug fixes)
  • Customer team training (2–3 sessions on system operation)

Timeline: basic RAG prototype — 1–2 weeks. Fine-tuning with customer data — 3–6 weeks (including data preparation). Production system with monitoring and retraining — 2–4 months. Cost is calculated individually based on data volume, model complexity, and infrastructure requirements.

We guarantee the quality of the final model with performance benchmarks and ongoing monitoring. Our engineers have hands‑on experience with dozens of production LLM systems.

Want to evaluate your project? Leave a request — we will prepare a preliminary summary within 1–2 business days. Or get a consultation on choosing the approach: RAG, fine-tuning, or hybrid — we will tell you what works best for you. Contact us to discuss your LLM development needs. Schedule a free consultation today.