<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Deepak Kumar on Medium]]></title>
        <description><![CDATA[Stories by Deepak Kumar on Medium]]></description>
        <link>https://medium.com/@pydeepak?source=rss-9b20269b5bff------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*90upN6FuGjn0Gj-cZqDUvg.png</url>
            <title>Stories by Deepak Kumar on Medium</title>
            <link>https://medium.com/@pydeepak?source=rss-9b20269b5bff------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 08:23:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pydeepak/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Optimizing Django APIs for Speed: A Practical Guide to Performance & Scalability]]></title>
            <link>https://pydeepak.medium.com/optimizing-django-apis-for-speed-a-practical-guide-to-performance-scalability-366da5447c23?source=rss-9b20269b5bff------2</link>
            <guid isPermaLink="false">https://medium.com/p/366da5447c23</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[performance-optimization]]></category>
            <dc:creator><![CDATA[Deepak Kumar]]></dc:creator>
            <pubDate>Sat, 21 Mar 2026 10:31:00 GMT</pubDate>
            <atom:updated>2026-03-21T10:31:00.742Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lH-XWl2GihF8qrVut55MXA.png" /><figcaption>Optimizing Django APIs for performance</figcaption></figure><p><strong>Introduction</strong></p><p>Creating APIs with Django is straightforward. But building APIs that remain <strong>fast under load, efficient with data, and scalable over time</strong> requires deeper understanding.</p><p>As your application grows, APIs often become the bottleneck due to:</p><ul><li>Inefficient database queries</li><li>Large payloads</li><li>Blocking operations</li><li>Poor caching strategies</li></ul><p>This guide focuses on <strong>practical optimization techniques</strong> you can apply immediately to improve your Django API performance.</p><p><strong>🔍 1. Start with Database Optimization</strong></p><p>The biggest performance issues usually come from the database layer.</p><p>❌ <strong>Inefficient Pattern</strong></p><pre>for order in orders:<br>    print(order.user.name)</pre><p>This triggers multiple queries (N+1 problem).</p><p><strong>✅ Optimized Approach</strong></p><pre>orders = Order.objects.select_related(&#39;user&#39;)</pre><p>For complex relationships:</p><pre>orders = Order.objects.prefetch_related(&#39;items&#39;)</pre><p>👉 Always ensure your API minimizes database hits.</p><p><strong>⚡ 2. Keep Serialization Lightweight</strong></p><p>Serialization is often overlooked but can slow down APIs significantly.</p><p><strong>Common Issues:</strong></p><ul><li>Returning unnecessary fields</li><li>Deeply nested serializers</li><li>Heavy computed fields</li></ul><p>✅ <strong>Better Approach</strong></p><pre>User.objects.values(&#39;id&#39;, &#39;name&#39;)</pre><p>👉 Tips:</p><ul><li>Limit fields strictly to what is needed</li><li>Avoid deep nesting unless required</li><li>Reduce use of expensive serializer methods</li></ul><p><strong>📄 3. Control Data with Pagination</strong></p><p>Sending large datasets in one response is a common mistake.</p><p>✅ <strong>Example</strong></p><pre>from rest_framework.pagination import PageNumberPagination<br><br>class StandardPagination(PageNumberPagination):<br>    page_size = 20</pre><p>👉 Benefits:</p><ul><li>Faster response time</li><li>Lower memory usage</li><li>Better frontend performance</li></ul><p>🧠 <strong>4. Use Caching Strategically</strong></p><p>Caching is one of the most effective ways to improve API performance.</p><p>🔥 <strong>Cache Entire Views</strong></p><pre>from django.views.decorators.cache import cache_page<br><br>@cache_page(60 * 5)<br>def product_list(request):<br>    ...</pre><p>🔥 <strong>Cache Query Results</strong></p><pre>from django.core.cache import cache<br><br>products = cache.get(&#39;products&#39;)<br>if not products:<br>    products = Product.objects.all()<br>    cache.set(&#39;products&#39;, products, 300)</pre><p>👉 Use Redis in production for better performance.</p><p><strong>⚙️ 5. Apply Rate Limiting</strong></p><p>Protect your API from excessive usage and abuse.</p><pre>REST_FRAMEWORK = {<br>    &#39;DEFAULT_THROTTLE_CLASSES&#39;: [<br>        &#39;rest_framework.throttling.UserRateThrottle&#39;<br>    ],<br>    &#39;DEFAULT_THROTTLE_RATES&#39;: {<br>        &#39;user&#39;: &#39;100/minute&#39;<br>    }<br>}</pre><p><strong>⚡ 6. Reduce Response Size</strong></p><p>Large responses increase latency.</p><p>✅ Techniques:</p><ul><li>Use .only() or .values()</li><li>Avoid unnecessary fields</li><li>Enable compression (GZIP/Brotli)</li></ul><p>🔄 <strong>7. Move Heavy Tasks to Background Jobs</strong></p><p>Avoid long-running operations inside API requests.</p><p>❌ <strong>Example</strong></p><pre>def create_order(request):<br>    send_email()</pre><p>✅ <strong>Optimized</strong></p><pre>send_email.delay()</pre><p>👉 Use background workers (like Celery) to handle:</p><ul><li>Emails</li><li>Reports</li><li>Data processing</li></ul><p>🧪 <strong>8. Measure Before You Optimize</strong></p><p>Performance tuning without measurement is guesswork.</p><h3>Track:</h3><ul><li>Query count</li><li>Response time</li><li>API latency</li></ul><p>Use:</p><ul><li>Logging</li><li>Monitoring tools</li><li>Debug panels</li></ul><p>🔐 <strong>9. Don’t Ignore Security</strong></p><p>Optimizing performance should not compromise security.</p><p><strong>Key Practices:</strong></p><ul><li>Authentication (JWT / tokens)</li><li>Input validation</li><li>Rate limiting</li></ul><p><strong>🧱 10. Scale When Needed</strong></p><p>If optimization is not enough:</p><ul><li>Use load balancers</li><li>Deploy multiple servers</li><li>Add database read replicas</li></ul><p>🏁 <strong>Final Thoughts</strong></p><p>Building high-performance Django APIs requires attention across multiple layers — not just code.</p><p><strong>Key Principles:</strong></p><ul><li>Optimize queries first</li><li>Minimize data transfer</li><li>Use caching effectively</li><li>Offload heavy work</li></ul><p>👉 Remember:<br><strong>“A fast API is the result of good design, not last-minute fixes.”</strong></p><p>💬 <strong>Conclusion</strong></p><p>Start applying these techniques early in your project. The earlier you optimize, the easier it becomes to scale without major rewrites.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=366da5447c23" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing Scalable Django Architecture: From Monolith to Maintainable Systems]]></title>
            <link>https://pydeepak.medium.com/designing-scalable-django-architecture-from-monolith-to-maintainable-systems-c9346cc2a23e?source=rss-9b20269b5bff------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9346cc2a23e</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Deepak Kumar]]></dc:creator>
            <pubDate>Sat, 21 Mar 2026 09:31:00 GMT</pubDate>
            <atom:updated>2026-03-21T09:31:00.628Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MSgy5aKq4Iv75NdKu8mpJA.png" /><figcaption>Designing scalable Django architecture</figcaption></figure><p><strong>Introduction</strong></p><p>Django makes it incredibly easy to start building applications. But as your project grows, what once felt simple can quickly become difficult to manage.</p><ul><li>Business logic scattered everywhere</li><li>Tight coupling between components</li><li>Hard-to-maintain codebase</li></ul><p>Scaling Django isn’t just about handling traffic — it’s about <strong>designing systems that remain clean, flexible, and maintainable over time</strong>.</p><p>In this article, we’ll explore how to design a scalable Django architecture beyond the basic monolith.</p><p><strong>🧩 Organize Apps by Domain, Not Just Features</strong></p><p>A common mistake is splitting apps based on generic features.</p><p><strong>❌ Example</strong></p><ul><li>users</li><li>products</li><li>orders</li></ul><p><strong>✅ Better Approach (Domain-driven)</strong></p><ul><li>accounts</li><li>billing</li><li>inventory</li></ul><p>This aligns code structure with business logic, making it easier to scale.</p><p><strong>🔄 Introduce a Service Layer</strong></p><p>One of the biggest improvements you can make is introducing a <strong>service layer</strong>.</p><p>❌ Problem</p><p>Business logic inside views:</p><pre>def create_order(request):<br>    # too much logic here</pre><p>✅ <strong>Solution</strong></p><p>Move logic into services:</p><pre># services/order_service.py<br><br>def create_order(user, items):<br>    # business logic</pre><p>View becomes clean:</p><pre>def create_order_view(request):<br>    create_order(request.user, request.data)</pre><p><strong>🧠 Use Models Wisely (Avoid “Fat Models”)</strong></p><p>While Django encourages fat models, overloading them can make things messy.</p><p>Instead:</p><ul><li>Keep models focused on data</li><li>Use services for logic</li><li>Use managers for query-related logic</li></ul><p><strong>⚙️ Custom QuerySets and Managers</strong></p><p>Encapsulate reusable query logic.</p><pre>class OrderQuerySet(models.QuerySet):<br>    def active(self):<br>        return self.filter(status=&#39;active&#39;)<br><br>class Order(models.Model):<br>    objects = OrderQuerySet.as_manager()</pre><p><strong>🔌 Be Careful with Signals</strong></p><p>Signals can make code feel magical — but they also introduce hidden behavior.</p><p><strong>⚠️ Problems:</strong></p><ul><li>Hard to debug</li><li>Implicit execution</li></ul><p><strong>✅ Use only when:</strong></p><ul><li>You truly need decoupling</li></ul><p><strong>🌐 Build APIs for Flexibility</strong></p><p>Decouple frontend and backend using APIs.</p><p>Benefits:</p><ul><li>Mobile apps</li><li>Frontend frameworks (React, Vue)</li><li>Third-party integrations</li></ul><p><strong>⚡ Handle Background Tasks Properly</strong></p><p>Not everything should run in the request-response cycle.</p><p>Use background workers for:</p><ul><li>Sending emails</li><li>Processing reports</li><li>Heavy computations</li></ul><p><strong>🧱 When to Consider Microservices</strong></p><p>Don’t jump to microservices too early.</p><p><strong>Use microservices when:</strong></p><ul><li>Your team grows significantly</li><li>Different services need independent scaling</li><li>Deployment complexity increases</li></ul><p><strong>🗄️ Database Scaling Strategies</strong></p><p>As your data grows:</p><ul><li>Use read replicas for scaling reads</li><li>Optimize queries (<a href="https://medium.com/@pydeepak/advanced-django-query-optimization-for-high-scale-applications-540e7c2bb9df">see previous article</a> 😉)</li><li>Consider sharding for extreme cases</li></ul><p><strong>🧠 Caching Strategy</strong></p><p>Introduce caching at multiple levels:</p><ul><li>View caching</li><li>Query caching</li><li>Template caching</li></ul><p>Caching can reduce load dramatically.</p><p><strong>🔍 Logging and Monitoring</strong></p><p>Scaling without monitoring is risky.</p><p>Track:</p><ul><li>Errors</li><li>Performance</li><li>API latency</li></ul><p><strong>🔐 Security at Scale</strong></p><p>As traffic grows, so do risks.</p><p>Key practices:</p><ul><li>Rate limiting</li><li>Authentication strategies (JWT, tokens)</li><li>Input validation</li></ul><p>🏁 <strong>Final Thoughts</strong></p><p>Scaling Django is not about adding more code — it’s about <strong>designing better systems</strong>.</p><p><strong>Core Principles:</strong></p><ul><li>Separation of concerns</li><li>Clean architecture</li><li>Controlled complexity</li></ul><p>👉 <strong>Remember</strong>:<br><strong>“Don’t just scale your app — scale your design.”</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9346cc2a23e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Django Query Optimization for High-Scale Applications]]></title>
            <link>https://pydeepak.medium.com/advanced-django-query-optimization-for-high-scale-applications-540e7c2bb9df?source=rss-9b20269b5bff------2</link>
            <guid isPermaLink="false">https://medium.com/p/540e7c2bb9df</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django-optimization]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[performance-optimization]]></category>
            <dc:creator><![CDATA[Deepak Kumar]]></dc:creator>
            <pubDate>Sat, 21 Mar 2026 07:27:30 GMT</pubDate>
            <atom:updated>2026-03-21T07:27:30.503Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VWsAY1cik2bXov7Yj20nFg.png" /><figcaption>Advanced Django Query Optimization for High-Scale Applications</figcaption></figure><p><strong>Introduction</strong></p><p>When building Django applications, everything works smoothly in the beginning. Queries are fast, responses are quick, and performance isn’t a concern.</p><p>But as your application grows — more users, more data, more relationships — things start slowing down. Pages take longer to load, APIs lag, and database load increases significantly.</p><p>This is where <strong>query optimization becomes critical</strong>.</p><p>In this article, we’ll explore advanced techniques to optimize Django ORM queries for large-scale applications, especially when working with multiple models and heavy datasets.</p><p><strong>Understanding Query Execution (The Hidden Cost)</strong></p><p>Django ORM is lazy. That means queries are not executed until the data is actually needed.</p><pre>qs = Product.objects.all() # No query yet <br>list(qs) # Query executes here</pre><p>This sounds efficient — but can easily backfire.</p><p>If you reuse the queryset multiple times, it may trigger multiple database hits.</p><p>✅ <strong>Best Practice</strong></p><pre>qs = list(Product.objects.all())</pre><p>Cache it when needed.</p><p><strong>⚡ Solving the N+1 Query Problem</strong></p><p>One of the most common performance issues in Django is the <strong>N+1 query problem</strong>.</p><p><strong>❌ Problem</strong></p><pre>for order in orders: <br>    print(order.customer.name)</pre><p>This executes:</p><ul><li>1 query for orders</li><li>N queries for customers</li></ul><p>✅ <strong>Solution:</strong> select_related</p><pre>orders = Order.objects.select_related(&#39;customer&#39;)</pre><p>This performs a SQL JOIN and fetches everything in a single query.</p><p>👉 Use it for:</p><ul><li>ForeignKey</li><li>OneToOne relationships</li></ul><p><strong>⚡ Handling Reverse and Many-to-Many Relations</strong></p><p>For reverse relationships or many-to-many fields, use:</p><pre>orders = Order.objects.prefetch_related(&#39;items&#39;)</pre><p>This performs separate queries but efficiently combines results in Python.</p><p>🧠 <strong>Fetch Only What You Need</strong></p><p>Fetching unnecessary fields increases memory usage and slows down queries.</p><p>✅ <strong>Use:</strong></p><pre>User.objects.only(&#39;id&#39;, &#39;name&#39;)</pre><p>or</p><pre>User.objects.values(&#39;id&#39;, &#39;name&#39;)</pre><p><strong>📊 Move Work to the Database</strong></p><p>Avoid loops that trigger queries.</p><p>❌ <strong>Bad Approach</strong></p><pre>for user in users:<br>    user.orders.count()</pre><p>✅ <strong>Optimized Approach</strong></p><pre>from django.db.models import Count<br><br>users = User.objects.annotate(order_count=Count(&#39;orders&#39;))</pre><p>Let the database do the heavy lifting.</p><p>🔄 <strong>Bulk Operations (Massive Performance Boost)</strong></p><p>Avoid saving objects one by one.</p><p>❌ <strong>Bad</strong></p><pre>for user in users:<br>    user.save()</pre><p>✅ <strong>Good</strong></p><pre>User.objects.bulk_create(users_list)<br>User.objects.bulk_update(users_list, [&#39;name&#39;])</pre><p>🧩 <strong>Indexing Strategy</strong></p><p>Indexes drastically improve query speed.</p><pre>class Product(models.Model):<br>    name = models.CharField(max_length=255, db_index=True)</pre><p>For complex queries:</p><pre>class Meta:<br>    indexes = [<br>        models.Index(fields=[&#39;name&#39;, &#39;category&#39;]),<br>    ]</pre><p>🔥 <strong>Use Caching for Expensive Queries</strong></p><p>Caching can reduce database load significantly.</p><pre>from django.core.cache import cache<br><br>data = cache.get(&#39;expensive_data&#39;)<br>if not data:<br>    data = expensive_query()<br>    cache.set(&#39;expensive_data&#39;, data, timeout=300)</pre><p><strong>🧪 Debug and Measure Queries</strong></p><p>Always measure before optimizing.</p><pre>from django.db import connection<br><br>print(connection.queries)</pre><p>Use tools like Django Debug Toolbar in development.</p><p><strong>🧠 Advanced ORM Techniques</strong></p><p><strong>Subqueries</strong></p><pre>from django.db.models import OuterRef, Subquery<br><br>latest_order = Order.objects.filter(user=OuterRef(&#39;pk&#39;)).order_by(&#39;-created_at&#39;)<br>users = User.objects.annotate(<br>    latest_order_date=Subquery(latest_order.values(&#39;created_at&#39;)[:1])<br>)</pre><p>🏁 <strong>Final Thoughts</strong></p><p>Optimizing Django queries is not about writing clever code — it’s about writing <strong>efficient data access patterns</strong>.</p><p><strong>Key Takeaways:</strong></p><ul><li>Avoid queries inside loops</li><li>Use select_related and prefetch_related</li><li>Push computation to the database</li><li>Use caching strategically</li></ul><p>👉 <strong>Remember:</strong></p><p><strong>“If your loop contains a query, you probably have a performance issue.”</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=540e7c2bb9df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Evaluating RAG Systems with Giskard: Automated Testing for Production AI Agents]]></title>
            <link>https://pydeepak.medium.com/evaluating-rag-systems-with-giskard-automated-testing-for-production-ai-agents-8a65551e9a21?source=rss-9b20269b5bff------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a65551e9a21</guid>
            <category><![CDATA[ml-engineering]]></category>
            <category><![CDATA[llmops]]></category>
            <category><![CDATA[rag-system]]></category>
            <category><![CDATA[ai-testing]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Deepak Kumar]]></dc:creator>
            <pubDate>Mon, 26 Jan 2026 09:59:36 GMT</pubDate>
            <atom:updated>2026-01-26T09:59:36.024Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EQJ2PaXXuxrQhUtRIhLV_g.png" /><figcaption>Evaluating RAG Systems with Giskard: Automated Testing for Production AI Agents</figcaption></figure><h3>Introduction: Beyond Manual Testing</h3><p>Building a Retrieval-Augmented Generation (RAG) system is one thing — ensuring it works reliably in production is another. Traditional testing approaches fall short when dealing with LLM-based systems because:</p><ul><li><strong>Outputs are non-deterministic:</strong> The same input can produce different responses</li><li><strong>Manual test creation is tedious:</strong> Creating hundreds of realistic test cases takes weeks</li><li><strong>Evaluation is subjective:</strong> How do you objectively measure answer quality?</li></ul><p>Enter <strong>Giskard —</strong> an open-source testing framework specifically designed for LLM applications that combines automatic test generation with comprehensive RAG evaluation metrics.</p><h3>What is Giskard?</h3><p>Giskard is a Python library that provides:</p><ol><li><strong>Automatic Test Generation:</strong> Creates realistic question-answer pairs from your knowledge base</li><li><strong>RAG-Specific Evaluation:</strong> Integrates RAGAS metrics with additional quality checks</li><li><strong>Production-Ready Reports:</strong> Generates HTML reports for stakeholder review</li><li><strong>Agent-Aware Testing: </strong>Customizes tests based on your agent’s role and behavior</li></ol><p>What is Ragas: <a href="https://pydeepak.medium.com/evaluating-rag-systems-with-ragas-a-complete-guide-to-synthetic-test-data-generation-3328c9bcf869">article link</a></p><p><strong>Key Differentiators</strong></p><p>Unlike pure RAGAS implementations, Giskard offers:</p><ul><li><strong>Agent description context:</strong> Tests tailored to your specific use case</li><li><strong>Built-in knowledge base management:</strong> Direct pandas DataFrame integration</li><li><strong>Report generation: </strong>Professional HTML reports out-of-the-box</li><li><strong>Simplified API:</strong> Less boilerplate, faster implementation</li></ul><h3>Architecture Overview</h3><p>The evaluation pipeline consists of three main stages:</p><p><strong>Data Preparation → Test Generation → Evaluation &amp; Reporting</strong></p><p>Let’s implement each stage using a real-world example.</p><h3>Implementation: Building a Complete Testing Pipeline</h3><h4>Stage 1: Data Preparation</h4><p>First, we need to prepare our knowledge base. Often, data comes in various formats that need standardization:</p><pre>import os<br>import csv<br>import json<br>import pandas as pd<br><br>def convert_json_to_csv():<br>    json_file_path = &quot;products.json&quot;<br>    csv_file_path = &quot;products.csv&quot;<br><br>    os.chdir(&quot;/giskard/data/&quot;)<br><br>    # Read the JSON file<br>    with open(json_file_path, &#39;r&#39;) as json_file:<br>        data = json.load(json_file)<br>    <br>    # Ensure the data is a list of dictionaries<br>    if not isinstance(data, list):<br>        data = [data]<br>    <br>    # Extract the keys from the first dictionary to use as CSV headers<br>    headers = list(data[0].keys())<br>    <br>    # Write to the CSV file<br>    with open(csv_file_path, &#39;w&#39;, newline=&#39;&#39;) as csv_file:<br>        writer = csv.DictWriter(csv_file, fieldnames=headers)<br>        <br>        # Write the header row<br>        writer.writeheader()<br>        <br>        # Write the data rows<br>        for row in data:<br>            writer.writerow(row)<br>    <br>    print(f&quot;Successfully converted {json_file_path} to {csv_file_path}&quot;)</pre><p><strong>Why This Matters:</strong> Giskard works best with structured data in tabular format. Converting JSON to CSV ensures consistent field mapping and better test generation quality.</p><h4>Stage 2: Test Set Generation</h4><p>Now we create synthetic test questions tailored to our specific agent:</p><pre>import giskard<br>import giskard.llm<br>from giskard.llm.client.openai import OpenAIClient<br>from giskard.rag import generate_testset, KnowledgeBase<br><br>def create_testset(number_of_questions = 10):<br>    # Configure Giskard with OpenAI<br>    giskard.llm.set_llm_api(&quot;openai&quot;)<br>    openai_client = OpenAIClient(model=&quot;gpt-4o-mini&quot;)<br>    giskard.llm.set_default_client(openai_client)<br><br>    os.chdir(&quot;/giskard/data/&quot;)<br>    csv_file_path = &quot;products.csv&quot;<br><br>    # Load data and create knowledge base<br>    df = pd.read_csv(csv_file_path)<br>    knowledge_base = KnowledgeBase.from_pandas(df)<br><br>    if number_of_questions &lt; 1:<br>        number_of_questions = 10<br><br>    # Generate test set with agent context<br>    testset = generate_testset(<br>        knowledge_base, <br>        num_questions = number_of_questions, <br>        language = &quot;en&quot;, <br>        agent_description = &quot;A customer support chatbot for business handling product inquiries and troubleshooting&quot;<br>    )<br>    <br>    os.chdir(&quot;/giskard/testset/&quot;)<br>    testset.save(&quot;giskard.jsonl&quot;)<br>    # &quot;Testset created ...&quot;<br>    return knowledge_base</pre><p><strong>Key Features:</strong></p><ol><li><strong>KnowledgeBase.from_pandas():</strong> Directly converts your DataFrame into a queryable knowledge base</li><li><strong>agent_description:</strong> Critical parameter that customizes questions to match your agent’s role (e.g., “customer support chatbot” generates different questions than “technical documentation assistant”)</li><li><strong>language:</strong> Ensures questions are generated in the target language</li><li><strong>Persistent storage:</strong> Saves to JSONL for reproducibility and version control</li></ol><h4>Stage 3: RAG Model Wrapping</h4><p>Giskard needs a way to query your RAG system. Here’s how to wrap an OpenAI Assistants API-based agent:</p><pre>import openai as oai<br><br># Wrap your RAG model<br>def get_answer_fn(question: str, history=None) -&gt; str:<br>    answer = get_answer_from_agent(question)<br>    return answer<br><br>def get_answer_from_agent(question):<br>    client = create_openai_client()<br>    assistant_id = &quot;asst_{assistant_id}&quot;<br>    thread_id = &quot;thread_{thread_id}&quot;<br>    latest_response = &quot;&quot;<br><br>    add_message_to_thread(client, thread_id, question)    <br>    run = create_run_wait_for_completion(client, assistant_id, thread_id)<br><br>    if run == None:<br>        latest_response = &quot;Unable to fetch RUN object&quot;<br>    else:<br>        if run.status == &quot;completed&quot;:<br>            run_response = get_messages_from_run_thread(client, run, thread_id)<br>            latest_response = run_response.data[0].content[0].text.value<br>        else:<br>            print(f&quot;\nThe status of RUN is {run.status}&quot;)<br>            print(f&quot;\nThe RUN failed due to {run.last_error}&quot;)            <br>            latest_response = &quot;&quot;<br><br>    print(f&quot;\nQuestion: {question}&quot;)<br>    print(f&quot;\nAgent Response: {latest_response}&quot;)<br><br>    return latest_response<br><br>def create_openai_client():<br>    return oai.Client(api_key=&quot;your-api-key-here&quot;)<br><br>def add_message_to_thread(client, thread_id, content):<br>    return client.beta.threads.messages.create(<br>        thread_id = thread_id,<br>        role = &quot;user&quot;,<br>        content = content<br>    )<br><br>def create_run_wait_for_completion(client, assistant_id, thread_id):<br>    try:<br>        return client.beta.threads.runs.create_and_poll(<br>            assistant_id = assistant_id,<br>            thread_id = thread_id,<br>            instructions = &quot;Please respond concisely and in polite manner&quot;)<br>    except Exception as e:<br>        print(f&quot;Error create_run_wait_for_completion: {e}&quot;)<br><br>def get_messages_from_run_thread(client, run, thread_id):<br>    if run.status == &quot;completed&quot;:<br>        return client.beta.threads.messages.list(thread_id)</pre><p><strong>Design Highlights:</strong></p><ul><li><strong>Error handling: </strong>Gracefully handles API failures and timeout scenarios</li><li><strong>Stateful conversations:</strong> Uses persistent threads for conversation context</li><li><strong>Custom instructions:</strong> Tailors response style at runtime</li><li><strong>Polling mechanism:</strong> Waits for async completion with create_and_poll()</li></ul><h4>Stage 4: Evaluation and Reporting</h4><p>The final stage runs your test set against the RAG model and generates comprehensive metrics:</p><pre>from giskard.rag import evaluate, QATestset<br>from giskard.rag.metrics.ragas_metrics import (<br>    ragas_context_precision, <br>    ragas_answer_relevancy, <br>    ragas_context_recall, <br>    ragas_faithfulness<br>)<br><br>def evaluate_model():<br>    # Configure Giskard<br>    giskard.llm.set_llm_api(&quot;openai&quot;)<br>    openai_client = OpenAIClient(model=&quot;gpt-4o-mini&quot;)<br>    giskard.llm.set_default_client(openai_client)<br><br>    os.chdir(&quot;\PROJECTS\giskard\giskard\data&quot;)<br>    csv_file_path = &quot;products.csv&quot;<br><br>    df = pd.read_csv(csv_file_path)<br><br>    # Load Knowledge base<br>    knowledge_base = KnowledgeBase.from_pandas(df)<br><br>    os.chdir(&quot;\PROJECTS\giskard\giskard\testset&quot;)<br><br>    # Load testset<br>    testset = QATestset.load(&quot;giskard.jsonl&quot;)<br><br>    # Run the evaluation and get a report<br>    report = evaluate(<br>        get_answer_fn, <br>        testset=testset, <br>        knowledge_base=knowledge_base, <br>        metrics=[<br>            ragas_context_precision, <br>            ragas_answer_relevancy, <br>            ragas_faithfulness<br>        ]<br>    )<br>    <br>    os.chdir(&quot;\PROJECTS\giskard\giskard\report&quot;)<br>    report.to_html(&quot;giskard.html&quot;)<br><br>    return report</pre><p><strong>Evaluation Metrics Explained:</strong></p><ol><li><strong>ragas_context_precision:</strong> Measures if retrieved contexts are relevant to the question (reduces noise)</li><li><strong>ragas_answer_relevancy:</strong> Evaluates if the answer directly addresses the question (no hallucinations)</li><li><strong>ragas_faithfulness:</strong> Checks if the answer is grounded in the retrieved context (fact-checking)</li></ol><h4>Stage 5: Orchestration</h4><p>The main entry point ties everything together:</p><pre>import os, sys<br>sys.path.append(&#39;\PROJECTS\giskard\giskard&#39;)<br>from utility import convert_json_to_csv, create_testset, evaluate_model<br><br>openai_apikey = &quot;your-api-key-here&quot;<br>os.environ[&quot;OPENAI_API_KEY&quot;] = openai_apikey<br><br># Pipeline execution<br># Step 1: Generate data from json to csv<br># convert_json_to_csv()<br><br># Step 2: Generate testset with questions and answers<br># knowledge_base = create_testset(20)<br><br># RUN THE ABOVE TWO STEPS ONLY ONCE, THEN RUN evaluate_model.<br><br># Step 3: Run evaluation<br>report = evaluate_model()</pre><p><strong>Pipeline Benefits:</strong></p><ul><li><strong>Modular design:</strong> Each stage can run independently</li><li><strong>Reproducible:</strong> Comment/uncomment stages as needed</li><li><strong>Scalable:</strong> Adjust <strong>num_questions </strong>parameter based on coverage needs</li></ul><h4>Understanding the Output: HTML Reports</h4><p>One of Giskard’s strongest features is the HTML report generation:</p><pre>report.to_html(&quot;giskard.html&quot;)</pre><p>This creates a comprehensive report with:</p><ul><li><strong>Metric scores:</strong> Visual charts showing performance across all metrics</li><li><strong>Failed test cases:</strong> Specific questions where the agent underperformed</li><li><strong>Detailed analysis:</strong> Question-by-question breakdown with retrieved contexts</li><li><strong>Actionable insights:</strong> Recommendations for improvement</li></ul><h3>Conclusion</h3><p>Giskard provides a streamlined path from data to production-ready evaluation reports. The combination of:</p><ul><li><strong>Agent-aware test generation</strong> ensuring realistic scenarios</li><li><strong>Integrated RAGAS metrics</strong> for comprehensive quality assessment</li><li><strong>HTML reporting</strong> for stakeholder communication</li><li><strong>Simple API</strong> reducing implementation time</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a65551e9a21" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Evaluating RAG Systems with RAGAS: A Complete Guide to Synthetic Test Data Generation]]></title>
            <link>https://pydeepak.medium.com/evaluating-rag-systems-with-ragas-a-complete-guide-to-synthetic-test-data-generation-3328c9bcf869?source=rss-9b20269b5bff------2</link>
            <guid isPermaLink="false">https://medium.com/p/3328c9bcf869</guid>
            <category><![CDATA[rag-system]]></category>
            <category><![CDATA[raga]]></category>
            <category><![CDATA[synthetic-test-data]]></category>
            <category><![CDATA[ai-tools]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Deepak Kumar]]></dc:creator>
            <pubDate>Mon, 26 Jan 2026 09:08:01 GMT</pubDate>
            <atom:updated>2026-01-26T09:08:01.829Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction: The Challenge of RAG Evaluation</h3><p>Retrieval-Augmented Generation (RAG) has revolutionized how Large Language Models (LLMs) access and utilize external knowledge. However, evaluating RAG systems presents a significant challenge: how do you test the quality of your retrieval and generation components without manually creating hundreds of test cases?</p><p>According to research, manually curating test datasets for RAG systems can consume up to 90% of development time. This is where RAGAS (Retrieval Augmented Generation Assessment) comes in — an open-source framework that automates synthetic test data generation and provides robust evaluation metrics.<br><strong>References: </strong><a href="https://docs.ragas.io/en/stable/">RAGAS Official Documentation</a></p><h3>What is RAGAS?</h3><p><strong>RAGAS</strong> is a specialized Python library designed for:</p><ol><li><strong>Synthetic Test Set Generation:</strong> Automatically creating question-answer pairs from your documents.</li><li><strong>RAG Evaluation:</strong> Measuring retrieval quality, generation accuracy, and overall system performance.</li><li><strong>Production Monitoring:</strong> Tracking RAG system performance over time.</li></ol><h3>Why Synthetic Data?</h3><p>Synthetic test data offers several advantages:</p><ul><li><strong>Cost-Effective:</strong> No need for expensive human annotation</li><li><strong>Scalable:</strong> Generate thousands of test cases in minutes</li><li><strong>Customizable:</strong> Target specific complexity levels and scenarios</li><li><strong>Privacy-Compliant:</strong> No sensitive user data required</li><li><strong>Comprehensive:</strong> Cover edge cases and diverse query patterns</li></ul><h3>The Evolutionary Generation Paradigm</h3><p>Unlike traditional test generation that relies on LLMs to directly produce questions, RAGAS uses an evolutionary approach inspired by Evol-Instruct. It systematically transforms seed questions through multiple evolution strategies:</p><p><strong>Evolution Types:</strong></p><ol><li><strong>Simple:</strong> Straightforward questions requiring basic information retrieval</li><li><strong>Reasoning:</strong> Questions demanding multi-step logical inference</li><li><strong>Multi-Context:</strong> Questions requiring information synthesis from multiple document sections</li><li><strong>Conditional:</strong> Questions with conditional constraints or parameters</li></ol><p>This approach ensures diversity and prevents the common patterns LLMs naturally gravitate toward.</p><h3>Implementation: Building a Complete RAG Evaluation Pipeline</h3><p>Let’s build a production-ready RAG evaluation system following best practices.</p><ol><li><strong>Environment Setup and Dependencies</strong></li></ol><pre>&quot;&quot;&quot;<br>RAGAS Evaluation System for RAG Applications<br>Implements synthetic test generation and comprehensive evaluation metrics<br>&quot;&quot;&quot;<br>import os<br>import openai<br>from langchain_openai import ChatOpenAI, OpenAIEmbeddings<br>from ragas.testset.evolutions import simple, reasoning, multi_context<br>from ragas.llms import LangchainLLMWrapper<br>from langchain_community.document_loaders import CSVLoader<br>from ragas.testset.generator import TestsetGenerator<br>from llama_index.core import SimpleDirectoryReader<br>from llama_index.core import VectorStoreIndex, ServiceContext<br>from llama_index.embeddings.openai import OpenAIEmbedding<br>from ragas.run_config import RunConfig<br>from datasets import Dataset<br>from tqdm.auto import tqdm<br>from time import sleep<br>from phoenix.otel import register<br>from openinference.instrumentation.langchain import LangChainInstrumentor<br>from openinference.instrumentation.llama_index import LlamaIndexInstrumentor<br>from phoenix.session.evaluation import get_qa_with_reference, get_retrieved_documents<br>from phoenix.trace import SpanEvaluations<br>import pandas as pd<br>from ragas import evaluate<br>from ragas.metrics import (<br>    faithfulness,<br>    answer_correctness,<br>    context_recall,<br>    context_precision,<br>)<br><br># Enable nested async operations<br>import nest_asyncio<br>nest_asyncio.apply()</pre><p><strong>Key Components:</strong></p><ul><li><strong>LangChain:</strong> For document loading and LLM integration</li><li><strong>LlamaIndex:</strong> For building vector indices and query engines</li><li><strong>RAGAS:</strong> Core library for test generation and evaluation</li><li><strong>Phoenix:</strong> For observability and tracing</li></ul><p><strong>2. Configuration and Observability</strong></p><p>Setting up performance configurations and observability tracing:</p><pre># Configure RAGAS for optimal performance<br>my_run_config = RunConfig(max_workers=64, timeout=60*30)<br><br># Set up Phoenix observability<br>tracer_provider = register(set_global_tracer_provider=False)<br><br># Configure API access<br>os.environ[&quot;OPENAI_API_KEY&quot;] = &quot;your-api-key-here&quot;</pre><p><strong>Performance Optimization:</strong></p><ul><li><strong>max_workers=64:</strong> Enables parallel processing of test generation.</li><li><strong>timeout=60*<em>30:</em></strong><em> 30-minute timeout for complex operations.</em></li><li><strong>Phoenix tracer:</strong> Captures all LLM calls and embeddings for debugging.</li></ul><h3>Part 1: Synthetic Test Data Generation</h3><h4>Method 1: Using LlamaIndex for Document Loading</h4><p>LlamaIndex provides a simple way to load multiple document types recursively:</p><pre>def generate_testset_by_llama_index():<br>    # Load documents from directory<br>    dir_path = &quot;./data&quot;<br>    reader = SimpleDirectoryReader(dir_path, recursive=True)<br>    docs = reader.load_data()<br><br>    # Initialize models<br>    generator_llm = ChatOpenAI(model=&quot;gpt-4o-mini&quot;)<br>    critic_llm = ChatOpenAI(model=&quot;gpt-4o&quot;)<br>    embeddings = OpenAIEmbeddings()<br><br>    # Create testset generator<br>    generator = TestsetGenerator.from_langchain(generator_llm, critic_llm, embeddings)<br>    <br>    # Define evolution distribution<br>    distribution = {simple: 0.5, reasoning: 0.25, multi_context: 0.25}<br>    <br>    # Generate test cases<br>    testset = generator.generate_with_llamaindex_docs(<br>        docs, test_size=50, distributions=distribution<br>    )<br>    test_df = testset.to_pandas()<br><br>    # Save results<br>    output_dir = &#39;ragas&#39;<br>    output_file = os.path.join(output_dir, &#39;llama_index_output.jsonl&#39;)<br>    os.makedirs(output_dir, exist_ok=True)<br>    test_df.to_json(output_file, orient=&#39;records&#39;, lines=True)</pre><p><strong>Key Design Decisions:</strong></p><ol><li><strong>Two-Model Approach:</strong> Using gpt-4o-mini as the generator (fast, cost-effective) and gpt-4o as the critic (high-quality validation).</li><li><strong>Evolution Distribution:</strong> 50% simple questions, 25% reasoning, 25% multi-context ensures balanced coverage.</li><li><strong>Test Size:</strong> Generating 50 samples provides good coverage without excessive cost.</li></ol><h4>Method 2: Using LangChain for CSV Data</h4><p>For structured data sources like CSV files:</p><pre>def generate_testset_by_langchain():<br>    # Load CSV data<br>    csv_loader = CSVLoader(&quot;data/products.csv&quot;)<br>    docs = csv_loader.load()<br>    docs = docs[:5]<br><br>    # Initialize models<br>    generator_llm = ChatOpenAI(model=&quot;gpt-4o-mini&quot;)<br>    critic_llm = ChatOpenAI(model=&quot;gpt-4o&quot;)<br>    embeddings = OpenAIEmbeddings()<br><br>    # Create testset generator<br>    generator = TestsetGenerator.from_langchain(generator_llm, critic_llm, embeddings)<br>    distribution = {simple: 0.5, reasoning: 0.25, multi_context: 0.25}<br><br>    # Generate smaller test set for validation<br>    dataset = generator.generate_with_langchain_docs(docs, test_size=1, distributions=distribution)<br>    test_df = dataset.to_pandas()<br><br>    # Save results<br>    output_dir = &#39;ragas&#39;<br>    output_file = os.path.join(output_dir, &#39;langchain_output.jsonl&#39;)<br>    os.makedirs(output_dir, exist_ok=True)<br>    test_df.to_json(output_file, orient=&#39;records&#39;, lines=True)</pre><p><strong>Use Case:</strong> Perfect for product catalogs, FAQ databases, or any tabular data source.</p><h3>Part 2: Building the RAG Query Engine</h3><p><strong>Creating a Vector Index</strong></p><pre># Load documents<br>dir_path = &quot;./data&quot;<br>reader = SimpleDirectoryReader(dir_path, recursive=True)<br>docs = reader.load_data()<br><br>def build_query_engine(documents):<br>    vector_index = VectorStoreIndex.from_documents(<br>        documents=documents,<br>        embed_model=OpenAIEmbedding(),<br>    )<br>    query_engine = vector_index.as_query_engine(similarity_top_k=2)<br>    return query_engine<br><br>query_engine = build_query_engine(docs)</pre><p><strong>Architecture Highlights:</strong></p><ul><li><strong>VectorStoreIndex:</strong> Creates embeddings and stores them for efficient retrieval.</li><li><strong>similarity_top_k=2:</strong> Retrieves the 2 most relevant document chunks.</li><li><strong>OpenAIEmbedding:</strong> Uses OpenAI’s embedding model for semantic search.</li></ul><h3>Generating Responses</h3><pre>def generate_response(query_engine, question):<br>    response = query_engine.query(question)<br>    print(f&quot;{question} - {response.response}&quot;)<br>    return {<br>        &quot;answer&quot;: response.response,<br>        &quot;contexts&quot;: [c.node.get_content() for c in response.source_nodes],<br>    }<br><br>def generate_ragas_dataset(query_engine, test_df):<br>    test_questions = test_df[&quot;question&quot;].values<br>    responses = [generate_response(query_engine, q) for q in tqdm(test_questions)]<br><br>    dataset_dict = {<br>        &quot;question&quot;: test_questions,<br>        &quot;answer&quot;: [response[&quot;answer&quot;] for response in responses],<br>        &quot;contexts&quot;: [response[&quot;contexts&quot;] for response in responses],<br>        &quot;ground_truth&quot;: test_df[&quot;ground_truth&quot;].values.tolist(),<br>    }<br>    ds = Dataset.from_dict(dataset_dict)<br>    return ds</pre><p><strong>Dataset Structure:</strong></p><ul><li><strong>question:</strong> The generated test question</li><li><strong>answer:</strong> RAG system’s response</li><li><strong>contexts:</strong> Retrieved document chunks</li><li><strong>ground_truth:</strong> Expected answer from synthetic generation</li></ul><h3>Part 3: Comprehensive Evaluation with RAGAS Metrics</h3><p><strong>Understanding RAGAS Metrics</strong></p><p>RAGAS provides four key metrics to evaluate different aspects of your RAG system:</p><ol><li><strong>Faithfulness:</strong> Measures if the answer is grounded in the retrieved context (hallucination detection)</li><li><strong>Answer Correctness:</strong> Compares generated answer with ground truth</li><li><strong>Context Recall:</strong> Evaluates if all relevant information was retrieved</li><li><strong>Context Precision:</strong> Measures if retrieved contexts are relevant to the question</li></ol><p><strong>Running Evaluation</strong></p><pre># Load test dataset<br>test_df = pd.read_json(&quot;output.jsonl&quot;, orient=&#39;records&#39;, lines=True)<br><br># Generate responses from RAG system<br>ragas_eval_dataset = generate_ragas_dataset(query_engine, test_df)<br>ragas_evals_df = pd.DataFrame(ragas_eval_dataset)<br><br># Evaluate with RAGAS metrics<br>evaluation_result = evaluate(<br>    dataset=ragas_eval_dataset,<br>    metrics=[faithfulness, answer_correctness, context_recall, context_precision],<br>)<br><br># Extract results<br>eval_scores_df = pd.DataFrame(evaluation_result.scores)<br>eval_data_df = pd.DataFrame(evaluation_result.dataset)</pre><h3>Part 4: Advanced Features — Observability and Monitoring</h3><p>Reference: <a href="https://docs.ragas.io/en/stable/howtos/integrations/_arize/?h=generator">Doc link</a></p><p><strong>Integrating with Phoenix for Production Monitoring</strong></p><p><strong>Benefits of Observability:</strong></p><ul><li>Track embedding quality and retrieval patterns</li><li>Debug retrieval failures</li><li>Monitor latency and performance</li><li>Identify data drift</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sZPWEi86x1VUVx-y3m-0ow.jpeg" /><figcaption>Phoenix (Arize)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qysMxHrElKng7l13vMulKw.jpeg" /><figcaption>Ragas annotations</figcaption></figure><h3>Conclusion</h3><p>RAGAS transforms RAG evaluation from a manual, time-consuming process into an automated, scalable workflow. By combining:</p><ul><li><strong>Evolutionary test generation</strong> for diverse, realistic questions</li><li><strong>Comprehensive metrics</strong> covering faithfulness, correctness, and retrieval quality</li><li><strong>Production observability</strong> for continuous monitoring</li></ul><p>You can build RAG systems with confidence, backed by data-driven evaluation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3328c9bcf869" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Behavior-Driven Development (BDD): A Real-World Implementation Guide]]></title>
            <link>https://pydeepak.medium.com/mastering-behavior-driven-development-bdd-a-real-world-implementation-guide-30c682ff6b23?source=rss-9b20269b5bff------2</link>
            <guid isPermaLink="false">https://medium.com/p/30c682ff6b23</guid>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[python-automation]]></category>
            <category><![CDATA[playwright-automation]]></category>
            <category><![CDATA[bdd]]></category>
            <dc:creator><![CDATA[Deepak Kumar]]></dc:creator>
            <pubDate>Sat, 04 Oct 2025 09:14:58 GMT</pubDate>
            <atom:updated>2025-10-04T09:14:58.281Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Mastering Behavior-Driven Development (BDD): A Real-World Implementation Guide" src="https://cdn-images-1.medium.com/max/1024/1*oMNC8j42g8mDyIORKwVSMA.png" /><figcaption>Mastering Behavior-Driven Development (BDD): A Real-World Implementation Guide</figcaption></figure><h4><strong>Introduction</strong></h4><p>Behavior-Driven Development (BDD) is a powerful methodology that bridges the gap between technical and non-technical stakeholders by expressing software behavior in a language everyone can understand. In this blog post, we’ll explore a real-world implementation of BDD using Python, Behave, and Playwright, showcasing best practices and patterns from an actual project.</p><p>I’ve been using Behave (Python) + Playwright to drive BDD in a production-facing admin console for subscription plan management. This post walks through the actual structure, hooks, and reusable step patterns from my codebase. No demo widgets — just the real files, how they fit together, and the decisions behind them.</p><h4>Why this structure works</h4><ul><li><strong>Clear separation of concerns:</strong> Feature files describe business behavior; step files implement UI interactions and assertions; <strong>environment.py </strong>manages the browser lifecycle and shared context.</li><li><strong>High reuse:</strong> A single <strong>common_steps.py</strong> centralizes generic steps and cross-feature utilities. Feature-specific step files inject only what’s unique.</li><li><strong>Consistency and maintainability:</strong> Backgrounds for shared setup, small and expressive steps, and composition with execute_steps to keep scenarios terse and DRY.</li></ul><h4>Folder Layout</h4><pre>features/<br>  environment.py<br>  ai_subscription_plan.feature<br>  savi_subscription_plan.feature<br>  ...<br>  steps/<br>    common_steps.py<br>    ai_subscription_steps.py<br>    savi_subscription_steps.py<br>    ...</pre><h4>Hooking PlayWright and context</h4><p>The test lifecycle is managed centrally in <strong>features/environment.py</strong>. I spin up Playwright once per test run and isolate a new page per scenario. I also make environment variables and dynamic data available everywhere via <strong>context</strong>.</p><pre># environment.py<br>from playwright.sync_api import sync_playwright<br>import os<br>from dotenv import load_dotenv<br><br>load_dotenv()<br><br>def before_all(context):<br>    &quot;&quot;&quot;Setup Playwright browser and context before all tests&quot;&quot;&quot;<br>    playwright = sync_playwright().start()<br>    browser = playwright.chromium.launch(headless=False)<br>    context.browser = browser<br>    context.playwright = playwright<br>    <br>    # Initialize dynamic data dictionary<br>    context.dynamic_data = {}<br>    <br>    # Store environment variables<br>    context.env = {<br>        &#39;BASE_URL&#39;: os.environ.get(&#39;BASE_URL&#39;, &#39;http://localhost:8000&#39;),<br>        &#39;BDD_EMAIL&#39;: os.environ.get(&#39;BDD_EMAIL&#39;),<br>        &#39;BDD_PASSWORD&#39;: os.environ.get(&#39;BDD_PASSWORD&#39;),<br>    }<br><br>def before_scenario(context, scenario):<br>    &quot;&quot;&quot;Setup new page for each scenario and handle dynamic parameters&quot;&quot;&quot;<br>    # Create new page for each scenario<br>    context.page = context.browser.new_page()<br>    context.page.goto(context.env[&#39;BASE_URL&#39;])<br>    <br>    # Reset dynamic data for each scenario<br>    context.dynamic_data = {}<br>    <br>    # Handle dynamic parameters from command line<br>    # Example: behave -D plan_name=&quot;Custom Plan Name&quot;<br>    if hasattr(context.config, &#39;userdata&#39;):<br>        for key, value in context.config.userdata.items():<br>            context.dynamic_data[key] = value<br><br>def after_scenario(context, scenario):<br>    &quot;&quot;&quot;Cleanup after each scenario&quot;&quot;&quot;<br>    if hasattr(context, &#39;page&#39;):<br>        context.page.close()<br><br>def after_all(context):<br>    &quot;&quot;&quot;Cleanup after all tests&quot;&quot;&quot;<br>    if hasattr(context, &#39;browser&#39;):<br>        context.browser.close()<br>    if hasattr(context, &#39;playwright&#39;):<br>        context.playwright.stop() </pre><ul><li><strong>Security:</strong> Credentials are injected via env vars (BDD_EMAIL, BDD_PASSWORD), not hardcoded.</li><li><strong>Object lifecycle:</strong> Browser and page are created/closed deterministically.</li><li><strong>Parameterization:</strong> I can drive scenarios with real data using <strong>behave -D key=value.</strong></li></ul><h4>Backgrounds and readable behavior: a feature example</h4><p>Features describe business intent. I keep them readable with a Background and focused scenarios.</p><pre>Feature: AI Subscription Plan Management<br>  As an admin<br>  I want to manage AI subscription plans<br>  So that I can offer different subscription options to users<br><br>  Background:<br>    Given I am logged in as an admin<br>    And I navigate to the &quot;Add AI Subscription Plan&quot; page<br>  <br>  Scenario: Successfully create a new AI subscription plan<br>    When I enter a unique &quot;Plan Name&quot;<br>    And Plan name can include a maximum 50 characters, after which the cursor will stop writing<br>    And I select a &quot;Business Model&quot; from the dropdown (Service Provider/Direct) and it will be default to 3<br>    And I enter a valid &quot;Price&quot; which is default to 0<br>    And I enter a valid &quot;Number of AI Agents Allowed&quot; which is default to 0<br>    And I enter a valid &quot;Additional AI Agents Allowed&quot; which is default to 0<br>    And I enter a valid &quot;Cost Per Additional AI Agent&quot; which is default to 0<br>    And I select &quot;Is Active&quot;<br>    And the &quot;Currency&quot; remains disabled (default to the region user is logged in to)<br>    And I select a &quot;Plan Duration&quot; from the dropdown<br>    And I enter a valid &quot;Number of Tokens Allowed&quot; which is default to 0</pre><h4>Shared steps and dynamic data: one place, many features</h4><p>All cross-cutting steps live in <strong>features/steps/common_steps.py</strong>. Login and field entry are reused by multiple features:</p><pre># common_steps.py<br>@given(&#39;I am logged in as an admin&#39;)<br>def step_impl(context):<br>    # Implement login logic here<br>    context.page.goto(f&#39;{context.env[&quot;BASE_URL&quot;]}/accounts/login/&#39;)<br>    context.page.fill(&#39;input[name=&quot;username&quot;]&#39;, os.environ.get(&#39;BDD_EMAIL&#39;))<br>    context.page.fill(&#39;input[name=&quot;password&quot;]&#39;, os.environ.get(&#39;BDD_PASSWORD&#39;))<br>    context.page.click(&#39;button[title=&quot;Sign In&quot;]&#39;)<br>    expect(context.page).to_have_url(https://medium.com/f&#39;{context.env[&quot;BASE_URL&quot;]}/console-ops/&#39;)</pre><p>I also centralize dynamic scenario data (e.g., randomized plan names or values passed via -D flags):</p><pre>context.plan_name = context.dynamic_data.get(&#39;plan_name&#39;, &#39;&#39;)<br>context.not_associated_plan_name = context.dynamic_data.get(&#39;not_associated_plan_name&#39;, &#39;&#39;)<br>context.associated_plan_name = context.dynamic_data.get(&#39;associated_plan_name&#39;, &#39;&#39;)<br>context.delete_plan_name = context.dynamic_data.get(&#39;delete_plan_name&#39;, &#39;&#39;)</pre><p>A generic “enter unique field” step handles different features uniformly:</p><pre>@when(&#39;I enter a unique &quot;{field_name}&quot;&#39;)<br>def step_impl(context, field_name):<br>    &quot;&quot;&quot;Dynamic step for entering any field value&quot;&quot;&quot;<br>    if not hasattr(context, &#39;dynamic_data&#39;):<br>        context.dynamic_data = {}<br>    if field_name == &quot;Plan Name&quot;:<br>        context.page.fill(&#39;input[name=&quot;name&quot;]&#39;, context.plan_name)<br><br>@when(&#39;Plan name can include a maximum 50 characters, after which the cursor will stop writing&#39;)<br>def step_impl(context):<br>    long_name = context.plan_name + &#39;X&#39; * (60 - len(context.plan_name))<br>    context.page.fill(&#39;input[name=&quot;name&quot;]&#39;, long_name)<br>    input_value = context.page.input_value(&#39;input[name=&quot;name&quot;]&#39;)<br>    assert len(input_value) &lt;= 50, f&quot;Plan name should be limited to 50 characters, got {len(input_value)}&quot;<br>    context.page.fill(&#39;input[name=&quot;name&quot;]&#39;, context.plan_name)<br><br>@when(&#39;I select a &quot;Business Model&quot; from the dropdown (Service Provider/Direct) and it will be default to 3&#39;)<br>def step_impl(context):<br>    default_value = context.page.eval_on_selector(&#39;select[name=&quot;program_type&quot;]&#39;, &#39;el =&gt; el.value&#39;)<br>    assert default_value == &#39;3&#39;, f&quot;Default value should be &#39;Direct&#39;, got {default_value}&quot;<br>    context.page.select_option(&#39;select[name=&quot;program_type&quot;]&#39;, &#39;Service Provider&#39;)<br><br>@when(&#39;I enter a valid &quot;Price&quot; which is default to 0&#39;)<br>def step_impl(context):<br>    default_value = context.page.input_value(&#39;input[name=&quot;price&quot;]&#39;)<br>    assert default_value == &#39;0&#39;, f&quot;Default price should be &#39;0&#39;, got {default_value}&quot;<br>    context.page.fill(&#39;input[name=&quot;price&quot;]&#39;, &#39;50&#39;)<br><br>@when(&#39;I select &quot;{field_name}&quot;&#39;)<br>def step_impl(context, field_name):<br>    &quot;&quot;&quot;Common step for selecting checkboxes&quot;&quot;&quot;<br>    if field_name == &quot;Is Active&quot;:<br>        context.page.check(&#39;input[name=&quot;is_active&quot;]&#39;)</pre><h4>Context as dependency injection: per-module navigation</h4><p>Each feature area injects its own navigation “strategy” and URL path into context, so common steps can operate generically. Example: AI subscription navigation:</p><pre># ai_subscription_steps.py<br>@given(&#39;I navigate to the &quot;Add AI Subscription Plan&quot; page&#39;)<br>def step_impl(context):<br>    # First hover over the menu item, then click<br>    context.page.click(&#39;#djHideToolBarButton&#39;)<br>    context.page.wait_for_timeout(1000)<br>    context.page.hover(&#39;text=Subscriptions&#39;)<br>    context.page.click(&#39;text=AI Subscription Plan(s)&#39;)<br>    context.page.wait_for_timeout(1000)<br>    context.page.click(&#39;text=Add AI Subscription Plan&#39;)<br>    expect(context.page).to_have_url(https://medium.com/f&#39;{context.env[&quot;BASE_URL&quot;]}/subscription/aisubscriptionplan/add/&#39;)<br>    context.go_to_active_plan_page = go_to_active_plan_page<br>    context.go_to_inactive_plan_page = go_to_inactive_plan_page<br>    context.url_path = &#39;aisubscriptionplan&#39;</pre><p>The injected functions are defined in the same module:</p><pre>def go_to_inactive_plan_page(context):<br>    context.page.goto(f&#39;{context.env[&quot;BASE_URL&quot;]}/subscription/proxyaisubscriptionplan/&#39;)<br><br>def go_to_active_plan_page(context):<br>    context.page.goto(f&#39;{context.env[&quot;BASE_URL&quot;]}/subscription/aisubscriptionplan/&#39;)</pre><p>This context-based injection keeps common_steps decoupled from any single module. It’s effectively a lightweight Strategy pattern.</p><h4>Composing scenarios from shared steps</h4><p>To express higher-level behaviors (e.g., “plan marked as Private”), I compose from existing steps rather than re-implementing flows. This keeps scenarios readable and steps DRY.<br>AI plan: mark as Private</p><pre>@given(&#39;an AI subscription plan is marked as &quot;Private&quot;&#39;)<br>def step_impl(context):<br>    # Create a private plan<br>    context.execute_steps(&#39;&#39;&#39;<br>        when I enter a unique &quot;Plan Name&quot;<br>        when Plan name can include a maximum 50 characters, after which the cursor will stop writing<br>        when I select a &quot;Business Model&quot; from the dropdown (Service Provider/Direct) and it will be default to 3<br>        when I enter a valid &quot;Price&quot; which is default to 0<br>        when I enter a valid &quot;Number of AI Agents Allowed&quot; which is default to 0<br>        when I enter a valid &quot;Additional AI Agents Allowed&quot; which is default to 0<br>        when I enter a valid &quot;Cost Per Additional AI Agent&quot; which is default to 0<br>        when I select &quot;Is Active&quot;<br>        when I select a &quot;Plan Duration&quot; from the dropdown<br>        # other steps.....<br>    &#39;&#39;&#39;)</pre><p>This composition pattern:<br>1. Encourages reuse and consistency across modules.<br>2. Keeps business intent at the Gherkin level while centralizing mechanics.</p><h4>Validations, constraints, and robust selectors</h4><p>I capture real form constraints as executable specs (length limits, defaults, disabled fields). For example, plan-name length enforcement:</p><pre># common_steps.py<br>@when(&#39;Plan name can include a maximum 50 characters, after which the cursor will stop writing&#39;)<br>def step_impl(context):<br>    long_name = context.plan_name + &#39;X&#39; * (60 - len(context.plan_name))<br>    context.page.fill(&#39;input[name=&quot;name&quot;]&#39;, long_name)<br>    input_value = context.page.input_value(&#39;input[name=&quot;name&quot;]&#39;)<br>    assert len(input_value) &lt;= 50, f&quot;Plan name should be limited to 50 characters, got {len(input_value)}&quot;<br>    context.page.fill(&#39;input[name=&quot;name&quot;]&#39;, context.plan_name)</pre><p>And list-validation that adapts to UI state (search fallback shown earlier) makes tests less brittle while remaining true to user behavior.<br>For flows that depend on the “active/inactive” state, common_steps relies on the injected navigation functions:</p><pre>@then(&#39;it should be listed in inactive list of plans&#39;)<br>def step_impl(context):<br>    context.page.wait_for_timeout(1000)<br>    # Look for the plan name in the inactive plans section<br>    context.go_to_inactive_plan_page(context)<br>    inactive_section = context.page.locator(f&#39;table:has-text(&quot;{context.plan_name}&quot;)&#39;)<br>    expect(inactive_section).to_be_visible()<br>    expect(inactive_section).to_contain_text(context.plan_name)<br><br>@given(&#39;it should be listed in inactive list of plans&#39;)<br>def step_impl(context):<br>    context.page.wait_for_timeout(1000)<br>    # Look for the plan name in the inactive plans section<br>    context.go_to_inactive_plan_page(context)<br>    inactive_section = context.page.locator(f&#39;table:has-text(&quot;{context.plan_name}&quot;)&#39;)<br>    expect(inactive_section).to_be_visible()<br>    expect(inactive_section).to_contain_text(context.plan_name)</pre><h4><strong>Running the suite with real data</strong></h4><p>I often pass dynamic inputs at runtime to target specific plans or users. <strong>environment.py</strong> picks up <strong>-D key=value </strong>flags and makes them available via <strong>context.dynamic_data</strong>.</p><p>Example run:</p><pre># single scenario<br>behave -n &quot;Ensure public plans are visible to all users&quot;<br><br># all scenarios of specific .feature file<br>behave features\ai_subscription_plan.feature<br><br># specific file with specific scenario with data<br>behave .\features\ai_subscription_plan.feature -n &quot;Verify flag-based access is removed&quot; -D customer=&#39;Name&#39;<br><br># scenario with dynamic data<br>behave ^<br>  -D plan_name=&quot;Plan_QA1234&quot; ^<br>  -D not_associated_plan_name=&quot;Value_Starter&quot; ^<br>  -D associated_plan_name=&quot;Pro_Customer_X&quot; ^<br>  -D delete_plan_name=&quot;Legacy_Trial&quot;<br><br># capture the output<br>behave features/ai_subscription_plan.feature --format=pretty | tee reports/behave_output.txt</pre><h4>Best practices I follow</h4><ul><li><strong>Keep Gherkin business-focused:</strong> Avoid UI details in features; keep them in steps.</li><li><strong>Use Background for common setup:</strong> e.g., login + navigation.</li><li><strong>Centralize shared steps:</strong> All common UI interactions and validations live in <strong>common_steps.py</strong>.</li><li><strong>Inject per-module strategies into context:</strong> <strong>go_to_active_plan_page</strong>, <strong>url_path </strong>let common steps work everywhere.</li><li><strong>Assert, don’t sleep:</strong> Prefer expect over <strong>wait_for_timeout</strong>.</li><li><strong>Secure by default:</strong> Use <strong>.env</strong> via <strong>python-dotenv </strong>for secrets; don’t hardcode credentials.</li><li><strong>Name things consistently:</strong> Scenario names map to reusable steps, and feature files mirror product domains.</li></ul><h4>Pros and cons of using BDD in this project</h4><h4>Pros</h4><ul><li><strong>Business-aligned specs:</strong> Features like <strong>ai_subscription_plan.feature </strong>and <strong>savi_subscription_plan.feature </strong>read like requirements, improving shared understanding across product, QA, and engineering.</li><li><strong>Reusable steps cut duplication:</strong> Centralizing login, field inputs, validations, and list assertions in <strong>steps/common_steps.py</strong> reduces repeated logic and makes edits ripple safely across features.</li><li><strong>Composable flows:</strong> Using <strong>context.execute_steps(…) </strong>for “Private/Prospect” setup keeps higher-level behavior readable while reusing the same mechanics.</li><li><strong>Stable lifecycle management:</strong> <strong>environment.py </strong>owns Playwright startup/shutdown and per-scenario page creation, reducing flakiness and resource leaks.</li><li><strong>Configurable, not hardcoded:</strong> <strong>.env + context.dynamic_data </strong>with <strong>-D </strong>flags allow realistic runs (e.g., <strong>plan_name</strong>, <strong>delete_plan_name</strong>) without changing feature text.</li><li><strong>UI constraints as living tests:</strong> Steps assert real behaviors like max lengths, default values, disabled fields, and visibility — keeping tests close to user experience.</li><li><strong>Module-agnostic common steps:</strong> Injected strategies (<strong>context.go_to_active_plan_page</strong>, <strong>context.url_path</strong>) let generic steps work across multiple plan types with minimal branching.</li></ul><h4>Cons</h4><ul><li><strong>Selector fragility:</strong> UI-driven tests can be brittle if CSS/text selectors change; maintenance is needed when front-end evolves.</li><li><strong>Timing flakiness:</strong> Any residual <strong>wait_for_timeout </strong>can cause flaky runs; migrating fully to <strong>expect(…)</strong> and explicit waits is ongoing effort.</li><li><strong>Abstraction overreach risk:</strong> Overloading <strong>common_steps.py</strong> can make debugging harder; balance reuse with clarity and keep feature-specific logic in their own files.</li><li><strong>Execution cost:</strong> End-to-end UI runs (Playwright, real browser) are slower than unit/integration tests; requires thoughtful tagging and CI parallelization.</li><li><strong>Onboarding curve:</strong> Contributors must learn both Gherkin conventions and the shared step utilities/injections (e.g., how <strong>context.url_path </strong>and navigation hooks work).</li><li><strong>Review discipline:</strong> Keeping Gherkin business-focused (vs UI details) and steps clean requires consistent code review standards to prevent drift.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30c682ff6b23" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>